From c80c15dcc33a70acc2b177691d33f088f8c2541e Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Thu, 6 Nov 2014 06:41:47 -0500 Subject: Include all vendor files in the repo to be easier for people --- vendor/autoload.php | 7 + vendor/composer/ClassLoader.php | 383 ++ vendor/composer/autoload_classmap.php | 9 + vendor/composer/autoload_files.php | 13 + vendor/composer/autoload_namespaces.php | 16 + vendor/composer/autoload_psr4.php | 9 + vendor/composer/autoload_real.php | 55 + vendor/composer/installed.json | 319 ++ vendor/erusev/parsedown/.travis.yml | 10 + vendor/erusev/parsedown/LICENSE.txt | 20 + vendor/erusev/parsedown/Parsedown.php | 1430 ++++++ vendor/erusev/parsedown/README.md | 43 + vendor/erusev/parsedown/composer.json | 18 + vendor/erusev/parsedown/phpunit.xml.dist | 8 + vendor/erusev/parsedown/test/ParsedownTest.php | 139 + vendor/erusev/parsedown/test/bootstrap.php | 3 + .../parsedown/test/data/aesthetic_table.html | 18 + .../erusev/parsedown/test/data/aesthetic_table.md | 4 + .../erusev/parsedown/test/data/aligned_table.html | 21 + vendor/erusev/parsedown/test/data/aligned_table.md | 4 + vendor/erusev/parsedown/test/data/atx_heading.html | 9 + vendor/erusev/parsedown/test/data/atx_heading.md | 17 + .../erusev/parsedown/test/data/automatic_link.html | 1 + .../erusev/parsedown/test/data/automatic_link.md | 1 + .../parsedown/test/data/block-level_html.html | 13 + .../erusev/parsedown/test/data/block-level_html.md | 17 + vendor/erusev/parsedown/test/data/code_block.html | 8 + vendor/erusev/parsedown/test/data/code_block.md | 10 + vendor/erusev/parsedown/test/data/code_span.html | 6 + vendor/erusev/parsedown/test/data/code_span.md | 11 + .../parsedown/test/data/compound_blockquote.html | 9 + .../parsedown/test/data/compound_blockquote.md | 10 + .../parsedown/test/data/compound_emphasis.html | 2 + .../parsedown/test/data/compound_emphasis.md | 4 + .../erusev/parsedown/test/data/compound_list.html | 12 + vendor/erusev/parsedown/test/data/compound_list.md | 7 + .../parsedown/test/data/deeply_nested_list.html | 12 + .../parsedown/test/data/deeply_nested_list.md | 6 + vendor/erusev/parsedown/test/data/em_strong.html | 8 + vendor/erusev/parsedown/test/data/em_strong.md | 15 + vendor/erusev/parsedown/test/data/email.html | 1 + vendor/erusev/parsedown/test/data/email.md | 1 + vendor/erusev/parsedown/test/data/emphasis.html | 8 + vendor/erusev/parsedown/test/data/emphasis.md | 13 + vendor/erusev/parsedown/test/data/escaping.html | 4 + vendor/erusev/parsedown/test/data/escaping.md | 7 + .../parsedown/test/data/fenced_code_block.html | 6 + .../parsedown/test/data/fenced_code_block.md | 14 + .../parsedown/test/data/horizontal_rule.html | 5 + .../erusev/parsedown/test/data/horizontal_rule.md | 9 + .../erusev/parsedown/test/data/html_comment.html | 5 + vendor/erusev/parsedown/test/data/html_comment.md | 8 + vendor/erusev/parsedown/test/data/html_entity.html | 1 + vendor/erusev/parsedown/test/data/html_entity.md | 1 + .../parsedown/test/data/image_reference.html | 1 + .../erusev/parsedown/test/data/image_reference.md | 3 + vendor/erusev/parsedown/test/data/image_title.html | 1 + vendor/erusev/parsedown/test/data/image_title.md | 1 + .../parsedown/test/data/implicit_reference.html | 4 + .../parsedown/test/data/implicit_reference.md | 13 + vendor/erusev/parsedown/test/data/inline_link.html | 4 + vendor/erusev/parsedown/test/data/inline_link.md | 7 + .../parsedown/test/data/inline_link_title.html | 1 + .../parsedown/test/data/inline_link_title.md | 1 + .../erusev/parsedown/test/data/inline_title.html | 1 + vendor/erusev/parsedown/test/data/inline_title.md | 1 + .../parsedown/test/data/lazy_blockquote.html | 6 + .../erusev/parsedown/test/data/lazy_blockquote.md | 5 + vendor/erusev/parsedown/test/data/lazy_list.html | 4 + vendor/erusev/parsedown/test/data/lazy_list.md | 2 + vendor/erusev/parsedown/test/data/line_break.html | 2 + vendor/erusev/parsedown/test/data/line_break.md | 2 + .../test/data/multiline_list_paragraph.html | 7 + .../test/data/multiline_list_paragraph.md | 4 + .../test/data/nested_block-level_html.html | 10 + .../parsedown/test/data/nested_block-level_html.md | 11 + .../erusev/parsedown/test/data/ordered_list.html | 13 + vendor/erusev/parsedown/test/data/ordered_list.md | 11 + .../erusev/parsedown/test/data/paragraph_list.html | 12 + .../erusev/parsedown/test/data/paragraph_list.md | 9 + .../parsedown/test/data/reference_title.html | 2 + .../erusev/parsedown/test/data/reference_title.md | 6 + .../parsedown/test/data/self-closing_html.html | 12 + .../parsedown/test/data/self-closing_html.md | 12 + .../parsedown/test/data/separated_nested_list.html | 9 + .../parsedown/test/data/separated_nested_list.md | 4 + .../erusev/parsedown/test/data/setext_header.html | 5 + vendor/erusev/parsedown/test/data/setext_header.md | 12 + .../parsedown/test/data/simple_blockquote.html | 11 + .../parsedown/test/data/simple_blockquote.md | 7 + .../erusev/parsedown/test/data/simple_table.html | 37 + vendor/erusev/parsedown/test/data/simple_table.md | 11 + .../parsedown/test/data/span-level_html.html | 5 + .../erusev/parsedown/test/data/span-level_html.md | 8 + .../parsedown/test/data/sparse_dense_list.html | 7 + .../parsedown/test/data/sparse_dense_list.md | 4 + vendor/erusev/parsedown/test/data/sparse_list.html | 15 + vendor/erusev/parsedown/test/data/sparse_list.md | 9 + .../parsedown/test/data/special_characters.html | 6 + .../parsedown/test/data/special_characters.md | 13 + .../erusev/parsedown/test/data/strikethrough.html | 3 + vendor/erusev/parsedown/test/data/strikethrough.md | 5 + vendor/erusev/parsedown/test/data/strong_em.html | 6 + vendor/erusev/parsedown/test/data/strong_em.md | 11 + .../test/data/tab-indented_code_block.html | 6 + .../parsedown/test/data/tab-indented_code_block.md | 6 + .../parsedown/test/data/table_inline_markdown.html | 18 + .../parsedown/test/data/table_inline_markdown.md | 4 + .../erusev/parsedown/test/data/text_reference.html | 8 + .../erusev/parsedown/test/data/text_reference.md | 21 + .../erusev/parsedown/test/data/unordered_list.html | 10 + .../erusev/parsedown/test/data/unordered_list.md | 8 + .../erusev/parsedown/test/data/untidy_table.html | 18 + vendor/erusev/parsedown/test/data/untidy_table.md | 4 + .../parsedown/test/data/url_autolinking.html | 3 + .../erusev/parsedown/test/data/url_autolinking.md | 5 + vendor/erusev/parsedown/test/data/whitespace.html | 1 + vendor/erusev/parsedown/test/data/whitespace.md | 5 + vendor/fguillot/json-rpc | 1 + vendor/fguillot/picodb | 1 + vendor/fguillot/simple-validator | 1 + vendor/ircmaxell/password-compat/.travis.yml | 8 + vendor/ircmaxell/password-compat/LICENSE.md | 7 + vendor/ircmaxell/password-compat/README.md | 75 + vendor/ircmaxell/password-compat/composer.json | 18 + vendor/ircmaxell/password-compat/lib/password.php | 222 + vendor/ircmaxell/password-compat/phpunit.xml.dist | 29 + .../test/Unit/PasswordGetInfoTest.php | 26 + .../password-compat/test/Unit/PasswordHashTest.php | 84 + .../test/Unit/PasswordNeedsRehashTest.php | 26 + .../test/Unit/PasswordVerifyTest.php | 29 + vendor/ircmaxell/password-compat/version-test.php | 8 + vendor/lusitanian/oauth/.gitignore | 6 + vendor/lusitanian/oauth/.scrutinizer.yml | 37 + vendor/lusitanian/oauth/.travis.yml | 22 + vendor/lusitanian/oauth/LICENSE | 20 + vendor/lusitanian/oauth/README.md | 102 + vendor/lusitanian/oauth/composer.json | 40 + vendor/lusitanian/oauth/examples/amazon.php | 52 + vendor/lusitanian/oauth/examples/bitbucket.php | 64 + vendor/lusitanian/oauth/examples/bitly.php | 53 + vendor/lusitanian/oauth/examples/bootstrap.php | 29 + vendor/lusitanian/oauth/examples/box.php | 58 + vendor/lusitanian/oauth/examples/buffer.php | 53 + vendor/lusitanian/oauth/examples/dailymotion.php | 52 + vendor/lusitanian/oauth/examples/dropbox.php | 52 + vendor/lusitanian/oauth/examples/etsy.php | 59 + vendor/lusitanian/oauth/examples/facebook.php | 54 + vendor/lusitanian/oauth/examples/fitbit.php | 61 + vendor/lusitanian/oauth/examples/flickr.php | 80 + vendor/lusitanian/oauth/examples/foursquare.php | 53 + vendor/lusitanian/oauth/examples/github.php | 52 + vendor/lusitanian/oauth/examples/google.php | 53 + vendor/lusitanian/oauth/examples/harvest.php | 74 + vendor/lusitanian/oauth/examples/init.example.php | 136 + vendor/lusitanian/oauth/examples/instagram.php | 56 + vendor/lusitanian/oauth/examples/linkedin.php | 57 + vendor/lusitanian/oauth/examples/mailchimp.php | 55 + vendor/lusitanian/oauth/examples/microsoft.php | 49 + vendor/lusitanian/oauth/examples/paypal.php | 52 + vendor/lusitanian/oauth/examples/pocket.php | 63 + vendor/lusitanian/oauth/examples/reddit.php | 54 + vendor/lusitanian/oauth/examples/runkeeper.php | 51 + vendor/lusitanian/oauth/examples/scoopit.php | 57 + vendor/lusitanian/oauth/examples/soundcloud.php | 53 + vendor/lusitanian/oauth/examples/tumblr.php | 62 + vendor/lusitanian/oauth/examples/twitter.php | 62 + vendor/lusitanian/oauth/examples/ustream.php | 54 + vendor/lusitanian/oauth/examples/yahoo.php | 57 + vendor/lusitanian/oauth/phpunit.xml.dist | 45 + .../oauth/src/OAuth/Common/AutoLoader.php | 81 + .../src/OAuth/Common/Consumer/Credentials.php | 60 + .../OAuth/Common/Consumer/CredentialsInterface.php | 24 + .../oauth/src/OAuth/Common/Exception/Exception.php | 10 + .../OAuth/Common/Http/Client/AbstractClient.php | 73 + .../OAuth/Common/Http/Client/ClientInterface.php | 32 + .../src/OAuth/Common/Http/Client/CurlClient.php | 142 + .../src/OAuth/Common/Http/Client/StreamClient.php | 92 + .../Http/Exception/TokenResponseException.php | 12 + .../oauth/src/OAuth/Common/Http/Uri/Uri.php | 408 ++ .../oauth/src/OAuth/Common/Http/Uri/UriFactory.php | 168 + .../OAuth/Common/Http/Uri/UriFactoryInterface.php | 42 + .../src/OAuth/Common/Http/Uri/UriInterface.php | 133 + .../src/OAuth/Common/Service/AbstractService.php | 100 + .../src/OAuth/Common/Service/ServiceInterface.php | 49 + .../AuthorizationStateNotFoundException.php | 10 + .../Common/Storage/Exception/StorageException.php | 12 + .../Storage/Exception/TokenNotFoundException.php | 10 + .../oauth/src/OAuth/Common/Storage/Memory.php | 139 + .../oauth/src/OAuth/Common/Storage/Redis.php | 230 + .../oauth/src/OAuth/Common/Storage/Session.php | 188 + .../src/OAuth/Common/Storage/SymfonySession.php | 200 + .../OAuth/Common/Storage/TokenStorageInterface.php | 98 + .../oauth/src/OAuth/Common/Token/AbstractToken.php | 128 + .../Token/Exception/ExpiredTokenException.php | 12 + .../src/OAuth/Common/Token/TokenInterface.php | 64 + .../src/OAuth/OAuth1/Service/AbstractService.php | 305 ++ .../oauth/src/OAuth/OAuth1/Service/BitBucket.php | 96 + .../oauth/src/OAuth/OAuth1/Service/Etsy.php | 132 + .../oauth/src/OAuth/OAuth1/Service/FitBit.php | 96 + .../oauth/src/OAuth/OAuth1/Service/Flickr.php | 91 + .../oauth/src/OAuth/OAuth1/Service/ScoopIt.php | 96 + .../src/OAuth/OAuth1/Service/ServiceInterface.php | 45 + .../oauth/src/OAuth/OAuth1/Service/Tumblr.php | 96 + .../oauth/src/OAuth/OAuth1/Service/Twitter.php | 121 + .../oauth/src/OAuth/OAuth1/Service/Xing.php | 96 + .../oauth/src/OAuth/OAuth1/Service/Yahoo.php | 96 + .../UnsupportedHashAlgorithmException.php | 12 + .../oauth/src/OAuth/OAuth1/Signature/Signature.php | 132 + .../OAuth/OAuth1/Signature/SignatureInterface.php | 28 + .../src/OAuth/OAuth1/Token/StdOAuth1Token.php | 75 + .../src/OAuth/OAuth1/Token/TokenInterface.php | 41 + .../src/OAuth/OAuth2/Service/AbstractService.php | 333 ++ .../oauth/src/OAuth/OAuth2/Service/Amazon.php | 97 + .../oauth/src/OAuth/OAuth2/Service/Bitly.php | 111 + .../oauth/src/OAuth/OAuth2/Service/Box.php | 88 + .../oauth/src/OAuth/OAuth2/Service/Buffer.php | 151 + .../oauth/src/OAuth/OAuth2/Service/Dailymotion.php | 129 + .../oauth/src/OAuth/OAuth2/Service/Dropbox.php | 111 + .../Exception/InvalidAccessTypeException.php | 12 + .../InvalidAuthorizationStateException.php | 10 + .../Service/Exception/InvalidScopeException.php | 17 + .../Exception/MissingRefreshTokenException.php | 17 + .../oauth/src/OAuth/OAuth2/Service/Facebook.php | 193 + .../oauth/src/OAuth/OAuth2/Service/Foursquare.php | 81 + .../oauth/src/OAuth/OAuth2/Service/GitHub.php | 208 + .../oauth/src/OAuth/OAuth2/Service/Google.php | 158 + .../oauth/src/OAuth/OAuth2/Service/Harvest.php | 157 + .../oauth/src/OAuth/OAuth2/Service/Heroku.php | 123 + .../oauth/src/OAuth/OAuth2/Service/Instagram.php | 85 + .../oauth/src/OAuth/OAuth2/Service/Linkedin.php | 102 + .../oauth/src/OAuth/OAuth2/Service/Mailchimp.php | 115 + .../oauth/src/OAuth/OAuth2/Service/Microsoft.php | 119 + .../oauth/src/OAuth/OAuth2/Service/Paypal.php | 103 + .../oauth/src/OAuth/OAuth2/Service/Pocket.php | 125 + .../oauth/src/OAuth/OAuth2/Service/Reddit.php | 114 + .../oauth/src/OAuth/OAuth2/Service/RunKeeper.php | 105 + .../oauth/src/OAuth/OAuth2/Service/Salesforce.php | 92 + .../src/OAuth/OAuth2/Service/ServiceInterface.php | 37 + .../oauth/src/OAuth/OAuth2/Service/SoundCloud.php | 77 + .../oauth/src/OAuth/OAuth2/Service/Ustream.php | 98 + .../oauth/src/OAuth/OAuth2/Service/Vkontakte.php | 109 + .../oauth/src/OAuth/OAuth2/Service/Yammer.php | 82 + .../src/OAuth/OAuth2/Token/StdOAuth2Token.php | 13 + .../src/OAuth/OAuth2/Token/TokenInterface.php | 9 + .../lusitanian/oauth/src/OAuth/ServiceFactory.php | 229 + vendor/lusitanian/oauth/src/OAuth/bootstrap.php | 13 + .../Mocks/Common/FakeProject/NS/SomeClass.php | 11 + .../oauth/tests/Mocks/Common/Service/Mock.php | 60 + .../oauth/tests/Mocks/OAuth1/Service/Fake.php | 57 + .../oauth/tests/Mocks/OAuth1/Service/Mock.php | 35 + .../oauth/tests/Mocks/OAuth2/Service/Fake.php | 32 + .../oauth/tests/Mocks/OAuth2/Service/Mock.php | 58 + .../oauth/tests/Unit/Common/AutoloaderTest.php | 126 + .../tests/Unit/Common/Consumer/CredentialsTest.php | 51 + .../Unit/Common/Http/Client/AbstractClientTest.php | 67 + .../Unit/Common/Http/Client/CurlClientTest.php | 378 ++ .../Unit/Common/Http/Client/StreamClientTest.php | 283 ++ .../tests/Unit/Common/Http/HttpClientsTest.php | 171 + .../tests/Unit/Common/Http/Uri/UriFactoryTest.php | 331 ++ .../oauth/tests/Unit/Common/Http/Uri/UriTest.php | 898 ++++ .../Unit/Common/Service/AbstractServiceTest.php | 171 + .../oauth/tests/Unit/Common/Storage/MemoryTest.php | 132 + .../oauth/tests/Unit/Common/Storage/RedisTest.php | 102 + .../tests/Unit/Common/Storage/SessionTest.php | 245 + .../tests/Unit/Common/Storage/StorageTest.php | 74 + .../Unit/Common/Storage/SymfonySessionTest.php | 111 + .../tests/Unit/Common/Token/AbstractTokenTest.php | 189 + .../Unit/OAuth1/Service/AbstractServiceTest.php | 215 + .../tests/Unit/OAuth1/Service/BitBucketTest.php | 278 ++ .../oauth/tests/Unit/OAuth1/Service/EtsyTest.php | 286 ++ .../oauth/tests/Unit/OAuth1/Service/FitBitTest.php | 278 ++ .../oauth/tests/Unit/OAuth1/Service/FlickrTest.php | 302 ++ .../tests/Unit/OAuth1/Service/ScoopItTest.php | 302 ++ .../oauth/tests/Unit/OAuth1/Service/TumblrTest.php | 278 ++ .../tests/Unit/OAuth1/Service/TwitterTest.php | 307 ++ .../oauth/tests/Unit/OAuth1/Service/XingTest.php | 239 + .../oauth/tests/Unit/OAuth1/Service/YahooTest.php | 302 ++ .../tests/Unit/OAuth1/Signature/SignatureTest.php | 325 ++ .../tests/Unit/OAuth1/Token/StdOAuth1TokenTest.php | 85 + .../Unit/OAuth2/Service/AbstractServiceTest.php | 401 ++ .../oauth/tests/Unit/OAuth2/Service/AmazonTest.php | 207 + .../oauth/tests/Unit/OAuth2/Service/BitlyTest.php | 150 + .../oauth/tests/Unit/OAuth2/Service/BoxTest.php | 207 + .../oauth/tests/Unit/OAuth2/Service/BufferTest.php | 150 + .../tests/Unit/OAuth2/Service/DailymotionTest.php | 230 + .../tests/Unit/OAuth2/Service/DropboxTest.php | 231 + .../tests/Unit/OAuth2/Service/FacebookTest.php | 242 + .../tests/Unit/OAuth2/Service/FoursquareTest.php | 197 + .../oauth/tests/Unit/OAuth2/Service/GitHubTest.php | 220 + .../oauth/tests/Unit/OAuth2/Service/GoogleTest.php | 195 + .../oauth/tests/Unit/OAuth2/Service/HerokuTest.php | 261 + .../tests/Unit/OAuth2/Service/InstagramTest.php | 193 + .../tests/Unit/OAuth2/Service/LinkedinTest.php | 213 + .../tests/Unit/OAuth2/Service/MailchimpTest.php | 179 + .../tests/Unit/OAuth2/Service/MicrosoftTest.php | 193 + .../oauth/tests/Unit/OAuth2/Service/PaypalTest.php | 213 + .../oauth/tests/Unit/OAuth2/Service/RedditTest.php | 193 + .../tests/Unit/OAuth2/Service/RunKeeperTest.php | 207 + .../tests/Unit/OAuth2/Service/SoundCloudTest.php | 159 + .../tests/Unit/OAuth2/Service/UstreamTest.php | 193 + .../tests/Unit/OAuth2/Service/VkontakteTest.php | 159 + .../oauth/tests/Unit/OAuth2/Service/YammerTest.php | 187 + .../oauth/tests/Unit/ServiceFactoryTest.php | 311 ++ vendor/lusitanian/oauth/tests/bootstrap.php | 42 + vendor/swiftmailer/swiftmailer/.gitattributes | 6 + vendor/swiftmailer/swiftmailer/.gitignore | 4 + vendor/swiftmailer/swiftmailer/.travis.yml | 25 + vendor/swiftmailer/swiftmailer/CHANGES | 186 + vendor/swiftmailer/swiftmailer/LICENSE | 19 + vendor/swiftmailer/swiftmailer/README | 16 + vendor/swiftmailer/swiftmailer/VERSION | 1 + vendor/swiftmailer/swiftmailer/composer.json | 31 + vendor/swiftmailer/swiftmailer/doc/headers.rst | 742 +++ .../swiftmailer/swiftmailer/doc/help-resources.rst | 44 + .../swiftmailer/doc/including-the-files.rst | 46 + vendor/swiftmailer/swiftmailer/doc/index.rst | 16 + vendor/swiftmailer/swiftmailer/doc/installing.rst | 89 + .../swiftmailer/swiftmailer/doc/introduction.rst | 135 + vendor/swiftmailer/swiftmailer/doc/japanese.rst | 22 + vendor/swiftmailer/swiftmailer/doc/messages.rst | 1057 ++++ vendor/swiftmailer/swiftmailer/doc/overview.rst | 161 + vendor/swiftmailer/swiftmailer/doc/plugins.rst | 385 ++ vendor/swiftmailer/swiftmailer/doc/sending.rst | 607 +++ .../swiftmailer/doc/uml/Encoders.graffle | Bin 0 -> 3503 bytes .../swiftmailer/swiftmailer/doc/uml/Mime.graffle | Bin 0 -> 5575 bytes .../swiftmailer/doc/uml/Transports.graffle | Bin 0 -> 3061 bytes .../swiftmailer/swiftmailer/lib/classes/Swift.php | 80 + .../swiftmailer/lib/classes/Swift/Attachment.php | 71 + .../ByteStream/AbstractFilterableInputStream.php | 179 + .../classes/Swift/ByteStream/ArrayByteStream.php | 184 + .../classes/Swift/ByteStream/FileByteStream.php | 229 + .../Swift/ByteStream/TemporaryFileByteStream.php | 42 + .../lib/classes/Swift/CharacterReader.php | 67 + .../CharacterReader/GenericFixedWidthReader.php | 97 + .../Swift/CharacterReader/UsAsciiReader.php | 84 + .../classes/Swift/CharacterReader/Utf8Reader.php | 179 + .../lib/classes/Swift/CharacterReaderFactory.php | 26 + .../SimpleCharacterReaderFactory.php | 124 + .../lib/classes/Swift/CharacterStream.php | 89 + .../Swift/CharacterStream/ArrayCharacterStream.php | 293 ++ .../Swift/CharacterStream/NgCharacterStream.php | 276 + .../lib/classes/Swift/ConfigurableSpool.php | 63 + .../lib/classes/Swift/DependencyContainer.php | 372 ++ .../lib/classes/Swift/DependencyException.php | 27 + .../swiftmailer/lib/classes/Swift/EmbeddedFile.php | 69 + .../swiftmailer/lib/classes/Swift/Encoder.php | 27 + .../lib/classes/Swift/Encoder/Base64Encoder.php | 58 + .../lib/classes/Swift/Encoder/QpEncoder.php | 289 ++ .../lib/classes/Swift/Encoder/Rfc2231Encoder.php | 92 + .../swiftmailer/lib/classes/Swift/Encoding.php | 64 + .../lib/classes/Swift/Events/CommandEvent.php | 65 + .../lib/classes/Swift/Events/CommandListener.php | 24 + .../swiftmailer/lib/classes/Swift/Events/Event.php | 38 + .../lib/classes/Swift/Events/EventDispatcher.php | 83 + .../lib/classes/Swift/Events/EventListener.php | 18 + .../lib/classes/Swift/Events/EventObject.php | 63 + .../lib/classes/Swift/Events/ResponseEvent.php | 65 + .../lib/classes/Swift/Events/ResponseListener.php | 24 + .../lib/classes/Swift/Events/SendEvent.php | 126 + .../lib/classes/Swift/Events/SendListener.php | 31 + .../classes/Swift/Events/SimpleEventDispatcher.php | 156 + .../classes/Swift/Events/TransportChangeEvent.php | 27 + .../Swift/Events/TransportChangeListener.php | 45 + .../Swift/Events/TransportExceptionEvent.php | 46 + .../Swift/Events/TransportExceptionListener.php | 24 + .../lib/classes/Swift/FailoverTransport.php | 45 + .../swiftmailer/lib/classes/Swift/FileSpool.php | 208 + .../swiftmailer/lib/classes/Swift/FileStream.php | 24 + .../swiftmailer/lib/classes/Swift/Filterable.php | 32 + .../swiftmailer/lib/classes/Swift/Image.php | 61 + .../lib/classes/Swift/InputByteStream.php | 75 + .../swiftmailer/lib/classes/Swift/IoException.php | 27 + .../swiftmailer/lib/classes/Swift/KeyCache.php | 105 + .../lib/classes/Swift/KeyCache/ArrayKeyCache.php | 206 + .../lib/classes/Swift/KeyCache/DiskKeyCache.php | 324 ++ .../classes/Swift/KeyCache/KeyCacheInputStream.php | 51 + .../lib/classes/Swift/KeyCache/NullKeyCache.php | 115 + .../Swift/KeyCache/SimpleKeyCacheInputStream.php | 127 + .../lib/classes/Swift/LoadBalancedTransport.php | 45 + .../lib/classes/Swift/MailTransport.php | 45 + .../swiftmailer/lib/classes/Swift/Mailer.php | 114 + .../Swift/Mailer/ArrayRecipientIterator.php | 55 + .../lib/classes/Swift/Mailer/RecipientIterator.php | 32 + .../swiftmailer/lib/classes/Swift/MemorySpool.php | 84 + .../swiftmailer/lib/classes/Swift/Message.php | 287 ++ .../lib/classes/Swift/Mime/Attachment.php | 153 + .../lib/classes/Swift/Mime/CharsetObserver.php | 24 + .../lib/classes/Swift/Mime/ContentEncoder.php | 34 + .../Mime/ContentEncoder/Base64ContentEncoder.php | 67 + .../Mime/ContentEncoder/NativeQpContentEncoder.php | 123 + .../Mime/ContentEncoder/PlainContentEncoder.php | 162 + .../Swift/Mime/ContentEncoder/QpContentEncoder.php | 123 + .../Mime/ContentEncoder/QpContentEncoderProxy.php | 97 + .../Mime/ContentEncoder/RawContentEncoder.php | 63 + .../lib/classes/Swift/Mime/EmbeddedFile.php | 45 + .../lib/classes/Swift/Mime/EncodingObserver.php | 24 + .../swiftmailer/lib/classes/Swift/Mime/Grammar.php | 176 + .../swiftmailer/lib/classes/Swift/Mime/Header.php | 93 + .../lib/classes/Swift/Mime/HeaderEncoder.php | 24 + .../Mime/HeaderEncoder/Base64HeaderEncoder.php | 55 + .../Swift/Mime/HeaderEncoder/QpHeaderEncoder.php | 65 + .../lib/classes/Swift/Mime/HeaderFactory.php | 78 + .../lib/classes/Swift/Mime/HeaderSet.php | 169 + .../classes/Swift/Mime/Headers/AbstractHeader.php | 503 ++ .../lib/classes/Swift/Mime/Headers/DateHeader.php | 125 + .../Swift/Mime/Headers/IdentificationHeader.php | 180 + .../classes/Swift/Mime/Headers/MailboxHeader.php | 354 ++ .../classes/Swift/Mime/Headers/OpenDKIMHeader.php | 135 + .../Swift/Mime/Headers/ParameterizedHeader.php | 260 + .../lib/classes/Swift/Mime/Headers/PathHeader.php | 143 + .../Swift/Mime/Headers/UnstructuredHeader.php | 112 + .../swiftmailer/lib/classes/Swift/Mime/Message.php | 223 + .../lib/classes/Swift/Mime/MimeEntity.php | 115 + .../lib/classes/Swift/Mime/MimePart.php | 214 + .../lib/classes/Swift/Mime/ParameterizedHeader.php | 34 + .../lib/classes/Swift/Mime/SimpleHeaderFactory.php | 197 + .../lib/classes/Swift/Mime/SimpleHeaderSet.php | 396 ++ .../lib/classes/Swift/Mime/SimpleMessage.php | 649 +++ .../lib/classes/Swift/Mime/SimpleMimeEntity.php | 866 ++++ .../swiftmailer/lib/classes/Swift/MimePart.php | 59 + .../lib/classes/Swift/NullTransport.php | 39 + .../lib/classes/Swift/OutputByteStream.php | 46 + .../lib/classes/Swift/Plugins/AntiFloodPlugin.php | 141 + .../Swift/Plugins/BandwidthMonitorPlugin.php | 164 + .../Swift/Plugins/Decorator/Replacements.php | 31 + .../lib/classes/Swift/Plugins/DecoratorPlugin.php | 207 + .../classes/Swift/Plugins/ImpersonatePlugin.php | 68 + .../lib/classes/Swift/Plugins/Logger.php | 36 + .../lib/classes/Swift/Plugins/LoggerPlugin.php | 141 + .../classes/Swift/Plugins/Loggers/ArrayLogger.php | 72 + .../classes/Swift/Plugins/Loggers/EchoLogger.php | 58 + .../lib/classes/Swift/Plugins/MessageLogger.php | 75 + .../classes/Swift/Plugins/Pop/Pop3Connection.php | 31 + .../classes/Swift/Plugins/Pop/Pop3Exception.php | 27 + .../classes/Swift/Plugins/PopBeforeSmtpPlugin.php | 273 + .../classes/Swift/Plugins/RedirectingPlugin.php | 211 + .../lib/classes/Swift/Plugins/Reporter.php | 32 + .../lib/classes/Swift/Plugins/ReporterPlugin.php | 73 + .../Swift/Plugins/Reporters/HitReporter.php | 59 + .../Swift/Plugins/Reporters/HtmlReporter.php | 39 + .../lib/classes/Swift/Plugins/Sleeper.php | 24 + .../lib/classes/Swift/Plugins/ThrottlerPlugin.php | 200 + .../lib/classes/Swift/Plugins/Timer.php | 24 + .../swiftmailer/lib/classes/Swift/Preferences.php | 103 + .../lib/classes/Swift/ReplacementFilterFactory.php | 27 + .../lib/classes/Swift/RfcComplianceException.php | 27 + .../lib/classes/Swift/SendmailTransport.php | 45 + .../lib/classes/Swift/SignedMessage.php | 22 + .../swiftmailer/lib/classes/Swift/Signer.php | 20 + .../lib/classes/Swift/Signers/BodySigner.php | 33 + .../lib/classes/Swift/Signers/DKIMSigner.php | 688 +++ .../lib/classes/Swift/Signers/DomainKeySigner.php | 512 ++ .../lib/classes/Swift/Signers/HeaderSigner.php | 65 + .../lib/classes/Swift/Signers/OpenDKIMSigner.php | 186 + .../lib/classes/Swift/Signers/SMimeSigner.php | 427 ++ .../lib/classes/Swift/SmtpTransport.php | 57 + .../swiftmailer/lib/classes/Swift/Spool.php | 53 + .../lib/classes/Swift/SpoolTransport.php | 47 + .../swiftmailer/lib/classes/Swift/StreamFilter.php | 35 + .../StreamFilters/ByteArrayReplacementFilter.php | 169 + .../StreamFilters/StringReplacementFilter.php | 66 + .../StringReplacementFilterFactory.php | 45 + .../lib/classes/Swift/SwiftException.php | 27 + .../swiftmailer/lib/classes/Swift/Transport.php | 54 + .../Swift/Transport/AbstractSmtpTransport.php | 489 ++ .../Transport/Esmtp/Auth/CramMd5Authenticator.php | 81 + .../Transport/Esmtp/Auth/LoginAuthenticator.php | 51 + .../Transport/Esmtp/Auth/NTLMAuthenticator.php | 700 +++ .../Transport/Esmtp/Auth/PlainAuthenticator.php | 50 + .../Transport/Esmtp/Auth/XOAuth2Authenticator.php | 69 + .../classes/Swift/Transport/Esmtp/AuthHandler.php | 263 + .../Swift/Transport/Esmtp/Authenticator.php | 35 + .../lib/classes/Swift/Transport/EsmtpHandler.php | 86 + .../lib/classes/Swift/Transport/EsmtpTransport.php | 386 ++ .../classes/Swift/Transport/FailoverTransport.php | 85 + .../lib/classes/Swift/Transport/IoBuffer.php | 67 + .../Swift/Transport/LoadBalancedTransport.php | 166 + .../lib/classes/Swift/Transport/MailInvoker.php | 32 + .../lib/classes/Swift/Transport/MailTransport.php | 226 + .../lib/classes/Swift/Transport/NullTransport.php | 93 + .../classes/Swift/Transport/SendmailTransport.php | 159 + .../classes/Swift/Transport/SimpleMailInvoker.php | 39 + .../lib/classes/Swift/Transport/SmtpAgent.php | 36 + .../lib/classes/Swift/Transport/SpoolTransport.php | 117 + .../lib/classes/Swift/Transport/StreamBuffer.php | 321 ++ .../lib/classes/Swift/TransportException.php | 27 + .../swiftmailer/lib/classes/Swift/Validate.php | 42 + .../swiftmailer/lib/dependency_maps/cache_deps.php | 23 + .../lib/dependency_maps/message_deps.php | 9 + .../swiftmailer/lib/dependency_maps/mime_deps.php | 123 + .../lib/dependency_maps/transport_deps.php | 76 + vendor/swiftmailer/swiftmailer/lib/mime_types.php | 1007 ++++ vendor/swiftmailer/swiftmailer/lib/preferences.php | 25 + vendor/swiftmailer/swiftmailer/lib/swift_init.php | 28 + .../swiftmailer/swiftmailer/lib/swift_required.php | 30 + .../swiftmailer/lib/swift_required_pear.php | 30 + .../lib/swiftmailer_generate_mimes_config.php | 194 + vendor/swiftmailer/swiftmailer/notes/APPS | 15 + vendor/swiftmailer/swiftmailer/notes/CHARSETS | 46 + vendor/swiftmailer/swiftmailer/notes/message.xml | 22 + .../swiftmailer/swiftmailer/notes/rfc/rfc0821.txt | 4050 +++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc0822.txt | 2901 +++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc1341.txt | 5265 ++++++++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc1521.txt | 4539 +++++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc1854.txt | 395 ++ .../swiftmailer/swiftmailer/notes/rfc/rfc2015.txt | 450 ++ .../swiftmailer/swiftmailer/notes/rfc/rfc2045.txt | 1739 +++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2046.txt | 2467 +++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2047.txt | 843 ++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2048.txt | 1180 +++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2049.txt | 1347 +++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2183.txt | 675 +++ .../swiftmailer/swiftmailer/notes/rfc/rfc2222.txt | 899 ++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2231.txt | 563 +++ .../swiftmailer/swiftmailer/notes/rfc/rfc2234.txt | 787 +++ .../swiftmailer/swiftmailer/notes/rfc/rfc2440.txt | 3642 ++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2487.txt | 451 ++ .../swiftmailer/swiftmailer/notes/rfc/rfc2554.txt | 619 +++ .../swiftmailer/swiftmailer/notes/rfc/rfc2821.txt | 4427 ++++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc2822.txt | 2859 +++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc3156.txt | 842 ++++ .../swiftmailer/swiftmailer/notes/rfc/rfc3676.txt | 1123 +++++ .../swiftmailer/swiftmailer/notes/rfc/rfc4505.txt | 507 ++ .../swiftmailer/swiftmailer/notes/rfc/rfc4616.txt | 619 +++ .../swiftmailer/swiftmailer/notes/rfc/rfc4870.txt | 2298 +++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc4871.txt | 3978 +++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc4880.txt | 5042 +++++++++++++++++++ .../swiftmailer/swiftmailer/notes/rfc/rfc4954.txt | 1123 +++++ .../swiftmailer/swiftmailer/notes/rfc/rfc5751.txt | 2523 ++++++++++ .../swiftmailer/notes/rfc/whats_where.txt | 90 + vendor/swiftmailer/swiftmailer/notes/smtp.txt | 48 + vendor/swiftmailer/swiftmailer/phpunit.xml.dist | 37 + .../tests/IdenticalBinaryConstraint.php | 60 + .../swiftmailer/tests/StreamCollector.php | 11 + .../swiftmailer/tests/SwiftMailerSmokeTestCase.php | 46 + .../swiftmailer/tests/SwiftMailerTestCase.php | 33 + .../tests/_samples/charsets/iso-2022-jp/one.txt | 11 + .../tests/_samples/charsets/iso-8859-1/one.txt | 19 + .../tests/_samples/charsets/utf-8/one.txt | 22 + .../tests/_samples/charsets/utf-8/three.txt | 45 + .../tests/_samples/charsets/utf-8/two.txt | 3 + .../swiftmailer/tests/_samples/dkim/dkim.test.priv | 15 + .../swiftmailer/tests/_samples/dkim/dkim.test.pub | 6 + .../swiftmailer/tests/_samples/files/data.txt | 1 + .../swiftmailer/tests/_samples/smime/CA.srl | 1 + .../swiftmailer/tests/_samples/smime/ca.crt | 21 + .../swiftmailer/tests/_samples/smime/ca.key | 27 + .../tests/_samples/smime/create-cert.sh | 26 + .../swiftmailer/tests/_samples/smime/encrypt.crt | 19 + .../swiftmailer/tests/_samples/smime/encrypt.key | 27 + .../swiftmailer/tests/_samples/smime/encrypt2.crt | 19 + .../swiftmailer/tests/_samples/smime/encrypt2.key | 27 + .../swiftmailer/tests/_samples/smime/sign.crt | 19 + .../swiftmailer/tests/_samples/smime/sign.key | 27 + .../swiftmailer/tests/acceptance.conf.php.default | 44 + .../acceptance/Swift/AttachmentAcceptanceTest.php | 12 + .../ByteStream/FileByteStreamAcceptanceTest.php | 174 + .../SimpleCharacterReaderFactoryAcceptanceTest.php | 179 + .../Swift/DependencyContainerAcceptanceTest.php | 20 + .../Swift/EmbeddedFileAcceptanceTest.php | 12 + .../Swift/Encoder/Base64EncoderAcceptanceTest.php | 45 + .../Swift/Encoder/QpEncoderAcceptanceTest.php | 50 + .../Swift/Encoder/Rfc2231EncoderAcceptanceTest.php | 50 + .../acceptance/Swift/EncodingAcceptanceTest.php | 30 + .../Swift/KeyCache/ArrayKeyCacheAcceptanceTest.php | 173 + .../Swift/KeyCache/DiskKeyCacheAcceptanceTest.php | 183 + .../acceptance/Swift/MessageAcceptanceTest.php | 57 + .../Swift/Mime/AttachmentAcceptanceTest.php | 125 + .../Base64ContentEncoderAcceptanceTest.php | 56 + .../NativeQpContentEncoderAcceptanceTest.php | 86 + .../PlainContentEncoderAcceptanceTest.php | 88 + .../QpContentEncoderAcceptanceTest.php | 157 + .../Swift/Mime/EmbeddedFileAcceptanceTest.php | 137 + .../Base64HeaderEncoderAcceptanceTest.php | 32 + .../Swift/Mime/MimePartAcceptanceTest.php | 129 + .../Swift/Mime/SimpleMessageAcceptanceTest.php | 1251 +++++ .../acceptance/Swift/MimePartAcceptanceTest.php | 15 + .../AbstractStreamBufferAcceptanceTest.php | 134 + .../StreamBuffer/BasicSocketAcceptanceTest.php | 34 + .../StreamBuffer/ProcessAcceptanceTest.php | 27 + .../Transport/StreamBuffer/SocketTimeoutTest.php | 65 + .../StreamBuffer/SslSocketAcceptanceTest.php | 41 + .../StreamBuffer/TlsSocketAcceptanceTest.php | 40 + vendor/swiftmailer/swiftmailer/tests/bootstrap.php | 18 + .../swiftmailer/tests/bug/Swift/Bug111Test.php | 42 + .../swiftmailer/tests/bug/Swift/Bug118Test.php | 20 + .../swiftmailer/tests/bug/Swift/Bug206Test.php | 38 + .../swiftmailer/tests/bug/Swift/Bug274Test.php | 21 + .../swiftmailer/tests/bug/Swift/Bug34Test.php | 75 + .../swiftmailer/tests/bug/Swift/Bug35Test.php | 73 + .../swiftmailer/tests/bug/Swift/Bug38Test.php | 194 + .../swiftmailer/tests/bug/Swift/Bug518Test.php | 38 + .../swiftmailer/tests/bug/Swift/Bug51Test.php | 121 + .../swiftmailer/tests/bug/Swift/Bug71Test.php | 20 + .../swiftmailer/tests/bug/Swift/Bug76Test.php | 82 + .../tests/fixtures/EsmtpTransportFixture.php | 10 + .../tests/fixtures/MimeEntityFixture.php | 41 + .../swiftmailer/tests/smoke.conf.php.default | 63 + .../smoke/Swift/Smoke/AttachmentSmokeTest.php | 30 + .../tests/smoke/Swift/Smoke/BasicSmokeTest.php | 23 + .../Swift/Smoke/HtmlWithAttachmentSmokeTest.php | 29 + .../smoke/Swift/Smoke/InternationalSmokeTest.php | 37 + .../unit/Swift/ByteStream/ArrayByteStreamTest.php | 204 + .../GenericFixedWidthReaderTest.php | 43 + .../Swift/CharacterReader/UsAsciiReaderTest.php | 52 + .../unit/Swift/CharacterReader/Utf8ReaderTest.php | 65 + .../CharacterStream/ArrayCharacterStreamTest.php | 360 ++ .../tests/unit/Swift/DependencyContainerTest.php | 174 + .../tests/unit/Swift/Encoder/Base64EncoderTest.php | 173 + .../tests/unit/Swift/Encoder/QpEncoderTest.php | 381 ++ .../unit/Swift/Encoder/Rfc2231EncoderTest.php | 141 + .../tests/unit/Swift/Events/CommandEventTest.php | 36 + .../tests/unit/Swift/Events/EventObjectTest.php | 34 + .../tests/unit/Swift/Events/ResponseEventTest.php | 40 + .../tests/unit/Swift/Events/SendEventTest.php | 99 + .../Swift/Events/SimpleEventDispatcherTest.php | 135 + .../unit/Swift/Events/TransportChangeEventTest.php | 32 + .../Swift/Events/TransportExceptionEventTest.php | 43 + .../unit/Swift/KeyCache/ArrayKeyCacheTest.php | 242 + .../KeyCache/SimpleKeyCacheInputStreamTest.php | 73 + .../Swift/Mailer/ArrayRecipientIteratorTest.php | 42 + .../swiftmailer/tests/unit/Swift/MailerTest.php | 152 + .../swiftmailer/tests/unit/Swift/MessageTest.php | 128 + .../unit/Swift/Mime/AbstractMimeEntityTest.php | 1052 ++++ .../tests/unit/Swift/Mime/AttachmentTest.php | 318 ++ .../ContentEncoder/Base64ContentEncoderTest.php | 323 ++ .../ContentEncoder/PlainContentEncoderTest.php | 173 + .../Mime/ContentEncoder/QpContentEncoderTest.php | 496 ++ .../tests/unit/Swift/Mime/EmbeddedFileTest.php | 57 + .../Mime/HeaderEncoder/Base64HeaderEncoderTest.php | 13 + .../Mime/HeaderEncoder/QpHeaderEncoderTest.php | 223 + .../unit/Swift/Mime/Headers/DateHeaderTest.php | 69 + .../Mime/Headers/IdentificationHeaderTest.php | 189 + .../unit/Swift/Mime/Headers/MailboxHeaderTest.php | 327 ++ .../Swift/Mime/Headers/ParameterizedHeaderTest.php | 400 ++ .../unit/Swift/Mime/Headers/PathHeaderTest.php | 77 + .../Swift/Mime/Headers/UnstructuredHeaderTest.php | 355 ++ .../tests/unit/Swift/Mime/MimePartTest.php | 233 + .../unit/Swift/Mime/SimpleHeaderFactoryTest.php | 168 + .../tests/unit/Swift/Mime/SimpleHeaderSetTest.php | 734 +++ .../tests/unit/Swift/Mime/SimpleMessageTest.php | 829 +++ .../tests/unit/Swift/Mime/SimpleMimeEntityTest.php | 11 + .../unit/Swift/Plugins/AntiFloodPluginTest.php | 95 + .../Swift/Plugins/BandwidthMonitorPluginTest.php | 127 + .../unit/Swift/Plugins/DecoratorPluginTest.php | 269 + .../tests/unit/Swift/Plugins/LoggerPluginTest.php | 190 + .../unit/Swift/Plugins/Loggers/ArrayLoggerTest.php | 65 + .../unit/Swift/Plugins/Loggers/EchoLoggerTest.php | 24 + .../unit/Swift/Plugins/PopBeforeSmtpPluginTest.php | 103 + .../unit/Swift/Plugins/RedirectingPluginTest.php | 185 + .../unit/Swift/Plugins/ReporterPluginTest.php | 88 + .../Swift/Plugins/Reporters/HitReporterTest.php | 64 + .../Swift/Plugins/Reporters/HtmlReporterTest.php | 54 + .../unit/Swift/Plugins/ThrottlerPluginTest.php | 104 + .../tests/unit/Swift/Signers/DKIMSignerTest.php | 227 + .../unit/Swift/Signers/OpenDKIMSignerTest.php | 45 + .../tests/unit/Swift/Signers/SMimeSignerTest.php | 511 ++ .../ByteArrayReplacementFilterTest.php | 131 + .../StringReplacementFilterFactoryTest.php | 38 + .../StreamFilters/StringReplacementFilterTest.php | 55 + .../Transport/AbstractSmtpEventSupportTest.php | 560 +++ .../unit/Swift/Transport/AbstractSmtpTest.php | 1249 +++++ .../Esmtp/Auth/CramMd5AuthenticatorTest.php | 66 + .../Esmtp/Auth/LoginAuthenticatorTest.php | 66 + .../Transport/Esmtp/Auth/NTLMAuthenticatorTest.php | 233 + .../Esmtp/Auth/PlainAuthenticatorTest.php | 69 + .../unit/Swift/Transport/Esmtp/AuthHandlerTest.php | 167 + .../EsmtpTransport/ExtensionSupportTest.php | 530 ++ .../unit/Swift/Transport/EsmtpTransportTest.php | 298 ++ .../unit/Swift/Transport/FailoverTransportTest.php | 525 ++ .../Swift/Transport/LoadBalancedTransportTest.php | 756 +++ .../unit/Swift/Transport/MailTransportTest.php | 311 ++ .../unit/Swift/Transport/SendmailTransportTest.php | 152 + .../unit/Swift/Transport/StreamBufferTest.php | 45 + 675 files changed, 130566 insertions(+) create mode 100644 vendor/autoload.php create mode 100644 vendor/composer/ClassLoader.php create mode 100644 vendor/composer/autoload_classmap.php create mode 100644 vendor/composer/autoload_files.php create mode 100644 vendor/composer/autoload_namespaces.php create mode 100644 vendor/composer/autoload_psr4.php create mode 100644 vendor/composer/autoload_real.php create mode 100644 vendor/composer/installed.json create mode 100644 vendor/erusev/parsedown/.travis.yml create mode 100644 vendor/erusev/parsedown/LICENSE.txt create mode 100755 vendor/erusev/parsedown/Parsedown.php create mode 100644 vendor/erusev/parsedown/README.md create mode 100644 vendor/erusev/parsedown/composer.json create mode 100644 vendor/erusev/parsedown/phpunit.xml.dist create mode 100644 vendor/erusev/parsedown/test/ParsedownTest.php create mode 100644 vendor/erusev/parsedown/test/bootstrap.php create mode 100644 vendor/erusev/parsedown/test/data/aesthetic_table.html create mode 100644 vendor/erusev/parsedown/test/data/aesthetic_table.md create mode 100644 vendor/erusev/parsedown/test/data/aligned_table.html create mode 100644 vendor/erusev/parsedown/test/data/aligned_table.md create mode 100644 vendor/erusev/parsedown/test/data/atx_heading.html create mode 100644 vendor/erusev/parsedown/test/data/atx_heading.md create mode 100644 vendor/erusev/parsedown/test/data/automatic_link.html create mode 100644 vendor/erusev/parsedown/test/data/automatic_link.md create mode 100644 vendor/erusev/parsedown/test/data/block-level_html.html create mode 100644 vendor/erusev/parsedown/test/data/block-level_html.md create mode 100644 vendor/erusev/parsedown/test/data/code_block.html create mode 100644 vendor/erusev/parsedown/test/data/code_block.md create mode 100644 vendor/erusev/parsedown/test/data/code_span.html create mode 100644 vendor/erusev/parsedown/test/data/code_span.md create mode 100644 vendor/erusev/parsedown/test/data/compound_blockquote.html create mode 100644 vendor/erusev/parsedown/test/data/compound_blockquote.md create mode 100644 vendor/erusev/parsedown/test/data/compound_emphasis.html create mode 100644 vendor/erusev/parsedown/test/data/compound_emphasis.md create mode 100644 vendor/erusev/parsedown/test/data/compound_list.html create mode 100644 vendor/erusev/parsedown/test/data/compound_list.md create mode 100644 vendor/erusev/parsedown/test/data/deeply_nested_list.html create mode 100644 vendor/erusev/parsedown/test/data/deeply_nested_list.md create mode 100644 vendor/erusev/parsedown/test/data/em_strong.html create mode 100644 vendor/erusev/parsedown/test/data/em_strong.md create mode 100644 vendor/erusev/parsedown/test/data/email.html create mode 100644 vendor/erusev/parsedown/test/data/email.md create mode 100644 vendor/erusev/parsedown/test/data/emphasis.html create mode 100644 vendor/erusev/parsedown/test/data/emphasis.md create mode 100644 vendor/erusev/parsedown/test/data/escaping.html create mode 100644 vendor/erusev/parsedown/test/data/escaping.md create mode 100644 vendor/erusev/parsedown/test/data/fenced_code_block.html create mode 100644 vendor/erusev/parsedown/test/data/fenced_code_block.md create mode 100644 vendor/erusev/parsedown/test/data/horizontal_rule.html create mode 100644 vendor/erusev/parsedown/test/data/horizontal_rule.md create mode 100644 vendor/erusev/parsedown/test/data/html_comment.html create mode 100644 vendor/erusev/parsedown/test/data/html_comment.md create mode 100644 vendor/erusev/parsedown/test/data/html_entity.html create mode 100644 vendor/erusev/parsedown/test/data/html_entity.md create mode 100644 vendor/erusev/parsedown/test/data/image_reference.html create mode 100644 vendor/erusev/parsedown/test/data/image_reference.md create mode 100644 vendor/erusev/parsedown/test/data/image_title.html create mode 100644 vendor/erusev/parsedown/test/data/image_title.md create mode 100644 vendor/erusev/parsedown/test/data/implicit_reference.html create mode 100644 vendor/erusev/parsedown/test/data/implicit_reference.md create mode 100644 vendor/erusev/parsedown/test/data/inline_link.html create mode 100644 vendor/erusev/parsedown/test/data/inline_link.md create mode 100644 vendor/erusev/parsedown/test/data/inline_link_title.html create mode 100644 vendor/erusev/parsedown/test/data/inline_link_title.md create mode 100644 vendor/erusev/parsedown/test/data/inline_title.html create mode 100644 vendor/erusev/parsedown/test/data/inline_title.md create mode 100644 vendor/erusev/parsedown/test/data/lazy_blockquote.html create mode 100644 vendor/erusev/parsedown/test/data/lazy_blockquote.md create mode 100644 vendor/erusev/parsedown/test/data/lazy_list.html create mode 100644 vendor/erusev/parsedown/test/data/lazy_list.md create mode 100644 vendor/erusev/parsedown/test/data/line_break.html create mode 100644 vendor/erusev/parsedown/test/data/line_break.md create mode 100644 vendor/erusev/parsedown/test/data/multiline_list_paragraph.html create mode 100644 vendor/erusev/parsedown/test/data/multiline_list_paragraph.md create mode 100644 vendor/erusev/parsedown/test/data/nested_block-level_html.html create mode 100644 vendor/erusev/parsedown/test/data/nested_block-level_html.md create mode 100644 vendor/erusev/parsedown/test/data/ordered_list.html create mode 100644 vendor/erusev/parsedown/test/data/ordered_list.md create mode 100644 vendor/erusev/parsedown/test/data/paragraph_list.html create mode 100644 vendor/erusev/parsedown/test/data/paragraph_list.md create mode 100644 vendor/erusev/parsedown/test/data/reference_title.html create mode 100644 vendor/erusev/parsedown/test/data/reference_title.md create mode 100644 vendor/erusev/parsedown/test/data/self-closing_html.html create mode 100644 vendor/erusev/parsedown/test/data/self-closing_html.md create mode 100644 vendor/erusev/parsedown/test/data/separated_nested_list.html create mode 100644 vendor/erusev/parsedown/test/data/separated_nested_list.md create mode 100644 vendor/erusev/parsedown/test/data/setext_header.html create mode 100644 vendor/erusev/parsedown/test/data/setext_header.md create mode 100644 vendor/erusev/parsedown/test/data/simple_blockquote.html create mode 100644 vendor/erusev/parsedown/test/data/simple_blockquote.md create mode 100644 vendor/erusev/parsedown/test/data/simple_table.html create mode 100644 vendor/erusev/parsedown/test/data/simple_table.md create mode 100644 vendor/erusev/parsedown/test/data/span-level_html.html create mode 100644 vendor/erusev/parsedown/test/data/span-level_html.md create mode 100644 vendor/erusev/parsedown/test/data/sparse_dense_list.html create mode 100644 vendor/erusev/parsedown/test/data/sparse_dense_list.md create mode 100644 vendor/erusev/parsedown/test/data/sparse_list.html create mode 100644 vendor/erusev/parsedown/test/data/sparse_list.md create mode 100644 vendor/erusev/parsedown/test/data/special_characters.html create mode 100644 vendor/erusev/parsedown/test/data/special_characters.md create mode 100644 vendor/erusev/parsedown/test/data/strikethrough.html create mode 100644 vendor/erusev/parsedown/test/data/strikethrough.md create mode 100644 vendor/erusev/parsedown/test/data/strong_em.html create mode 100644 vendor/erusev/parsedown/test/data/strong_em.md create mode 100644 vendor/erusev/parsedown/test/data/tab-indented_code_block.html create mode 100644 vendor/erusev/parsedown/test/data/tab-indented_code_block.md create mode 100644 vendor/erusev/parsedown/test/data/table_inline_markdown.html create mode 100644 vendor/erusev/parsedown/test/data/table_inline_markdown.md create mode 100644 vendor/erusev/parsedown/test/data/text_reference.html create mode 100644 vendor/erusev/parsedown/test/data/text_reference.md create mode 100644 vendor/erusev/parsedown/test/data/unordered_list.html create mode 100644 vendor/erusev/parsedown/test/data/unordered_list.md create mode 100644 vendor/erusev/parsedown/test/data/untidy_table.html create mode 100644 vendor/erusev/parsedown/test/data/untidy_table.md create mode 100644 vendor/erusev/parsedown/test/data/url_autolinking.html create mode 100644 vendor/erusev/parsedown/test/data/url_autolinking.md create mode 100644 vendor/erusev/parsedown/test/data/whitespace.html create mode 100644 vendor/erusev/parsedown/test/data/whitespace.md create mode 160000 vendor/fguillot/json-rpc create mode 160000 vendor/fguillot/picodb create mode 160000 vendor/fguillot/simple-validator create mode 100644 vendor/ircmaxell/password-compat/.travis.yml create mode 100644 vendor/ircmaxell/password-compat/LICENSE.md create mode 100644 vendor/ircmaxell/password-compat/README.md create mode 100644 vendor/ircmaxell/password-compat/composer.json create mode 100644 vendor/ircmaxell/password-compat/lib/password.php create mode 100644 vendor/ircmaxell/password-compat/phpunit.xml.dist create mode 100644 vendor/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php create mode 100644 vendor/ircmaxell/password-compat/test/Unit/PasswordHashTest.php create mode 100644 vendor/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php create mode 100644 vendor/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php create mode 100644 vendor/ircmaxell/password-compat/version-test.php create mode 100644 vendor/lusitanian/oauth/.gitignore create mode 100644 vendor/lusitanian/oauth/.scrutinizer.yml create mode 100644 vendor/lusitanian/oauth/.travis.yml create mode 100644 vendor/lusitanian/oauth/LICENSE create mode 100644 vendor/lusitanian/oauth/README.md create mode 100644 vendor/lusitanian/oauth/composer.json create mode 100644 vendor/lusitanian/oauth/examples/amazon.php create mode 100644 vendor/lusitanian/oauth/examples/bitbucket.php create mode 100644 vendor/lusitanian/oauth/examples/bitly.php create mode 100644 vendor/lusitanian/oauth/examples/bootstrap.php create mode 100644 vendor/lusitanian/oauth/examples/box.php create mode 100644 vendor/lusitanian/oauth/examples/buffer.php create mode 100644 vendor/lusitanian/oauth/examples/dailymotion.php create mode 100644 vendor/lusitanian/oauth/examples/dropbox.php create mode 100644 vendor/lusitanian/oauth/examples/etsy.php create mode 100644 vendor/lusitanian/oauth/examples/facebook.php create mode 100644 vendor/lusitanian/oauth/examples/fitbit.php create mode 100644 vendor/lusitanian/oauth/examples/flickr.php create mode 100644 vendor/lusitanian/oauth/examples/foursquare.php create mode 100644 vendor/lusitanian/oauth/examples/github.php create mode 100644 vendor/lusitanian/oauth/examples/google.php create mode 100644 vendor/lusitanian/oauth/examples/harvest.php create mode 100644 vendor/lusitanian/oauth/examples/init.example.php create mode 100644 vendor/lusitanian/oauth/examples/instagram.php create mode 100644 vendor/lusitanian/oauth/examples/linkedin.php create mode 100644 vendor/lusitanian/oauth/examples/mailchimp.php create mode 100644 vendor/lusitanian/oauth/examples/microsoft.php create mode 100644 vendor/lusitanian/oauth/examples/paypal.php create mode 100644 vendor/lusitanian/oauth/examples/pocket.php create mode 100644 vendor/lusitanian/oauth/examples/reddit.php create mode 100644 vendor/lusitanian/oauth/examples/runkeeper.php create mode 100644 vendor/lusitanian/oauth/examples/scoopit.php create mode 100644 vendor/lusitanian/oauth/examples/soundcloud.php create mode 100644 vendor/lusitanian/oauth/examples/tumblr.php create mode 100644 vendor/lusitanian/oauth/examples/twitter.php create mode 100644 vendor/lusitanian/oauth/examples/ustream.php create mode 100644 vendor/lusitanian/oauth/examples/yahoo.php create mode 100644 vendor/lusitanian/oauth/phpunit.xml.dist create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/AutoLoader.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Consumer/Credentials.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Consumer/CredentialsInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Exception/Exception.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/AbstractClient.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/ClientInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/CurlClient.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/StreamClient.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Exception/TokenResponseException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/Uri.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactory.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactoryInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Service/AbstractService.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Service/ServiceInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Exception/AuthorizationStateNotFoundException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Exception/StorageException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Exception/TokenNotFoundException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Memory.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Redis.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/Session.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/SymfonySession.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Storage/TokenStorageInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Token/AbstractToken.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Token/Exception/ExpiredTokenException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/Common/Token/TokenInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/AbstractService.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/BitBucket.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Etsy.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/FitBit.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Flickr.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ScoopIt.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ServiceInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Tumblr.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Twitter.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Xing.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Yahoo.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/Exception/UnsupportedHashAlgorithmException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/Signature.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/SignatureInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Token/StdOAuth1Token.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth1/Token/TokenInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/AbstractService.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Amazon.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Bitly.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Box.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Buffer.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dailymotion.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dropbox.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidAccessTypeException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidAuthorizationStateException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidScopeException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/MissingRefreshTokenException.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Facebook.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Foursquare.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/GitHub.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Google.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Harvest.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Heroku.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Instagram.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Linkedin.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Mailchimp.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Microsoft.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Paypal.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Pocket.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Reddit.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/RunKeeper.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Salesforce.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/ServiceInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/SoundCloud.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Ustream.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Vkontakte.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Yammer.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Token/StdOAuth2Token.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/OAuth2/Token/TokenInterface.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/ServiceFactory.php create mode 100644 vendor/lusitanian/oauth/src/OAuth/bootstrap.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/Common/FakeProject/NS/SomeClass.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/Common/Service/Mock.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/OAuth1/Service/Fake.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/OAuth1/Service/Mock.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/OAuth2/Service/Fake.php create mode 100644 vendor/lusitanian/oauth/tests/Mocks/OAuth2/Service/Mock.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/AutoloaderTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Consumer/CredentialsTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/AbstractClientTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/CurlClientTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/StreamClientTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/HttpClientsTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriFactoryTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Service/AbstractServiceTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Storage/MemoryTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Storage/RedisTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Storage/SessionTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Storage/StorageTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Storage/SymfonySessionTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/Common/Token/AbstractTokenTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/AbstractServiceTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/BitBucketTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/EtsyTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FitBitTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FlickrTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/ScoopItTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TumblrTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TwitterTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/XingTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/YahooTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Signature/SignatureTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth1/Token/StdOAuth1TokenTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AbstractServiceTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AmazonTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BitlyTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BoxTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BufferTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DailymotionTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DropboxTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FacebookTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FoursquareTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GitHubTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GoogleTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/HerokuTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/InstagramTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/LinkedinTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MailchimpTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MicrosoftTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/PaypalTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RedditTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RunKeeperTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/SoundCloudTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/UstreamTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/VkontakteTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/YammerTest.php create mode 100644 vendor/lusitanian/oauth/tests/Unit/ServiceFactoryTest.php create mode 100644 vendor/lusitanian/oauth/tests/bootstrap.php create mode 100644 vendor/swiftmailer/swiftmailer/.gitattributes create mode 100644 vendor/swiftmailer/swiftmailer/.gitignore create mode 100644 vendor/swiftmailer/swiftmailer/.travis.yml create mode 100644 vendor/swiftmailer/swiftmailer/CHANGES create mode 100644 vendor/swiftmailer/swiftmailer/LICENSE create mode 100644 vendor/swiftmailer/swiftmailer/README create mode 100644 vendor/swiftmailer/swiftmailer/VERSION create mode 100644 vendor/swiftmailer/swiftmailer/composer.json create mode 100644 vendor/swiftmailer/swiftmailer/doc/headers.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/help-resources.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/including-the-files.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/index.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/installing.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/introduction.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/japanese.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/messages.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/overview.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/plugins.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/sending.rst create mode 100644 vendor/swiftmailer/swiftmailer/doc/uml/Encoders.graffle create mode 100644 vendor/swiftmailer/swiftmailer/doc/uml/Mime.graffle create mode 100644 vendor/swiftmailer/swiftmailer/doc/uml/Transports.graffle create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Attachment.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/ArrayCharacterStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/EmbeddedFile.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Base64Encoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoding.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/Event.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventDispatcher.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/EventObject.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendEvent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SimpleEventDispatcher.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionEvent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/FailoverTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Filterable.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Image.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/IoException.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/ArrayKeyCache.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/NullKeyCache.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/MailTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Grammar.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderSet.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/AbstractHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Message.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimePart.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/AntiFloodPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/DecoratorPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/LoggerPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Exception.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/PopBeforeSmtpPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ReporterPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ThrottlerPlugin.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Preferences.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/RfcComplianceException.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/SendmailTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/SignedMessage.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpHandler.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/LoadBalancedTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/MailTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SmtpAgent.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SpoolTransport.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/classes/Swift/Validate.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/mime_types.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/preferences.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/swift_init.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/swift_required.php create mode 100644 vendor/swiftmailer/swiftmailer/lib/swift_required_pear.php create mode 100755 vendor/swiftmailer/swiftmailer/lib/swiftmailer_generate_mimes_config.php create mode 100644 vendor/swiftmailer/swiftmailer/notes/APPS create mode 100644 vendor/swiftmailer/swiftmailer/notes/CHARSETS create mode 100644 vendor/swiftmailer/swiftmailer/notes/message.xml create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc0821.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc0822.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc1341.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc1521.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc1854.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2015.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2045.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2046.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2047.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2048.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2049.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2183.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2222.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2231.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2234.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2440.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2487.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2554.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2821.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc2822.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc3156.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc3676.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4505.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4616.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4870.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4871.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4880.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc4954.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/rfc5751.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/rfc/whats_where.txt create mode 100644 vendor/swiftmailer/swiftmailer/notes/smtp.txt create mode 100644 vendor/swiftmailer/swiftmailer/phpunit.xml.dist create mode 100644 vendor/swiftmailer/swiftmailer/tests/IdenticalBinaryConstraint.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/StreamCollector.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/SwiftMailerSmokeTestCase.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/SwiftMailerTestCase.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/charsets/iso-2022-jp/one.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/charsets/iso-8859-1/one.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/charsets/utf-8/one.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/charsets/utf-8/three.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/charsets/utf-8/two.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/dkim/dkim.test.priv create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/dkim/dkim.test.pub create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/files/data.txt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/CA.srl create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.crt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.key create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/create-cert.sh create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.crt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.key create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.crt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.key create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.crt create mode 100644 vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.key create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance.conf.php.default create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/AttachmentAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/ByteStream/FileByteStreamAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/CharacterReaderFactory/SimpleCharacterReaderFactoryAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/DependencyContainerAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EmbeddedFileAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/Base64EncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/QpEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/Rfc2231EncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EncodingAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/ArrayKeyCacheAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/DiskKeyCacheAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MessageAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/AttachmentAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/Base64ContentEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/NativeQpContentEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/PlainContentEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/QpContentEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/EmbeddedFileAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/HeaderEncoder/Base64HeaderEncoderAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/MimePartAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/SimpleMessageAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MimePartAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/AbstractStreamBufferAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/BasicSocketAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/ProcessAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SocketTimeoutTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SslSocketAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/TlsSocketAcceptanceTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bootstrap.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug111Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug118Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug206Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug274Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug34Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug35Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug38Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug518Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug51Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug71Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug76Test.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/fixtures/EsmtpTransportFixture.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/fixtures/MimeEntityFixture.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/smoke.conf.php.default create mode 100644 vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/AttachmentSmokeTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/BasicSmokeTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/HtmlWithAttachmentSmokeTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/InternationalSmokeTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/ByteStream/ArrayByteStreamTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/GenericFixedWidthReaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/UsAsciiReaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/Utf8ReaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterStream/ArrayCharacterStreamTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/DependencyContainerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Base64EncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/QpEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Rfc2231EncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/CommandEventTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/EventObjectTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/ResponseEventTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SendEventTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SimpleEventDispatcherTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportChangeEventTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportExceptionEventTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/ArrayKeyCacheTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/SimpleKeyCacheInputStreamTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mailer/ArrayRecipientIteratorTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/MailerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/MessageTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AbstractMimeEntityTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AttachmentTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/Base64ContentEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/PlainContentEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/QpContentEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/EmbeddedFileTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/Base64HeaderEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/QpHeaderEncoderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/DateHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/MailboxHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/ParameterizedHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/PathHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/UnstructuredHeaderTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/MimePartTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderFactoryTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderSetTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMessageTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMimeEntityTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/AntiFloodPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/BandwidthMonitorPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/DecoratorPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/LoggerPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/ArrayLoggerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/EchoLoggerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/PopBeforeSmtpPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/RedirectingPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ReporterPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HitReporterTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HtmlReporterTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ThrottlerPluginTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/DKIMSignerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/OpenDKIMSignerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/SMimeSignerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/ByteArrayReplacementFilterTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterFactoryTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpEventSupportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/CramMd5AuthenticatorTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/LoginAuthenticatorTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/NTLMAuthenticatorTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/PlainAuthenticatorTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/AuthHandlerTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransport/ExtensionSupportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/FailoverTransportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/LoadBalancedTransportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/MailTransportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/SendmailTransportTest.php create mode 100644 vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/StreamBufferTest.php (limited to 'vendor') diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 00000000..b09bfaf4 --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0 class loader + * + * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + */ +class ClassLoader +{ + // PSR-4 + private $prefixLengthsPsr4 = array(); + private $prefixDirsPsr4 = array(); + private $fallbackDirsPsr4 = array(); + + // PSR-0 + private $prefixesPsr0 = array(); + private $fallbackDirsPsr0 = array(); + + private $useIncludePath = false; + private $classMap = array(); + + public function getPrefixes() + { + return call_user_func_array('array_merge', $this->prefixesPsr0); + } + + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-0 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 base directories + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 + if ('\\' == $class[0]) { + $class = substr($class, 1); + } + + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if ($file === null && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if ($file === null) { + // Remember that this class does not exist. + return $this->classMap[$class] = false; + } + + return $file; + } + + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) { + if (0 === strpos($class, $prefix)) { + foreach ($this->prefixDirsPsr4[$prefix] as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ +function includeFile($file) +{ + include $file; +} diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 00000000..7a91153b --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,9 @@ + array($vendorDir . '/fguillot/simple-validator/src'), + 'PicoDb' => array($vendorDir . '/fguillot/picodb/lib'), + 'Parsedown' => array($vendorDir . '/erusev/parsedown'), + 'OAuth\\Unit' => array($vendorDir . '/lusitanian/oauth/tests'), + 'OAuth' => array($vendorDir . '/lusitanian/oauth/src'), + 'JsonRPC' => array($vendorDir . '/fguillot/json-rpc/src'), + '' => array($baseDir . '/app'), +); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php new file mode 100644 index 00000000..b265c64a --- /dev/null +++ b/vendor/composer/autoload_psr4.php @@ -0,0 +1,9 @@ + $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + + $loader->register(true); + + $includeFiles = require __DIR__ . '/autoload_files.php'; + foreach ($includeFiles as $file) { + composerRequiredca459c5d320c1273e90aa3e7abc662b($file); + } + + return $loader; + } +} + +function composerRequiredca459c5d320c1273e90aa3e7abc662b($file) +{ + require $file; +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 00000000..960429bb --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,319 @@ +[ + { + "name": "erusev/parsedown", + "version": "1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "da5d75e97e1ed19e57bd54fa6cb595a6a0879a67" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/da5d75e97e1ed19e57bd54fa6cb595a6a0879a67", + "reference": "da5d75e97e1ed19e57bd54fa6cb595a6a0879a67", + "shasum": "" + }, + "time": "2014-10-29 20:29:46", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ] + }, + { + "name": "fguillot/picodb", + "version": "dev-master", + "version_normalized": "9999999-dev", + "source": { + "type": "git", + "url": "https://github.com/fguillot/picoDb.git", + "reference": "dbf15938687ca800abfccc424390add33dd95181" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fguillot/picoDb/zipball/dbf15938687ca800abfccc424390add33dd95181", + "reference": "dbf15938687ca800abfccc424390add33dd95181", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2014-10-19 18:40:25", + "type": "library", + "installation-source": "source", + "autoload": { + "psr-0": { + "PicoDb": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "WTFPL" + ], + "authors": [ + { + "name": "Frédéric Guillot", + "homepage": "http://fredericguillot.com" + } + ], + "description": "Minimalist database query builder", + "homepage": "https://github.com/fguillot/picoDb" + }, + { + "name": "fguillot/simple-validator", + "version": "dev-master", + "version_normalized": "9999999-dev", + "source": { + "type": "git", + "url": "https://github.com/fguillot/simpleValidator.git", + "reference": "14f7c0b111444a5b26ce447ef5f0de655279b5f1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fguillot/simpleValidator/zipball/14f7c0b111444a5b26ce447ef5f0de655279b5f1", + "reference": "14f7c0b111444a5b26ce447ef5f0de655279b5f1", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2014-09-09 05:31:14", + "type": "library", + "installation-source": "source", + "autoload": { + "psr-0": { + "SimpleValidator": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frédéric Guillot", + "homepage": "http://fredericguillot.com" + } + ], + "description": "The most easy to use validator library for PHP :)", + "homepage": "https://github.com/fguillot/simpleValidator" + }, + { + "name": "ircmaxell/password-compat", + "version": "1.0.3", + "version_normalized": "1.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "1fc1521b5e9794ea77e4eca30717be9635f1d4f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/1fc1521b5e9794ea77e4eca30717be9635f1d4f4", + "reference": "1fc1521b5e9794ea77e4eca30717be9635f1d4f4", + "shasum": "" + }, + "time": "2013-04-30 19:58:08", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@ircmaxell.com", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ] + }, + { + "name": "lusitanian/oauth", + "version": "v0.3.5", + "version_normalized": "0.3.5.0", + "source": { + "type": "git", + "url": "https://github.com/Lusitanian/PHPoAuthLib.git", + "reference": "ac5a1cd5a4519143728dce2213936eea302edf8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Lusitanian/PHPoAuthLib/zipball/ac5a1cd5a4519143728dce2213936eea302edf8a", + "reference": "ac5a1cd5a4519143728dce2213936eea302edf8a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*", + "predis/predis": "0.8.*@dev", + "symfony/http-foundation": "~2.1" + }, + "suggest": { + "ext-openssl": "Allows for usage of secure connections with the stream-based HTTP client.", + "predis/predis": "Allows using the Redis storage backend.", + "symfony/http-foundation": "Allows using the Symfony Session storage backend." + }, + "time": "2014-09-05 15:19:58", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.1-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "OAuth": "src", + "OAuth\\Unit": "tests" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "David Desberg", + "email": "david@daviddesberg.com" + }, + { + "name": "Pieter Hordijk", + "email": "info@pieterhordijk.com" + } + ], + "description": "PHP 5.3+ oAuth 1/2 Library", + "keywords": [ + "Authentication", + "authorization", + "oauth", + "security" + ] + }, + { + "name": "swiftmailer/swiftmailer", + "version": "v5.3.0", + "version_normalized": "5.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/swiftmailer/swiftmailer.git", + "reference": "b86b927dfefdb56ab0b22d1350033d9a38e9f205" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/b86b927dfefdb56ab0b22d1350033d9a38e9f205", + "reference": "b86b927dfefdb56ab0b22d1350033d9a38e9f205", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "mockery/mockery": "~0.9.1" + }, + "time": "2014-10-04 05:53:18", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.3-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "lib/swift_required.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Corbyn" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Swiftmailer, free feature-rich PHP mailer", + "homepage": "http://swiftmailer.org", + "keywords": [ + "mail", + "mailer" + ] + }, + { + "name": "fguillot/json-rpc", + "version": "dev-master", + "version_normalized": "9999999-dev", + "source": { + "type": "git", + "url": "https://github.com/fguillot/JsonRPC.git", + "reference": "66db4093984790c34577c0ba0e17f2e3d2dc14a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fguillot/JsonRPC/zipball/66db4093984790c34577c0ba0e17f2e3d2dc14a0", + "reference": "66db4093984790c34577c0ba0e17f2e3d2dc14a0", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2014-11-05 01:56:31", + "type": "library", + "installation-source": "source", + "autoload": { + "psr-0": { + "JsonRPC": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Unlicense" + ], + "authors": [ + { + "name": "Frédéric Guillot", + "homepage": "http://fredericguillot.com" + } + ], + "description": "A simple Json-RPC client/server library that just works", + "homepage": "https://github.com/fguillot/JsonRPC" + } +] diff --git a/vendor/erusev/parsedown/.travis.yml b/vendor/erusev/parsedown/.travis.yml new file mode 100644 index 00000000..dade2579 --- /dev/null +++ b/vendor/erusev/parsedown/.travis.yml @@ -0,0 +1,10 @@ +language: php + +php: + - 5.6 + - 5.5 + - 5.4 + - 5.3 + - 5.2 + - hhvm + \ No newline at end of file diff --git a/vendor/erusev/parsedown/LICENSE.txt b/vendor/erusev/parsedown/LICENSE.txt new file mode 100644 index 00000000..baca86f5 --- /dev/null +++ b/vendor/erusev/parsedown/LICENSE.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Emanuil Rusev, erusev.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/erusev/parsedown/Parsedown.php b/vendor/erusev/parsedown/Parsedown.php new file mode 100755 index 00000000..9aebef52 --- /dev/null +++ b/vendor/erusev/parsedown/Parsedown.php @@ -0,0 +1,1430 @@ +Definitions = array(); + + # standardize line breaks + $text = str_replace("\r\n", "\n", $text); + $text = str_replace("\r", "\n", $text); + + # replace tabs with spaces + $text = str_replace("\t", ' ', $text); + + # remove surrounding line breaks + $text = trim($text, "\n"); + + # split text into lines + $lines = explode("\n", $text); + + # iterate through lines to identify blocks + $markup = $this->lines($lines); + + # trim line breaks + $markup = trim($markup, "\n"); + + return $markup; + } + + # + # Setters + # + + private $breaksEnabled; + + function setBreaksEnabled($breaksEnabled) + { + $this->breaksEnabled = $breaksEnabled; + + return $this; + } + + private $markupEscaped; + + function setMarkupEscaped($markupEscaped) + { + $this->markupEscaped = $markupEscaped; + + return $this; + } + + # + # Lines + # + + protected $BlockTypes = array( + '#' => array('Atx'), + '*' => array('Rule', 'List'), + '+' => array('List'), + '-' => array('Setext', 'Table', 'Rule', 'List'), + '0' => array('List'), + '1' => array('List'), + '2' => array('List'), + '3' => array('List'), + '4' => array('List'), + '5' => array('List'), + '6' => array('List'), + '7' => array('List'), + '8' => array('List'), + '9' => array('List'), + ':' => array('Table'), + '<' => array('Comment', 'Markup'), + '=' => array('Setext'), + '>' => array('Quote'), + '_' => array('Rule'), + '`' => array('FencedCode'), + '|' => array('Table'), + '~' => array('FencedCode'), + ); + + # ~ + + protected $DefinitionTypes = array( + '[' => array('Reference'), + ); + + # ~ + + protected $unmarkedBlockTypes = array( + 'CodeBlock', + ); + + # + # Blocks + # + + private function lines(array $lines) + { + $CurrentBlock = null; + + foreach ($lines as $line) + { + if (chop($line) === '') + { + if (isset($CurrentBlock)) + { + $CurrentBlock['interrupted'] = true; + } + + continue; + } + + $indent = 0; + + while (isset($line[$indent]) and $line[$indent] === ' ') + { + $indent ++; + } + + $text = $indent > 0 ? substr($line, $indent) : $line; + + # ~ + + $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); + + # ~ + + if (isset($CurrentBlock['incomplete'])) + { + $Block = $this->{'addTo'.$CurrentBlock['type']}($Line, $CurrentBlock); + + if (isset($Block)) + { + $CurrentBlock = $Block; + + continue; + } + else + { + if (method_exists($this, 'complete'.$CurrentBlock['type'])) + { + $CurrentBlock = $this->{'complete'.$CurrentBlock['type']}($CurrentBlock); + } + + unset($CurrentBlock['incomplete']); + } + } + + # ~ + + $marker = $text[0]; + + if (isset($this->DefinitionTypes[$marker])) + { + foreach ($this->DefinitionTypes[$marker] as $definitionType) + { + $Definition = $this->{'identify'.$definitionType}($Line, $CurrentBlock); + + if (isset($Definition)) + { + $this->Definitions[$definitionType][$Definition['id']] = $Definition['data']; + + continue 2; + } + } + } + + # ~ + + $blockTypes = $this->unmarkedBlockTypes; + + if (isset($this->BlockTypes[$marker])) + { + foreach ($this->BlockTypes[$marker] as $blockType) + { + $blockTypes []= $blockType; + } + } + + # + # ~ + + foreach ($blockTypes as $blockType) + { + $Block = $this->{'identify'.$blockType}($Line, $CurrentBlock); + + if (isset($Block)) + { + $Block['type'] = $blockType; + + if ( ! isset($Block['identified'])) + { + $Elements []= $CurrentBlock['element']; + + $Block['identified'] = true; + } + + if (method_exists($this, 'addTo'.$blockType)) + { + $Block['incomplete'] = true; + } + + $CurrentBlock = $Block; + + continue 2; + } + } + + # ~ + + if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted'])) + { + $CurrentBlock['element']['text'] .= "\n".$text; + } + else + { + $Elements []= $CurrentBlock['element']; + + $CurrentBlock = $this->buildParagraph($Line); + + $CurrentBlock['identified'] = true; + } + } + + # ~ + + if (isset($CurrentBlock['incomplete']) and method_exists($this, 'complete'.$CurrentBlock['type'])) + { + $CurrentBlock = $this->{'complete'.$CurrentBlock['type']}($CurrentBlock); + } + + # ~ + + $Elements []= $CurrentBlock['element']; + + unset($Elements[0]); + + # ~ + + $markup = $this->elements($Elements); + + # ~ + + return $markup; + } + + # + # Atx + + protected function identifyAtx($Line) + { + if (isset($Line['text'][1])) + { + $level = 1; + + while (isset($Line['text'][$level]) and $Line['text'][$level] === '#') + { + $level ++; + } + + $text = trim($Line['text'], '# '); + + $Block = array( + 'element' => array( + 'name' => 'h' . min(6, $level), + 'text' => $text, + 'handler' => 'line', + ), + ); + + return $Block; + } + } + + # + # Code + + protected function identifyCodeBlock($Line) + { + if ($Line['indent'] >= 4) + { + $text = substr($Line['body'], 4); + + $Block = array( + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => array( + 'name' => 'code', + 'text' => $text, + ), + ), + ); + + return $Block; + } + } + + protected function addToCodeBlock($Line, $Block) + { + if ($Line['indent'] >= 4) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + $Block['element']['text']['text'] .= "\n"; + + $text = substr($Line['body'], 4); + + $Block['element']['text']['text'] .= $text; + + return $Block; + } + } + + protected function completeCodeBlock($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # Comment + + protected function identifyComment($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!') + { + $Block = array( + 'element' => $Line['body'], + ); + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + } + + protected function addToComment($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + $Block['element'] .= "\n" . $Line['body']; + + if (preg_match('/-->$/', $Line['text'])) + { + $Block['closed'] = true; + } + + return $Block; + } + + # + # Fenced Code + + protected function identifyFencedCode($Line) + { + if (preg_match('/^(['.$Line['text'][0].']{3,})[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches)) + { + $Element = array( + 'name' => 'code', + 'text' => '', + ); + + if (isset($matches[2])) + { + $class = 'language-'.$matches[2]; + + $Element['attributes'] = array( + 'class' => $class, + ); + } + + $Block = array( + 'char' => $Line['text'][0], + 'element' => array( + 'name' => 'pre', + 'handler' => 'element', + 'text' => $Element, + ), + ); + + return $Block; + } + } + + protected function addToFencedCode($Line, $Block) + { + if (isset($Block['complete'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['element']['text']['text'] .= "\n"; + + unset($Block['interrupted']); + } + + if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text'])) + { + $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1); + + $Block['complete'] = true; + + return $Block; + } + + $Block['element']['text']['text'] .= "\n".$Line['body'];; + + return $Block; + } + + protected function completeFencedCode($Block) + { + $text = $Block['element']['text']['text']; + + $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); + + $Block['element']['text']['text'] = $text; + + return $Block; + } + + # + # List + + protected function identifyList($Line) + { + list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]'); + + if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'indent' => $Line['indent'], + 'pattern' => $pattern, + 'element' => array( + 'name' => $name, + 'handler' => 'elements', + ), + ); + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $matches[2], + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + } + + protected function addToList($Line, array $Block) + { + if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'[ ]+(.*)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['li']['text'] []= ''; + + unset($Block['interrupted']); + } + + unset($Block['li']); + + $Block['li'] = array( + 'name' => 'li', + 'handler' => 'li', + 'text' => array( + $matches[1], + ), + ); + + $Block['element']['text'] []= & $Block['li']; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + return $Block; + } + + if ($Line['indent'] > 0) + { + $Block['li']['text'] []= ''; + + $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']); + + $Block['li']['text'] []= $text; + + unset($Block['interrupted']); + + return $Block; + } + } + + # + # Quote + + protected function identifyQuote($Line) + { + if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + $Block = array( + 'element' => array( + 'name' => 'blockquote', + 'handler' => 'lines', + 'text' => (array) $matches[1], + ), + ); + + return $Block; + } + } + + protected function addToQuote($Line, array $Block) + { + if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches)) + { + if (isset($Block['interrupted'])) + { + $Block['element']['text'] []= ''; + + unset($Block['interrupted']); + } + + $Block['element']['text'] []= $matches[1]; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $Block['element']['text'] []= $Line['text']; + + return $Block; + } + } + + # + # Rule + + protected function identifyRule($Line) + { + if (preg_match('/^(['.$Line['text'][0].'])([ ]{0,2}\1){2,}[ ]*$/', $Line['text'])) + { + $Block = array( + 'element' => array( + 'name' => 'hr' + ), + ); + + return $Block; + } + } + + # + # Setext + + protected function identifySetext($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (chop($Line['text'], $Line['text'][0]) === '') + { + $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; + + return $Block; + } + } + + # + # Markup + + protected function identifyMarkup($Line) + { + if ($this->markupEscaped) + { + return; + } + + if (preg_match('/^<(\w[\w\d]*)(?:[ ][^>]*)?(\/?)[ ]*>/', $Line['text'], $matches)) + { + if (in_array($matches[1], $this->textLevelElements)) + { + return; + } + + $Block = array( + 'element' => $Line['body'], + ); + + if ($matches[2] or in_array($matches[1], $this->voidElements) or preg_match('/<\/'.$matches[1].'>[ ]*$/', $Line['text'])) + { + $Block['closed'] = true; + } + else + { + $Block['depth'] = 0; + $Block['name'] = $matches[1]; + } + + return $Block; + } + } + + protected function addToMarkup($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + if (preg_match('/<'.$Block['name'].'([ ][^\/]+)?>/', $Line['text'])) # opening tag + { + $Block['depth'] ++; + } + + if (stripos($Line['text'], '') !== false) # closing tag + { + if ($Block['depth'] > 0) + { + $Block['depth'] --; + } + else + { + $Block['closed'] = true; + } + } + + $Block['element'] .= "\n".$Line['body']; + + return $Block; + } + + # + # Table + + protected function identifyTable($Line, array $Block = null) + { + if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted'])) + { + return; + } + + if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '') + { + $alignments = array(); + + $divider = $Line['text']; + + $divider = trim($divider); + $divider = trim($divider, '|'); + + $dividerCells = explode('|', $divider); + + foreach ($dividerCells as $dividerCell) + { + $dividerCell = trim($dividerCell); + + if ($dividerCell === '') + { + continue; + } + + $alignment = null; + + if ($dividerCell[0] === ':') + { + $alignment = 'left'; + } + + if (substr($dividerCell, -1) === ':') + { + $alignment = $alignment === 'left' ? 'center' : 'right'; + } + + $alignments []= $alignment; + } + + # ~ + + $HeaderElements = array(); + + $header = $Block['element']['text']; + + $header = trim($header); + $header = trim($header, '|'); + + $headerCells = explode('|', $header); + + foreach ($headerCells as $index => $headerCell) + { + $headerCell = trim($headerCell); + + $HeaderElement = array( + 'name' => 'th', + 'text' => $headerCell, + 'handler' => 'line', + ); + + if (isset($alignments[$index])) + { + $alignment = $alignments[$index]; + + $HeaderElement['attributes'] = array( + 'align' => $alignment, + ); + } + + $HeaderElements []= $HeaderElement; + } + + # ~ + + $Block = array( + 'alignments' => $alignments, + 'identified' => true, + 'element' => array( + 'name' => 'table', + 'handler' => 'elements', + ), + ); + + $Block['element']['text'] []= array( + 'name' => 'thead', + 'handler' => 'elements', + ); + + $Block['element']['text'] []= array( + 'name' => 'tbody', + 'handler' => 'elements', + 'text' => array(), + ); + + $Block['element']['text'][0]['text'] []= array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $HeaderElements, + ); + + return $Block; + } + } + + protected function addToTable($Line, array $Block) + { + if ($Line['text'][0] === '|' or strpos($Line['text'], '|')) + { + $Elements = array(); + + $row = $Line['text']; + + $row = trim($row); + $row = trim($row, '|'); + + $cells = explode('|', $row); + + foreach ($cells as $index => $cell) + { + $cell = trim($cell); + + $Element = array( + 'name' => 'td', + 'handler' => 'line', + 'text' => $cell, + ); + + if (isset($Block['alignments'][$index])) + { + $Element['attributes'] = array( + 'align' => $Block['alignments'][$index], + ); + } + + $Elements []= $Element; + } + + $Element = array( + 'name' => 'tr', + 'handler' => 'elements', + 'text' => $Elements, + ); + + $Block['element']['text'][1]['text'] []= $Element; + + return $Block; + } + } + + # + # Definitions + # + + protected function identifyReference($Line) + { + if (preg_match('/^\[(.+?)\]:[ ]*?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches)) + { + $Definition = array( + 'id' => strtolower($matches[1]), + 'data' => array( + 'url' => $matches[2], + ), + ); + + if (isset($matches[3])) + { + $Definition['data']['title'] = $matches[3]; + } + + return $Definition; + } + } + + # + # ~ + # + + protected function buildParagraph($Line) + { + $Block = array( + 'element' => array( + 'name' => 'p', + 'text' => $Line['text'], + 'handler' => 'line', + ), + ); + + return $Block; + } + + # + # ~ + # + + protected function element(array $Element) + { + $markup = '<'.$Element['name']; + + if (isset($Element['attributes'])) + { + foreach ($Element['attributes'] as $name => $value) + { + $markup .= ' '.$name.'="'.$value.'"'; + } + } + + if (isset($Element['text'])) + { + $markup .= '>'; + + if (isset($Element['handler'])) + { + $markup .= $this->$Element['handler']($Element['text']); + } + else + { + $markup .= $Element['text']; + } + + $markup .= ''; + } + else + { + $markup .= ' />'; + } + + return $markup; + } + + protected function elements(array $Elements) + { + $markup = ''; + + foreach ($Elements as $Element) + { + if ($Element === null) + { + continue; + } + + $markup .= "\n"; + + if (is_string($Element)) # because of Markup + { + $markup .= $Element; + + continue; + } + + $markup .= $this->element($Element); + } + + $markup .= "\n"; + + return $markup; + } + + # + # Spans + # + + protected $SpanTypes = array( + '!' => array('Link'), # ? + '&' => array('Ampersand'), + '*' => array('Emphasis'), + '/' => array('Url'), + '<' => array('UrlTag', 'EmailTag', 'Tag', 'LessThan'), + '[' => array('Link'), + '_' => array('Emphasis'), + '`' => array('InlineCode'), + '~' => array('Strikethrough'), + '\\' => array('EscapeSequence'), + ); + + # ~ + + protected $spanMarkerList = '*_!&[spanMarkerList)) + { + $marker = $excerpt[0]; + + $markerPosition += strpos($remainder, $marker); + + $Excerpt = array('text' => $excerpt, 'context' => $text); + + foreach ($this->SpanTypes[$marker] as $spanType) + { + $handler = 'identify'.$spanType; + + $Span = $this->$handler($Excerpt); + + if ( ! isset($Span)) + { + continue; + } + + # The identified span can be ahead of the marker. + + if (isset($Span['position']) and $Span['position'] > $markerPosition) + { + continue; + } + + # Spans that start at the position of their marker don't have to set a position. + + if ( ! isset($Span['position'])) + { + $Span['position'] = $markerPosition; + } + + $plainText = substr($text, 0, $Span['position']); + + $markup .= $this->readPlainText($plainText); + + $markup .= isset($Span['markup']) ? $Span['markup'] : $this->element($Span['element']); + + $text = substr($text, $Span['position'] + $Span['extent']); + + $remainder = $text; + + $markerPosition = 0; + + continue 2; + } + + $remainder = substr($excerpt, 1); + + $markerPosition ++; + } + + $markup .= $this->readPlainText($text); + + return $markup; + } + + # + # ~ + # + + protected function identifyUrl($Excerpt) + { + if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '/') + { + return; + } + + if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE)) + { + $url = str_replace(array('&', '<'), array('&', '<'), $matches[0][0]); + + return array( + 'extent' => strlen($matches[0][0]), + 'position' => $matches[0][1], + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function identifyAmpersand($Excerpt) + { + if ( ! preg_match('/^&#?\w+;/', $Excerpt['text'])) + { + return array( + 'markup' => '&', + 'extent' => 1, + ); + } + } + + protected function identifyStrikethrough($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'del', + 'text' => $matches[1], + 'handler' => 'line', + ), + ); + } + } + + protected function identifyEscapeSequence($Excerpt) + { + if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) + { + return array( + 'markup' => $Excerpt['text'][1], + 'extent' => 2, + ); + } + } + + protected function identifyLessThan() + { + return array( + 'markup' => '<', + 'extent' => 1, + ); + } + + protected function identifyUrlTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(https?:[\/]{2}[^\s]+?)>/i', $Excerpt['text'], $matches)) + { + $url = str_replace(array('&', '<'), array('&', '<'), $matches[1]); + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function identifyEmailTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\S+?@\S+?)>/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $matches[1], + 'attributes' => array( + 'href' => 'mailto:'.$matches[1], + ), + ), + ); + } + } + + protected function identifyTag($Excerpt) + { + if ($this->markupEscaped) + { + return; + } + + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<\/?\w.*?>/', $Excerpt['text'], $matches)) + { + return array( + 'markup' => $matches[0], + 'extent' => strlen($matches[0]), + ); + } + } + + protected function identifyInlineCode($Excerpt) + { + $marker = $Excerpt['text'][0]; + + if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(? strlen($matches[0]), + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ); + } + } + + protected function identifyLink($Excerpt) + { + $extent = $Excerpt['text'][0] === '!' ? 1 : 0; + + if (strpos($Excerpt['text'], ']') and preg_match('/\[((?:[^][]|(?R))*)\]/', $Excerpt['text'], $matches)) + { + $Link = array('text' => $matches[1], 'label' => strtolower($matches[1])); + + $extent += strlen($matches[0]); + + $substring = substr($Excerpt['text'], $extent); + + if (preg_match('/^\s*\[([^][]+)\]/', $substring, $matches)) + { + $Link['label'] = strtolower($matches[1]); + + if (isset($this->Definitions['Reference'][$Link['label']])) + { + $Link += $this->Definitions['Reference'][$Link['label']]; + + $extent += strlen($matches[0]); + } + else + { + return; + } + } + elseif (isset($this->Definitions['Reference'][$Link['label']])) + { + $Link += $this->Definitions['Reference'][$Link['label']]; + + if (preg_match('/^[ ]*\[\]/', $substring, $matches)) + { + $extent += strlen($matches[0]); + } + } + elseif (preg_match('/^\([ ]*(.*?)(?:[ ]+[\'"](.+?)[\'"])?[ ]*\)/', $substring, $matches)) + { + $Link['url'] = $matches[1]; + + if (isset($matches[2])) + { + $Link['title'] = $matches[2]; + } + + $extent += strlen($matches[0]); + } + else + { + return; + } + } + else + { + return; + } + + $url = str_replace(array('&', '<'), array('&', '<'), $Link['url']); + + if ($Excerpt['text'][0] === '!') + { + $Element = array( + 'name' => 'img', + 'attributes' => array( + 'alt' => $Link['text'], + 'src' => $url, + ), + ); + } + else + { + $Element = array( + 'name' => 'a', + 'handler' => 'line', + 'text' => $Link['text'], + 'attributes' => array( + 'href' => $url, + ), + ); + } + + if (isset($Link['title'])) + { + $Element['attributes']['title'] = $Link['title']; + } + + return array( + 'extent' => $extent, + 'element' => $Element, + ); + } + + protected function identifyEmphasis($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + $marker = $Excerpt['text'][0]; + + if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'strong'; + } + elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'em'; + } + else + { + return; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => $emphasis, + 'handler' => 'line', + 'text' => $matches[1], + ), + ); + } + + # + # ~ + + protected function readPlainText($text) + { + $breakMarker = $this->breaksEnabled ? "\n" : " \n"; + + $text = str_replace($breakMarker, "
\n", $text); + + return $text; + } + + # + # ~ + # + + protected function li($lines) + { + $markup = $this->lines($lines); + + $trimmedMarkup = trim($markup); + + if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '

') + { + $markup = $trimmedMarkup; + $markup = substr($markup, 3); + + $position = strpos($markup, "

"); + + $markup = substr_replace($markup, '', $position, 4); + } + + return $markup; + } + + # + # Multiton + # + + static function instance($name = 'default') + { + if (isset(self::$instances[$name])) + { + return self::$instances[$name]; + } + + $instance = new self(); + + self::$instances[$name] = $instance; + + return $instance; + } + + private static $instances = array(); + + # + # Deprecated Methods + # + + /** + * @deprecated in favor of "text" + */ + function parse($text) + { + $markup = $this->text($text); + + return $markup; + } + + # + # Fields + # + + protected $Definitions; + + # + # Read-only + + protected $specialCharacters = array( + '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', + ); + + protected $StrongRegex = array( + '*' => '/^[*]{2}((?:[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s', + '_' => '/^__((?:[^_]|_[^_]*_)+?)__(?!_)/us', + ); + + protected $EmRegex = array( + '*' => '/^[*]((?:[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', + '_' => '/^_((?:[^_]|__[^_]*__)+?)_(?!_)\b/us', + ); + + protected $voidElements = array( + 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', + ); + + protected $textLevelElements = array( + 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', + 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', + 'i', 'rp', 'del', 'code', 'strike', 'marquee', + 'q', 'rt', 'ins', 'font', 'strong', + 's', 'tt', 'sub', 'mark', + 'u', 'xm', 'sup', 'nobr', + 'var', 'ruby', + 'wbr', 'span', + 'time', + ); +} diff --git a/vendor/erusev/parsedown/README.md b/vendor/erusev/parsedown/README.md new file mode 100644 index 00000000..beda06b0 --- /dev/null +++ b/vendor/erusev/parsedown/README.md @@ -0,0 +1,43 @@ +## Parsedown + +Better [Markdown](http://en.wikipedia.org/wiki/Markdown) parser for PHP. + +[[ demo ]](http://parsedown.org/demo) + +### Features + +* [Fast](http://parsedown.org/speed) +* [Consistent](http://parsedown.org/consistency) +* [GitHub Flavored](https://help.github.com/articles/github-flavored-markdown) +* [Tested](http://parsedown.org/tests/) in PHP 5.2, 5.3, 5.4, 5.5, 5.6 and [hhvm](http://www.hhvm.com/) +* Extensible +* [Markdown Extra extension](https://github.com/erusev/parsedown-extra) new +* [JavaScript port](https://github.com/hkdobrev/parsedown.js) under development new + +### Installation + +Include `Parsedown.php` or install [the composer package](https://packagist.org/packages/erusev/parsedown). + +### Example + +``` php +$Parsedown = new Parsedown(); + +echo $Parsedown->text('Hello _Parsedown_!'); # prints:

Hello Parsedown!

+``` + +More examples in [the wiki](https://github.com/erusev/parsedown/wiki/Usage) and in [this video tutorial](http://youtu.be/wYZBY8DEikI). + +### Questions + +**How does Parsedown work?**
+Parsedown recognises that the Markdown syntax is optimised for humans so it tries to read like one. It goes through text line by line. It looks at how lines start to identify blocks. It looks for special characters to identify inline elements. + +**Why doesn’t Parsedown use namespaces?**
+Using namespaces would mean dropping support for PHP 5.2. We believe that since Parsedown is a single class with an uncommon name, making this trade wouldn't be worth it. + +**Is Parsedown compliant with CommonMark?**
+We are [working on it](https://github.com/erusev/parsedown/tree/commonmark). + +**Who uses Parsedown?**
+[phpDocumentor](http://www.phpdoc.org/), [October CMS](http://octobercms.com/), [Bolt CMS](http://bolt.cm/), [RaspberryPi.org](http://www.raspberrypi.org/) and [more](https://www.versioneye.com/php/erusev:parsedown/references). diff --git a/vendor/erusev/parsedown/composer.json b/vendor/erusev/parsedown/composer.json new file mode 100644 index 00000000..1439b824 --- /dev/null +++ b/vendor/erusev/parsedown/composer.json @@ -0,0 +1,18 @@ +{ + "name": "erusev/parsedown", + "description": "Parser for Markdown.", + "keywords": ["markdown", "parser"], + "homepage": "http://parsedown.org", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "autoload": { + "psr-0": {"Parsedown": ""} + } +} \ No newline at end of file diff --git a/vendor/erusev/parsedown/phpunit.xml.dist b/vendor/erusev/parsedown/phpunit.xml.dist new file mode 100644 index 00000000..b2d5e9d4 --- /dev/null +++ b/vendor/erusev/parsedown/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + test/ParsedownTest.php + + + \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/ParsedownTest.php b/vendor/erusev/parsedown/test/ParsedownTest.php new file mode 100644 index 00000000..d094f2da --- /dev/null +++ b/vendor/erusev/parsedown/test/ParsedownTest.php @@ -0,0 +1,139 @@ +dirs = $this->initDirs(); + $this->Parsedown = $this->initParsedown(); + + parent::__construct($name, $data, $dataName); + } + + private $dirs, $Parsedown; + + /** + * @return array + */ + protected function initDirs() + { + $dirs []= dirname(__FILE__).'/data/'; + + return $dirs; + } + + /** + * @return Parsedown + */ + protected function initParsedown() + { + $Parsedown = new Parsedown(); + + return $Parsedown; + } + + /** + * @dataProvider data + * @param $test + * @param $dir + */ + function test_($test, $dir) + { + $markdown = file_get_contents($dir . $test . '.md'); + + $expectedMarkup = file_get_contents($dir . $test . '.html'); + + $expectedMarkup = str_replace("\r\n", "\n", $expectedMarkup); + $expectedMarkup = str_replace("\r", "\n", $expectedMarkup); + + $actualMarkup = $this->Parsedown->text($markdown); + + $this->assertEquals($expectedMarkup, $actualMarkup); + } + + function data() + { + $data = array(); + + foreach ($this->dirs as $dir) + { + $Folder = new DirectoryIterator($dir); + + foreach ($Folder as $File) + { + /** @var $File DirectoryIterator */ + + if ( ! $File->isFile()) + { + continue; + } + + $filename = $File->getFilename(); + + $extension = pathinfo($filename, PATHINFO_EXTENSION); + + if ($extension !== 'md') + { + continue; + } + + $basename = $File->getBasename('.md'); + + if (file_exists($dir . $basename . '.html')) + { + $data []= array($basename, $dir); + } + } + } + + return $data; + } + + public function test_no_markup() + { + $markdownWithHtml = <<_content_ + +sparse: + +
+
+_content_ +
+
+ +paragraph + + + +comment + + +MARKDOWN_WITH_MARKUP; + + $expectedHtml = <<<div>content</div>

+

sparse:

+

<div> +<div class="inner"> +content +</div> +</div>

+

paragraph

+

<style type="text/css">

+
p {
+    color: red;
+}
+

</style>

+

comment

+

<!-- html comment -->

+EXPECTED_HTML; + $parsedownWithNoMarkup = new Parsedown(); + $parsedownWithNoMarkup->setMarkupEscaped(true); + $this->assertEquals($expectedHtml, $parsedownWithNoMarkup->text($markdownWithHtml)); + } +} diff --git a/vendor/erusev/parsedown/test/bootstrap.php b/vendor/erusev/parsedown/test/bootstrap.php new file mode 100644 index 00000000..5f264d2f --- /dev/null +++ b/vendor/erusev/parsedown/test/bootstrap.php @@ -0,0 +1,3 @@ + + + +header 1 +header 2 + + + + +cell 1.1 +cell 1.2 + + +cell 2.1 +cell 2.2 + + + \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/aesthetic_table.md b/vendor/erusev/parsedown/test/data/aesthetic_table.md new file mode 100644 index 00000000..5245e6c9 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/aesthetic_table.md @@ -0,0 +1,4 @@ +| header 1 | header 2 | +| -------- | -------- | +| cell 1.1 | cell 1.2 | +| cell 2.1 | cell 2.2 | \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/aligned_table.html b/vendor/erusev/parsedown/test/data/aligned_table.html new file mode 100644 index 00000000..0657bd17 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/aligned_table.html @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + +
header 1header 2header 2
cell 1.1cell 1.2cell 1.3
cell 2.1cell 2.2cell 2.3
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/aligned_table.md b/vendor/erusev/parsedown/test/data/aligned_table.md new file mode 100644 index 00000000..69a45f90 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/aligned_table.md @@ -0,0 +1,4 @@ +| header 1 | header 2 | header 2 | +| :------- | :------: | -------: | +| cell 1.1 | cell 1.2 | cell 1.3 | +| cell 2.1 | cell 2.2 | cell 2.3 | \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/atx_heading.html b/vendor/erusev/parsedown/test/data/atx_heading.html new file mode 100644 index 00000000..3ab3fd54 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/atx_heading.html @@ -0,0 +1,9 @@ +

h1

+

h2

+

h3

+

h4

+
h5
+
h6
+
h6
+

closed h1

+

#

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/atx_heading.md b/vendor/erusev/parsedown/test/data/atx_heading.md new file mode 100644 index 00000000..5339a5b0 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/atx_heading.md @@ -0,0 +1,17 @@ +# h1 + +## h2 + +### h3 + +#### h4 + +##### h5 + +###### h6 + +####### h6 + +# closed h1 # + +# \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/automatic_link.html b/vendor/erusev/parsedown/test/data/automatic_link.html new file mode 100644 index 00000000..50a94ba0 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/automatic_link.html @@ -0,0 +1 @@ +

http://example.com

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/automatic_link.md b/vendor/erusev/parsedown/test/data/automatic_link.md new file mode 100644 index 00000000..08d3bf46 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/automatic_link.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/block-level_html.html b/vendor/erusev/parsedown/test/data/block-level_html.html new file mode 100644 index 00000000..86ff8655 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/block-level_html.html @@ -0,0 +1,13 @@ +
_content_
+

sparse:

+
+
+_content_ +
+
+

paragraph

+ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/block-level_html.md b/vendor/erusev/parsedown/test/data/block-level_html.md new file mode 100644 index 00000000..679832cd --- /dev/null +++ b/vendor/erusev/parsedown/test/data/block-level_html.md @@ -0,0 +1,17 @@ +
_content_
+ +sparse: + +
+
+_content_ +
+
+ +paragraph + + diff --git a/vendor/erusev/parsedown/test/data/code_block.html b/vendor/erusev/parsedown/test/data/code_block.html new file mode 100644 index 00000000..889b02d9 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/code_block.html @@ -0,0 +1,8 @@ +
<?php
+
+$message = 'Hello World!';
+echo $message;
+
+
> not a quote
+- not a list item
+[not a reference]: http://foo.com
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/code_block.md b/vendor/erusev/parsedown/test/data/code_block.md new file mode 100644 index 00000000..2cfc953c --- /dev/null +++ b/vendor/erusev/parsedown/test/data/code_block.md @@ -0,0 +1,10 @@ + not a quote + - not a list item + [not a reference]: http://foo.com \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/code_span.html b/vendor/erusev/parsedown/test/data/code_span.html new file mode 100644 index 00000000..5c4c231e --- /dev/null +++ b/vendor/erusev/parsedown/test/data/code_span.html @@ -0,0 +1,6 @@ +

a code span

+

this is also a codespan trailing text

+

and look at this one!

+

single backtick in a code span: `

+

backtick-delimited string in a code span: `foo`

+

sth `` sth

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/code_span.md b/vendor/erusev/parsedown/test/data/code_span.md new file mode 100644 index 00000000..c2f1a744 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/code_span.md @@ -0,0 +1,11 @@ +a `code span` + +`this is also a codespan` trailing text + +`and look at this one!` + +single backtick in a code span: `` ` `` + +backtick-delimited string in a code span: `` `foo` `` + +`sth `` sth` \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/compound_blockquote.html b/vendor/erusev/parsedown/test/data/compound_blockquote.html new file mode 100644 index 00000000..37afb57a --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_blockquote.html @@ -0,0 +1,9 @@ +
+

header

+

paragraph

+
    +
  • li
  • +
+
+

paragraph

+
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/compound_blockquote.md b/vendor/erusev/parsedown/test/data/compound_blockquote.md new file mode 100644 index 00000000..80c4aed1 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_blockquote.md @@ -0,0 +1,10 @@ +> header +> ------ +> +> paragraph +> +> - li +> +> --- +> +> paragraph \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/compound_emphasis.html b/vendor/erusev/parsedown/test/data/compound_emphasis.html new file mode 100644 index 00000000..178dd54b --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_emphasis.html @@ -0,0 +1,2 @@ +

code code

+

codecodecode

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/compound_emphasis.md b/vendor/erusev/parsedown/test/data/compound_emphasis.md new file mode 100644 index 00000000..6fe07f26 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_emphasis.md @@ -0,0 +1,4 @@ +_`code`_ __`code`__ + +*`code`**`code`**`code`* + diff --git a/vendor/erusev/parsedown/test/data/compound_list.html b/vendor/erusev/parsedown/test/data/compound_list.html new file mode 100644 index 00000000..f5593c14 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_list.html @@ -0,0 +1,12 @@ +
    +
  • +

    paragraph

    +

    paragraph

    +
  • +
  • +

    paragraph

    +
    +

    quote

    +
    +
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/compound_list.md b/vendor/erusev/parsedown/test/data/compound_list.md new file mode 100644 index 00000000..ed7f0c60 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/compound_list.md @@ -0,0 +1,7 @@ +- paragraph + + paragraph + +- paragraph + + > quote \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/deeply_nested_list.html b/vendor/erusev/parsedown/test/data/deeply_nested_list.html new file mode 100644 index 00000000..d2c7e5ac --- /dev/null +++ b/vendor/erusev/parsedown/test/data/deeply_nested_list.html @@ -0,0 +1,12 @@ +
    +
  • li +
      +
    • li +
        +
      • li
      • +
      • li
      • +
    • +
    • li
    • +
  • +
  • li
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/deeply_nested_list.md b/vendor/erusev/parsedown/test/data/deeply_nested_list.md new file mode 100644 index 00000000..76b7552d --- /dev/null +++ b/vendor/erusev/parsedown/test/data/deeply_nested_list.md @@ -0,0 +1,6 @@ +- li + - li + - li + - li + - li +- li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/em_strong.html b/vendor/erusev/parsedown/test/data/em_strong.html new file mode 100644 index 00000000..323d60ae --- /dev/null +++ b/vendor/erusev/parsedown/test/data/em_strong.html @@ -0,0 +1,8 @@ +

em strong

+

em strong strong

+

strong em strong

+

strong em strong strong

+

em strong

+

em strong strong

+

strong em strong

+

strong em strong strong

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/em_strong.md b/vendor/erusev/parsedown/test/data/em_strong.md new file mode 100644 index 00000000..9abeb3fd --- /dev/null +++ b/vendor/erusev/parsedown/test/data/em_strong.md @@ -0,0 +1,15 @@ +___em strong___ + +___em strong_ strong__ + +__strong _em strong___ + +__strong _em strong_ strong__ + +***em strong*** + +***em strong* strong** + +**strong *em strong*** + +**strong *em strong* strong** \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/email.html b/vendor/erusev/parsedown/test/data/email.html new file mode 100644 index 00000000..c40759c9 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/email.html @@ -0,0 +1 @@ +

my email is me@example.com

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/email.md b/vendor/erusev/parsedown/test/data/email.md new file mode 100644 index 00000000..26b7b6cc --- /dev/null +++ b/vendor/erusev/parsedown/test/data/email.md @@ -0,0 +1 @@ +my email is \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/emphasis.html b/vendor/erusev/parsedown/test/data/emphasis.html new file mode 100644 index 00000000..60ff4bd8 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/emphasis.html @@ -0,0 +1,8 @@ +

underscore, asterisk, one two, three four, a, b

+

strong and em and strong and em

+

line +line +line

+

this_is_not_an_emphasis

+

an empty emphasis __ ** is not an emphasis

+

*mixed *double and single asterisk** spans

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/emphasis.md b/vendor/erusev/parsedown/test/data/emphasis.md new file mode 100644 index 00000000..85b9d229 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/emphasis.md @@ -0,0 +1,13 @@ +_underscore_, *asterisk*, _one two_, *three four*, _a_, *b* + +**strong** and *em* and **strong** and *em* + +_line +line +line_ + +this_is_not_an_emphasis + +an empty emphasis __ ** is not an emphasis + +*mixed **double and* single asterisk** spans \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/escaping.html b/vendor/erusev/parsedown/test/data/escaping.html new file mode 100644 index 00000000..64676cb1 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/escaping.html @@ -0,0 +1,4 @@ +

escaped *emphasis*.

+

escaped \*emphasis\* in a code span

+
escaped \*emphasis\* in a code block
+

\ ` * _ { } [ ] ( ) > # + - . !

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/escaping.md b/vendor/erusev/parsedown/test/data/escaping.md new file mode 100644 index 00000000..164039f8 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/escaping.md @@ -0,0 +1,7 @@ +escaped \*emphasis\*. + +`escaped \*emphasis\* in a code span` + + escaped \*emphasis\* in a code block + +\\ \` \* \_ \{ \} \[ \] \( \) \> \# \+ \- \. \! \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/fenced_code_block.html b/vendor/erusev/parsedown/test/data/fenced_code_block.html new file mode 100644 index 00000000..8bdabba9 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/fenced_code_block.html @@ -0,0 +1,6 @@ +
<?php
+
+$message = 'fenced code block';
+echo $message;
+
tilde
+
echo 'language identifier';
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/fenced_code_block.md b/vendor/erusev/parsedown/test/data/fenced_code_block.md new file mode 100644 index 00000000..cbed8ebb --- /dev/null +++ b/vendor/erusev/parsedown/test/data/fenced_code_block.md @@ -0,0 +1,14 @@ +``` + +
+
+
+
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/horizontal_rule.md b/vendor/erusev/parsedown/test/data/horizontal_rule.md new file mode 100644 index 00000000..bf461a92 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/horizontal_rule.md @@ -0,0 +1,9 @@ +--- + +- - - + + - - - + +*** + +___ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/html_comment.html b/vendor/erusev/parsedown/test/data/html_comment.html new file mode 100644 index 00000000..566dc3ad --- /dev/null +++ b/vendor/erusev/parsedown/test/data/html_comment.html @@ -0,0 +1,5 @@ + +

paragraph

+ +

paragraph

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/html_comment.md b/vendor/erusev/parsedown/test/data/html_comment.md new file mode 100644 index 00000000..6ddfdb44 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/html_comment.md @@ -0,0 +1,8 @@ + + +paragraph + + + +paragraph \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/html_entity.html b/vendor/erusev/parsedown/test/data/html_entity.html new file mode 100644 index 00000000..4d23e3cd --- /dev/null +++ b/vendor/erusev/parsedown/test/data/html_entity.html @@ -0,0 +1 @@ +

& © {

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/html_entity.md b/vendor/erusev/parsedown/test/data/html_entity.md new file mode 100644 index 00000000..ff545ea5 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/html_entity.md @@ -0,0 +1 @@ +& © { \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/image_reference.html b/vendor/erusev/parsedown/test/data/image_reference.html new file mode 100644 index 00000000..b3249cba --- /dev/null +++ b/vendor/erusev/parsedown/test/data/image_reference.html @@ -0,0 +1 @@ +

Markdown Logo

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/image_reference.md b/vendor/erusev/parsedown/test/data/image_reference.md new file mode 100644 index 00000000..dcb1414d --- /dev/null +++ b/vendor/erusev/parsedown/test/data/image_reference.md @@ -0,0 +1,3 @@ +![Markdown Logo][image] + +[image]: /md.png diff --git a/vendor/erusev/parsedown/test/data/image_title.html b/vendor/erusev/parsedown/test/data/image_title.html new file mode 100644 index 00000000..82c155f6 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/image_title.html @@ -0,0 +1 @@ +

alt

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/image_title.md b/vendor/erusev/parsedown/test/data/image_title.md new file mode 100644 index 00000000..3e58ee55 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/image_title.md @@ -0,0 +1 @@ +![alt](/md.png "title") \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/implicit_reference.html b/vendor/erusev/parsedown/test/data/implicit_reference.html new file mode 100644 index 00000000..24b51c1b --- /dev/null +++ b/vendor/erusev/parsedown/test/data/implicit_reference.html @@ -0,0 +1,4 @@ +

an implicit reference link

+

an implicit reference link with an empty link definition

+

an implicit reference link followed by another

+

an explicit reference link with a title

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/implicit_reference.md b/vendor/erusev/parsedown/test/data/implicit_reference.md new file mode 100644 index 00000000..f850df96 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/implicit_reference.md @@ -0,0 +1,13 @@ +an [implicit] reference link + +[implicit]: http://example.com + +an [implicit][] reference link with an empty link definition + +an [implicit][] reference link followed by [another][] + +[another]: http://cnn.com + +an [explicit][example] reference link with a title + +[example]: http://example.com "Example" \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_link.html b/vendor/erusev/parsedown/test/data/inline_link.html new file mode 100644 index 00000000..2b9e649d --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_link.html @@ -0,0 +1,4 @@ +

link and another link

+

link

+

MD Logo

+

MD Logo and text

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_link.md b/vendor/erusev/parsedown/test/data/inline_link.md new file mode 100644 index 00000000..cd8e5a63 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_link.md @@ -0,0 +1,7 @@ +[link](http://example.com) and [another link](/tests/) + +[`link`](http://example.com) + +[![MD Logo](http://parsedown.org/md.png)](http://example.com) + +[![MD Logo](http://parsedown.org/md.png) and text](http://example.com) \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_link_title.html b/vendor/erusev/parsedown/test/data/inline_link_title.html new file mode 100644 index 00000000..70e589aa --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_link_title.html @@ -0,0 +1 @@ +

single quotes and double quotes

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_link_title.md b/vendor/erusev/parsedown/test/data/inline_link_title.md new file mode 100644 index 00000000..162b832a --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_link_title.md @@ -0,0 +1 @@ +[single quotes](http://example.com 'Title') and [double quotes](http://example.com "Title") \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_title.html b/vendor/erusev/parsedown/test/data/inline_title.html new file mode 100644 index 00000000..bbab93b6 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_title.html @@ -0,0 +1 @@ +

single quotes and double quotes

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/inline_title.md b/vendor/erusev/parsedown/test/data/inline_title.md new file mode 100644 index 00000000..cb09344a --- /dev/null +++ b/vendor/erusev/parsedown/test/data/inline_title.md @@ -0,0 +1 @@ +[single quotes](http://example.com 'Example') and [double quotes](http://example.com "Example") \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/lazy_blockquote.html b/vendor/erusev/parsedown/test/data/lazy_blockquote.html new file mode 100644 index 00000000..0a2a2aaf --- /dev/null +++ b/vendor/erusev/parsedown/test/data/lazy_blockquote.html @@ -0,0 +1,6 @@ +
+

quote +the rest of it

+

another paragraph +the rest of it

+
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/lazy_blockquote.md b/vendor/erusev/parsedown/test/data/lazy_blockquote.md new file mode 100644 index 00000000..48f645f9 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/lazy_blockquote.md @@ -0,0 +1,5 @@ +> quote +the rest of it + +> another paragraph +the rest of it \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/lazy_list.html b/vendor/erusev/parsedown/test/data/lazy_list.html new file mode 100644 index 00000000..1a519924 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/lazy_list.html @@ -0,0 +1,4 @@ +
    +
  • li +the rest of it
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/lazy_list.md b/vendor/erusev/parsedown/test/data/lazy_list.md new file mode 100644 index 00000000..62ad9d71 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/lazy_list.md @@ -0,0 +1,2 @@ +- li +the rest of it \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/line_break.html b/vendor/erusev/parsedown/test/data/line_break.html new file mode 100644 index 00000000..5f37d854 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/line_break.html @@ -0,0 +1,2 @@ +

line
+line

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/line_break.md b/vendor/erusev/parsedown/test/data/line_break.md new file mode 100644 index 00000000..04dff43e --- /dev/null +++ b/vendor/erusev/parsedown/test/data/line_break.md @@ -0,0 +1,2 @@ +line +line \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/multiline_list_paragraph.html b/vendor/erusev/parsedown/test/data/multiline_list_paragraph.html new file mode 100644 index 00000000..3247bd22 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/multiline_list_paragraph.html @@ -0,0 +1,7 @@ +
    +
  • +

    li

    +

    line +line

    +
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/multiline_list_paragraph.md b/vendor/erusev/parsedown/test/data/multiline_list_paragraph.md new file mode 100644 index 00000000..f5b42729 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/multiline_list_paragraph.md @@ -0,0 +1,4 @@ +- li + + line + line \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/nested_block-level_html.html b/vendor/erusev/parsedown/test/data/nested_block-level_html.html new file mode 100644 index 00000000..bfbef54d --- /dev/null +++ b/vendor/erusev/parsedown/test/data/nested_block-level_html.html @@ -0,0 +1,10 @@ +
+_parent_ +
+_child_ +
+
+_adopted child_
+
+
+

outside

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/nested_block-level_html.md b/vendor/erusev/parsedown/test/data/nested_block-level_html.md new file mode 100644 index 00000000..5e01e109 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/nested_block-level_html.md @@ -0,0 +1,11 @@ +
+_parent_ +
+_child_ +
+
+_adopted child_
+
+
+ +_outside_ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/ordered_list.html b/vendor/erusev/parsedown/test/data/ordered_list.html new file mode 100644 index 00000000..b6c5216c --- /dev/null +++ b/vendor/erusev/parsedown/test/data/ordered_list.html @@ -0,0 +1,13 @@ +
    +
  1. one
  2. +
  3. two
  4. +
+

repeating numbers:

+
    +
  1. one
  2. +
  3. two
  4. +
+

large numbers:

+
    +
  1. one
  2. +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/ordered_list.md b/vendor/erusev/parsedown/test/data/ordered_list.md new file mode 100644 index 00000000..b307032c --- /dev/null +++ b/vendor/erusev/parsedown/test/data/ordered_list.md @@ -0,0 +1,11 @@ +1. one +2. two + +repeating numbers: + +1. one +1. two + +large numbers: + +123. one \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/paragraph_list.html b/vendor/erusev/parsedown/test/data/paragraph_list.html new file mode 100644 index 00000000..ced1c43e --- /dev/null +++ b/vendor/erusev/parsedown/test/data/paragraph_list.html @@ -0,0 +1,12 @@ +

paragraph

+
    +
  • li
  • +
  • li
  • +
+

paragraph

+
    +
  • +

    li

    +
  • +
  • li
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/paragraph_list.md b/vendor/erusev/parsedown/test/data/paragraph_list.md new file mode 100644 index 00000000..b973908c --- /dev/null +++ b/vendor/erusev/parsedown/test/data/paragraph_list.md @@ -0,0 +1,9 @@ +paragraph +- li +- li + +paragraph + + * li + + * li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/reference_title.html b/vendor/erusev/parsedown/test/data/reference_title.html new file mode 100644 index 00000000..8f2be944 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/reference_title.html @@ -0,0 +1,2 @@ +

double quotes and single quotes and parentheses

+

[invalid title]: http://example.com example title

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/reference_title.md b/vendor/erusev/parsedown/test/data/reference_title.md new file mode 100644 index 00000000..43cb2170 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/reference_title.md @@ -0,0 +1,6 @@ +[double quotes] and [single quotes] and [parentheses] + +[double quotes]: http://example.com "example title" +[single quotes]: http://example.com 'example title' +[parentheses]: http://example.com (example title) +[invalid title]: http://example.com example title \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/self-closing_html.html b/vendor/erusev/parsedown/test/data/self-closing_html.html new file mode 100644 index 00000000..4d072b43 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/self-closing_html.html @@ -0,0 +1,12 @@ +
+

paragraph

+
+

paragraph

+
+

paragraph

+
+

paragraph

+
+

paragraph

+
+

paragraph

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/self-closing_html.md b/vendor/erusev/parsedown/test/data/self-closing_html.md new file mode 100644 index 00000000..acb20327 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/self-closing_html.md @@ -0,0 +1,12 @@ +
+paragraph +
+paragraph +
+paragraph +
+paragraph +
+paragraph +
+paragraph \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/separated_nested_list.html b/vendor/erusev/parsedown/test/data/separated_nested_list.html new file mode 100644 index 00000000..80a5cae2 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/separated_nested_list.html @@ -0,0 +1,9 @@ +
    +
  • +

    li

    +
      +
    • li
    • +
    • li
    • +
    +
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/separated_nested_list.md b/vendor/erusev/parsedown/test/data/separated_nested_list.md new file mode 100644 index 00000000..d7cd1af7 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/separated_nested_list.md @@ -0,0 +1,4 @@ +- li + + - li + - li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/setext_header.html b/vendor/erusev/parsedown/test/data/setext_header.html new file mode 100644 index 00000000..60aac081 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/setext_header.html @@ -0,0 +1,5 @@ +

h1

+

h2

+

single character

+

not a header

+
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/setext_header.md b/vendor/erusev/parsedown/test/data/setext_header.md new file mode 100644 index 00000000..c43b52c3 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/setext_header.md @@ -0,0 +1,12 @@ +h1 +== + +h2 +-- + +single character +- + +not a header + +------------ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/simple_blockquote.html b/vendor/erusev/parsedown/test/data/simple_blockquote.html new file mode 100644 index 00000000..8225d57c --- /dev/null +++ b/vendor/erusev/parsedown/test/data/simple_blockquote.html @@ -0,0 +1,11 @@ +
+

quote

+
+

indented:

+
+

quote

+
+

no space after >:

+
+

quote

+
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/simple_blockquote.md b/vendor/erusev/parsedown/test/data/simple_blockquote.md new file mode 100644 index 00000000..22b6b11a --- /dev/null +++ b/vendor/erusev/parsedown/test/data/simple_blockquote.md @@ -0,0 +1,7 @@ +> quote + +indented: + > quote + +no space after `>`: +>quote \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/simple_table.html b/vendor/erusev/parsedown/test/data/simple_table.html new file mode 100644 index 00000000..64b7a9a2 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/simple_table.html @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + +
header 1header 2
cell 1.1cell 1.2
cell 2.1cell 2.2
+
+ + + + + + + + + + + + + + + + + +
header 1header 2
cell 1.1cell 1.2
cell 2.1cell 2.2
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/simple_table.md b/vendor/erusev/parsedown/test/data/simple_table.md new file mode 100644 index 00000000..466d140e --- /dev/null +++ b/vendor/erusev/parsedown/test/data/simple_table.md @@ -0,0 +1,11 @@ +header 1 | header 2 +-------- | -------- +cell 1.1 | cell 1.2 +cell 2.1 | cell 2.2 + +--- + +header 1 | header 2 +:------- | -------- +cell 1.1 | cell 1.2 +cell 2.1 | cell 2.2 \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/span-level_html.html b/vendor/erusev/parsedown/test/data/span-level_html.html new file mode 100644 index 00000000..f852a25a --- /dev/null +++ b/vendor/erusev/parsedown/test/data/span-level_html.html @@ -0,0 +1,5 @@ +

an important link

+

broken
+line

+

inline tag at the beginning

+

http://example.com

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/span-level_html.md b/vendor/erusev/parsedown/test/data/span-level_html.md new file mode 100644 index 00000000..f2219655 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/span-level_html.md @@ -0,0 +1,8 @@ +an important link + +broken
+line + +inline tag at the beginning + +http://example.com \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/sparse_dense_list.html b/vendor/erusev/parsedown/test/data/sparse_dense_list.html new file mode 100644 index 00000000..095bc739 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/sparse_dense_list.html @@ -0,0 +1,7 @@ +
    +
  • +

    li

    +
  • +
  • li
  • +
  • li
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/sparse_dense_list.md b/vendor/erusev/parsedown/test/data/sparse_dense_list.md new file mode 100644 index 00000000..57684227 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/sparse_dense_list.md @@ -0,0 +1,4 @@ +- li + +- li +- li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/sparse_list.html b/vendor/erusev/parsedown/test/data/sparse_list.html new file mode 100644 index 00000000..452b2b86 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/sparse_list.html @@ -0,0 +1,15 @@ +
    +
  • +

    li

    +
  • +
  • li
  • +
+
+
    +
  • +

    li

    +
      +
    • indented li
    • +
    +
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/sparse_list.md b/vendor/erusev/parsedown/test/data/sparse_list.md new file mode 100644 index 00000000..362a35f5 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/sparse_list.md @@ -0,0 +1,9 @@ +- li + +- li + +--- + +- li + + - indented li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/special_characters.html b/vendor/erusev/parsedown/test/data/special_characters.html new file mode 100644 index 00000000..8199abc1 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/special_characters.html @@ -0,0 +1,6 @@ +

AT&T has an ampersand in their name

+

this & that

+

4 < 5 and 6 > 5

+

http://example.com/autolink?a=1&b=2

+

inline link

+

reference link

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/special_characters.md b/vendor/erusev/parsedown/test/data/special_characters.md new file mode 100644 index 00000000..111b03b6 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/special_characters.md @@ -0,0 +1,13 @@ +AT&T has an ampersand in their name + +this & that + +4 < 5 and 6 > 5 + + + +[inline link](/script?a=1&b=2) + +[reference link][1] + +[1]: http://example.com/?a=1&b=2 \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/strikethrough.html b/vendor/erusev/parsedown/test/data/strikethrough.html new file mode 100644 index 00000000..2a9da982 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/strikethrough.html @@ -0,0 +1,3 @@ +

strikethrough

+

here's one followed by another one

+

~~ this ~~ is not one neither is ~this~

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/strikethrough.md b/vendor/erusev/parsedown/test/data/strikethrough.md new file mode 100644 index 00000000..d169144d --- /dev/null +++ b/vendor/erusev/parsedown/test/data/strikethrough.md @@ -0,0 +1,5 @@ +~~strikethrough~~ + +here's ~~one~~ followed by ~~another one~~ + +~~ this ~~ is not one neither is ~this~ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/strong_em.html b/vendor/erusev/parsedown/test/data/strong_em.html new file mode 100644 index 00000000..b709c991 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/strong_em.html @@ -0,0 +1,6 @@ +

em strong em

+

strong em em

+

em strong em em

+

em strong em

+

strong em em

+

em strong em em

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/strong_em.md b/vendor/erusev/parsedown/test/data/strong_em.md new file mode 100644 index 00000000..f2aa3c78 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/strong_em.md @@ -0,0 +1,11 @@ +*em **strong em*** + +***strong em** em* + +*em **strong em** em* + +_em __strong em___ + +___strong em__ em_ + +_em __strong em__ em_ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/tab-indented_code_block.html b/vendor/erusev/parsedown/test/data/tab-indented_code_block.html new file mode 100644 index 00000000..7c140de7 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/tab-indented_code_block.html @@ -0,0 +1,6 @@ +
<?php
+
+$message = 'Hello World!';
+echo $message;
+
+echo "following a blank line";
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/tab-indented_code_block.md b/vendor/erusev/parsedown/test/data/tab-indented_code_block.md new file mode 100644 index 00000000..a405a160 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/tab-indented_code_block.md @@ -0,0 +1,6 @@ + + + +header 1 +header 2 + + + + +cell 1.1 +cell 1.2 + + +cell 2.1 +cell 2.2 + + + \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/table_inline_markdown.md b/vendor/erusev/parsedown/test/data/table_inline_markdown.md new file mode 100644 index 00000000..c2fe1080 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/table_inline_markdown.md @@ -0,0 +1,4 @@ +| _header_ 1 | header 2 | +| ------------ | ------------ | +| _cell_ 1.1 | ~~cell~~ 1.2 | +| `cell` 2.1 | cell 2.2 | \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/text_reference.html b/vendor/erusev/parsedown/test/data/text_reference.html new file mode 100644 index 00000000..11e4d37f --- /dev/null +++ b/vendor/erusev/parsedown/test/data/text_reference.html @@ -0,0 +1,8 @@ +

reference link

+

one with a semantic name

+

[one][404] with no definition

+

multiline +one defined on 2 lines

+

one with a mixed case label and an upper case definition

+

one with the a label on the next line

+

link

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/text_reference.md b/vendor/erusev/parsedown/test/data/text_reference.md new file mode 100644 index 00000000..1a66a5cf --- /dev/null +++ b/vendor/erusev/parsedown/test/data/text_reference.md @@ -0,0 +1,21 @@ +[reference link][1] + +[1]: http://example.com + +[one][website] with a semantic name + +[website]: http://example.com + +[one][404] with no definition + +[multiline +one][website] defined on 2 lines + +[one][Label] with a mixed case label and an upper case definition + +[LABEL]: http://example.com + +[one] +[1] with the a label on the next line + +[`link`][website] \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/unordered_list.html b/vendor/erusev/parsedown/test/data/unordered_list.html new file mode 100644 index 00000000..cd95567b --- /dev/null +++ b/vendor/erusev/parsedown/test/data/unordered_list.html @@ -0,0 +1,10 @@ +
    +
  • li
  • +
  • li
  • +
+

mixed markers:

+
    +
  • li
  • +
  • li
  • +
  • li
  • +
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/unordered_list.md b/vendor/erusev/parsedown/test/data/unordered_list.md new file mode 100644 index 00000000..cf62c99f --- /dev/null +++ b/vendor/erusev/parsedown/test/data/unordered_list.md @@ -0,0 +1,8 @@ +- li +- li + +mixed markers: + +* li ++ li +- li \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/untidy_table.html b/vendor/erusev/parsedown/test/data/untidy_table.html new file mode 100644 index 00000000..88e1c2bd --- /dev/null +++ b/vendor/erusev/parsedown/test/data/untidy_table.html @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + +
header 1header 2
cell 1.1cell 1.2
cell 2.1cell 2.2
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/untidy_table.md b/vendor/erusev/parsedown/test/data/untidy_table.md new file mode 100644 index 00000000..8524eb18 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/untidy_table.md @@ -0,0 +1,4 @@ +| header 1 | header 2 | +| ------------- | ----------- | +| cell 1.1 | cell 1.2 | +| cell 2.1 | cell 2.2 | \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/url_autolinking.html b/vendor/erusev/parsedown/test/data/url_autolinking.html new file mode 100644 index 00000000..58ca94c6 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/url_autolinking.html @@ -0,0 +1,3 @@ +

an autolink http://example.com

+

inside of brackets [http://example.com], inside of braces {http://example.com}, inside of parentheses (http://example.com)

+

trailing slash http://example.com/ and http://example.com/path/

\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/url_autolinking.md b/vendor/erusev/parsedown/test/data/url_autolinking.md new file mode 100644 index 00000000..840f3540 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/url_autolinking.md @@ -0,0 +1,5 @@ +an autolink http://example.com + +inside of brackets [http://example.com], inside of braces {http://example.com}, inside of parentheses (http://example.com) + +trailing slash http://example.com/ and http://example.com/path/ \ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/whitespace.html b/vendor/erusev/parsedown/test/data/whitespace.html new file mode 100644 index 00000000..f2dd7a00 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/whitespace.html @@ -0,0 +1 @@ +
code
\ No newline at end of file diff --git a/vendor/erusev/parsedown/test/data/whitespace.md b/vendor/erusev/parsedown/test/data/whitespace.md new file mode 100644 index 00000000..4cf926a8 --- /dev/null +++ b/vendor/erusev/parsedown/test/data/whitespace.md @@ -0,0 +1,5 @@ + + + code + + \ No newline at end of file diff --git a/vendor/fguillot/json-rpc b/vendor/fguillot/json-rpc new file mode 160000 index 00000000..66db4093 --- /dev/null +++ b/vendor/fguillot/json-rpc @@ -0,0 +1 @@ +Subproject commit 66db4093984790c34577c0ba0e17f2e3d2dc14a0 diff --git a/vendor/fguillot/picodb b/vendor/fguillot/picodb new file mode 160000 index 00000000..dbf15938 --- /dev/null +++ b/vendor/fguillot/picodb @@ -0,0 +1 @@ +Subproject commit dbf15938687ca800abfccc424390add33dd95181 diff --git a/vendor/fguillot/simple-validator b/vendor/fguillot/simple-validator new file mode 160000 index 00000000..14f7c0b1 --- /dev/null +++ b/vendor/fguillot/simple-validator @@ -0,0 +1 @@ +Subproject commit 14f7c0b111444a5b26ce447ef5f0de655279b5f1 diff --git a/vendor/ircmaxell/password-compat/.travis.yml b/vendor/ircmaxell/password-compat/.travis.yml new file mode 100644 index 00000000..a960061c --- /dev/null +++ b/vendor/ircmaxell/password-compat/.travis.yml @@ -0,0 +1,8 @@ +language: php + +php: + - 5.5 + - 5.4 + - 5.3 + +script: phpunit --configuration phpunit.xml.dist \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/LICENSE.md b/vendor/ircmaxell/password-compat/LICENSE.md new file mode 100644 index 00000000..1efc565f --- /dev/null +++ b/vendor/ircmaxell/password-compat/LICENSE.md @@ -0,0 +1,7 @@ +Copyright (c) 2012 Anthony Ferrara + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/README.md b/vendor/ircmaxell/password-compat/README.md new file mode 100644 index 00000000..e158f7d0 --- /dev/null +++ b/vendor/ircmaxell/password-compat/README.md @@ -0,0 +1,75 @@ +password_compat +=============== + +[![Build Status](https://travis-ci.org/ircmaxell/password_compat.png?branch=master)](https://travis-ci.org/ircmaxell/password_compat) + +This library is intended to provide forward compatibility with the password_* functions being worked on for PHP 5.5. + +See [the RFC](https://wiki.php.net/rfc/password_hash) for more detailed information. + + +Requirements +============ + +This library requires `PHP >= 5.3.7` OR a version that has the `$2y` fix backported into it (such as Debian provides). + +The runtime checks have been removed due to this version issue. To see if password_compat is available for your system, run the included `version-test.php`. If it outputs "Pass", you can safely use the library. If not, you cannot. + +If you attempt to use password-compat on an unsupported version, attempts to create or verify hashes will return `false`. You have been warned! + +The reason for this is that PHP prior to 5.3.7 contains a security issue with its BCRYPT implementation. Therefore, it's highly recommended that you upgrade to a newer version of PHP prior to using this layer. + +Installation +============ + +To install, simply `require` the `password.php` file under `lib`. + +You can also install it via `Composer` by using the [Packagist archive](http://packagist.org/packages/ircmaxell/password-compat). + +Usage +===== + +**Creating Password Hashes** + +To create a password hash from a password, simply use the `password_hash` function. + + $hash = password_hash($password, PASSWORD_BCRYPT); + +Note that the algorithm that we chose is `PASSWORD_BCRYPT`. That's the current strongest algorithm supported. This is the `BCRYPT` crypt algorithm. It produces a 60 character hash as the result. + +`BCRYPT` also allows for you to define a `cost` parameter in the options array. This allows for you to change the CPU cost of the algorithm: + + $hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 10]); + +That's the same as the default. The cost can range from `4` to `31`. I would suggest that you use the highest cost that you can, while keeping response time reasonable (I target between 0.1 and 0.5 seconds for a hash, depending on use-case). + +Another algorithm name is supported: + + PASSWORD_DEFAULT + +This will use the strongest algorithm available to PHP at the current time. Presently, this is the same as specifying `PASSWORD_BCRYPT`. But in future versions of PHP, it may be updated to use a stronger algorithm if one is introduced. It can also be changed if a problem is identified with the BCRYPT algorithm. Note that if you use this option, you are **strongly** encouraged to store it in a `VARCHAR(255)` column to avoid truncation issues if a future algorithm increases the length of the generated hash. + +It is very important that you should check the return value of `password_hash` prior to storing it, because a `false` may be returned if it encountered an error. + +**Verifying Password Hashes** + +To verify a hash created by `password_hash`, simply call: + + if (password_verify($password, $hash)) { + /* Valid */ + } else { + /* Invalid */ + } + +That's all there is to it. + +**Rehashing Passwords** + +From time to time you may update your hashing parameters (algorithm, cost, etc). So a function to determine if rehashing is necessary is available: + + if (password_verify($password, $hash)) { + if (password_needs_rehash($hash, $algorithm, $options)) { + $hash = password_hash($password, $algorithm, $options); + /* Store new hash in db */ + } + } diff --git a/vendor/ircmaxell/password-compat/composer.json b/vendor/ircmaxell/password-compat/composer.json new file mode 100644 index 00000000..e0d4f14c --- /dev/null +++ b/vendor/ircmaxell/password-compat/composer.json @@ -0,0 +1,18 @@ +{ + "name": "ircmaxell/password-compat", + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "version": "1.0.3", + "keywords": ["password", "hashing"], + "homepage": "https://github.com/ircmaxell/password_compat", + "license": "MIT", + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "autoload": { + "files": ["lib/password.php"] + } +} \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/lib/password.php b/vendor/ircmaxell/password-compat/lib/password.php new file mode 100644 index 00000000..4d0e8b7a --- /dev/null +++ b/vendor/ircmaxell/password-compat/lib/password.php @@ -0,0 +1,222 @@ + + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @copyright 2012 The Authors + */ + +if (!defined('PASSWORD_BCRYPT')) { + + define('PASSWORD_BCRYPT', 1); + define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); + + /** + * Hash the password using the specified algorithm + * + * @param string $password The password to hash + * @param int $algo The algorithm to use (Defined by PASSWORD_* constants) + * @param array $options The options for the algorithm to use + * + * @return string|false The hashed password, or false on error. + */ + function password_hash($password, $algo, array $options = array()) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING); + return null; + } + if (!is_string($password)) { + trigger_error("password_hash(): Password must be a string", E_USER_WARNING); + return null; + } + if (!is_int($algo)) { + trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING); + return null; + } + switch ($algo) { + case PASSWORD_BCRYPT: + // Note that this is a C constant, but not exposed to PHP, so we don't define it here. + $cost = 10; + if (isset($options['cost'])) { + $cost = $options['cost']; + if ($cost < 4 || $cost > 31) { + trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); + return null; + } + } + // The length of salt to generate + $raw_salt_len = 16; + // The length required in the final serialization + $required_salt_len = 22; + $hash_format = sprintf("$2y$%02d$", $cost); + break; + default: + trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); + return null; + } + if (isset($options['salt'])) { + switch (gettype($options['salt'])) { + case 'NULL': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $salt = (string) $options['salt']; + break; + case 'object': + if (method_exists($options['salt'], '__tostring')) { + $salt = (string) $options['salt']; + break; + } + case 'array': + case 'resource': + default: + trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); + return null; + } + if (strlen($salt) < $required_salt_len) { + trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING); + return null; + } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { + $salt = str_replace('+', '.', base64_encode($salt)); + } + } else { + $buffer = ''; + $buffer_valid = false; + if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { + $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { + $buffer = openssl_random_pseudo_bytes($raw_salt_len); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && is_readable('/dev/urandom')) { + $f = fopen('/dev/urandom', 'r'); + $read = strlen($buffer); + while ($read < $raw_salt_len) { + $buffer .= fread($f, $raw_salt_len - $read); + $read = strlen($buffer); + } + fclose($f); + if ($read >= $raw_salt_len) { + $buffer_valid = true; + } + } + if (!$buffer_valid || strlen($buffer) < $raw_salt_len) { + $bl = strlen($buffer); + for ($i = 0; $i < $raw_salt_len; $i++) { + if ($i < $bl) { + $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); + } else { + $buffer .= chr(mt_rand(0, 255)); + } + } + } + $salt = str_replace('+', '.', base64_encode($buffer)); + } + $salt = substr($salt, 0, $required_salt_len); + + $hash = $hash_format . $salt; + + $ret = crypt($password, $hash); + + if (!is_string($ret) || strlen($ret) <= 13) { + return false; + } + + return $ret; + } + + /** + * Get information about the password hash. Returns an array of the information + * that was used to generate the password hash. + * + * array( + * 'algo' => 1, + * 'algoName' => 'bcrypt', + * 'options' => array( + * 'cost' => 10, + * ), + * ) + * + * @param string $hash The password hash to extract info from + * + * @return array The array of information about the hash. + */ + function password_get_info($hash) { + $return = array( + 'algo' => 0, + 'algoName' => 'unknown', + 'options' => array(), + ); + if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { + $return['algo'] = PASSWORD_BCRYPT; + $return['algoName'] = 'bcrypt'; + list($cost) = sscanf($hash, "$2y$%d$"); + $return['options']['cost'] = $cost; + } + return $return; + } + + /** + * Determine if the password hash needs to be rehashed according to the options provided + * + * If the answer is true, after validating the password using password_verify, rehash it. + * + * @param string $hash The hash to test + * @param int $algo The algorithm used for new password hashes + * @param array $options The options array passed to password_hash + * + * @return boolean True if the password needs to be rehashed. + */ + function password_needs_rehash($hash, $algo, array $options = array()) { + $info = password_get_info($hash); + if ($info['algo'] != $algo) { + return true; + } + switch ($algo) { + case PASSWORD_BCRYPT: + $cost = isset($options['cost']) ? $options['cost'] : 10; + if ($cost != $info['options']['cost']) { + return true; + } + break; + } + return false; + } + + /** + * Verify a password against a hash using a timing attack resistant approach + * + * @param string $password The password to verify + * @param string $hash The hash to verify against + * + * @return boolean If the password matches the hash + */ + function password_verify($password, $hash) { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); + return false; + } + $ret = crypt($password, $hash); + if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) { + return false; + } + + $status = 0; + for ($i = 0; $i < strlen($ret); $i++) { + $status |= (ord($ret[$i]) ^ ord($hash[$i])); + } + + return $status === 0; + } +} + + + diff --git a/vendor/ircmaxell/password-compat/phpunit.xml.dist b/vendor/ircmaxell/password-compat/phpunit.xml.dist new file mode 100644 index 00000000..b2b3afbd --- /dev/null +++ b/vendor/ircmaxell/password-compat/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + test/Unit + + + + + lib/ + + + diff --git a/vendor/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php b/vendor/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php new file mode 100644 index 00000000..6aab976a --- /dev/null +++ b/vendor/ircmaxell/password-compat/test/Unit/PasswordGetInfoTest.php @@ -0,0 +1,26 @@ + 0, 'algoName' => 'unknown', 'options' => array())), + array('$2y$', array('algo' => 0, 'algoName' => 'unknown', 'options' => array())), + array('$2y$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', array('algo' => PASSWORD_BCRYPT, 'algoName' => 'bcrypt', 'options' => array('cost' => 7))), + array('$2y$10$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', array('algo' => PASSWORD_BCRYPT, 'algoName' => 'bcrypt', 'options' => array('cost' => 10))), + + ); + } + + public function testFuncExists() { + $this->assertTrue(function_exists('password_get_info')); + } + + /** + * @dataProvider provideInfo + */ + public function testInfo($hash, $info) { + $this->assertEquals($info, password_get_info($hash)); + } + +} \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/test/Unit/PasswordHashTest.php b/vendor/ircmaxell/password-compat/test/Unit/PasswordHashTest.php new file mode 100644 index 00000000..9e5e9ec6 --- /dev/null +++ b/vendor/ircmaxell/password-compat/test/Unit/PasswordHashTest.php @@ -0,0 +1,84 @@ +assertTrue(function_exists('password_hash')); + } + + public function testStringLength() { + $this->assertEquals(60, strlen(password_hash('foo', PASSWORD_BCRYPT))); + } + + public function testHash() { + $hash = password_hash('foo', PASSWORD_BCRYPT); + $this->assertEquals($hash, crypt('foo', $hash)); + } + + public function testKnownSalt() { + $hash = password_hash("rasmuslerdorf", PASSWORD_BCRYPT, array("cost" => 7, "salt" => "usesomesillystringforsalt")); + $this->assertEquals('$2y$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi', $hash); + } + + public function testRawSalt() { + $hash = password_hash("test", PASSWORD_BCRYPT, array("salt" => "123456789012345678901" . chr(0))); + $this->assertEquals('$2y$10$MTIzNDU2Nzg5MDEyMzQ1Nej0NmcAWSLR.oP7XOR9HD/vjUuOj100y', $hash); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidAlgo() { + password_hash('foo', array()); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidAlgo2() { + password_hash('foo', 2); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidPassword() { + password_hash(array(), 1); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidSalt() { + password_hash('foo', PASSWORD_BCRYPT, array('salt' => array())); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostLow() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 3)); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostHigh() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 32)); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptCostInvalid() { + password_hash('foo', PASSWORD_BCRYPT, array('cost' => 'foo')); + } + + /** + * @expectedException PHPUnit_Framework_Error + */ + public function testInvalidBcryptSaltShort() { + password_hash('foo', PASSWORD_BCRYPT, array('salt' => 'abc')); + } + +} \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php b/vendor/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php new file mode 100644 index 00000000..c2932dc6 --- /dev/null +++ b/vendor/ircmaxell/password-compat/test/Unit/PasswordNeedsRehashTest.php @@ -0,0 +1,26 @@ + 7), false), + array('$2y$07$usesomesillystringfore2udlvp1ii2e./u9c8sbjqp8i90dh6hi', PASSWORD_BCRYPT, array('cost' => 5), true), + ); + } + + public function testFuncExists() { + $this->assertTrue(function_exists('password_needs_rehash')); + } + + /** + * @dataProvider provideCases + */ + public function testCases($hash, $algo, $options, $valid) { + $this->assertEquals($valid, password_needs_rehash($hash, $algo, $options)); + } + +} \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php b/vendor/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php new file mode 100644 index 00000000..9f67bb9f --- /dev/null +++ b/vendor/ircmaxell/password-compat/test/Unit/PasswordVerifyTest.php @@ -0,0 +1,29 @@ +assertTrue(function_exists('password_verify')); + } + + public function testFailedType() { + $this->assertFalse(password_verify(123, 123)); + } + + public function testSaltOnly() { + $this->assertFalse(password_verify('foo', '$2a$07$usesomesillystringforsalt$')); + } + + public function testInvalidPassword() { + $this->assertFalse(password_verify('rasmusler', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi')); + } + + public function testValidPassword() { + $this->assertTrue(password_verify('rasmuslerdorf', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi')); + } + + public function testInValidHash() { + $this->assertFalse(password_verify('rasmuslerdorf', '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hj')); + } + +} \ No newline at end of file diff --git a/vendor/ircmaxell/password-compat/version-test.php b/vendor/ircmaxell/password-compat/version-test.php new file mode 100644 index 00000000..f527e30f --- /dev/null +++ b/vendor/ircmaxell/password-compat/version-test.php @@ -0,0 +1,8 @@ + +Contributions (c) 2013 Pieter Hordijk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/lusitanian/oauth/README.md b/vendor/lusitanian/oauth/README.md new file mode 100644 index 00000000..e7c2f792 --- /dev/null +++ b/vendor/lusitanian/oauth/README.md @@ -0,0 +1,102 @@ +PHPoAuthLib +=========== +PHPoAuthLib provides oAuth support in PHP 5.3+ and is very easy to integrate with any project which requires an oAuth client. + +[![Build Status](https://travis-ci.org/Lusitanian/PHPoAuthLib.png?branch=master)](https://travis-ci.org/Lusitanian/PHPoAuthLib) +[![Code Coverage](https://scrutinizer-ci.com/g/Lusitanian/PHPoAuthLib/badges/coverage.png?s=a0a15bebfda49e79f9ce289b00c6dfebd18fc98e)](https://scrutinizer-ci.com/g/Lusitanian/PHPoAuthLib/) +[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/Lusitanian/PHPoAuthLib/badges/quality-score.png?s=c5976d2fefceb501f0d886c1a5bf087e69b44533)](https://scrutinizer-ci.com/g/Lusitanian/PHPoAuthLib/) +[![Latest Stable Version](https://poser.pugx.org/lusitanian/oauth/v/stable.png)](https://packagist.org/packages/lusitanian/oauth) +[![Total Downloads](https://poser.pugx.org/lusitanian/oauth/downloads.png)](https://packagist.org/packages/lusitanian/oauth) + +Installation +------------ +This library can be found on [Packagist](https://packagist.org/packages/lusitanian/oauth). +The recommended way to install this is through [composer](http://getcomposer.org). + +Edit your `composer.json` and add: + +```json +{ + "require": { + "lusitanian/oauth": "~0.3" + } +} +``` + +And install dependencies: + +```bash +$ curl -sS https://getcomposer.org/installer | php +$ php composer.phar install +``` + +Features +-------- +- PSR-0 compliant for easy interoperability +- Fully extensible in every facet. + - You can implement any service with any custom requirements by extending the protocol version's `AbstractService` implementation. + - You can use any HTTP client you desire, just create a class utilizing it which implements `OAuth\Common\Http\ClientInterface` (two implementations are included) + - You can use any storage mechanism for tokens. By default, session, in-memory and Redis.io (requires PHPRedis) storage mechanisms are included. Implement additional mechanisms by implementing `OAuth\Common\Token\TokenStorageInterface`. + +Service support +--------------- +The library supports both oAuth 1.x and oAuth 2.0 compliant services. A list of currently implemented services can be found below. + +Included service implementations +-------------------------------- +- OAuth1 + - BitBucket + - Etsy + - FitBit + - Flickr + - Scoop.it! + - Tumblr + - Twitter + - Xing + - Yahoo +- OAuth2 + - Amazon + - BitLy + - Box + - Dailymotion + - Dropbox + - Facebook + - Foursquare + - GitHub + - Google + - Harvest + - Heroku + - Instagram + - LinkedIn + - Mailchimp + - Microsoft + - PayPal + - Pocket + - Reddit + - RunKeeper + - SoundCloud + - Ustream + - Vkontakte + - Yammer +- more to come! + +Examples +-------- +Examples of basic usage are located in the examples/ directory. + +Usage +------ +For usage with complete auth flow, please see the examples. More in-depth documentation will come with release 1.0. + +Framework Integration +--------------------- +* Lithium: Sébastien Charrier has written [an adapter](https://github.com/scharrier/li3_socialauth) for the library. +* Laravel 4: Dariusz Prząda has written [a service provider](https://github.com/artdarek/oauth-4-laravel) for the library. + +Extensions +---------- +* Extract normalized user data from OAuth Services with the library [PHPoAuthUserData](https://github.com/Oryzone/PHPoAuthUserData) by Luciano Mammino + +Tests +------ +To run the tests, you must install dependencies with `composer install --dev` diff --git a/vendor/lusitanian/oauth/composer.json b/vendor/lusitanian/oauth/composer.json new file mode 100644 index 00000000..cc0bdcf2 --- /dev/null +++ b/vendor/lusitanian/oauth/composer.json @@ -0,0 +1,40 @@ +{ + "name": "lusitanian/oauth", + "description": "PHP 5.3+ oAuth 1/2 Library", + "keywords": ["oauth", "authentication", "authorization", "security"], + "license": "MIT", + "authors": [ + { + "name": "David Desberg", + "email": "david@daviddesberg.com" + }, + { + "name": "Pieter Hordijk", + "email": "info@pieterhordijk.com" + } + ], + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "symfony/http-foundation": "~2.1", + "predis/predis": "0.8.*@dev", + "phpunit/phpunit": "3.7.*" + }, + "suggest": { + "symfony/http-foundation": "Allows using the Symfony Session storage backend.", + "predis/predis": "Allows using the Redis storage backend.", + "ext-openssl": "Allows for usage of secure connections with the stream-based HTTP client." + }, + "autoload": { + "psr-0": { + "OAuth": "src", + "OAuth\\Unit": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-master": "0.1-dev" + } + } +} diff --git a/vendor/lusitanian/oauth/examples/amazon.php b/vendor/lusitanian/oauth/examples/amazon.php new file mode 100644 index 00000000..0798eafc --- /dev/null +++ b/vendor/lusitanian/oauth/examples/amazon.php @@ -0,0 +1,52 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Amazon; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['amazon']['key'], + $servicesCredentials['amazon']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Amazon service using the credentials, http client, storage mechanism for the token and profile scope +/** @var $amazonService Amazon */ +$amazonService = $serviceFactory->createService('amazon', $credentials, $storage, array('profile')); + +if (!empty($_GET['code'])) { + // This was a callback request from Amazon, get the token + $token = $amazonService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($amazonService->request('/user/profile'), true); + + // Show some of the resultant data + echo 'Your unique Amazon user id is: ' . $result['user_id'] . ' and your name is ' . $result['name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $amazonService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Amazon!"; +} diff --git a/vendor/lusitanian/oauth/examples/bitbucket.php b/vendor/lusitanian/oauth/examples/bitbucket.php new file mode 100644 index 00000000..d9330961 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/bitbucket.php @@ -0,0 +1,64 @@ + + * + * Shamelessly cribbed from work by: + * @author David Desberg + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\BitBucket; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// We need to use a persistent storage to save the token, because oauth1 requires the token secret received before' +// the redirect (request token request) in the access token request. +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['bitbucket']['key'], + $servicesCredentials['bitbucket']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the BitBucket service using the credentials, http client and storage mechanism for the token +/** @var $bbService BitBucket */ +$bbService = $serviceFactory->createService('BitBucket', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('BitBucket'); + + // This was a callback request from BitBucket, get the token + $bbService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($bbService->request('user/repositories')); + + echo('The first repo in the list is ' . $result[0]->name); + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $bbService->requestRequestToken(); + + $url = $bbService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with BitBucket!"; +} diff --git a/vendor/lusitanian/oauth/examples/bitly.php b/vendor/lusitanian/oauth/examples/bitly.php new file mode 100644 index 00000000..9cd27e34 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/bitly.php @@ -0,0 +1,53 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Bitly; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['bitly']['key'], + $servicesCredentials['bitly']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Bitly service using the credentials, http client and storage mechanism for the token +/** @var $bitlyService Bitly */ +$bitlyService = $serviceFactory->createService('bitly', $credentials, $storage); + +if (!empty($_GET['code'])) { + // This was a callback request from bitly, get the token + $bitlyService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($bitlyService->request('user/info'), true); + + // Show some of the resultant data + echo 'Your unique user id is: ' . $result['data']['login'] . ' and your name is ' . $result['data']['display_name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $bitlyService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Bitly!"; +} diff --git a/vendor/lusitanian/oauth/examples/bootstrap.php b/vendor/lusitanian/oauth/examples/bootstrap.php new file mode 100644 index 00000000..f02da414 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/bootstrap.php @@ -0,0 +1,29 @@ +createFromSuperGlobalArray($_SERVER); +$currentUri->setQuery(''); + +/** + * Load the credential for the different services + */ +require_once __DIR__ . '/init.php'; diff --git a/vendor/lusitanian/oauth/examples/box.php b/vendor/lusitanian/oauth/examples/box.php new file mode 100644 index 00000000..f1b06443 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/box.php @@ -0,0 +1,58 @@ + + * @author Pieter Hordijk + * @author Antoine Corcy + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Box; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['box']['key'], + $servicesCredentials['box']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Box service using the credentials, http client and storage mechanism for the token +/** @var $boxService Box */ +$boxService = $serviceFactory->createService('box', $credentials, $storage); + +if (!empty($_GET['code'])) { + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + + // This was a callback request from box, get the token + $token = $boxService->requestAccessToken($_GET['code'], $state); + + // Send a request with it + $result = json_decode($boxService->request('/users/me'), true); + + // Show some of the resultant data + echo 'Your Box name is ' . $result['name'] . ' and your email is ' . $result['login']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $boxService->getAuthorizationUri(); + // var_dump($url); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Box!"; +} diff --git a/vendor/lusitanian/oauth/examples/buffer.php b/vendor/lusitanian/oauth/examples/buffer.php new file mode 100644 index 00000000..c1b9ddde --- /dev/null +++ b/vendor/lusitanian/oauth/examples/buffer.php @@ -0,0 +1,53 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Buffer; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['buffer']['key'], + $servicesCredentials['buffer']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the buffer service using the credentials, http client and storage mechanism for the token +/** @var $bufferService buffer */ +$bufferService = $serviceFactory->createService('buffer', $credentials, $storage); + +if (!empty($_GET['code'])) { + // This was a callback request from buffer, get the token + $bufferService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($bufferService->request('user.json'), true); + + // Show some of the resultant data + echo 'Your unique user id is: ' . $result['id'] . ' and your plan is ' . $result['plan']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $bufferService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with buffer!"; +} diff --git a/vendor/lusitanian/oauth/examples/dailymotion.php b/vendor/lusitanian/oauth/examples/dailymotion.php new file mode 100644 index 00000000..53f0878a --- /dev/null +++ b/vendor/lusitanian/oauth/examples/dailymotion.php @@ -0,0 +1,52 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Dailymotion; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['dailymotion']['key'], + $servicesCredentials['dailymotion']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Dailymotion service using the credentials, http client, storage mechanism for the token and email scope +/** @var $dailymotionService Dailymotion */ +$dailymotionService = $serviceFactory->createService('dailymotion', $credentials, $storage, array('email')); + +if (!empty($_GET['code'])) { + // This was a callback request from Dailymotion, get the token + $token = $dailymotionService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($dailymotionService->request('/me?fields=email,id'), true); + + // Show some of the resultant data + echo 'Your unique Dailymotion user id is: ' . $result['id'] . ' and your email is ' . $result['email']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $dailymotionService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Dailymotion!"; +} diff --git a/vendor/lusitanian/oauth/examples/dropbox.php b/vendor/lusitanian/oauth/examples/dropbox.php new file mode 100644 index 00000000..0d60551c --- /dev/null +++ b/vendor/lusitanian/oauth/examples/dropbox.php @@ -0,0 +1,52 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Dropbox; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['dropbox']['key'], + $servicesCredentials['dropbox']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Dropbox service using the credentials, http client and storage mechanism for the token +/** @var $dropboxService Dropbox */ +$dropboxService = $serviceFactory->createService('dropbox', $credentials, $storage, array()); + +if (!empty($_GET['code'])) { + // This was a callback request from Dropbox, get the token + $token = $dropboxService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($dropboxService->request('/account/info'), true); + + // Show some of the resultant data + echo 'Your unique Dropbox user id is: ' . $result['uid'] . ' and your name is ' . $result['display_name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $dropboxService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Dropbox!"; +} diff --git a/vendor/lusitanian/oauth/examples/etsy.php b/vendor/lusitanian/oauth/examples/etsy.php new file mode 100644 index 00000000..0c0b79b7 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/etsy.php @@ -0,0 +1,59 @@ + + * @copyright Copyright (c) 2013 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\Etsy; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['etsy']['key'], + $servicesCredentials['etsy']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Etsy service using the credentials, http client and storage mechanism for the token +/** @var $etsyService Etsy */ +$etsyService = $serviceFactory->createService('Etsy', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('Etsy'); + + // This was a callback request from Etsy, get the token + $etsyService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($etsyService->request('/private/users/__SELF__')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $response = $etsyService->requestRequestToken(); + $extra = $response->getExtraParams(); + $url = $extra['login_url']; + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Etsy!"; +} diff --git a/vendor/lusitanian/oauth/examples/facebook.php b/vendor/lusitanian/oauth/examples/facebook.php new file mode 100644 index 00000000..b6426721 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/facebook.php @@ -0,0 +1,54 @@ + + * @author David Desberg + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Facebook; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['facebook']['key'], + $servicesCredentials['facebook']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Facebook service using the credentials, http client and storage mechanism for the token +/** @var $facebookService Facebook */ +$facebookService = $serviceFactory->createService('facebook', $credentials, $storage, array()); + +if (!empty($_GET['code'])) { + // This was a callback request from facebook, get the token + $token = $facebookService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($facebookService->request('/me'), true); + + // Show some of the resultant data + echo 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $facebookService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Facebook!"; +} diff --git a/vendor/lusitanian/oauth/examples/fitbit.php b/vendor/lusitanian/oauth/examples/fitbit.php new file mode 100644 index 00000000..35b3d09f --- /dev/null +++ b/vendor/lusitanian/oauth/examples/fitbit.php @@ -0,0 +1,61 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\FitBit; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['fitbit']['key'], + $servicesCredentials['fitbit']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the FitBit service using the credentials, http client and storage mechanism for the token +/** @var $fitbitService FitBit */ +$fitbitService = $serviceFactory->createService('FitBit', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('FitBit'); + + // This was a callback request from fitbit, get the token + $fitbitService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($fitbitService->request('user/-/profile.json')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $fitbitService->requestRequestToken(); + + $url = $fitbitService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with FitBit!"; +} diff --git a/vendor/lusitanian/oauth/examples/flickr.php b/vendor/lusitanian/oauth/examples/flickr.php new file mode 100644 index 00000000..f7a80f67 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/flickr.php @@ -0,0 +1,80 @@ + + * @copyright Copyright (c) 2013 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\Flickr; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; +use OAuth\Common\Http\Client\CurlClient; + +/** + * Bootstrap the example + */ +require_once __DIR__.'/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['flickr']['key'], + $servicesCredentials['flickr']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Flickr service using the credentials, http client and storage mechanism for the token +$flickrService = $serviceFactory->createService('Flickr', $credentials, $storage); + +$step = isset($_GET['step']) ? (int)$_GET['step'] : null; + +$oauth_token = isset($_GET['oauth_token']) ? $_GET['oauth_token'] : null; +$oauth_verifier = isset($_GET['oauth_verifier']) ? $_GET['oauth_verifier'] : null; + +if($oauth_token && $oauth_verifier){ + $step = 2; +} + +switch($step){ + default: + print "Login with Flickr!"; + break; + + case 1: + + if($token = $flickrService->requestRequestToken()){ + $oauth_token = $token->getAccessToken(); + $secret = $token->getAccessTokenSecret(); + + if($oauth_token && $secret){ + $url = $flickrService->getAuthorizationUri(array('oauth_token' => $oauth_token, 'perms' => 'write')); + header('Location: '.$url); + } + } + + break; + + case 2: + $token = $storage->retrieveAccessToken('Flickr'); + $secret = $token->getAccessTokenSecret(); + + if($token = $flickrService->requestAccessToken($oauth_token, $oauth_verifier, $secret)){ + $oauth_token = $token->getAccessToken(); + $secret = $token->getAccessTokenSecret(); + + $storage->storeAccessToken('Flickr', $token); + + header('Location: '.$currentUri->getAbsoluteUri().'?step=3'); + } + break; + + case 3: + $xml = simplexml_load_string($flickrService->request('flickr.test.login')); + print "status: ".(string)$xml->attributes()->stat."\n"; + break; +} diff --git a/vendor/lusitanian/oauth/examples/foursquare.php b/vendor/lusitanian/oauth/examples/foursquare.php new file mode 100644 index 00000000..f7920724 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/foursquare.php @@ -0,0 +1,53 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Foursquare; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['foursquare']['key'], + $servicesCredentials['foursquare']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Foursquare service using the credentials, http client and storage mechanism for the token +/** @var $foursquareService Foursquare */ +$foursquareService = $serviceFactory->createService('foursquare', $credentials, $storage); + +if (!empty($_GET['code'])) { + // This was a callback request from foursquare, get the token + $foursquareService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($foursquareService->request('users/self'), true); + + // Show some of the resultant data + echo 'Your unique foursquare user id is: ' . $result['response']['user']['id'] . ' and your name is ' . $result['response']['user']['firstName'] . $result['response']['user']['lastName']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $foursquareService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Foursquare!"; +} diff --git a/vendor/lusitanian/oauth/examples/github.php b/vendor/lusitanian/oauth/examples/github.php new file mode 100644 index 00000000..23e971f8 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/github.php @@ -0,0 +1,52 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\GitHub; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['github']['key'], + $servicesCredentials['github']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the GitHub service using the credentials, http client and storage mechanism for the token +/** @var $gitHub GitHub */ +$gitHub = $serviceFactory->createService('GitHub', $credentials, $storage, array('user')); + +if (!empty($_GET['code'])) { + // This was a callback request from github, get the token + $gitHub->requestAccessToken($_GET['code']); + + $result = json_decode($gitHub->request('user/emails'), true); + + echo 'The first email on your github account is ' . $result[0]; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $gitHub->getAuthorizationUri(); + header('Location: ' . $url); + +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Github!"; +} diff --git a/vendor/lusitanian/oauth/examples/google.php b/vendor/lusitanian/oauth/examples/google.php new file mode 100644 index 00000000..f05a03e0 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/google.php @@ -0,0 +1,53 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Google; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['google']['key'], + $servicesCredentials['google']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Google service using the credentials, http client and storage mechanism for the token +/** @var $googleService Google */ +$googleService = $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile')); + +if (!empty($_GET['code'])) { + // This was a callback request from google, get the token + $googleService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true); + + // Show some of the resultant data + echo 'Your unique google user id is: ' . $result['id'] . ' and your name is ' . $result['name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $googleService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Google!"; +} diff --git a/vendor/lusitanian/oauth/examples/harvest.php b/vendor/lusitanian/oauth/examples/harvest.php new file mode 100644 index 00000000..1d11584a --- /dev/null +++ b/vendor/lusitanian/oauth/examples/harvest.php @@ -0,0 +1,74 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\Common\Consumer\Credentials; +use OAuth\Common\Storage\Session; +use OAuth\Common\Token\Exception\ExpiredTokenException; +use OAuth\OAuth2\Service\Harvest; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +$serviceName = 'Harvest'; +$scopes = array(); + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['harvest']['key'], + $servicesCredentials['harvest']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Harvest service using the credentials, http client and storage mechanism for the token +/** @var $harves Harves */ +$harvest = $serviceFactory->createService($serviceName, $credentials, $storage, $scopes); + +if (!empty($_GET['clearToken'])) { + // Clear the current AccessToken and go back to the Beginning. + $storage->clearToken($serviceName); + header('Location: ' . $currentUri->getAbsoluteUri()); + +} elseif ($storage->hasAccessToken($serviceName)) { + // fetch the accessToken for the service + $accessToken = $storage->retrieveAccessToken($serviceName); + + // is the accessToken expired? then let's refesh it! + if ($accessToken->isExpired() === TRUE) { + $harvest->refreshAccessToken($accessToken); + } + + // use the service with the valid access token to fetch my email + $result = json_decode($harvest->request('account/who_am_i'), true); + echo 'The email on your harvest account is ' . $result['user']['email']; + + $url = $currentUri->getRelativeUri() . '?clearToken=1'; + echo " Click here to clear the current access token"; + +} elseif (!empty($_GET['code'])) { + // This was a callback request from harvest, get the token + $harvest->requestAccessToken($_GET['code']); + header('Location: ' . $currentUri->getAbsoluteUri()); + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // Redirect to the Authorization uri + $url = $harvest->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Harvest!"; +} diff --git a/vendor/lusitanian/oauth/examples/init.example.php b/vendor/lusitanian/oauth/examples/init.example.php new file mode 100644 index 00000000..fb6aee40 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/init.example.php @@ -0,0 +1,136 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +/** + * @var array A list of all the credentials to be used by the different services in the examples + */ +$servicesCredentials = array( + 'amazon' => array( + 'key' => '', + 'secret' => '', + ), + 'bitbucket' => array( + 'key' => '', + 'secret' => '', + ), + 'bitly' => array( + 'key' => '', + 'secret' => '', + ), + 'box' => array( + 'key' => '', + 'secret' => '', + ), + 'buffer' => array( + 'key' => '', + 'secret' => '', + ), + 'dailymotion' => array( + 'key' => '', + 'secret' => '', + ), + 'dropbox' => array( + 'key' => '', + 'secret' => '', + ), + 'etsy' => array( + 'key' => '', + 'secret' => '', + ), + 'facebook' => array( + 'key' => '', + 'secret' => '', + ), + 'fitbit' => array( + 'key' => '', + 'secret' => '', + ), + 'flickr' => array( + 'key' => '', + 'secret' => '', + ), + 'foursquare' => array( + 'key' => '', + 'secret' => '', + ), + 'github' => array( + 'key' => '', + 'secret' => '', + ), + 'google' => array( + 'key' => '', + 'secret' => '', + ), + 'instagram' => array( + 'key' => '', + 'secret' => '', + ), + 'linkedin' => array( + 'key' => '', + 'secret' => '', + ), + 'mailchimp' => array( + 'key' => '', + 'secret' => '', + ), + 'microsoft' => array( + 'key' => '', + 'secret' => '', + ), + 'paypal' => array( + 'key' => '', + 'secret' => '', + ), + 'pocket' => array( + 'key' => '', + ), + 'reddit' => array( + 'key' => '', + 'secret' => '', + ), + 'runkeeper' => array( + 'key' => '', + 'secret' => '', + ), + 'scoopit' => array( + 'key' => '', + 'secret' => '' + ), + 'soundcloud' => array( + 'key' => '', + 'secret' => '', + ), + 'tumblr' => array( + 'key' => '', + 'secret' => '', + ), + 'twitter' => array( + 'key' => '', + 'secret' => '', + ), + 'ustream' => array( + 'key' => '', + 'secret' => '', + ), + 'yahoo' => array( + 'key' => '', + 'secret' => '' + ), + 'yammer' => array( + 'key' => '', + 'secret' => '' + ), +); + +/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */ +$serviceFactory = new \OAuth\ServiceFactory(); diff --git a/vendor/lusitanian/oauth/examples/instagram.php b/vendor/lusitanian/oauth/examples/instagram.php new file mode 100644 index 00000000..2e44094c --- /dev/null +++ b/vendor/lusitanian/oauth/examples/instagram.php @@ -0,0 +1,56 @@ + + * @author Pieter Hordijk + * @author Hannes Van De Vreken + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Instagram; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['instagram']['key'], + $servicesCredentials['instagram']['secret'], + $currentUri->getAbsoluteUri() +); + +$scopes = array('basic', 'comments', 'relationships', 'likes'); + +// Instantiate the Instagram service using the credentials, http client and storage mechanism for the token +/** @var $instagramService Instagram */ +$instagramService = $serviceFactory->createService('instagram', $credentials, $storage, $scopes); + +if (!empty($_GET['code'])) { + // This was a callback request from Instagram, get the token + $instagramService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($instagramService->request('users/self'), true); + + // Show some of the resultant data + echo 'Your unique instagram user id is: ' . $result['data']['id'] . ' and your name is ' . $result['data']['full_name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $instagramService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Instagram!"; +} diff --git a/vendor/lusitanian/oauth/examples/linkedin.php b/vendor/lusitanian/oauth/examples/linkedin.php new file mode 100644 index 00000000..db14ab25 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/linkedin.php @@ -0,0 +1,57 @@ + + * @author Pieter Hordijk + * @author Antoine Corcy + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Linkedin; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['linkedin']['key'], + $servicesCredentials['linkedin']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Linkedin service using the credentials, http client and storage mechanism for the token +/** @var $linkedinService Linkedin */ +$linkedinService = $serviceFactory->createService('linkedin', $credentials, $storage, array('r_basicprofile')); + +if (!empty($_GET['code'])) { + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + + // This was a callback request from linkedin, get the token + $token = $linkedinService->requestAccessToken($_GET['code'], $state); + + // Send a request with it. Please note that XML is the default format. + $result = json_decode($linkedinService->request('/people/~?format=json'), true); + + // Show some of the resultant data + echo 'Your linkedin first name is ' . $result['firstName'] . ' and your last name is ' . $result['lastName']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $linkedinService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Linkedin!"; +} diff --git a/vendor/lusitanian/oauth/examples/mailchimp.php b/vendor/lusitanian/oauth/examples/mailchimp.php new file mode 100644 index 00000000..dd7e12bd --- /dev/null +++ b/vendor/lusitanian/oauth/examples/mailchimp.php @@ -0,0 +1,55 @@ + + * @author Hannes Van De Vreken + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Mailchimp; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +$_SERVER['SERVER_PORT'] = 80; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['mailchimp']['key'], + $servicesCredentials['mailchimp']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Mailchimp service using the credentials, http client and storage mechanism for the token +/** @var $mailchimpService Mailchimp */ +$mailchimpService = $serviceFactory->createService('mailchimp', $credentials, $storage, array()); + +if (!empty($_GET['code'])) { + // This was a callback request from mailchimp, get the token + $token = $mailchimpService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = $mailchimpService->request('/users/profile.json'); + + header('Content-Type: application/json'); + echo $result; exit; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $mailchimpService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Mailchimp!"; +} diff --git a/vendor/lusitanian/oauth/examples/microsoft.php b/vendor/lusitanian/oauth/examples/microsoft.php new file mode 100644 index 00000000..1edb13f1 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/microsoft.php @@ -0,0 +1,49 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Microsoft; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['microsoft']['key'], + $servicesCredentials['microsoft']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Microsoft service using the credentials, http client and storage mechanism for the token +/** @var $microsoft Microsoft */ +$microsoft = $serviceFactory->createService('microsoft', $credentials, $storage, array('basic')); + +if (!empty($_GET['code'])) { + // This was a callback request from Microsoft, get the token + $token = $microsoft->requestAccessToken($_GET['code']); + + var_dump($token); + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $microsoft->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Microsoft!"; +} diff --git a/vendor/lusitanian/oauth/examples/paypal.php b/vendor/lusitanian/oauth/examples/paypal.php new file mode 100644 index 00000000..207357f2 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/paypal.php @@ -0,0 +1,52 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Paypal; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['paypal']['key'], + $servicesCredentials['paypal']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the PayPal service using the credentials, http client, storage mechanism for the token and profile/openid scopes +/** @var $paypalService PayPal */ +$paypalService = $serviceFactory->createService('paypal', $credentials, $storage, array('profile', 'openid')); + +if (!empty($_GET['code'])) { + // This was a callback request from PayPal, get the token + $token = $paypalService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($paypalService->request('/identity/openidconnect/userinfo/?schema=openid'), true); + + // Show some of the resultant data + echo 'Your unique PayPal user id is: ' . $result['user_id'] . ' and your name is ' . $result['name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $paypalService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with PayPal!"; +} diff --git a/vendor/lusitanian/oauth/examples/pocket.php b/vendor/lusitanian/oauth/examples/pocket.php new file mode 100644 index 00000000..b96d2ace --- /dev/null +++ b/vendor/lusitanian/oauth/examples/pocket.php @@ -0,0 +1,63 @@ + + * @copyright Copyright (c) 2014 Christian Mayer + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Pocket; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; +use OAuth\Common\Http\Client\CurlClient; + +/** + * Bootstrap the example + */ +require_once __DIR__.'/bootstrap.php'; + +$step = isset($_GET['step']) ? (int)$_GET['step'] : null; +$code = isset($_GET['code']) ? $_GET['code'] : null; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['pocket']['key'], + null, // Pocket API doesn't have a secret key. :S + $currentUri->getAbsoluteUri().($code ? '?step=3&code='.$code : '') +); + +// Instantiate the Pocket service using the credentials, http client and storage mechanism for the token +$pocketService = $serviceFactory->createService('Pocket', $credentials, $storage); + +switch($step){ + default: + print 'Login with Pocket'; + + break; + + case 1: + $code = $pocketService->requestRequestToken(); + header('Location: '.$currentUri->getRelativeUri().'?step=2&code='.$code); + + break; + + case 2: + $url = $pocketService->getAuthorizationUri(array('request_token' => $code)); + header('Location: '.$url); + + break; + + case 3: + $token = $pocketService->requestAccessToken($code); + $accessToken = $token->getAccessToken(); + $extraParams = $token->getExtraParams(); + + print 'User: '.$extraParams['username'].'
'; + print 'Access Token: '.$accessToken; + break; +} diff --git a/vendor/lusitanian/oauth/examples/reddit.php b/vendor/lusitanian/oauth/examples/reddit.php new file mode 100644 index 00000000..7363d840 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/reddit.php @@ -0,0 +1,54 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Reddit; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['reddit']['key'], + $servicesCredentials['reddit']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Reddit service using the credentials, http client and storage mechanism for the token +/** @var $reddit Reddit */ +$reddit = $serviceFactory->createService('Reddit', $credentials, $storage, array('identity')); + +if (!empty($_GET['code'])) { + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + + // This was a callback request from reddit, get the token + $reddit->requestAccessToken($_GET['code'], $state); + + $result = json_decode($reddit->request('api/v1/me.json'), true); + + echo 'Your unique reddit user id is: ' . $result['id'] . ' and your username is ' . $result['name']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $reddit->getAuthorizationUri(); + header('Location: ' . $url); + +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Reddit!"; +} diff --git a/vendor/lusitanian/oauth/examples/runkeeper.php b/vendor/lusitanian/oauth/examples/runkeeper.php new file mode 100644 index 00000000..61a203f9 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/runkeeper.php @@ -0,0 +1,51 @@ +getAbsoluteUri() +); + +// Instantiate the Runkeeper service using the credentials, http client and storage mechanism for the token +/** @var $runkeeperService RunKeeper */ +$runkeeperService = $serviceFactory->createService('RunKeeper', $credentials, $storage, array()); + +if (!empty($_GET['code'])) { + // This was a callback request from RunKeeper, get the token + $token = $runkeeperService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($runkeeperService->request('/user'), true); + + // Show some of the resultant data + echo 'Your unique RunKeeper user id is: ' . $result['userID']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $runkeeperService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with RunKeeper!"; +} diff --git a/vendor/lusitanian/oauth/examples/scoopit.php b/vendor/lusitanian/oauth/examples/scoopit.php new file mode 100644 index 00000000..cc1c103b --- /dev/null +++ b/vendor/lusitanian/oauth/examples/scoopit.php @@ -0,0 +1,57 @@ + + * @copyright Copyright (c) 2013 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\ScoopIt; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__.'/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['scoopit']['key'], + $servicesCredentials['scoopit']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the ScoopIt service using the credentials, http client and storage mechanism for the token +$scoopItService = $serviceFactory->createService('ScoopIt', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('ScoopIt'); + + // This was a callback request from ScoopIt, get the token + $scoopItService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($scoopItService->request('profile')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $scoopItService->requestRequestToken(); + + $url = $scoopItService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with ScoopIt!"; +} diff --git a/vendor/lusitanian/oauth/examples/soundcloud.php b/vendor/lusitanian/oauth/examples/soundcloud.php new file mode 100644 index 00000000..2629490b --- /dev/null +++ b/vendor/lusitanian/oauth/examples/soundcloud.php @@ -0,0 +1,53 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\SoundCloud; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['soundcloud']['key'], + $servicesCredentials['soundcloud']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the SoundCloud service using the credentials, http client and storage mechanism for the token +/** @var $soundcloudService SoundCloud */ +$soundcloudService = $serviceFactory->createService('soundCloud', $credentials, $storage); + +if (!empty($_GET['code'])) { + // This was a callback request from SoundCloud, get the token + $soundcloudService->requestAccessToken($_GET['code']); + + // Send a request with it + $result = json_decode($soundcloudService->request('me.json'), true); + + // Show some of the resultant data + echo 'Your unique user id is: ' . $result['id'] . ' and your name is ' . $result['username']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $soundcloudService->getAuthorizationUri(); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with SoundCloud!"; +} diff --git a/vendor/lusitanian/oauth/examples/tumblr.php b/vendor/lusitanian/oauth/examples/tumblr.php new file mode 100644 index 00000000..bde0521b --- /dev/null +++ b/vendor/lusitanian/oauth/examples/tumblr.php @@ -0,0 +1,62 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\Tumblr; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// We need to use a persistent storage to save the token, because oauth1 requires the token secret received before' +// the redirect (request token request) in the access token request. +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['tumblr']['key'], + $servicesCredentials['tumblr']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the tumblr service using the credentials, http client and storage mechanism for the token +/** @var $tumblrService Tumblr */ +$tumblrService = $serviceFactory->createService('tumblr', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('Tumblr'); + + // This was a callback request from tumblr, get the token + $tumblrService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($tumblrService->request('user/info')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $tumblrService->requestRequestToken(); + + $url = $tumblrService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Tumblr!"; +} diff --git a/vendor/lusitanian/oauth/examples/twitter.php b/vendor/lusitanian/oauth/examples/twitter.php new file mode 100644 index 00000000..6b14a222 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/twitter.php @@ -0,0 +1,62 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\Twitter; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// We need to use a persistent storage to save the token, because oauth1 requires the token secret received before' +// the redirect (request token request) in the access token request. +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['twitter']['key'], + $servicesCredentials['twitter']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the twitter service using the credentials, http client and storage mechanism for the token +/** @var $twitterService Twitter */ +$twitterService = $serviceFactory->createService('twitter', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('Twitter'); + + // This was a callback request from twitter, get the token + $twitterService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($twitterService->request('account/verify_credentials.json')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $twitterService->requestRequestToken(); + + $url = $twitterService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Twitter!"; +} diff --git a/vendor/lusitanian/oauth/examples/ustream.php b/vendor/lusitanian/oauth/examples/ustream.php new file mode 100644 index 00000000..e3ca0bb4 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/ustream.php @@ -0,0 +1,54 @@ + + * @copyright Copyright (c) 2014 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth2\Service\Ustream; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__ . '/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['ustream']['key'], + $servicesCredentials['ustream']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Ustream service using the credentials, http client and storage mechanism for the token +/** @var $ustream Ustream */ +$ustream = $serviceFactory->createService('Ustream', $credentials, $storage, array('identity')); + +if (!empty($_GET['code'])) { + // retrieve the CSRF state parameter + $state = isset($_GET['state']) ? $_GET['state'] : null; + + // This was a callback request from Ustream, get the token + $ustream->requestAccessToken($_GET['code'], $state); + + $result = json_decode($ustream->request('users/self.json'), true); + + echo 'Your unique Ustream user id is: ' . $result['id'] . ' and your username is ' . $result['username']; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + $url = $ustream->getAuthorizationUri(); + header('Location: ' . $url); + +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Ustream!"; +} diff --git a/vendor/lusitanian/oauth/examples/yahoo.php b/vendor/lusitanian/oauth/examples/yahoo.php new file mode 100644 index 00000000..549332e9 --- /dev/null +++ b/vendor/lusitanian/oauth/examples/yahoo.php @@ -0,0 +1,57 @@ + + * @copyright Copyright (c) 2014 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +use OAuth\OAuth1\Service\Yahoo; +use OAuth\Common\Storage\Session; +use OAuth\Common\Consumer\Credentials; + +/** + * Bootstrap the example + */ +require_once __DIR__.'/bootstrap.php'; + +// Session storage +$storage = new Session(); + +// Setup the credentials for the requests +$credentials = new Credentials( + $servicesCredentials['yahoo']['key'], + $servicesCredentials['yahoo']['secret'], + $currentUri->getAbsoluteUri() +); + +// Instantiate the Yahoo service using the credentials, http client and storage mechanism for the token +$yahooService = $serviceFactory->createService('Yahoo', $credentials, $storage); + +if (!empty($_GET['oauth_token'])) { + $token = $storage->retrieveAccessToken('Yahoo'); + + // This was a callback request from Yahoo, get the token + $yahooService->requestAccessToken( + $_GET['oauth_token'], + $_GET['oauth_verifier'], + $token->getRequestTokenSecret() + ); + + // Send a request now that we have access token + $result = json_decode($yahooService->request('profile')); + + echo 'result:
' . print_r($result, true) . '
'; + +} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') { + // extra request needed for oauth1 to request a request token :-) + $token = $yahooService->requestRequestToken(); + + $url = $yahooService->getAuthorizationUri(array('oauth_token' => $token->getRequestToken())); + header('Location: ' . $url); +} else { + $url = $currentUri->getRelativeUri() . '?go=go'; + echo "Login with Yahoo!"; +} diff --git a/vendor/lusitanian/oauth/phpunit.xml.dist b/vendor/lusitanian/oauth/phpunit.xml.dist new file mode 100644 index 00000000..ee281953 --- /dev/null +++ b/vendor/lusitanian/oauth/phpunit.xml.dist @@ -0,0 +1,45 @@ + + + + + tests/Unit + + + + + src/ + + src/OAuth/bootstrap.php + src/OAuth/Common/Exception/Exception.php + src/OAuth/Common/Http/Exception/TokenResponseException.php + src/OAuth/Common/Storage/Exception/StorageException.php + src/OAuth/Common/Storage/Exception/TokenNotFoundException.php + src/OAuth/Common/Token/Exception/ExpiredTokenException.php + src/OAuth/OAuth1/Signature/Exception/UnsupportedHashAlgorithmException.php + src/OAuth/OAuth2/Service/Exception/InvalidScopeException.php + src/OAuth/OAuth2/Service/Exception/MissingRefreshTokenException.php + src/OAuth/OAuth2/Token/StdOAuth2Token.php + + + + + + + + diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/AutoLoader.php b/vendor/lusitanian/oauth/src/OAuth/Common/AutoLoader.php new file mode 100644 index 00000000..9fe7951c --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/AutoLoader.php @@ -0,0 +1,81 @@ + + */ +class AutoLoader +{ + /** + * @var string The namespace prefix for this instance. + */ + protected $namespace = ''; + + /** + * @var string The filesystem prefix to use for this instance + */ + protected $path = ''; + + /** + * Build the instance of the autoloader + * + * @param string $namespace The prefixed namespace this instance will load + * @param string $path The filesystem path to the root of the namespace + */ + public function __construct($namespace, $path) + { + $this->namespace = ltrim($namespace, '\\'); + $this->path = rtrim($path, '/\\') . DIRECTORY_SEPARATOR; + } + + /** + * Try to load a class + * + * @param string $class The class name to load + * + * @return boolean If the loading was successful + */ + public function load($class) + { + $class = ltrim($class, '\\'); + + if (strpos($class, $this->namespace) === 0) { + $nsparts = explode('\\', $class); + $class = array_pop($nsparts); + $nsparts[] = ''; + $path = $this->path . implode(DIRECTORY_SEPARATOR, $nsparts); + $path .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php'; + + if (file_exists($path)) { + require $path; + + return true; + } + } + + return false; + } + + /** + * Register the autoloader to PHP + * + * @return boolean The status of the registration + */ + public function register() + { + return spl_autoload_register(array($this, 'load')); + } + + /** + * Unregister the autoloader to PHP + * + * @return boolean The status of the unregistration + */ + public function unregister() + { + return spl_autoload_unregister(array($this, 'load')); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/Credentials.php b/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/Credentials.php new file mode 100644 index 00000000..8e98e9fa --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/Credentials.php @@ -0,0 +1,60 @@ +consumerId = $consumerId; + $this->consumerSecret = $consumerSecret; + $this->callbackUrl = $callbackUrl; + } + + /** + * @return string + */ + public function getCallbackUrl() + { + return $this->callbackUrl; + } + + /** + * @return string + */ + public function getConsumerId() + { + return $this->consumerId; + } + + /** + * @return string + */ + public function getConsumerSecret() + { + return $this->consumerSecret; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/CredentialsInterface.php b/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/CredentialsInterface.php new file mode 100644 index 00000000..a33e54e9 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Consumer/CredentialsInterface.php @@ -0,0 +1,24 @@ +userAgent = $userAgent; + } + + /** + * @param int $redirects Maximum redirects for client + * + * @return ClientInterface + */ + public function setMaxRedirects($redirects) + { + $this->maxRedirects = $redirects; + + return $this; + } + + /** + * @param int $timeout Request timeout time for client in seconds + * + * @return ClientInterface + */ + public function setTimeout($timeout) + { + $this->timeout = $timeout; + + return $this; + } + + /** + * @param array $headers + */ + public function normalizeHeaders(&$headers) + { + // Normalize headers + array_walk( + $headers, + function (&$val, &$key) { + $key = ucfirst(strtolower($key)); + $val = ucfirst(strtolower($key)) . ': ' . $val; + } + ); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/ClientInterface.php b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/ClientInterface.php new file mode 100644 index 00000000..f9c20226 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/ClientInterface.php @@ -0,0 +1,32 @@ + value` pairs) to be passed to `curl_setopt` + * + * @var array + */ + private $parameters = array(); + + /** + * Additional `curl_setopt` parameters + * + * @param array $parameters + */ + public function setCurlParameters(array $parameters) + { + $this->parameters = $parameters; + } + + /** + * @param bool $force + * + * @return CurlClient + */ + public function setForceSSL3($force) + { + $this->forceSSL3 = $force; + + return $this; + } + + /** + * Any implementing HTTP providers should send a request to the provided endpoint with the parameters. + * They should return, in string form, the response body and throw an exception on error. + * + * @param UriInterface $endpoint + * @param mixed $requestBody + * @param array $extraHeaders + * @param string $method + * + * @return string + * + * @throws TokenResponseException + * @throws \InvalidArgumentException + */ + public function retrieveResponse( + UriInterface $endpoint, + $requestBody, + array $extraHeaders = array(), + $method = 'POST' + ) { + // Normalize method name + $method = strtoupper($method); + + $this->normalizeHeaders($extraHeaders); + + if ($method === 'GET' && !empty($requestBody)) { + throw new \InvalidArgumentException('No body expected for "GET" request.'); + } + + if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) { + $extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded'; + } + + $extraHeaders['Host'] = 'Host: '.$endpoint->getHost(); + $extraHeaders['Connection'] = 'Connection: close'; + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL, $endpoint->getAbsoluteUri()); + + if ($method === 'POST' || $method === 'PUT') { + if ($requestBody && is_array($requestBody)) { + $requestBody = http_build_query($requestBody, '', '&'); + } + + if ($method === 'PUT') { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); + } else { + curl_setopt($ch, CURLOPT_POST, true); + } + + curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody); + } else { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + } + + if ($this->maxRedirects > 0) { + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_MAXREDIRS, $this->maxRedirects); + } + + curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, $extraHeaders); + curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent); + + foreach ($this->parameters as $key => $value) { + curl_setopt($ch, $key, $value); + } + + if ($this->forceSSL3) { + curl_setopt($ch, CURLOPT_SSLVERSION, 3); + } + + $response = curl_exec($ch); + $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + if (false === $response) { + $errNo = curl_errno($ch); + $errStr = curl_error($ch); + curl_close($ch); + if (empty($errStr)) { + throw new TokenResponseException('Failed to request resource.', $responseCode); + } + throw new TokenResponseException('cURL Error # '.$errNo.': '.$errStr, $responseCode); + } + + curl_close($ch); + + return $response; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/StreamClient.php b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/StreamClient.php new file mode 100644 index 00000000..7f3c5249 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Client/StreamClient.php @@ -0,0 +1,92 @@ +normalizeHeaders($extraHeaders); + + if ($method === 'GET' && !empty($requestBody)) { + throw new \InvalidArgumentException('No body expected for "GET" request.'); + } + + if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) { + $extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded'; + } + + $host = 'Host: '.$endpoint->getHost(); + // Append port to Host if it has been specified + if ($endpoint->hasExplicitPortSpecified()) { + $host .= ':'.$endpoint->getPort(); + } + + $extraHeaders['Host'] = $host; + $extraHeaders['Connection'] = 'Connection: close'; + + if (is_array($requestBody)) { + $requestBody = http_build_query($requestBody, '', '&'); + } + $extraHeaders['Content-length'] = 'Content-length: '.strlen($requestBody); + + $context = $this->generateStreamContext($requestBody, $extraHeaders, $method); + + $level = error_reporting(0); + $response = file_get_contents($endpoint->getAbsoluteUri(), false, $context); + error_reporting($level); + if (false === $response) { + $lastError = error_get_last(); + if (is_null($lastError)) { + throw new TokenResponseException('Failed to request resource.'); + } + throw new TokenResponseException($lastError['message']); + } + + return $response; + } + + private function generateStreamContext($body, $headers, $method) + { + return stream_context_create( + array( + 'http' => array( + 'method' => $method, + 'header' => implode("\r\n", array_values($headers)), + 'content' => $body, + 'protocol_version' => '1.1', + 'user_agent' => $this->userAgent, + 'max_redirects' => $this->maxRedirects, + 'timeout' => $this->timeout + ), + ) + ); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Http/Exception/TokenResponseException.php b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Exception/TokenResponseException.php new file mode 100644 index 00000000..c519a223 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Exception/TokenResponseException.php @@ -0,0 +1,12 @@ +parseUri($uri); + } + } + + /** + * @param string $uri + * + * @throws \InvalidArgumentException + */ + protected function parseUri($uri) + { + if (false === ($uriParts = parse_url($uri))) { + // congratulations if you've managed to get parse_url to fail, + // it seems to always return some semblance of a parsed url no matter what + throw new InvalidArgumentException("Invalid URI: $uri"); + } + + if (!isset($uriParts['scheme'])) { + throw new InvalidArgumentException('Invalid URI: http|https scheme required'); + } + + $this->scheme = $uriParts['scheme']; + $this->host = $uriParts['host']; + + if (isset($uriParts['port'])) { + $this->port = $uriParts['port']; + $this->explicitPortSpecified = true; + } else { + $this->port = strcmp('https', $uriParts['scheme']) ? 80 : 443; + $this->explicitPortSpecified = false; + } + + if (isset($uriParts['path'])) { + $this->path = $uriParts['path']; + if ('/' === $uriParts['path']) { + $this->explicitTrailingHostSlash = true; + } + } else { + $this->path = '/'; + } + + $this->query = isset($uriParts['query']) ? $uriParts['query'] : ''; + $this->fragment = isset($uriParts['fragment']) ? $uriParts['fragment'] : ''; + + $userInfo = ''; + if (!empty($uriParts['user'])) { + $userInfo .= $uriParts['user']; + } + if ($userInfo && !empty($uriParts['pass'])) { + $userInfo .= ':' . $uriParts['pass']; + } + + $this->setUserInfo($userInfo); + } + + /** + * @param string $rawUserInfo + * + * @return string + */ + protected function protectUserInfo($rawUserInfo) + { + $colonPos = strpos($rawUserInfo, ':'); + + // rfc3986-3.2.1 | http://tools.ietf.org/html/rfc3986#section-3.2 + // "Applications should not render as clear text any data + // after the first colon (":") character found within a userinfo + // subcomponent unless the data after the colon is the empty string + // (indicating no password)" + if ($colonPos !== false && strlen($rawUserInfo)-1 > $colonPos) { + return substr($rawUserInfo, 0, $colonPos) . ':********'; + } else { + return $rawUserInfo; + } + } + + /** + * @return string + */ + public function getScheme() + { + return $this->scheme; + } + + /** + * @return string + */ + public function getUserInfo() + { + return $this->userInfo; + } + + /** + * @return string + */ + public function getRawUserInfo() + { + return $this->rawUserInfo; + } + + /** + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * @return int + */ + public function getPort() + { + return $this->port; + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * @return string + */ + public function getQuery() + { + return $this->query; + } + + /** + * @return string + */ + public function getFragment() + { + return $this->fragment; + } + + /** + * Uses protected user info by default as per rfc3986-3.2.1 + * Uri::getRawAuthority() is available if plain-text password information is desirable. + * + * @return string + */ + public function getAuthority() + { + $authority = $this->userInfo ? $this->userInfo.'@' : ''; + $authority .= $this->host; + + if ($this->explicitPortSpecified) { + $authority .= ":{$this->port}"; + } + + return $authority; + } + + /** + * @return string + */ + public function getRawAuthority() + { + $authority = $this->rawUserInfo ? $this->rawUserInfo.'@' : ''; + $authority .= $this->host; + + if ($this->explicitPortSpecified) { + $authority .= ":{$this->port}"; + } + + return $authority; + } + + /** + * @return string + */ + public function getAbsoluteUri() + { + $uri = $this->scheme . '://' . $this->getRawAuthority(); + + if ('/' === $this->path) { + $uri .= $this->explicitTrailingHostSlash ? '/' : ''; + } else { + $uri .= $this->path; + } + + if (!empty($this->query)) { + $uri .= "?{$this->query}"; + } + + if (!empty($this->fragment)) { + $uri .= "#{$this->fragment}"; + } + + return $uri; + } + + /** + * @return string + */ + public function getRelativeUri() + { + $uri = ''; + + if ('/' === $this->path) { + $uri .= $this->explicitTrailingHostSlash ? '/' : ''; + } else { + $uri .= $this->path; + } + + return $uri; + } + + /** + * Uses protected user info by default as per rfc3986-3.2.1 + * Uri::getAbsoluteUri() is available if plain-text password information is desirable. + * + * @return string + */ + public function __toString() + { + $uri = $this->scheme . '://' . $this->getAuthority(); + + if ('/' === $this->path) { + $uri .= $this->explicitTrailingHostSlash ? '/' : ''; + } else { + $uri .= $this->path; + } + + if (!empty($this->query)) { + $uri .= "?{$this->query}"; + } + + if (!empty($this->fragment)) { + $uri .= "#{$this->fragment}"; + } + + return $uri; + } + + /** + * @param $path + */ + public function setPath($path) + { + if (empty($path)) { + $this->path = '/'; + $this->explicitTrailingHostSlash = false; + } else { + $this->path = $path; + if ('/' === $this->path) { + $this->explicitTrailingHostSlash = true; + } + } + } + + /** + * @param string $query + */ + public function setQuery($query) + { + $this->query = $query; + } + + /** + * @param string $var + * @param string $val + */ + public function addToQuery($var, $val) + { + if (strlen($this->query) > 0) { + $this->query .= '&'; + } + $this->query .= http_build_query(array($var => $val), '', '&'); + } + + /** + * @param string $fragment + */ + public function setFragment($fragment) + { + $this->fragment = $fragment; + } + + /** + * @param string $scheme + */ + public function setScheme($scheme) + { + $this->scheme = $scheme; + } + + + /** + * @param string $userInfo + */ + public function setUserInfo($userInfo) + { + $this->userInfo = $userInfo ? $this->protectUserInfo($userInfo) : ''; + $this->rawUserInfo = $userInfo; + } + + + /** + * @param int $port + */ + public function setPort($port) + { + $this->port = intval($port); + + if (('https' === $this->scheme && $this->port === 443) || ('http' === $this->scheme && $this->port === 80)) { + $this->explicitPortSpecified = false; + } else { + $this->explicitPortSpecified = true; + } + } + + /** + * @param string $host + */ + public function setHost($host) + { + $this->host = $host; + } + + /** + * @return bool + */ + public function hasExplicitTrailingHostSlash() + { + return $this->explicitTrailingHostSlash; + } + + /** + * @return bool + */ + public function hasExplicitPortSpecified() + { + return $this->explicitPortSpecified; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactory.php b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactory.php new file mode 100644 index 00000000..127aa203 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactory.php @@ -0,0 +1,168 @@ +attemptProxyStyleParse($_server)) { + return $uri; + } + + $scheme = $this->detectScheme($_server); + $host = $this->detectHost($_server); + $port = $this->detectPort($_server); + $path = $this->detectPath($_server); + $query = $this->detectQuery($_server); + + return $this->createFromParts($scheme, '', $host, $port, $path, $query); + } + + /** + * @param string $absoluteUri + * + * @return UriInterface + */ + public function createFromAbsolute($absoluteUri) + { + return new Uri($absoluteUri); + } + + /** + * Factory method to build a URI from parts + * + * @param string $scheme + * @param string $userInfo + * @param string $host + * @param string $port + * @param string $path + * @param string $query + * @param string $fragment + * + * @return UriInterface + */ + public function createFromParts($scheme, $userInfo, $host, $port, $path = '', $query = '', $fragment = '') + { + $uri = new Uri(); + $uri->setScheme($scheme); + $uri->setUserInfo($userInfo); + $uri->setHost($host); + $uri->setPort($port); + $uri->setPath($path); + $uri->setQuery($query); + $uri->setFragment($fragment); + + return $uri; + } + + /** + * @param array $_server + * + * @return UriInterface|null + */ + private function attemptProxyStyleParse($_server) + { + // If the raw HTTP request message arrives with a proxy-style absolute URI in the + // initial request line, the absolute URI is stored in $_SERVER['REQUEST_URI'] and + // we only need to parse that. + if (isset($_server['REQUEST_URI']) && parse_url($_server['REQUEST_URI'], PHP_URL_SCHEME)) { + return new Uri($_server['REQUEST_URI']); + } + + return null; + } + + /** + * @param array $_server + * + * @return string + * + * @throws RuntimeException + */ + private function detectPath($_server) + { + if (isset($_server['REQUEST_URI'])) { + $uri = $_server['REQUEST_URI']; + } elseif (isset($_server['REDIRECT_URL'])) { + $uri = $_server['REDIRECT_URL']; + } else { + throw new RuntimeException('Could not detect URI path from superglobal'); + } + + $queryStr = strpos($uri, '?'); + if ($queryStr !== false) { + $uri = substr($uri, 0, $queryStr); + } + + return $uri; + } + + /** + * @param array $_server + * + * @return string + */ + private function detectHost(array $_server) + { + $host = isset($_server['HTTP_HOST']) ? $_server['HTTP_HOST'] : ''; + + if (strstr($host, ':')) { + $host = parse_url($host, PHP_URL_HOST); + } + + return $host; + } + + /** + * @param array $_server + * + * @return string + */ + private function detectPort(array $_server) + { + return isset($_server['SERVER_PORT']) ? $_server['SERVER_PORT'] : 80; + } + + /** + * @param array $_server + * + * @return string + */ + private function detectQuery(array $_server) + { + return isset($_server['QUERY_STRING']) ? $_server['QUERY_STRING'] : ''; + } + + /** + * Determine URI scheme component from superglobal array + * + * When using ISAPI with IIS, the value will be "off" if the request was + * not made through the HTTPS protocol. As a result, we filter the + * value to a bool. + * + * @param array $_server A super-global $_SERVER array + * + * @return string Returns http or https depending on the URI scheme + */ + private function detectScheme(array $_server) + { + if (isset($_server['HTTPS']) && filter_var($_server['HTTPS'], FILTER_VALIDATE_BOOLEAN)) { + return 'https'; + } else { + return 'http'; + } + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactoryInterface.php b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactoryInterface.php new file mode 100644 index 00000000..2b157d84 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Http/Uri/UriFactoryInterface.php @@ -0,0 +1,42 @@ +credentials = $credentials; + $this->httpClient = $httpClient; + $this->storage = $storage; + } + + /** + * @param UriInterface|string $path + * @param UriInterface $baseApiUri + * + * @return UriInterface + * + * @throws Exception + */ + protected function determineRequestUriFromPath($path, UriInterface $baseApiUri = null) + { + if ($path instanceof UriInterface) { + $uri = $path; + } elseif (stripos($path, 'http://') === 0 || stripos($path, 'https://') === 0) { + $uri = new Uri($path); + } else { + if (null === $baseApiUri) { + throw new Exception( + 'An absolute URI must be passed to ServiceInterface::request as no baseApiUri is set.' + ); + } + + $uri = clone $baseApiUri; + if (false !== strpos($path, '?')) { + $parts = explode('?', $path, 2); + $path = $parts[0]; + $query = $parts[1]; + $uri->setQuery($query); + } + + if ($path[0] === '/') { + $path = substr($path, 1); + } + + $uri->setPath($uri->getPath() . $path); + } + + return $uri; + } + + /** + * Accessor to the storage adapter to be able to retrieve tokens + * + * @return TokenStorageInterface + */ + public function getStorage() + { + return $this->storage; + } + + /** + * @return string + */ + public function service() + { + // get class name without backslashes + $classname = get_class($this); + + return preg_replace('/^.*\\\\/', '', $classname); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Service/ServiceInterface.php b/vendor/lusitanian/oauth/src/OAuth/Common/Service/ServiceInterface.php new file mode 100644 index 00000000..5856a039 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Service/ServiceInterface.php @@ -0,0 +1,49 @@ +tokens = array(); + $this->states = array(); + } + + /** + * {@inheritDoc} + */ + public function retrieveAccessToken($service) + { + if ($this->hasAccessToken($service)) { + return $this->tokens[$service]; + } + + throw new TokenNotFoundException('Token not stored'); + } + + /** + * {@inheritDoc} + */ + public function storeAccessToken($service, TokenInterface $token) + { + $this->tokens[$service] = $token; + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAccessToken($service) + { + return isset($this->tokens[$service]) && $this->tokens[$service] instanceof TokenInterface; + } + + /** + * {@inheritDoc} + */ + public function clearToken($service) + { + if (array_key_exists($service, $this->tokens)) { + unset($this->tokens[$service]); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllTokens() + { + $this->tokens = array(); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function retrieveAuthorizationState($service) + { + if ($this->hasAuthorizationState($service)) { + return $this->states[$service]; + } + + throw new AuthorizationStateNotFoundException('State not stored'); + } + + /** + * {@inheritDoc} + */ + public function storeAuthorizationState($service, $state) + { + $this->states[$service] = $state; + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAuthorizationState($service) + { + return isset($this->states[$service]) && null !== $this->states[$service]; + } + + /** + * {@inheritDoc} + */ + public function clearAuthorizationState($service) + { + if (array_key_exists($service, $this->states)) { + unset($this->states[$service]); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllAuthorizationStates() + { + $this->states = array(); + + // allow chaining + return $this; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Redis.php b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Redis.php new file mode 100644 index 00000000..77318bd6 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Redis.php @@ -0,0 +1,230 @@ +redis = $redis; + $this->key = $key; + $this->stateKey = $stateKey; + $this->cachedTokens = array(); + $this->cachedStates = array(); + } + + /** + * {@inheritDoc} + */ + public function retrieveAccessToken($service) + { + if (!$this->hasAccessToken($service)) { + throw new TokenNotFoundException('Token not found in redis'); + } + + if (isset($this->cachedTokens[$service])) { + return $this->cachedTokens[$service]; + } + + $val = $this->redis->hget($this->key, $service); + + return $this->cachedTokens[$service] = unserialize($val); + } + + /** + * {@inheritDoc} + */ + public function storeAccessToken($service, TokenInterface $token) + { + // (over)write the token + $this->redis->hset($this->key, $service, serialize($token)); + $this->cachedTokens[$service] = $token; + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAccessToken($service) + { + if (isset($this->cachedTokens[$service]) + && $this->cachedTokens[$service] instanceof TokenInterface + ) { + return true; + } + + return $this->redis->hexists($this->key, $service); + } + + /** + * {@inheritDoc} + */ + public function clearToken($service) + { + $this->redis->hdel($this->key, $service); + unset($this->cachedTokens[$service]); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllTokens() + { + // memory + $this->cachedTokens = array(); + + // redis + $keys = $this->redis->hkeys($this->key); + $me = $this; // 5.3 compat + + // pipeline for performance + $this->redis->pipeline( + function ($pipe) use ($keys, $me) { + foreach ($keys as $k) { + $pipe->hdel($me->getKey(), $k); + } + } + ); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function retrieveAuthorizationState($service) + { + if (!$this->hasAuthorizationState($service)) { + throw new AuthorizationStateNotFoundException('State not found in redis'); + } + + if (isset($this->cachedStates[$service])) { + return $this->cachedStates[$service]; + } + + $val = $this->redis->hget($this->stateKey, $service); + + return $this->cachedStates[$service] = unserialize($val); + } + + /** + * {@inheritDoc} + */ + public function storeAuthorizationState($service, $state) + { + // (over)write the token + $this->redis->hset($this->stateKey, $service, $state); + $this->cachedStates[$service] = $state; + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAuthorizationState($service) + { + if (isset($this->cachedStates[$service]) + && null !== $this->cachedStates[$service] + ) { + return true; + } + + return $this->redis->hexists($this->stateKey, $service); + } + + /** + * {@inheritDoc} + */ + public function clearAuthorizationState($service) + { + $this->redis->hdel($this->stateKey, $service); + unset($this->cachedStates[$service]); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllAuthorizationStates() + { + // memory + $this->cachedStates = array(); + + // redis + $keys = $this->redis->hkeys($this->stateKey); + $me = $this; // 5.3 compat + + // pipeline for performance + $this->redis->pipeline( + function ($pipe) use ($keys, $me) { + foreach ($keys as $k) { + $pipe->hdel($me->getKey(), $k); + } + } + ); + + // allow chaining + return $this; + } + + /** + * @return Predis $redis + */ + public function getRedis() + { + return $this->redis; + } + + /** + * @return string $key + */ + public function getKey() + { + return $this->key; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Session.php b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Session.php new file mode 100644 index 00000000..e908a67e --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Session.php @@ -0,0 +1,188 @@ +startSession = $startSession; + $this->sessionVariableName = $sessionVariableName; + $this->stateVariableName = $stateVariableName; + if (!isset($_SESSION[$sessionVariableName])) { + $_SESSION[$sessionVariableName] = array(); + } + if (!isset($_SESSION[$stateVariableName])) { + $_SESSION[$stateVariableName] = array(); + } + } + + /** + * {@inheritDoc} + */ + public function retrieveAccessToken($service) + { + if ($this->hasAccessToken($service)) { + return unserialize($_SESSION[$this->sessionVariableName][$service]); + } + + throw new TokenNotFoundException('Token not found in session, are you sure you stored it?'); + } + + /** + * {@inheritDoc} + */ + public function storeAccessToken($service, TokenInterface $token) + { + $serializedToken = serialize($token); + + if (isset($_SESSION[$this->sessionVariableName]) + && is_array($_SESSION[$this->sessionVariableName]) + ) { + $_SESSION[$this->sessionVariableName][$service] = $serializedToken; + } else { + $_SESSION[$this->sessionVariableName] = array( + $service => $serializedToken, + ); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAccessToken($service) + { + return isset($_SESSION[$this->sessionVariableName], $_SESSION[$this->sessionVariableName][$service]); + } + + /** + * {@inheritDoc} + */ + public function clearToken($service) + { + if (array_key_exists($service, $_SESSION[$this->sessionVariableName])) { + unset($_SESSION[$this->sessionVariableName][$service]); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllTokens() + { + unset($_SESSION[$this->sessionVariableName]); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function storeAuthorizationState($service, $state) + { + if (isset($_SESSION[$this->stateVariableName]) + && is_array($_SESSION[$this->stateVariableName]) + ) { + $_SESSION[$this->stateVariableName][$service] = $state; + } else { + $_SESSION[$this->stateVariableName] = array( + $service => $state, + ); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAuthorizationState($service) + { + return isset($_SESSION[$this->stateVariableName], $_SESSION[$this->stateVariableName][$service]); + } + + /** + * {@inheritDoc} + */ + public function retrieveAuthorizationState($service) + { + if ($this->hasAuthorizationState($service)) { + return $_SESSION[$this->stateVariableName][$service]; + } + + throw new AuthorizationStateNotFoundException('State not found in session, are you sure you stored it?'); + } + + /** + * {@inheritDoc} + */ + public function clearAuthorizationState($service) + { + if (array_key_exists($service, $_SESSION[$this->stateVariableName])) { + unset($_SESSION[$this->stateVariableName][$service]); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllAuthorizationStates() + { + unset($_SESSION[$this->stateVariableName]); + + // allow chaining + return $this; + } + + public function __destruct() + { + if ($this->startSession) { + session_write_close(); + } + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Storage/SymfonySession.php b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/SymfonySession.php new file mode 100644 index 00000000..6c5fbf60 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/SymfonySession.php @@ -0,0 +1,200 @@ +session = $session; + $this->sessionVariableName = $sessionVariableName; + $this->stateVariableName = $stateVariableName; + } + + /** + * {@inheritDoc} + */ + public function retrieveAccessToken($service) + { + if ($this->hasAccessToken($service)) { + // get from session + $tokens = $this->session->get($this->sessionVariableName); + + // one item + return $tokens[$service]; + } + + throw new TokenNotFoundException('Token not found in session, are you sure you stored it?'); + } + + /** + * {@inheritDoc} + */ + public function storeAccessToken($service, TokenInterface $token) + { + // get previously saved tokens + $tokens = $this->session->get($this->sessionVariableName); + + if (!is_array($tokens)) { + $tokens = array(); + } + + $tokens[$service] = $token; + + // save + $this->session->set($this->sessionVariableName, $tokens); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAccessToken($service) + { + // get from session + $tokens = $this->session->get($this->sessionVariableName); + + return is_array($tokens) + && isset($tokens[$service]) + && $tokens[$service] instanceof TokenInterface; + } + + /** + * {@inheritDoc} + */ + public function clearToken($service) + { + // get previously saved tokens + $tokens = $this->session->get($this->sessionVariableName); + + if (is_array($tokens) && array_key_exists($service, $tokens)) { + unset($tokens[$service]); + + // Replace the stored tokens array + $this->session->set($this->sessionVariableName, $tokens); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllTokens() + { + $this->session->remove($this->sessionVariableName); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function retrieveAuthorizationState($service) + { + if ($this->hasAuthorizationState($service)) { + // get from session + $states = $this->session->get($this->stateVariableName); + + // one item + return $states[$service]; + } + + throw new AuthorizationStateNotFoundException('State not found in session, are you sure you stored it?'); + } + + /** + * {@inheritDoc} + */ + public function storeAuthorizationState($service, $state) + { + // get previously saved tokens + $states = $this->session->get($this->stateVariableName); + + if (!is_array($states)) { + $states = array(); + } + + $states[$service] = $state; + + // save + $this->session->set($this->stateVariableName, $states); + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function hasAuthorizationState($service) + { + // get from session + $states = $this->session->get($this->stateVariableName); + + return is_array($states) + && isset($states[$service]) + && null !== $states[$service]; + } + + /** + * {@inheritDoc} + */ + public function clearAuthorizationState($service) + { + // get previously saved tokens + $states = $this->session->get($this->stateVariableName); + + if (is_array($states) && array_key_exists($service, $states)) { + unset($states[$service]); + + // Replace the stored tokens array + $this->session->set($this->stateVariableName, $states); + } + + // allow chaining + return $this; + } + + /** + * {@inheritDoc} + */ + public function clearAllAuthorizationStates() + { + $this->session->remove($this->stateVariableName); + + // allow chaining + return $this; + } + + /** + * @return Session + */ + public function getSession() + { + return $this->session; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Storage/TokenStorageInterface.php b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/TokenStorageInterface.php new file mode 100644 index 00000000..46552cee --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Storage/TokenStorageInterface.php @@ -0,0 +1,98 @@ +accessToken = $accessToken; + $this->refreshToken = $refreshToken; + $this->setLifetime($lifetime); + $this->extraParams = $extraParams; + } + + /** + * @return string + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * @return string + */ + public function getRefreshToken() + { + return $this->refreshToken; + } + + /** + * @return int + */ + public function getEndOfLife() + { + return $this->endOfLife; + } + + /** + * @param array $extraParams + */ + public function setExtraParams(array $extraParams) + { + $this->extraParams = $extraParams; + } + + /** + * @return array + */ + public function getExtraParams() + { + return $this->extraParams; + } + + /** + * @param string $accessToken + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + } + + /** + * @param int $endOfLife + */ + public function setEndOfLife($endOfLife) + { + $this->endOfLife = $endOfLife; + } + + /** + * @param int $lifetime + */ + public function setLifetime($lifetime) + { + if (0 === $lifetime || static::EOL_NEVER_EXPIRES === $lifetime) { + $this->endOfLife = static::EOL_NEVER_EXPIRES; + } elseif (null !== $lifetime) { + $this->endOfLife = intval($lifetime) + time(); + } else { + $this->endOfLife = static::EOL_UNKNOWN; + } + } + + /** + * @param string $refreshToken + */ + public function setRefreshToken($refreshToken) + { + $this->refreshToken = $refreshToken; + } + + public function isExpired() + { + return ($this->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES + && $this->getEndOfLife() !== TokenInterface::EOL_UNKNOWN + && time() > $this->getEndOfLife()); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/Common/Token/Exception/ExpiredTokenException.php b/vendor/lusitanian/oauth/src/OAuth/Common/Token/Exception/ExpiredTokenException.php new file mode 100644 index 00000000..26ad6cc5 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/Common/Token/Exception/ExpiredTokenException.php @@ -0,0 +1,12 @@ +signature = $signature; + $this->baseApiUri = $baseApiUri; + + $this->signature->setHashingAlgorithm($this->getSignatureMethod()); + } + + /** + * {@inheritDoc} + */ + public function requestRequestToken() + { + $authorizationHeader = array('Authorization' => $this->buildAuthorizationHeaderForTokenRequest()); + $headers = array_merge($authorizationHeader, $this->getExtraOAuthHeaders()); + + $responseBody = $this->httpClient->retrieveResponse($this->getRequestTokenEndpoint(), array(), $headers); + + $token = $this->parseRequestTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($additionalParameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritDoc} + */ + public function requestAccessToken($token, $verifier, $tokenSecret = null) + { + if (is_null($tokenSecret)) { + $storedRequestToken = $this->storage->retrieveAccessToken($this->service()); + $tokenSecret = $storedRequestToken->getRequestTokenSecret(); + } + $this->signature->setTokenSecret($tokenSecret); + + $bodyParams = array( + 'oauth_verifier' => $verifier, + ); + + $authorizationHeader = array( + 'Authorization' => $this->buildAuthorizationHeaderForAPIRequest( + 'POST', + $this->getAccessTokenEndpoint(), + $this->storage->retrieveAccessToken($this->service()), + $bodyParams + ) + ); + + $headers = array_merge($authorizationHeader, $this->getExtraOAuthHeaders()); + + $responseBody = $this->httpClient->retrieveResponse($this->getAccessTokenEndpoint(), $bodyParams, $headers); + + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + /** + * Sends an authenticated API request to the path provided. + * If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used. + * + * @param string|UriInterface $path + * @param string $method HTTP method + * @param array $body Request body if applicable (key/value pairs) + * @param array $extraHeaders Extra headers if applicable. + * These will override service-specific any defaults. + * + * @return string + */ + public function request($path, $method = 'GET', $body = null, array $extraHeaders = array()) + { + $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri); + + /** @var $token StdOAuth1Token */ + $token = $this->storage->retrieveAccessToken($this->service()); + $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders); + $authorizationHeader = array( + 'Authorization' => $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $token, $body) + ); + $headers = array_merge($authorizationHeader, $extraHeaders); + + return $this->httpClient->retrieveResponse($uri, $body, $headers, $method); + } + + /** + * Return any additional headers always needed for this service implementation's OAuth calls. + * + * @return array + */ + protected function getExtraOAuthHeaders() + { + return array(); + } + + /** + * Return any additional headers always needed for this service implementation's API calls. + * + * @return array + */ + protected function getExtraApiHeaders() + { + return array(); + } + + /** + * Builds the authorization header for getting an access or request token. + * + * @param array $extraParameters + * + * @return string + */ + protected function buildAuthorizationHeaderForTokenRequest(array $extraParameters = array()) + { + $parameters = $this->getBasicAuthorizationHeaderInfo(); + $parameters = array_merge($parameters, $extraParameters); + $parameters['oauth_signature'] = $this->signature->getSignature( + $this->getRequestTokenEndpoint(), + $parameters, + 'POST' + ); + + $authorizationHeader = 'OAuth '; + $delimiter = ''; + foreach ($parameters as $key => $value) { + $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"'; + + $delimiter = ', '; + } + + return $authorizationHeader; + } + + /** + * Builds the authorization header for an authenticated API request + * + * @param string $method + * @param UriInterface $uri The uri the request is headed + * @param TokenInterface $token + * @param array $bodyParams Request body if applicable (key/value pairs) + * + * @return string + */ + protected function buildAuthorizationHeaderForAPIRequest( + $method, + UriInterface $uri, + TokenInterface $token, + $bodyParams = null + ) { + $this->signature->setTokenSecret($token->getAccessTokenSecret()); + $parameters = $this->getBasicAuthorizationHeaderInfo(); + if (isset($parameters['oauth_callback'])) { + unset($parameters['oauth_callback']); + } + + $parameters = array_merge($parameters, array('oauth_token' => $token->getAccessToken())); + $parameters = (is_array($bodyParams)) ? array_merge($parameters, $bodyParams) : $parameters; + $parameters['oauth_signature'] = $this->signature->getSignature($uri, $parameters, $method); + + $authorizationHeader = 'OAuth '; + $delimiter = ''; + + foreach ($parameters as $key => $value) { + $authorizationHeader .= $delimiter . rawurlencode($key) . '="' . rawurlencode($value) . '"'; + $delimiter = ', '; + } + + return $authorizationHeader; + } + + /** + * Builds the authorization header array. + * + * @return array + */ + protected function getBasicAuthorizationHeaderInfo() + { + $dateTime = new \DateTime(); + $headerParameters = array( + 'oauth_callback' => $this->credentials->getCallbackUrl(), + 'oauth_consumer_key' => $this->credentials->getConsumerId(), + 'oauth_nonce' => $this->generateNonce(), + 'oauth_signature_method' => $this->getSignatureMethod(), + 'oauth_timestamp' => $dateTime->format('U'), + 'oauth_version' => $this->getVersion(), + ); + + return $headerParameters; + } + + /** + * Pseudo random string generator used to build a unique string to sign each request + * + * @param int $length + * + * @return string + */ + protected function generateNonce($length = 32) + { + $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; + + $nonce = ''; + $maxRand = strlen($characters)-1; + for ($i = 0; $i < $length; $i++) { + $nonce.= $characters[rand(0, $maxRand)]; + } + + return $nonce; + } + + /** + * @return string + */ + protected function getSignatureMethod() + { + return 'HMAC-SHA1'; + } + + /** + * This returns the version used in the authorization header of the requests + * + * @return string + */ + protected function getVersion() + { + return '1.0'; + } + + /** + * Parses the request token response and returns a TokenInterface. + * This is only needed to verify the `oauth_callback_confirmed` parameter. The actual + * parsing logic is contained in the access token parser. + * + * @abstract + * + * @param string $responseBody + * + * @return TokenInterface + * + * @throws TokenResponseException + */ + abstract protected function parseRequestTokenResponse($responseBody); + + /** + * Parses the access token response and returns a TokenInterface. + * + * @abstract + * + * @param string $responseBody + * + * @return TokenInterface + * + * @throws TokenResponseException + */ + abstract protected function parseAccessTokenResponse($responseBody); +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/BitBucket.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/BitBucket.php new file mode 100644 index 00000000..f6d8edfe --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/BitBucket.php @@ -0,0 +1,96 @@ +baseApiUri = new Uri('https://bitbucket.org/api/1.0/'); + } + } + + /** + * {@inheritDoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://bitbucket.org/!api/1.0/oauth/request_token'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://bitbucket.org/!api/1.0/oauth/authenticate'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://bitbucket.org/!api/1.0/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Etsy.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Etsy.php new file mode 100644 index 00000000..30dc331c --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Etsy.php @@ -0,0 +1,132 @@ +baseApiUri = new Uri('https://openapi.etsy.com/v2/'); + } + } + + /** + * {@inheritdoc} + */ + public function getRequestTokenEndpoint() + { + $uri = new Uri($this->baseApiUri . 'oauth/request_token'); + $scopes = $this->getScopes(); + + if (count($scopes)) { + $uri->setQuery('scope=' . implode('%20', $scopes)); + } + + return $uri; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri($this->baseApiUri); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri($this->baseApiUri . 'oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } + + /** + * Set the scopes for permissions + * @see https://www.etsy.com/developers/documentation/getting_started/oauth#section_permission_scopes + * @param array $scopes + * + * @return $this + */ + public function setScopes(array $scopes) + { + if (!is_array($scopes)) { + $scopes = array(); + } + + $this->scopes = $scopes; + return $this; + } + + /** + * Return the defined scopes + * @return array + */ + public function getScopes() + { + return $this->scopes; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/FitBit.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/FitBit.php new file mode 100644 index 00000000..78032d75 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/FitBit.php @@ -0,0 +1,96 @@ +baseApiUri = new Uri('https://api.fitbit.com/1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://api.fitbit.com/oauth/request_token'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.fitbit.com/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.fitbit.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Flickr.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Flickr.php new file mode 100644 index 00000000..f06d282a --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Flickr.php @@ -0,0 +1,91 @@ +baseApiUri = new Uri('https://api.flickr.com/services/rest/'); + } + } + + public function getRequestTokenEndpoint() + { + return new Uri('https://www.flickr.com/services/oauth/request_token'); + } + + public function getAuthorizationEndpoint() + { + return new Uri('https://www.flickr.com/services/oauth/authorize'); + } + + public function getAccessTokenEndpoint() + { + return new Uri('https://www.flickr.com/services/oauth/access_token'); + } + + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] != 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + return $this->parseAccessTokenResponse($responseBody); + } + + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + if ($data === null || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } + + public function request($path, $method = 'GET', $body = null, array $extraHeaders = array()) + { + $uri = $this->determineRequestUriFromPath('/', $this->baseApiUri); + $uri->addToQuery('method', $path); + + $token = $this->storage->retrieveAccessToken($this->service()); + $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders); + $authorizationHeader = array( + 'Authorization' => $this->buildAuthorizationHeaderForAPIRequest($method, $uri, $token, $body) + ); + $headers = array_merge($authorizationHeader, $extraHeaders); + + return $this->httpClient->retrieveResponse($uri, $body, $headers, $method); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ScoopIt.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ScoopIt.php new file mode 100644 index 00000000..28bd250b --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ScoopIt.php @@ -0,0 +1,96 @@ +baseApiUri = new Uri('https://www.scoop.it/api/1/'); + } + } + + /** + * {@inheritDoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://www.scoop.it/oauth/request'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.scoop.it/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.scoop.it/oauth/access'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ServiceInterface.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ServiceInterface.php new file mode 100644 index 00000000..3f91fbf2 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/ServiceInterface.php @@ -0,0 +1,45 @@ +baseApiUri = new Uri('https://api.tumblr.com/v2/'); + } + } + + /** + * {@inheritdoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://www.tumblr.com/oauth/request_token'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.tumblr.com/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.tumblr.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Twitter.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Twitter.php new file mode 100644 index 00000000..f46c34e4 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Twitter.php @@ -0,0 +1,121 @@ +baseApiUri = new Uri('https://api.twitter.com/1.1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://api.twitter.com/oauth/request_token'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + if ($this->authorizationEndpoint != self::ENDPOINT_AUTHENTICATE + && $this->authorizationEndpoint != self::ENDPOINT_AUTHORIZE) { + $this->authorizationEndpoint = self::ENDPOINT_AUTHENTICATE; + } + return new Uri($this->authorizationEndpoint); + } + + /** + * @param string $authorizationEndpoint + * + * @throws Exception + */ + public function setAuthorizationEndpoint($endpoint) + { + if ($endpoint != self::ENDPOINT_AUTHENTICATE && $endpoint != self::ENDPOINT_AUTHORIZE) { + throw new Exception( + sprintf("'%s' is not a correct Twitter authorization endpoint.", $endpoint) + ); + } + $this->authorizationEndpoint = $endpoint; + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.twitter.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Xing.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Xing.php new file mode 100644 index 00000000..03e3357f --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Xing.php @@ -0,0 +1,96 @@ +baseApiUri = new Uri('https://api.xing.com/v1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://api.xing.com/v1/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.xing.com/v1/access_token'); + } + + /** + * {@inheritdoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://api.xing.com/v1/request_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Yahoo.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Yahoo.php new file mode 100644 index 00000000..cff291d4 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Service/Yahoo.php @@ -0,0 +1,96 @@ +baseApiUri = new Uri('https://social.yahooapis.com/v1/'); + } + } + + /** + * {@inheritDoc} + */ + public function getRequestTokenEndpoint() + { + return new Uri('https://api.login.yahoo.com/oauth/v2/get_request_token'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://api.login.yahoo.com/oauth/v2/request_auth'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.login.yahoo.com/oauth/v2/get_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true') { + throw new TokenResponseException('Error in retrieving token.'); + } + + return $this->parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth1Token(); + + $token->setRequestToken($data['oauth_token']); + $token->setRequestTokenSecret($data['oauth_token_secret']); + $token->setAccessToken($data['oauth_token']); + $token->setAccessTokenSecret($data['oauth_token_secret']); + + $token->setEndOfLife(StdOAuth1Token::EOL_NEVER_EXPIRES); + unset($data['oauth_token'], $data['oauth_token_secret']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/Exception/UnsupportedHashAlgorithmException.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/Exception/UnsupportedHashAlgorithmException.php new file mode 100644 index 00000000..44c36ce7 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/Exception/UnsupportedHashAlgorithmException.php @@ -0,0 +1,12 @@ +credentials = $credentials; + } + + /** + * @param string $algorithm + */ + public function setHashingAlgorithm($algorithm) + { + $this->algorithm = $algorithm; + } + + /** + * @param string $token + */ + public function setTokenSecret($token) + { + $this->tokenSecret = $token; + } + + /** + * @param UriInterface $uri + * @param array $params + * @param string $method + * + * @return string + */ + public function getSignature(UriInterface $uri, array $params, $method = 'POST') + { + parse_str($uri->getQuery(), $queryStringData); + + foreach (array_merge($queryStringData, $params) as $key => $value) { + $signatureData[rawurlencode($key)] = rawurlencode($value); + } + + ksort($signatureData); + + // determine base uri + $baseUri = $uri->getScheme() . '://' . $uri->getRawAuthority(); + + if ('/' === $uri->getPath()) { + $baseUri .= $uri->hasExplicitTrailingHostSlash() ? '/' : ''; + } else { + $baseUri .= $uri->getPath(); + } + + $baseString = strtoupper($method) . '&'; + $baseString .= rawurlencode($baseUri) . '&'; + $baseString .= rawurlencode($this->buildSignatureDataString($signatureData)); + + return base64_encode($this->hash($baseString)); + } + + /** + * @param array $signatureData + * + * @return string + */ + protected function buildSignatureDataString(array $signatureData) + { + $signatureString = ''; + $delimiter = ''; + foreach ($signatureData as $key => $value) { + $signatureString .= $delimiter . $key . '=' . $value; + + $delimiter = '&'; + } + + return $signatureString; + } + + /** + * @return string + */ + protected function getSigningKey() + { + $signingKey = rawurlencode($this->credentials->getConsumerSecret()) . '&'; + if ($this->tokenSecret !== null) { + $signingKey .= rawurlencode($this->tokenSecret); + } + + return $signingKey; + } + + /** + * @param string $data + * + * @return string + * + * @throws UnsupportedHashAlgorithmException + */ + protected function hash($data) + { + switch (strtoupper($this->algorithm)) { + case 'HMAC-SHA1': + return hash_hmac('sha1', $data, $this->getSigningKey(), true); + default: + throw new UnsupportedHashAlgorithmException( + 'Unsupported hashing algorithm (' . $this->algorithm . ') used.' + ); + } + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/SignatureInterface.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/SignatureInterface.php new file mode 100644 index 00000000..da50ddb6 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Signature/SignatureInterface.php @@ -0,0 +1,28 @@ +requestToken = $requestToken; + } + + /** + * @return string + */ + public function getRequestToken() + { + return $this->requestToken; + } + + /** + * @param string $requestTokenSecret + */ + public function setRequestTokenSecret($requestTokenSecret) + { + $this->requestTokenSecret = $requestTokenSecret; + } + + /** + * @return string + */ + public function getRequestTokenSecret() + { + return $this->requestTokenSecret; + } + + /** + * @param string $accessTokenSecret + */ + public function setAccessTokenSecret($accessTokenSecret) + { + $this->accessTokenSecret = $accessTokenSecret; + } + + /** + * @return string + */ + public function getAccessTokenSecret() + { + return $this->accessTokenSecret; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth1/Token/TokenInterface.php b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Token/TokenInterface.php new file mode 100644 index 00000000..0bc3f739 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth1/Token/TokenInterface.php @@ -0,0 +1,41 @@ +stateParameterInAuthUrl = $stateParameterInAutUrl; + + foreach ($scopes as $scope) { + if (!$this->isValidScope($scope)) { + throw new InvalidScopeException('Scope ' . $scope . ' is not valid for service ' . get_class($this)); + } + } + + $this->scopes = $scopes; + + $this->baseApiUri = $baseApiUri; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'type' => 'web_server', + 'client_id' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'response_type' => 'code', + ) + ); + + $parameters['scope'] = implode(' ', $this->scopes); + + if ($this->needsStateParameterInAuthUrl()) { + if (!isset($parameters['state'])) { + $parameters['state'] = $this->generateAuthorizationState(); + } + $this->storeAuthorizationState($parameters['state']); + } + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function requestAccessToken($code, $state = null) + { + if (null !== $state) { + $this->validateAuthorizationState($state); + } + + $bodyParams = array( + 'code' => $code, + 'client_id' => $this->credentials->getConsumerId(), + 'client_secret' => $this->credentials->getConsumerSecret(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'grant_type' => 'authorization_code', + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $bodyParams, + $this->getExtraOAuthHeaders() + ); + + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + /** + * Sends an authenticated API request to the path provided. + * If the path provided is not an absolute URI, the base API Uri (must be passed into constructor) will be used. + * + * @param string|UriInterface $path + * @param string $method HTTP method + * @param array $body Request body if applicable. + * @param array $extraHeaders Extra headers if applicable. These will override service-specific + * any defaults. + * + * @return string + * + * @throws ExpiredTokenException + * @throws Exception + */ + public function request($path, $method = 'GET', $body = null, array $extraHeaders = array()) + { + $uri = $this->determineRequestUriFromPath($path, $this->baseApiUri); + $token = $this->storage->retrieveAccessToken($this->service()); + + if ($token->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES + && $token->getEndOfLife() !== TokenInterface::EOL_UNKNOWN + && time() > $token->getEndOfLife() + ) { + throw new ExpiredTokenException( + sprintf( + 'Token expired on %s at %s', + date('m/d/Y', $token->getEndOfLife()), + date('h:i:s A', $token->getEndOfLife()) + ) + ); + } + + // add the token where it may be needed + if (static::AUTHORIZATION_METHOD_HEADER_OAUTH === $this->getAuthorizationMethod()) { + $extraHeaders = array_merge(array('Authorization' => 'OAuth ' . $token->getAccessToken()), $extraHeaders); + } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING === $this->getAuthorizationMethod()) { + $uri->addToQuery('access_token', $token->getAccessToken()); + } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V2 === $this->getAuthorizationMethod()) { + $uri->addToQuery('oauth2_access_token', $token->getAccessToken()); + } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V3 === $this->getAuthorizationMethod()) { + $uri->addToQuery('apikey', $token->getAccessToken()); + } elseif (static::AUTHORIZATION_METHOD_HEADER_BEARER === $this->getAuthorizationMethod()) { + $extraHeaders = array_merge(array('Authorization' => 'Bearer ' . $token->getAccessToken()), $extraHeaders); + } + + $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders); + + return $this->httpClient->retrieveResponse($uri, $body, $extraHeaders, $method); + } + + /** + * Accessor to the storage adapter to be able to retrieve tokens + * + * @return TokenStorageInterface + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Refreshes an OAuth2 access token. + * + * @param TokenInterface $token + * + * @return TokenInterface $token + * + * @throws MissingRefreshTokenException + */ + public function refreshAccessToken(TokenInterface $token) + { + $refreshToken = $token->getRefreshToken(); + + if (empty($refreshToken)) { + throw new MissingRefreshTokenException(); + } + + $parameters = array( + 'grant_type' => 'refresh_token', + 'type' => 'web_server', + 'client_id' => $this->credentials->getConsumerId(), + 'client_secret' => $this->credentials->getConsumerSecret(), + 'refresh_token' => $refreshToken, + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $parameters, + $this->getExtraOAuthHeaders() + ); + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + /** + * Return whether or not the passed scope value is valid. + * + * @param string $scope + * + * @return bool + */ + public function isValidScope($scope) + { + $reflectionClass = new \ReflectionClass(get_class($this)); + + return in_array($scope, $reflectionClass->getConstants(), true); + } + + /** + * Check if the given service need to generate a unique state token to build the authorization url + * + * @return bool + */ + public function needsStateParameterInAuthUrl() + { + return $this->stateParameterInAuthUrl; + } + + /** + * Validates the authorization state against a given one + * + * @param string $state + * @throws InvalidAuthorizationStateException + */ + protected function validateAuthorizationState($state) + { + if ($this->retrieveAuthorizationState() !== $state) { + throw new InvalidAuthorizationStateException(); + } + } + + /** + * Generates a random string to be used as state + * + * @return string + */ + protected function generateAuthorizationState() + { + return md5(rand()); + } + + /** + * Retrieves the authorization state for the current service + * + * @return string + */ + protected function retrieveAuthorizationState() + { + return $this->storage->retrieveAuthorizationState($this->service()); + } + + /** + * Stores a given authorization state into the storage + * + * @param string $state + */ + protected function storeAuthorizationState($state) + { + $this->storage->storeAuthorizationState($this->service(), $state); + } + + /** + * Return any additional headers always needed for this service implementation's OAuth calls. + * + * @return array + */ + protected function getExtraOAuthHeaders() + { + return array(); + } + + /** + * Return any additional headers always needed for this service implementation's API calls. + * + * @return array + */ + protected function getExtraApiHeaders() + { + return array(); + } + + /** + * Parses the access token response and returns a TokenInterface. + * + * @abstract + * + * @param string $responseBody + * + * @return TokenInterface + * + * @throws TokenResponseException + */ + abstract protected function parseAccessTokenResponse($responseBody); + + /** + * Returns a class constant from ServiceInterface defining the authorization method used for the API + * Header is the sane default. + * + * @return int + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_OAUTH; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Amazon.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Amazon.php new file mode 100644 index 00000000..035d1a55 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Amazon.php @@ -0,0 +1,97 @@ + + * @link https://images-na.ssl-images-amazon.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf + */ +class Amazon extends AbstractService +{ + /** + * Defined scopes + * @link https://images-na.ssl-images-amazon.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf + */ + const SCOPE_PROFILE = 'profile'; + const SCOPE_POSTAL_CODE = 'postal_code'; + + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.amazon.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.amazon.com/ap/oa'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.amazon.com/ap/oatoken'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error_description'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error_description'] . '"'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Bitly.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Bitly.php new file mode 100644 index 00000000..e01cbc42 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Bitly.php @@ -0,0 +1,111 @@ +baseApiUri = new Uri('https://api-ssl.bitly.com/v3/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://bitly.com/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api-ssl.bitly.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + // I'm invincible!!! + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + public function requestAccessToken($code, $state = null) + { + if (null !== $state) { + $this->validateAuthorizationState($state); + } + + $bodyParams = array( + 'code' => $code, + 'client_id' => $this->credentials->getConsumerId(), + 'client_secret' => $this->credentials->getConsumerSecret(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'grant_type' => 'authorization_code', + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $bodyParams, + $this->getExtraOAuthHeaders() + ); + + // we can scream what we want that we want bitly to return a json encoded string (format=json), but the + // WOAH WATCH YOUR LANGUAGE ;) service doesn't seem to like screaming, hence we need to manually + // parse the result + $parsedResult = array(); + parse_str($responseBody, $parsedResult); + + $token = $this->parseAccessTokenResponse(json_encode($parsedResult)); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Box.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Box.php new file mode 100644 index 00000000..14696c59 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Box.php @@ -0,0 +1,88 @@ + + * @link https://developers.box.com/oauth/ + */ +class Box extends AbstractService +{ + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, true); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.box.com/2.0/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.box.com/api/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.box.com/api/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Buffer.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Buffer.php new file mode 100644 index 00000000..5905678e --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Buffer.php @@ -0,0 +1,151 @@ + + * @link https://bufferapp.com/developers/api + */ +class Buffer extends AbstractService +{ + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + if ($baseApiUri === null) { + $this->baseApiUri = new Uri('https://api.bufferapp.com/1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://bufferapp.com/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.bufferapp.com/1/oauth2/token.json'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'client_id' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'response_type' => 'code', + ) + ); + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function requestRequestToken() + { + $responseBody = $this->httpClient->retrieveResponse( + $this->getRequestTokenEndpoint(), + array( + 'client_key' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'response_type' => 'code', + ) + ); + + $code = $this->parseRequestTokenResponse($responseBody); + + return $code; + } + + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['code'])) { + throw new TokenResponseException('Error in retrieving code.'); + } + return $data['code']; + } + + public function requestAccessToken($code) + { + $bodyParams = array( + 'client_id' => $this->credentials->getConsumerId(), + 'client_secret' => $this->credentials->getConsumerSecret(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'code' => $code, + 'grant_type' => 'authorization_code', + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $bodyParams, + $this->getExtraOAuthHeaders() + ); + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if ($data === null || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dailymotion.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dailymotion.php new file mode 100644 index 00000000..095a467f --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dailymotion.php @@ -0,0 +1,129 @@ + + * @link http://www.dailymotion.com/doc/api/authentication.html + */ +class Dailymotion extends AbstractService +{ + /** + * Scopes + * + * @var string + */ + const SCOPE_EMAIL = 'email', + SCOPE_PROFILE = 'userinfo', + SCOPE_VIDEOS = 'manage_videos', + SCOPE_COMMENTS = 'manage_comments', + SCOPE_PLAYLIST = 'manage_playlists', + SCOPE_TILES = 'manage_tiles', + SCOPE_SUBSCRIPTIONS = 'manage_subscriptions', + SCOPE_FRIENDS = 'manage_friends', + SCOPE_FAVORITES = 'manage_favorites', + SCOPE_GROUPS = 'manage_groups'; + + /** + * Dialog form factors + * + * @var string + */ + const DISPLAY_PAGE = 'page', + DISPLAY_POPUP = 'popup', + DISPLAY_MOBILE = 'mobile'; + + /** + * {@inheritdoc} + */ + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.dailymotion.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://api.dailymotion.com/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.dailymotion.com/oauth/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_OAUTH; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error_description']) || isset($data['error'])) { + throw new TokenResponseException( + sprintf( + 'Error in retrieving token: "%s"', + isset($data['error_description']) ? $data['error_description'] : $data['error'] + ) + ); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getExtraOAuthHeaders() + { + return array('Accept' => 'application/json'); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dropbox.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dropbox.php new file mode 100644 index 00000000..43ec6c7f --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Dropbox.php @@ -0,0 +1,111 @@ + + * @link https://www.dropbox.com/developers/core/docs + */ +class Dropbox extends AbstractService +{ + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.dropbox.com/1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'client_id' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'response_type' => 'code', + ) + ); + + $parameters['scope'] = implode(' ', $this->scopes); + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.dropbox.com/1/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.dropbox.com/1/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidAccessTypeException.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidAccessTypeException.php new file mode 100644 index 00000000..398df2fd --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/InvalidAccessTypeException.php @@ -0,0 +1,12 @@ + + * Released under the MIT license. + */ + +namespace OAuth\OAuth2\Service\Exception; + +use OAuth\Common\Exception\Exception; + +/** + * Exception thrown when a scope provided to a service is invalid. + */ +class InvalidScopeException extends Exception +{ +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/MissingRefreshTokenException.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/MissingRefreshTokenException.php new file mode 100644 index 00000000..21eece6a --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Exception/MissingRefreshTokenException.php @@ -0,0 +1,17 @@ + + * Released under the MIT license. + */ + +namespace OAuth\OAuth2\Service\Exception; + +use OAuth\Common\Exception\Exception; + +/** + * Exception thrown when service is requested to refresh the access token but no refresh token can be found. + */ +class MissingRefreshTokenException extends Exception +{ +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Facebook.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Facebook.php new file mode 100644 index 00000000..80b25c05 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Facebook.php @@ -0,0 +1,193 @@ +baseApiUri = new Uri('https://graph.facebook.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.facebook.com/dialog/oauth'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://graph.facebook.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + // Facebook gives us a query string ... Oh wait. JSON is too simple, understand ? + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + + if (isset($data['expires'])) { + $token->setLifeTime($data['expires']); + } + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires']); + + $token->setExtraParams($data); + + return $token; + } + + public function getDialogUri($dialogPath, array $parameters) + { + if (!isset($parameters['redirect_uri'])) { + throw new Exception("Redirect uri is mandatory for this request"); + } + $parameters['app_id'] = $this->credentials->getConsumerId(); + $baseUrl = self::WWW_URL . 'dialog/' . $dialogPath; + $query = http_build_query($parameters); + return new Uri($baseUrl . '?' . $query); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Foursquare.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Foursquare.php new file mode 100644 index 00000000..fdbabf98 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Foursquare.php @@ -0,0 +1,81 @@ +baseApiUri = new Uri('https://api.foursquare.com/v2/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://foursquare.com/oauth2/authenticate'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://foursquare.com/oauth2/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + // Foursquare tokens evidently never expire... + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + public function request($path, $method = 'GET', $body = null, array $extraHeaders = array()) + { + $uri = new Uri($this->baseApiUri . $path); + $uri->addToQuery('v', $this->apiVersionDate); + + return parent::request($uri, $method, $body, $extraHeaders); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/GitHub.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/GitHub.php new file mode 100644 index 00000000..9fee2ba0 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/GitHub.php @@ -0,0 +1,208 @@ +baseApiUri = new Uri('https://api.github.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://github.com/login/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://github.com/login/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + // Github tokens evidently never expire... + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * Used to configure response type -- we want JSON from github, default is query string format + * + * @return array + */ + protected function getExtraOAuthHeaders() + { + return array('Accept' => 'application/json'); + } + + /** + * Required for GitHub API calls. + * + * @return array + */ + protected function getExtraApiHeaders() + { + return array('Accept' => 'application/vnd.github.beta+json'); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Google.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Google.php new file mode 100644 index 00000000..096876b6 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Google.php @@ -0,0 +1,158 @@ +accessType = $accessType; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://accounts.google.com/o/oauth2/auth?access_type=' . $this->accessType); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://accounts.google.com/o/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifetime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Harvest.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Harvest.php new file mode 100644 index 00000000..96fb0f2d --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Harvest.php @@ -0,0 +1,157 @@ +baseApiUri = new Uri('https://api.harvestapp.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'client_id' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'state' => 'optional-csrf-token', + 'response_type' => 'code', + ) + ); + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://api.harvestapp.com/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.harvestapp.com/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || ! is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifetime($data['expires_in']); + $token->setRefreshToken($data['refresh_token']); + + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * Refreshes an OAuth2 access token. + * + * @param TokenInterface $token + * + * @return TokenInterface $token + * + * @throws MissingRefreshTokenException + */ + public function refreshAccessToken(TokenInterface $token) + { + $refreshToken = $token->getRefreshToken(); + + if (empty($refreshToken)) { + throw new MissingRefreshTokenException(); + } + + $parameters = array( + 'grant_type' => 'refresh_token', + 'type' => 'web_server', + 'client_id' => $this->credentials->getConsumerId(), + 'client_secret' => $this->credentials->getConsumerSecret(), + 'refresh_token' => $refreshToken, + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $parameters, + $this->getExtraOAuthHeaders() + ); + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + /** + * @return array + */ + protected function getExtraOAuthHeaders() + { + return array('Accept' => 'application/json'); + } + + /** + * Return any additional headers always needed for this service implementation's API calls. + * + * @return array + */ + protected function getExtraApiHeaders() + { + return array('Accept' => 'application/json'); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Heroku.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Heroku.php new file mode 100644 index 00000000..470cedc3 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Heroku.php @@ -0,0 +1,123 @@ + + * @link https://devcenter.heroku.com/articles/oauth + */ +class Heroku extends AbstractService +{ + /** + * Defined scopes + * @link https://devcenter.heroku.com/articles/oauth#scopes + */ + const SCOPE_GLOBAL = 'global'; + const SCOPE_IDENTITY = 'identity'; + const SCOPE_READ = 'read'; + const SCOPE_WRITE = 'write'; + const SCOPE_READ_PROTECTED = 'read-protected'; + const SCOPE_WRITE_PROTECTED = 'write-protected'; + + /** + * {@inheritdoc} + */ + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.heroku.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://id.heroku.com/oauth/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://id.heroku.com/oauth/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error_description']) || isset($data['error'])) { + throw new TokenResponseException( + sprintf( + 'Error in retrieving token: "%s"', + isset($data['error_description']) ? $data['error_description'] : $data['error'] + ) + ); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getExtraOAuthHeaders() + { + return array('Accept' => 'application/vnd.heroku+json; version=3'); + } + + /** + * {@inheritdoc} + */ + protected function getExtraApiHeaders() + { + return array('Accept' => 'application/vnd.heroku+json; version=3', 'Content-Type' => 'application/json'); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Instagram.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Instagram.php new file mode 100644 index 00000000..49e9c8c9 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Instagram.php @@ -0,0 +1,85 @@ +baseApiUri = new Uri('https://api.instagram.com/v1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://api.instagram.com/oauth/authorize/'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.instagram.com/oauth/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + // Instagram tokens evidently never expire... + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Linkedin.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Linkedin.php new file mode 100644 index 00000000..bb801e6a --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Linkedin.php @@ -0,0 +1,102 @@ + + * @link http://developer.linkedin.com/documents/authentication + */ +class Linkedin extends AbstractService +{ + /** + * Defined scopes + * @link http://developer.linkedin.com/documents/authentication#granting + */ + const SCOPE_R_BASICPROFILE = 'r_basicprofile'; + const SCOPE_R_FULLPROFILE = 'r_fullprofile'; + const SCOPE_R_EMAILADDRESS = 'r_emailaddress'; + const SCOPE_R_NETWORK = 'r_network'; + const SCOPE_R_CONTACTINFO = 'r_contactinfo'; + const SCOPE_RW_NUS = 'rw_nus'; + const SCOPE_RW_COMPANY_ADMIN = 'rw_company_admin'; + const SCOPE_RW_GROUPS = 'rw_groups'; + const SCOPE_W_MESSAGES = 'w_messages'; + + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, true); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.linkedin.com/v1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.linkedin.com/uas/oauth2/authorization'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.linkedin.com/uas/oauth2/accessToken'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING_V2; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Mailchimp.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Mailchimp.php new file mode 100644 index 00000000..42abd3c1 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Mailchimp.php @@ -0,0 +1,115 @@ +baseApiUri) && $storage->hasAccessToken($this->service())) { + $this->setBaseApiUri($storage->retrieveAccessToken($this->service())); + } + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING_V3; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://login.mailchimp.com/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://login.mailchimp.com/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + // Parse JSON + $data = json_decode($responseBody, true); + + // Do validation. + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + // Create token object. + $token = new StdOAuth2Token($data['access_token']); + + // Set the right API endpoint. + $this->setBaseApiUri($token); + + // Mailchimp tokens evidently never expire... + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + + return $token; + } + + /** + * {@inheritdoc} + */ + public function request($path, $method = 'GET', $body = null, array $extraHeaders = array()) + { + if (is_null($this->baseApiUri)) { + $this->setBaseApiUri($this->storage->retrieveAccessToken($this->service())); + } + + return parent::request($path, $method, $body, $extraHeaders); + } + + /** + * Set the right base endpoint. + * + * @param StdOAuth2Token $token + */ + protected function setBaseApiUri(StdOAuth2Token $token) + { + // Make request uri. + $endpoint = 'https://login.mailchimp.com/oauth2/metadata?oauth_token='. $token->getAccessToken(); + + // Grab meta data about the token. + $response = $this->httpClient->retrieveResponse(new Uri($endpoint), array(), array(), 'GET'); + + // Parse JSON. + $meta = json_decode($response, true); + + // Set base api uri. + $this->baseApiUri = new Uri('https://'. $meta['dc'] .'.api.mailchimp.com/2.0/'); + + // Allow chaining. + return $this; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Microsoft.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Microsoft.php new file mode 100644 index 00000000..183ef452 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Microsoft.php @@ -0,0 +1,119 @@ +baseApiUri = new Uri('https://apis.live.net/v5.0/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://login.live.com/oauth20_authorize.srf'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://login.live.com/oauth20_token.srf'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifetime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Paypal.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Paypal.php new file mode 100644 index 00000000..761c09d6 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Paypal.php @@ -0,0 +1,103 @@ + + * @link https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/ + */ +class Paypal extends AbstractService +{ + /** + * Defined scopes + * @link https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/ + * @see #attributes + */ + const SCOPE_OPENID = 'openid'; + const SCOPE_PROFILE = 'profile'; + const SCOPE_PAYPALATTRIBUTES = 'https://uri.paypal.com/services/paypalattributes'; + const SCOPE_EMAIL = 'email'; + const SCOPE_ADDRESS = 'address'; + const SCOPE_PHONE = 'phone'; + const SCOPE_EXPRESSCHECKOUT = 'https://uri.paypal.com/services/expresscheckout'; + + public function __construct( + CredentialsInterface $credentials, + ClientInterface $httpClient, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri); + + if (null === $baseApiUri) { + $this->baseApiUri = new Uri('https://api.paypal.com/v1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.paypal.com/v1/identity/openidconnect/tokenservice'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['message'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['message'] . '"'); + } elseif (isset($data['name'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['name'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Pocket.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Pocket.php new file mode 100644 index 00000000..8c955440 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Pocket.php @@ -0,0 +1,125 @@ +baseApiUri = new Uri('https://getpocket.com/v3/'); + } + } + + public function getRequestTokenEndpoint() + { + return new Uri('https://getpocket.com/v3/oauth/request'); + } + + public function getAuthorizationEndpoint() + { + return new Uri('https://getpocket.com/auth/authorize'); + } + + public function getAccessTokenEndpoint() + { + return new Uri('https://getpocket.com/v3/oauth/authorize'); + } + + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'redirect_uri' => $this->credentials->getCallbackUrl(), + ) + ); + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + public function requestRequestToken() + { + $responseBody = $this->httpClient->retrieveResponse( + $this->getRequestTokenEndpoint(), + array( + 'consumer_key' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + ) + ); + + $code = $this->parseRequestTokenResponse($responseBody); + + return $code; + } + + protected function parseRequestTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (!isset($data['code'])) { + throw new TokenResponseException('Error in retrieving code.'); + } + return $data['code']; + } + + public function requestAccessToken($code) + { + $bodyParams = array( + 'consumer_key' => $this->credentials->getConsumerId(), + 'code' => $code, + ); + + $responseBody = $this->httpClient->retrieveResponse( + $this->getAccessTokenEndpoint(), + $bodyParams, + $this->getExtraOAuthHeaders() + ); + $token = $this->parseAccessTokenResponse($responseBody); + $this->storage->storeAccessToken($this->service(), $token); + + return $token; + } + + protected function parseAccessTokenResponse($responseBody) + { + parse_str($responseBody, $data); + + if ($data === null || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + #$token->setRequestToken($data['access_token']); + $token->setAccessToken($data['access_token']); + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Reddit.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Reddit.php new file mode 100644 index 00000000..9e524d12 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Reddit.php @@ -0,0 +1,114 @@ +baseApiUri = new Uri('https://oauth.reddit.com'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://ssl.reddit.com/api/v1/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://ssl.reddit.com/api/v1/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getExtraOAuthHeaders() + { + // Reddit uses a Basic OAuth header + return array('Authorization' => 'Basic ' . + base64_encode($this->credentials->getConsumerId() . ':' . $this->credentials->getConsumerSecret())); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/RunKeeper.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/RunKeeper.php new file mode 100644 index 00000000..71584076 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/RunKeeper.php @@ -0,0 +1,105 @@ +baseApiUri = new Uri('https://api.runkeeper.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationUri(array $additionalParameters = array()) + { + $parameters = array_merge( + $additionalParameters, + array( + 'client_id' => $this->credentials->getConsumerId(), + 'redirect_uri' => $this->credentials->getCallbackUrl(), + 'response_type' => 'code', + ) + ); + + $parameters['scope'] = implode(' ', $this->scopes); + + // Build the url + $url = clone $this->getAuthorizationEndpoint(); + foreach ($parameters as $key => $val) { + $url->addToQuery($key, $val); + } + + return $url; + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://runkeeper.com/apps/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://runkeeper.com/apps/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Salesforce.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Salesforce.php new file mode 100644 index 00000000..583e4347 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Salesforce.php @@ -0,0 +1,92 @@ +parseAccessTokenResponse($responseBody); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + // Salesforce tokens evidently never expire... + $token->setEndOfLife(StdOAuth2Token::EOL_NEVER_EXPIRES); + unset($data['access_token']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getExtraOAuthHeaders() + { + return array('Accept' => 'application/json'); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/ServiceInterface.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/ServiceInterface.php new file mode 100644 index 00000000..f3d1bdad --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/ServiceInterface.php @@ -0,0 +1,37 @@ +baseApiUri = new Uri('https://api.soundcloud.com/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://soundcloud.com/connect'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://api.soundcloud.com/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + + if (isset($data['expires_in'])) { + $token->setLifetime($data['expires_in']); + unset($data['expires_in']); + } + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Ustream.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Ustream.php new file mode 100644 index 00000000..7e558153 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Ustream.php @@ -0,0 +1,98 @@ +baseApiUri = new Uri('https://api.ustream.tv/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.ustream.tv/oauth2/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.ustream.tv/oauth2/token'); + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getExtraOAuthHeaders() + { + return array('Authorization' => 'Basic ' . $this->credentials->getConsumerSecret()); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Vkontakte.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Vkontakte.php new file mode 100644 index 00000000..4a7744ec --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Vkontakte.php @@ -0,0 +1,109 @@ +baseApiUri = new Uri('https://api.vk.com/method/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://oauth.vk.com/authorize'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://oauth.vk.com/access_token'); + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']); + $token->setLifeTime($data['expires_in']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } + + /** + * {@inheritdoc} + */ + protected function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_QUERY_STRING; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Yammer.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Yammer.php new file mode 100644 index 00000000..994a2935 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Service/Yammer.php @@ -0,0 +1,82 @@ +baseApiUri = new Uri('https://www.yammer.com/api/v1/'); + } + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationEndpoint() + { + return new Uri('https://www.yammer.com/dialog/oauth'); + } + + /** + * {@inheritdoc} + */ + public function getAccessTokenEndpoint() + { + return new Uri('https://www.yammer.com/oauth2/access_token.json'); + } + + /** + * {@inheritdoc} + */ + public function getAuthorizationMethod() + { + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + /** + * {@inheritdoc} + */ + protected function parseAccessTokenResponse($responseBody) + { + $data = json_decode($responseBody, true); + + if (null === $data || !is_array($data)) { + throw new TokenResponseException('Unable to parse response.'); + } elseif (isset($data['error'])) { + throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"'); + } + + $token = new StdOAuth2Token(); + $token->setAccessToken($data['access_token']['token']); + $token->setLifetime($data['access_token']['expires_at']); + + if (isset($data['refresh_token'])) { + $token->setRefreshToken($data['refresh_token']); + unset($data['refresh_token']); + } + + unset($data['access_token']); + unset($data['expires_in']); + + $token->setExtraParams($data); + + return $token; + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/OAuth2/Token/StdOAuth2Token.php b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Token/StdOAuth2Token.php new file mode 100644 index 00000000..eaaacac7 --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/OAuth2/Token/StdOAuth2Token.php @@ -0,0 +1,13 @@ + + * @author Pieter Hordijk + * @copyright Copyright (c) 2013 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +namespace OAuth; + +use OAuth\Common\Service\ServiceInterface; +use OAuth\Common\Consumer\CredentialsInterface; +use OAuth\Common\Storage\TokenStorageInterface; +use OAuth\Common\Http\Client\ClientInterface; +use OAuth\Common\Http\Client\StreamClient; +use OAuth\Common\Http\Uri\UriInterface; +use OAuth\Common\Exception\Exception; +use OAuth\OAuth1\Signature\Signature; + +class ServiceFactory +{ + /** + *@var ClientInterface + */ + protected $httpClient; + + /** + * @var array + */ + protected $serviceClassMap = array( + 'OAuth1' => array(), + 'OAuth2' => array() + ); + + /** + * @var array + */ + protected $serviceBuilders = array( + 'OAuth2' => 'buildV2Service', + 'OAuth1' => 'buildV1Service', + ); + + /** + * @param ClientInterface $httpClient + * + * @return ServiceFactory + */ + public function setHttpClient(ClientInterface $httpClient) + { + $this->httpClient = $httpClient; + + return $this; + } + + /** + * Register a custom service to classname mapping. + * + * @param string $serviceName Name of the service + * @param string $className Class to instantiate + * + * @return ServiceFactory + * + * @throws Exception If the class is nonexistent or does not implement a valid ServiceInterface + */ + public function registerService($serviceName, $className) + { + if (!class_exists($className)) { + throw new Exception(sprintf('Service class %s does not exist.', $className)); + } + + $reflClass = new \ReflectionClass($className); + + foreach (array('OAuth2', 'OAuth1') as $version) { + if ($reflClass->implementsInterface('OAuth\\' . $version . '\\Service\\ServiceInterface')) { + $this->serviceClassMap[$version][ucfirst($serviceName)] = $className; + + return $this; + } + } + + throw new Exception(sprintf('Service class %s must implement ServiceInterface.', $className)); + } + + /** + * Builds and returns oauth services + * + * It will first try to build an OAuth2 service and if none found it will try to build an OAuth1 service + * + * @param string $serviceName Name of service to create + * @param CredentialsInterface $credentials + * @param TokenStorageInterface $storage + * @param array|null $scopes If creating an oauth2 service, array of scopes + * @param UriInterface|null $baseApiUri + * + * @return ServiceInterface + */ + public function createService( + $serviceName, + CredentialsInterface $credentials, + TokenStorageInterface $storage, + $scopes = array(), + UriInterface $baseApiUri = null + ) { + if (!$this->httpClient) { + // for backwards compatibility. + $this->httpClient = new StreamClient(); + } + + foreach ($this->serviceBuilders as $version => $buildMethod) { + $fullyQualifiedServiceName = $this->getFullyQualifiedServiceName($serviceName, $version); + + if (class_exists($fullyQualifiedServiceName)) { + return $this->$buildMethod($fullyQualifiedServiceName, $credentials, $storage, $scopes, $baseApiUri); + } + } + + return null; + } + + /** + * Gets the fully qualified name of the service + * + * @param string $serviceName The name of the service of which to get the fully qualified name + * @param string $type The type of the service to get (either OAuth1 or OAuth2) + * + * @return string The fully qualified name of the service + */ + private function getFullyQualifiedServiceName($serviceName, $type) + { + $serviceName = ucfirst($serviceName); + + if (isset($this->serviceClassMap[$type][$serviceName])) { + return $this->serviceClassMap[$type][$serviceName]; + } + + return '\\OAuth\\' . $type . '\\Service\\' . $serviceName; + } + + /** + * Builds v2 services + * + * @param string $serviceName The fully qualified service name + * @param CredentialsInterface $credentials + * @param TokenStorageInterface $storage + * @param array|null $scopes Array of scopes for the service + * @param UriInterface|null $baseApiUri + * + * @return ServiceInterface + * + * @throws Exception + */ + private function buildV2Service( + $serviceName, + CredentialsInterface $credentials, + TokenStorageInterface $storage, + array $scopes, + UriInterface $baseApiUri = null + ) { + return new $serviceName( + $credentials, + $this->httpClient, + $storage, + $this->resolveScopes($serviceName, $scopes), + $baseApiUri + ); + } + + /** + * Resolves scopes for v2 services + * + * @param string $serviceName The fully qualified service name + * @param array $scopes List of scopes for the service + * + * @return array List of resolved scopes + */ + private function resolveScopes($serviceName, array $scopes) + { + $reflClass = new \ReflectionClass($serviceName); + $constants = $reflClass->getConstants(); + + $resolvedScopes = array(); + foreach ($scopes as $scope) { + $key = strtoupper('SCOPE_' . $scope); + + if (array_key_exists($key, $constants)) { + $resolvedScopes[] = $constants[$key]; + } else { + $resolvedScopes[] = $scope; + } + } + + return $resolvedScopes; + } + + /** + * Builds v1 services + * + * @param string $serviceName The fully qualified service name + * @param CredentialsInterface $credentials + * @param TokenStorageInterface $storage + * @param array $scopes + * @param UriInterface $baseApiUri + * + * @return ServiceInterface + * + * @throws Exception + */ + private function buildV1Service( + $serviceName, + CredentialsInterface $credentials, + TokenStorageInterface $storage, + $scopes, + UriInterface $baseApiUri = null + ) { + if (!empty($scopes)) { + throw new Exception( + 'Scopes passed to ServiceFactory::createService but an OAuth1 service was requested.' + ); + } + + return new $serviceName($credentials, $this->httpClient, $storage, new Signature($credentials), $baseApiUri); + } +} diff --git a/vendor/lusitanian/oauth/src/OAuth/bootstrap.php b/vendor/lusitanian/oauth/src/OAuth/bootstrap.php new file mode 100644 index 00000000..548678aa --- /dev/null +++ b/vendor/lusitanian/oauth/src/OAuth/bootstrap.php @@ -0,0 +1,13 @@ +register(); diff --git a/vendor/lusitanian/oauth/tests/Mocks/Common/FakeProject/NS/SomeClass.php b/vendor/lusitanian/oauth/tests/Mocks/Common/FakeProject/NS/SomeClass.php new file mode 100644 index 00000000..c033c4e2 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Mocks/Common/FakeProject/NS/SomeClass.php @@ -0,0 +1,11 @@ +determineRequestUriFromPath($path, $baseApiUri); + } +} diff --git a/vendor/lusitanian/oauth/tests/Mocks/OAuth1/Service/Fake.php b/vendor/lusitanian/oauth/tests/Mocks/OAuth1/Service/Fake.php new file mode 100644 index 00000000..5dac52e7 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Mocks/OAuth1/Service/Fake.php @@ -0,0 +1,57 @@ +authorizationMethod = $method; + } + + /** + * Returns a class constant from ServiceInterface defining the authorization method used for the API + * Header is the sane default. + * + * @return int + */ + protected function getAuthorizationMethod() + { + switch($this->authorizationMethod) { + case 'querystring': + return static::AUTHORIZATION_METHOD_QUERY_STRING; + + case 'querystring2': + return static::AUTHORIZATION_METHOD_QUERY_STRING_V2; + + case 'bearer': + return static::AUTHORIZATION_METHOD_HEADER_BEARER; + } + + return parent::getAuthorizationMethod(); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/AutoloaderTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/AutoloaderTest.php new file mode 100644 index 00000000..eebc3408 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/AutoloaderTest.php @@ -0,0 +1,126 @@ +assertTrue($autoloader->register()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::unregister + */ + public function testUnregister() + { + $autoloader = new AutoLoader('Test', '/'); + + $this->assertTrue($autoloader->register()); + $this->assertTrue($autoloader->unregister()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadSuccess() + { + $autoloader = new AutoLoader('FakeProject', dirname(__DIR__) . '/../Mocks/Common'); + + $this->assertTrue($autoloader->register()); + + $someClass = new \FakeProject\NS\SomeClass(); + + $this->assertTrue($someClass->isLoaded()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadSuccessExtraSlashedNamespace() + { + $autoloader = new AutoLoader('\\\\FakeProject', dirname(__DIR__) . '/../Mocks/Common'); + + $this->assertTrue($autoloader->register()); + + $someClass = new \FakeProject\NS\SomeClass(); + + $this->assertTrue($someClass->isLoaded()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadSuccessExtraForwardSlashedPath() + { + $autoloader = new AutoLoader('FakeProject', dirname(__DIR__) . '/../Mocks/Common//'); + + $this->assertTrue($autoloader->register()); + + $someClass = new \FakeProject\NS\SomeClass(); + + $this->assertTrue($someClass->isLoaded()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadSuccessExtraBackwardSlashedPath() + { + $autoloader = new AutoLoader('FakeProject', dirname(__DIR__) . '/../Mocks/Common\\'); + + $this->assertTrue($autoloader->register()); + + $someClass = new \FakeProject\NS\SomeClass(); + + $this->assertTrue($someClass->isLoaded()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadSuccessExtraMixedSlashedPath() + { + $autoloader = new AutoLoader('FakeProject', dirname(__DIR__) . '/../Mocks/Common\\\\/\\//'); + + $this->assertTrue($autoloader->register()); + + $someClass = new \FakeProject\NS\SomeClass(); + + $this->assertTrue($someClass->isLoaded()); + } + + /** + * @covers OAuth\Common\AutoLoader::__construct + * @covers OAuth\Common\AutoLoader::register + * @covers OAuth\Common\AutoLoader::load + */ + public function testLoadUnknownClass() + { + $autoloader = new AutoLoader('FakeProject', dirname(__DIR__) . '/../Mocks/Common\\\\/\\//'); + + $this->assertTrue($autoloader->register()); + + $this->assertFalse($autoloader->load('IDontExistClass')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Consumer/CredentialsTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Consumer/CredentialsTest.php new file mode 100644 index 00000000..1a895fbc --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Consumer/CredentialsTest.php @@ -0,0 +1,51 @@ +assertInstanceOf('\\OAuth\\Common\\Consumer\\CredentialsInterface', $credentials); + } + + /** + * @covers OAuth\Common\Consumer\Credentials::__construct + * @covers OAuth\Common\Consumer\Credentials::getConsumerId + */ + public function testGetConsumerId() + { + $credentials = new Credentials('foo', 'bar', 'baz'); + + $this->assertSame('foo', $credentials->getConsumerId()); + } + + /** + * @covers OAuth\Common\Consumer\Credentials::__construct + * @covers OAuth\Common\Consumer\Credentials::getConsumerSecret + */ + public function testGetConsumerSecret() + { + $credentials = new Credentials('foo', 'bar', 'baz'); + + $this->assertSame('bar', $credentials->getConsumerSecret()); + } + + /** + * @covers OAuth\Common\Consumer\Credentials::__construct + * @covers OAuth\Common\Consumer\Credentials::getCallbackUrl + */ + public function testGetCallbackUrl() + { + $credentials = new Credentials('foo', 'bar', 'baz'); + + $this->assertSame('baz', $credentials->getCallbackUrl()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/AbstractClientTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/AbstractClientTest.php new file mode 100644 index 00000000..b3531527 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/AbstractClientTest.php @@ -0,0 +1,67 @@ +getMockForAbstractClass('\\OAuth\\Common\\Http\\Client\\AbstractClient'); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\ClientInterface', $client); + } + + /** + * @covers OAuth\Common\Http\Client\AbstractClient::__construct + * @covers OAuth\Common\Http\Client\AbstractClient::setMaxRedirects + */ + public function testSetMaxRedirects() + { + $client = $this->getMockForAbstractClass('\\OAuth\\Common\\Http\\Client\\AbstractClient'); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\AbstractClient', $client->setMaxRedirects(10)); + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\ClientInterface', $client->setMaxRedirects(10)); + } + + /** + * @covers OAuth\Common\Http\Client\AbstractClient::__construct + * @covers OAuth\Common\Http\Client\AbstractClient::setTimeout + */ + public function testSetTimeout() + { + $client = $this->getMockForAbstractClass('\\OAuth\\Common\\Http\\Client\\AbstractClient'); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\AbstractClient', $client->setTimeout(25)); + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\ClientInterface', $client->setTimeout(25)); + } + + /** + * @covers OAuth\Common\Http\Client\AbstractClient::__construct + * @covers OAuth\Common\Http\Client\AbstractClient::normalizeHeaders + */ + public function testNormalizeHeaders() + { + $client = $this->getMockForAbstractClass('\\OAuth\\Common\\Http\\Client\\AbstractClient'); + + $original = array( + 'lowercasekey' => 'lowercasevalue', + 'UPPERCASEKEY' => 'UPPERCASEVALUE', + 'mIxEdCaSeKey' => 'MiXeDcAsEvAlUe', + '31i71casekey' => '31i71casevalue', + ); + + $goal = array( + 'lowercasekey' => 'Lowercasekey: lowercasevalue', + 'UPPERCASEKEY' => 'Uppercasekey: UPPERCASEVALUE', + 'mIxEdCaSeKey' => 'Mixedcasekey: MiXeDcAsEvAlUe', + '31i71casekey' => '31i71casekey: 31i71casevalue', + ); + + $client->normalizeHeaders($original); + + $this->assertSame($goal, $original); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/CurlClientTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/CurlClientTest.php new file mode 100644 index 00000000..f635ce89 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/CurlClientTest.php @@ -0,0 +1,378 @@ +assertInstanceOf('\\OAuth\\Common\\Http\\Client\\AbstractClient', $client); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::setForceSSL3 + */ + public function testSetForceSSL3() + { + $client = new CurlClient(); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Client\\CurlClient', $client->setForceSSL3(true)); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseThrowsExceptionOnGetRequestWithBody() + { + $this->setExpectedException('\\InvalidArgumentException'); + + $client = new CurlClient(); + + $client->retrieveResponse( + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + 'foo', + array(), + 'GET' + ); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseThrowsExceptionOnGetRequestWithBodyMethodConvertedToUpper() + { + $this->setExpectedException('\\InvalidArgumentException'); + + $client = new CurlClient(); + + $client->retrieveResponse( + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + 'foo', + array(), + 'get' + ); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseDefaultUserAgent() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + '', + array(), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('PHPoAuthLib', $response['headers']['User-Agent']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseCustomUserAgent() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new CurlClient('My Super Awesome Http Client'); + + $response = $client->retrieveResponse( + $endPoint, + '', + array(), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('My Super Awesome Http Client', $response['headers']['User-Agent']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseWithCustomContentType() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + '', + array('Content-Type' => 'foo/bar'), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('foo/bar', $response['headers']['Content-Type']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseWithFormUrlEncodedContentType() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + array('foo' => 'bar', 'baz' => 'fab'), + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame('application/x-www-form-urlencoded', $response['headers']['Content-Type']); + $this->assertEquals(array('foo' => 'bar', 'baz' => 'fab'), $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseHost() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + array('foo' => 'bar', 'baz' => 'fab'), + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame('httpbin.org', $response['headers']['Host']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponsePostRequestWithRequestBodyAsString() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $formData = array('baz' => 'fab', 'foo' => 'bar'); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + $formData, + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame($formData, $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponsePutRequestWithRequestBodyAsString() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/put')); + + $formData = array('baz' => 'fab', 'foo' => 'bar'); + + $client = new CurlClient(); + + $response = $client->retrieveResponse( + $endPoint, + $formData, + array(), + 'PUT' + ); + + $response = json_decode($response, true); + + $this->assertSame($formData, $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponsePutRequestWithRequestBodyAsStringNoRedirects() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/put')); + + $formData = array('baz' => 'fab', 'foo' => 'bar'); + + $client = new CurlClient(); + + $client->setMaxRedirects(0); + + $response = $client->retrieveResponse( + $endPoint, + $formData, + array(), + 'PUT' + ); + + $response = json_decode($response, true); + + $this->assertSame($formData, $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseWithForcedSsl3() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('https://httpbin.org/get')); + + $client = new CurlClient(); + + $client->setForceSSL3(true); + + $response = $client->retrieveResponse( + $endPoint, + '', + array('Content-Type' => 'foo/bar'), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('foo/bar', $response['headers']['Content-Type']); + } + + /** + * @covers OAuth\Common\Http\Client\CurlClient::retrieveResponse + */ + public function testRetrieveResponseThrowsExceptionOnInvalidUrl() + { + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('jkehfkefcmekjhcnkerjh')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('jkehfkefcmekjhcnkerjh')); + + $client = new CurlClient(); + + $client->setForceSSL3(true); + + $response = $client->retrieveResponse( + $endPoint, + '', + array('Content-Type' => 'foo/bar'), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('foo/bar', $response['headers']['Content-Type']); + } + + public function testAdditionalParameters() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/gzip')); + + $client = new CurlClient(); + $client->setCurlParameters(array( + CURLOPT_ENCODING => 'gzip', + )); + + $response = $client->retrieveResponse( + $endPoint, + '', + array(), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertNotNull($response); + $this->assertSame('gzip', $response['headers']['Accept-Encoding']); + $this->assertTrue($response['gzipped']); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/StreamClientTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/StreamClientTest.php new file mode 100644 index 00000000..f634f406 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Client/StreamClientTest.php @@ -0,0 +1,283 @@ +assertInstanceOf('\\OAuth\\Common\\Http\\Client\\AbstractClient', $client); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + */ + public function testRetrieveResponseThrowsExceptionOnGetRequestWithBody() + { + $this->setExpectedException('\\InvalidArgumentException'); + + $client = new StreamClient(); + + $client->retrieveResponse( + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + 'foo', + array(), + 'GET' + ); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + */ + public function testRetrieveResponseThrowsExceptionOnGetRequestWithBodyMethodConvertedToUpper() + { + $this->setExpectedException('\\InvalidArgumentException'); + + $client = new StreamClient(); + + $client->retrieveResponse( + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + 'foo', + array(), + 'get' + ); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseDefaultUserAgent() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + '', + array(), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('PHPoAuthLib', $response['headers']['User-Agent']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseCustomUserAgent() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new StreamClient('My Super Awesome Http Client'); + + $response = $client->retrieveResponse( + $endPoint, + '', + array(), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('My Super Awesome Http Client', $response['headers']['User-Agent']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseWithCustomContentType() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/get')); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + '', + array('Content-Type' => 'foo/bar'), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('foo/bar', $response['headers']['Content-Type']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseWithFormUrlEncodedContentType() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + array('foo' => 'bar', 'baz' => 'fab'), + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame('application/x-www-form-urlencoded', $response['headers']['Content-Type']); + $this->assertEquals(array('foo' => 'bar', 'baz' => 'fab'), $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseHost() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + array('foo' => 'bar', 'baz' => 'fab'), + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame('httpbin.org', $response['headers']['Host']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponsePostRequestWithRequestBodyAsString() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/post')); + + $formData = array('baz' => 'fab', 'foo' => 'bar'); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + $formData, + array(), + 'POST' + ); + + $response = json_decode($response, true); + + $this->assertSame($formData, $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponsePutRequestWithRequestBodyAsString() + { + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('httpbin.org')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('http://httpbin.org/put')); + + $formData = array('baz' => 'fab', 'foo' => 'bar'); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + $formData, + array(), + 'PUT' + ); + + $response = json_decode($response, true); + + $this->assertSame($formData, $response['form']); + } + + /** + * @covers OAuth\Common\Http\Client\StreamClient::retrieveResponse + * @covers OAuth\Common\Http\Client\StreamClient::generateStreamContext + */ + public function testRetrieveResponseThrowsExceptionOnInvalidRequest() + { + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $endPoint = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $endPoint->expects($this->any()) + ->method('getHost') + ->will($this->returnValue('dskjhfckjhekrsfhkehfkreljfrekljfkre')); + $endPoint->expects($this->any()) + ->method('getAbsoluteUri') + ->will($this->returnValue('dskjhfckjhekrsfhkehfkreljfrekljfkre')); + + $client = new StreamClient(); + + $response = $client->retrieveResponse( + $endPoint, + '', + array('Content-Type' => 'foo/bar'), + 'get' + ); + + $response = json_decode($response, true); + + $this->assertSame('foo/bar', $response['headers']['Content-Type']); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/HttpClientsTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/HttpClientsTest.php new file mode 100644 index 00000000..6fa9eace --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/HttpClientsTest.php @@ -0,0 +1,171 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +namespace OAuth\Unit\Common\Http; + +use OAuth\Common\Http\Uri\Uri; +use OAuth\Common\Http\Uri\UriInterface; +use OAuth\Common\Http\Client; + +class HttpClientsTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var object|\OAuth\Common\Http\Client\ClientInterface[] + */ + protected $clients; + + public function setUp() + { + $streamClient = new Client\StreamClient(); + $streamClient->setTimeout(3); + + $curlClient = new Client\CurlClient(); + $curlClient->setTimeout(3); + + $this->clients[] = $streamClient; + $this->clients[] = $curlClient; + } + + public function tearDown() + { + foreach ($this->clients as $client) { + unset($client); + } + } + + /** + * Test that extra headers are passed properly + */ + public function testHeaders() + { + $testUri = new Uri('http://httpbin.org/get'); + + $me = $this; + $headerCb = function ($response) use ($me) { + $data = json_decode($response, true); + $me->assertEquals('extraheadertest', $data['headers']['Testingheader']); + }; + + $this->__doTestRetrieveResponse($testUri, array(), array('Testingheader' => 'extraheadertest'), 'GET', $headerCb); + } + + /** + * Tests that we get an exception for a >= 400 status code + */ + public function testException() + { + // sending a post here should get us a 405 which should trigger an exception + $testUri = new Uri('http://httpbin.org/delete'); + foreach ($this->clients as $client) { + $this->setExpectedException('OAuth\Common\Http\Exception\TokenResponseException'); + $client->retrieveResponse($testUri, array('blah' => 'blih')); + } + } + + /** + * Tests the DELETE method + */ + public function testDelete() + { + $testUri = new Uri('http://httpbin.org/delete'); + + $me = $this; + $deleteTestCb = function ($response) use ($me) { + $data = json_decode($response, true); + $me->assertEquals('', $data['data']); + }; + + $this->__doTestRetrieveResponse($testUri, array(), array(), 'DELETE', $deleteTestCb); + } + + /** + * Tests the PUT method + */ + public function testPut() + { + $testUri = new Uri('http://httpbin.org/put'); + + $me = $this; + $putTestCb = function ($response) use ($me) { + // verify the put response + $data = json_decode($response, true); + $me->assertEquals(json_encode(array('testKey' => 'testValue')), $data['data']); + }; + + $this->__doTestRetrieveResponse($testUri, json_encode(array('testKey' => 'testValue')), array('Content-Type' => 'application/json'), 'PUT', $putTestCb); + } + + /** + * Tests the POST method + */ + public function testPost() + { + // http test server + $testUri = new Uri('http://httpbin.org/post'); + + $me = $this; + $postTestCb = function ($response) use ($me) { + // verify the post response + $data = json_decode($response, true); + // note that we check this because the retrieveResponse wrapper function automatically adds a content-type + // if there isn't one and it + $me->assertEquals('testValue', $data['form']['testKey']); + }; + + $this->__doTestRetrieveResponse($testUri, array('testKey' => 'testValue'), array(), 'POST', $postTestCb); + } + + /** + * Expect exception when we try to send a GET request with a body + */ + public function testInvalidGet() + { + $testUri = new Uri('http://site.net'); + + foreach ($this->clients as $client) { + $this->setExpectedException('InvalidArgumentException'); + $client->retrieveResponse($testUri, array('blah' => 'blih'), array(), 'GET'); + } + } + + /** + * Tests the GET method + */ + public function testGet() + { + // test uri + $testUri = new Uri('http://httpbin.org/get?testKey=testValue'); + + $me = $this; + $getTestCb = function ($response) use ($me) { + $data = json_decode($response, true); + $me->assertEquals('testValue', $data['args']['testKey']); + }; + + $this->__doTestRetrieveResponse($testUri, array(), array(), 'GET', $getTestCb); + } + + /** + * Test on all HTTP clients. + * + * @param UriInterface $uri + * @param array $param + * @param array $header + * @param string $method + * @param \Closure $responseCallback + */ + protected function __doTestRetrieveResponse(UriInterface $uri, $param, array $header, $method, $responseCallback) + { + foreach ($this->clients as $client) { + $response = $client->retrieveResponse($uri, $param, $header, $method); + $responseCallback($response, $client); + } + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriFactoryTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriFactoryTest.php new file mode 100644 index 00000000..ea743509 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriFactoryTest.php @@ -0,0 +1,331 @@ +assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriFactoryInterface', $factory); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + */ + public function testCreateFromSuperGlobalArrayUsingProxyStyle() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array('REQUEST_URI' => 'http://example.com')); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayHttp() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTPS' => 'off', + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * This looks wonky David. Should the port really fallback to 80 even when supplying https as scheme? + * + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayHttps() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTPS' => 'on', + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('https://example.com:80/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayPortSupplied() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'SERVER_PORT' => 21, + 'REQUEST_URI' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com:21/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayPortNotSet() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayRequestUriSet() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayRedirectUrlSet() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'REDIRECT_URL' => '/foo', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayThrowsExceptionOnDetectingPathMissingIndices() + { + $factory = new UriFactory(); + + $this->setExpectedException('\\RuntimeException'); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'QUERY_STRING' => 'param1=value1', + )); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayWithQueryString() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo?param1=value1', + 'QUERY_STRING' => 'param1=value1', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayWithoutQueryString() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com', + 'REQUEST_URI' => '/foo', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromSuperGlobalArray + * @covers OAuth\Common\Http\Uri\UriFactory::attemptProxyStyleParse + * @covers OAuth\Common\Http\Uri\UriFactory::detectScheme + * @covers OAuth\Common\Http\Uri\UriFactory::detectHost + * @covers OAuth\Common\Http\Uri\UriFactory::detectPort + * @covers OAuth\Common\Http\Uri\UriFactory::detectPath + * @covers OAuth\Common\Http\Uri\UriFactory::detectQuery + * @covers OAuth\Common\Http\Uri\UriFactory::createFromParts + */ + public function testCreateFromSuperGlobalArrayHostWithColon() + { + $factory = new UriFactory(); + + $uri = $factory->createFromSuperGlobalArray(array( + 'HTTP_HOST' => 'example.com:80', + 'REQUEST_URI' => '/foo', + )); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com/foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\UriFactory::createFromAbsolute + */ + public function testCreateFromAbsolute() + { + $factory = new UriFactory(); + + $uri = $factory->createFromAbsolute('http://example.com'); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $uri + ); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriTest.php new file mode 100644 index 00000000..bc158ffa --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Http/Uri/UriTest.php @@ -0,0 +1,898 @@ +assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriInterface', $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + */ + public function testConstructThrowsExceptionOnInvalidUri() + { + $this->setExpectedException('\\InvalidArgumentException'); + + // http://lxr.php.net/xref/PHP_5_4/ext/standard/tests/url/urls.inc#92 + $uri = new Uri('http://@:/'); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + */ + public function testConstructThrowsExceptionOnUriWithoutScheme() + { + $this->setExpectedException('\\InvalidArgumentException'); + + $uri = new Uri('www.pieterhordijk.com'); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getScheme + */ + public function testGetScheme() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('http', $uri->getScheme()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getUserInfo + */ + public function testGetUserInfo() + { + $uri = new Uri('http://peehaa@example.com'); + + $this->assertSame('peehaa', $uri->getUserInfo()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getUserInfo + */ + public function testGetUserInfoWithPass() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('peehaa:********', $uri->getUserInfo()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawUserInfo + */ + public function testGetRawUserInfo() + { + $uri = new Uri('http://peehaa@example.com'); + + $this->assertSame('peehaa', $uri->getRawUserInfo()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawUserInfo + */ + public function testGetRawUserInfoWithPass() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('peehaa:pass', $uri->getRawUserInfo()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getHost + */ + public function testGetHost() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('example.com', $uri->getHost()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPort + */ + public function testGetPortImplicitHttp() + { + $uri = new Uri('http://example.com'); + + $this->assertSame(80, $uri->getPort()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPort + */ + public function testGetPortImplicitHttps() + { + $uri = new Uri('https://example.com'); + + $this->assertSame(443, $uri->getPort()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPort + */ + public function testGetPortExplicit() + { + $uri = new Uri('http://example.com:21'); + + $this->assertSame(21, $uri->getPort()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPath + */ + public function testGetPathNotSupplied() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('/', $uri->getPath()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPath + */ + public function testGetPathSlash() + { + $uri = new Uri('http://example.com/'); + + $this->assertSame('/', $uri->getPath()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getPath + */ + public function testGetPath() + { + $uri = new Uri('http://example.com/foo'); + + $this->assertSame('/foo', $uri->getPath()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getQuery + */ + public function testGetQueryWithParams() + { + $uri = new Uri('http://example.com?param1=first¶m2=second'); + + $this->assertSame('param1=first¶m2=second', $uri->getQuery()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getQuery + */ + public function testGetQueryWithoutParams() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('', $uri->getQuery()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getFragment + */ + public function testGetFragmentExists() + { + $uri = new Uri('http://example.com#foo'); + + $this->assertSame('foo', $uri->getFragment()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getFragment + */ + public function testGetFragmentNotExists() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('', $uri->getFragment()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAuthority + */ + public function testGetAuthorityWithoutUserInfo() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('example.com', $uri->getAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAuthority + */ + public function testGetAuthorityWithoutUserInfoWithExplicitPort() + { + $uri = new Uri('http://example.com:21'); + + $this->assertSame('example.com:21', $uri->getAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getAuthority + */ + public function testGetAuthorityWithUsernameWithExplicitPort() + { + $uri = new Uri('http://peehaa@example.com:21'); + + $this->assertSame('peehaa@example.com:21', $uri->getAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getAuthority + */ + public function testGetAuthorityWithUsernameAndPassWithExplicitPort() + { + $uri = new Uri('http://peehaa:pass@example.com:21'); + + $this->assertSame('peehaa:********@example.com:21', $uri->getAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getAuthority + */ + public function testGetAuthorityWithUsernameAndPassWithoutExplicitPort() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('peehaa:********@example.com', $uri->getAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + */ + public function testGetRawAuthorityWithoutUserInfo() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('example.com', $uri->getRawAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + */ + public function testGetRawAuthorityWithoutUserInfoWithExplicitPort() + { + $uri = new Uri('http://example.com:21'); + + $this->assertSame('example.com:21', $uri->getRawAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + */ + public function testGetRawAuthorityWithUsernameWithExplicitPort() + { + $uri = new Uri('http://peehaa@example.com:21'); + + $this->assertSame('peehaa@example.com:21', $uri->getRawAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + */ + public function testGetRawAuthorityWithUsernameAndPassWithExplicitPort() + { + $uri = new Uri('http://peehaa:pass@example.com:21'); + + $this->assertSame('peehaa:pass@example.com:21', $uri->getRawAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + */ + public function testGetRawAuthorityWithUsernameAndPassWithoutExplicitPort() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('peehaa:pass@example.com', $uri->getRawAuthority()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriBare() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithAuthority() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('http://peehaa:pass@example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithPath() + { + $uri = new Uri('http://example.com/foo'); + + $this->assertSame('http://example.com/foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithoutPath() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithoutPathExplicitTrailingSlash() + { + $uri = new Uri('http://example.com/'); + + $this->assertSame('http://example.com/', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithQuery() + { + $uri = new Uri('http://example.com?param1=value1'); + + $this->assertSame('http://example.com?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testGetAbsoluteUriWithFragment() + { + $uri = new Uri('http://example.com#foo'); + + $this->assertSame('http://example.com#foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getRelativeUri + */ + public function testGetRelativeUriWithoutPath() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('', $uri->getRelativeUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getRelativeUri + */ + public function testGetRelativeUriWithPath() + { + $uri = new Uri('http://example.com/foo'); + + $this->assertSame('/foo', $uri->getRelativeUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::getRelativeUri + */ + public function testGetRelativeUriWithExplicitTrailingSlash() + { + $uri = new Uri('http://example.com/'); + + $this->assertSame('/', $uri->getRelativeUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringBare() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('http://example.com', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getRawAuthority + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithAuthority() + { + $uri = new Uri('http://peehaa:pass@example.com'); + + $this->assertSame('http://peehaa:********@example.com', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithPath() + { + $uri = new Uri('http://example.com/foo'); + + $this->assertSame('http://example.com/foo', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithoutPath() + { + $uri = new Uri('http://example.com'); + + $this->assertSame('http://example.com', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithoutPathExplicitTrailingSlash() + { + $uri = new Uri('http://example.com/'); + + $this->assertSame('http://example.com/', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithQuery() + { + $uri = new Uri('http://example.com?param1=value1'); + + $this->assertSame('http://example.com?param1=value1', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::__toString + */ + public function testToStringWithFragment() + { + $uri = new Uri('http://example.com#foo'); + + $this->assertSame('http://example.com#foo', (string) $uri); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPath + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPathEmpty() + { + $uri = new Uri('http://example.com'); + $uri->setPath(''); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPath + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPathWithPath() + { + $uri = new Uri('http://example.com'); + $uri->setPath('/foo'); + + $this->assertSame('http://example.com/foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPath + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPathWithOnlySlash() + { + $uri = new Uri('http://example.com'); + $uri->setPath('/'); + + $this->assertSame('http://example.com/', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setQuery + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetQueryEmpty() + { + $uri = new Uri('http://example.com'); + $uri->setQuery(''); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setQuery + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetQueryFilled() + { + $uri = new Uri('http://example.com'); + $uri->setQuery('param1=value1¶m2=value2'); + + $this->assertSame('http://example.com?param1=value1¶m2=value2', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::addToQuery + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testAddToQueryAppend() + { + $uri = new Uri('http://example.com?param1=value1'); + $uri->addToQuery('param2', 'value2'); + + $this->assertSame('http://example.com?param1=value1¶m2=value2', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::addToQuery + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testAddToQueryCreate() + { + $uri = new Uri('http://example.com'); + $uri->addToQuery('param1', 'value1'); + + $this->assertSame('http://example.com?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setFragment + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetFragmentEmpty() + { + $uri = new Uri('http://example.com'); + $uri->setFragment(''); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setFragment + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetFragmentWithData() + { + $uri = new Uri('http://example.com'); + $uri->setFragment('foo'); + + $this->assertSame('http://example.com#foo', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setScheme + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetSchemeWithEmpty() + { + $uri = new Uri('http://example.com'); + $uri->setScheme(''); + + $this->assertSame('://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setScheme + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetSchemeWithData() + { + $uri = new Uri('http://example.com'); + $uri->setScheme('foo'); + + $this->assertSame('foo://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetUserInfoEmpty() + { + $uri = new Uri('http://example.com'); + $uri->setUserInfo(''); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setUserInfo + * @covers OAuth\Common\Http\Uri\Uri::protectUserInfo + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetUserInfoWithData() + { + $uri = new Uri('http://example.com'); + $uri->setUserInfo('foo:bar'); + + $this->assertSame('http://foo:bar@example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPort + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPortCustom() + { + $uri = new Uri('http://example.com'); + $uri->setPort('21'); + + $this->assertSame('http://example.com:21', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPort + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPortHttpImplicit() + { + $uri = new Uri('http://example.com'); + $uri->setPort(80); + + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPort + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPortHttpsImplicit() + { + $uri = new Uri('https://example.com'); + $uri->setPort(443); + + $this->assertSame('https://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPort + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPortHttpExplicit() + { + $uri = new Uri('http://example.com'); + $uri->setPort(443); + + $this->assertSame('http://example.com:443', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setPort + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetPortHttpsExplicit() + { + $uri = new Uri('https://example.com'); + $uri->setPort(80); + + $this->assertSame('https://example.com:80', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::setHost + * @covers OAuth\Common\Http\Uri\Uri::getAbsoluteUri + */ + public function testSetHost() + { + $uri = new Uri('http://example.com'); + $uri->setHost('pieterhordijk.com'); + + $this->assertSame('http://pieterhordijk.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::hasExplicitTrailingHostSlash + */ + public function testHasExplicitTrailingHostSlashTrue() + { + $uri = new Uri('http://example.com/'); + + $this->assertTrue($uri->hasExplicitTrailingHostSlash()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::hasExplicitTrailingHostSlash + */ + public function testHasExplicitTrailingHostSlashFalse() + { + $uri = new Uri('http://example.com/foo'); + + $this->assertFalse($uri->hasExplicitTrailingHostSlash()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::hasExplicitPortSpecified + */ + public function testHasExplicitPortSpecifiedTrue() + { + $uri = new Uri('http://example.com:8080'); + + $this->assertTrue($uri->hasExplicitPortSpecified()); + } + + /** + * @covers OAuth\Common\Http\Uri\Uri::__construct + * @covers OAuth\Common\Http\Uri\Uri::parseUri + * @covers OAuth\Common\Http\Uri\Uri::hasExplicitPortSpecified + */ + public function testHasExplicitPortSpecifiedFalse() + { + $uri = new Uri('http://example.com'); + + $this->assertFalse($uri->hasExplicitPortSpecified()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Service/AbstractServiceTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Service/AbstractServiceTest.php new file mode 100644 index 00000000..2d8bff46 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Service/AbstractServiceTest.php @@ -0,0 +1,171 @@ +getMockForAbstractClass( + '\\OAuth\\Common\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ) + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::getStorage + */ + public function testGetStorage() + { + $service = $this->getMockForAbstractClass( + '\\OAuth\\Common\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ) + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $service->getStorage()); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::service + */ + public function testService() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('Mock', $service->service()); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathUsingUriObject() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Http\\Uri\\UriInterface', + $service->testDetermineRequestUriFromPath($this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface')) + ); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathUsingHttpPath() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $uri = $service->testDetermineRequestUriFromPath('http://example.com'); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriInterface', $uri); + $this->assertSame('http://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathUsingHttpsPath() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $uri = $service->testDetermineRequestUriFromPath('https://example.com'); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriInterface', $uri); + $this->assertSame('https://example.com', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathThrowsExceptionOnInvalidUri() + { + $this->setExpectedException('\\OAuth\\Common\\Exception\\Exception'); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $uri = $service->testDetermineRequestUriFromPath('example.com'); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathWithQueryString() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $uri = $service->testDetermineRequestUriFromPath( + 'path?param1=value1', + new \OAuth\Common\Http\Uri\Uri('https://example.com') + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriInterface', $uri); + $this->assertSame('https://example.com/path?param1=value1', $uri->getAbsoluteUri()); + } + + /** + * @covers OAuth\Common\Service\AbstractService::__construct + * @covers OAuth\Common\Service\AbstractService::determineRequestUriFromPath + */ + public function testDetermineRequestUriFromPathWithLeadingSlashInPath() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $uri = $service->testDetermineRequestUriFromPath( + '/path', + new \OAuth\Common\Http\Uri\Uri('https://example.com') + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\UriInterface', $uri); + $this->assertSame('https://example.com/path', $uri->getAbsoluteUri()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Storage/MemoryTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/MemoryTest.php new file mode 100644 index 00000000..93a01a79 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/MemoryTest.php @@ -0,0 +1,132 @@ +assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $storage); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::storeAccessToken + */ + public function testStoreAccessToken() + { + $storage = new Memory(); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Storage\\Memory', + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')) + ); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::storeAccessToken + * @covers OAuth\Common\Storage\Memory::retrieveAccessToken + * @covers OAuth\Common\Storage\Memory::hasAccessToken + */ + public function testRetrieveAccessTokenValid() + { + $storage = new Memory(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertInstanceOf('\\OAuth\\Common\\Token\\TokenInterface', $storage->retrieveAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::retrieveAccessToken + * @covers OAuth\Common\Storage\Memory::hasAccessToken + */ + public function testRetrieveAccessTokenThrowsExceptionWhenTokenIsNotFound() + { + $this->setExpectedException('\\OAuth\\Common\\Storage\\Exception\\TokenNotFoundException'); + + $storage = new Memory(); + + $storage->retrieveAccessToken('foo'); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::storeAccessToken + * @covers OAuth\Common\Storage\Memory::hasAccessToken + */ + public function testHasAccessTokenTrue() + { + $storage = new Memory(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::hasAccessToken + */ + public function testHasAccessTokenFalse() + { + $storage = new Memory(); + + $this->assertFalse($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::clearToken + */ + public function testClearTokenIsNotSet() + { + $storage = new Memory(); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Memory', $storage->clearToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::storeAccessToken + * @covers OAuth\Common\Storage\Memory::clearToken + */ + public function testClearTokenSet() + { + $storage = new Memory(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Memory', $storage->clearToken('foo')); + $this->assertFalse($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Memory::__construct + * @covers OAuth\Common\Storage\Memory::storeAccessToken + * @covers OAuth\Common\Storage\Memory::clearAllTokens + */ + public function testClearAllTokens() + { + $storage = new Memory(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + $storage->storeAccessToken('bar', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + $this->assertTrue($storage->hasAccessToken('bar')); + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Memory', $storage->clearAllTokens()); + $this->assertFalse($storage->hasAccessToken('foo')); + $this->assertFalse($storage->hasAccessToken('bar')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Storage/RedisTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/RedisTest.php new file mode 100644 index 00000000..83e7a284 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/RedisTest.php @@ -0,0 +1,102 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +namespace OAuth\Unit\Common\Storage; + +use OAuth\Common\Storage\Redis; +use Predis\Client as Predis; +use OAuth\OAuth2\Token\StdOAuth2Token; + +class RedisTest extends \PHPUnit_Framework_TestCase +{ + protected $storage; + + public function setUp() + { + // connect to a redis daemon + $predis = new Predis(array( + 'host' => $_ENV['redis_host'], + 'port' => $_ENV['redis_port'], + )); + + // set it + $this->storage = new Redis($predis, 'test_user_token', 'test_user_state'); + + try { + $predis->connect(); + } catch (\Predis\Connection\ConnectionException $e) { + $this->markTestSkipped('No redis instance available: ' . $e->getMessage()); + } + } + + public function tearDown() + { + // delete + $this->storage->clearAllTokens(); + + // close connection + $this->storage->getRedis()->quit(); + } + + /** + * Check that the token gets properly stored. + */ + public function testStorage() + { + // arrange + $service_1 = 'Facebook'; + $service_2 = 'Foursquare'; + + $token_1 = new StdOAuth2Token('access_1', 'refresh_1', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + $token_2 = new StdOAuth2Token('access_2', 'refresh_2', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service_1, $token_1); + $this->storage->storeAccessToken($service_2, $token_2); + + // assert + $extraParams = $this->storage->retrieveAccessToken($service_1)->getExtraParams(); + $this->assertEquals('param', $extraParams['extra']); + $this->assertEquals($token_1, $this->storage->retrieveAccessToken($service_1)); + $this->assertEquals($token_2, $this->storage->retrieveAccessToken($service_2)); + } + + /** + * Test hasAccessToken. + */ + public function testHasAccessToken() + { + // arrange + $service = 'Facebook'; + $this->storage->clearToken($service); + + // act + // assert + $this->assertFalse($this->storage->hasAccessToken($service)); + } + + /** + * Check that the token gets properly deleted. + */ + public function testStorageClears() + { + // arrange + $service = 'Facebook'; + $token = new StdOAuth2Token('access', 'refresh', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service, $token); + $this->storage->clearToken($service); + + // assert + $this->setExpectedException('OAuth\Common\Storage\Exception\TokenNotFoundException'); + $this->storage->retrieveAccessToken($service); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SessionTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SessionTest.php new file mode 100644 index 00000000..72f38b1a --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SessionTest.php @@ -0,0 +1,245 @@ +assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $storage); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * + * @runInSeparateProcess + */ + public function testConstructWithoutStartingSession() + { + session_start(); + + $storage = new Session(false); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $storage); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * + * @runInSeparateProcess + */ + public function testConstructTryingToStartWhileSessionAlreadyExists() + { + session_start(); + + $storage = new Session(); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $storage); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * + * @runInSeparateProcess + */ + public function testConstructWithExistingSessionKey() + { + session_start(); + + $_SESSION['lusitanian_oauth_token'] = array(); + + $storage = new Session(); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $storage); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * + * @runInSeparateProcess + */ + public function testStoreAccessTokenIsAlreadyArray() + { + $storage = new Session(); + + $this->assertInstanceOf( + '\\OAuth\\Common\\Storage\\Session', + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')) + ); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * + * @runInSeparateProcess + */ + public function testStoreAccessTokenIsNotArray() + { + $storage = new Session(); + + $_SESSION['lusitanian_oauth_token'] = 'foo'; + + $this->assertInstanceOf( + '\\OAuth\\Common\\Storage\\Session', + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')) + ); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * @covers OAuth\Common\Storage\Session::retrieveAccessToken + * @covers OAuth\Common\Storage\Session::hasAccessToken + * + * @runInSeparateProcess + */ + public function testRetrieveAccessTokenValid() + { + $storage = new Session(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertInstanceOf('\\OAuth\\Common\\Token\\TokenInterface', $storage->retrieveAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::retrieveAccessToken + * @covers OAuth\Common\Storage\Session::hasAccessToken + * + * @runInSeparateProcess + */ + public function testRetrieveAccessTokenThrowsExceptionWhenTokenIsNotFound() + { + $this->setExpectedException('\\OAuth\\Common\\Storage\\Exception\\TokenNotFoundException'); + + $storage = new Session(); + + $storage->retrieveAccessToken('foo'); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * @covers OAuth\Common\Storage\Session::hasAccessToken + * + * @runInSeparateProcess + */ + public function testHasAccessTokenTrue() + { + $storage = new Session(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::hasAccessToken + * + * @runInSeparateProcess + */ + public function testHasAccessTokenFalse() + { + $storage = new Session(); + + $this->assertFalse($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::clearToken + * + * @runInSeparateProcess + */ + public function testClearTokenIsNotSet() + { + $storage = new Session(); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Session', $storage->clearToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * @covers OAuth\Common\Storage\Session::clearToken + * + * @runInSeparateProcess + */ + public function testClearTokenSet() + { + $storage = new Session(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Session', $storage->clearToken('foo')); + $this->assertFalse($storage->hasAccessToken('foo')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::storeAccessToken + * @covers OAuth\Common\Storage\Session::clearAllTokens + * + * @runInSeparateProcess + */ + public function testClearAllTokens() + { + $storage = new Session(); + + $storage->storeAccessToken('foo', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + $storage->storeAccessToken('bar', $this->getMock('\\OAuth\\Common\\Token\\TokenInterface')); + + $this->assertTrue($storage->hasAccessToken('foo')); + $this->assertTrue($storage->hasAccessToken('bar')); + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\Session', $storage->clearAllTokens()); + $this->assertFalse($storage->hasAccessToken('foo')); + $this->assertFalse($storage->hasAccessToken('bar')); + } + + /** + * @covers OAuth\Common\Storage\Session::__construct + * @covers OAuth\Common\Storage\Session::__destruct + * + * @runInSeparateProcess + */ + public function testDestruct() + { + $storage = new Session(); + + unset($storage); + } + + /** + * @covers OAuth\Common\Storage\Session::storeAccessToken + * @covers OAuth\Common\Storage\Session::retrieveAccessToken + * + * @runInSeparateProcess + */ + public function testSerializeUnserialize() + { + $mock = $this->getMock('\\OAuth\\Common\\Token\\AbstractToken', array('__sleep')); + $mock->expects($this->once()) + ->method('__sleep') + ->will($this->returnValue(array('accessToken'))); + + $storage = new Session(); + $storage->storeAccessToken('foo', $mock); + $retrievedToken = $storage->retrieveAccessToken('foo'); + + $this->assertInstanceOf('\\OAuth\\Common\\Token\\AbstractToken', $retrievedToken); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Storage/StorageTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/StorageTest.php new file mode 100644 index 00000000..3fe19906 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/StorageTest.php @@ -0,0 +1,74 @@ + + * @author Hannes Van De Vreken + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +namespace OAuth\Unit\Common\Storage; + +use \OAuth\OAuth2\Token\StdOAuth2Token; + +abstract class StorageTest extends \PHPUnit_Framework_TestCase +{ + protected $storage; + + /** + * Check that the token gets properly stored. + */ + public function testStorage() + { + // arrange + $service_1 = 'Facebook'; + $service_2 = 'Foursquare'; + + $token_1 = new StdOAuth2Token('access_1', 'refresh_1', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + $token_2 = new StdOAuth2Token('access_2', 'refresh_2', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service_1, $token_1); + $this->storage->storeAccessToken($service_2, $token_2); + + // assert + $extraParams = $this->storage->retrieveAccessToken($service_1)->getExtraParams(); + $this->assertEquals('param', $extraParams['extra']); + $this->assertEquals($token_1, $this->storage->retrieveAccessToken($service_1)); + $this->assertEquals($token_2, $this->storage->retrieveAccessToken($service_2)); + } + + /** + * Test hasAccessToken. + */ + public function testHasAccessToken() + { + // arrange + $service = 'Facebook'; + $this->storage->clearToken($service); + + // act + // assert + $this->assertFalse($this->storage->hasAccessToken($service)); + } + + /** + * Check that the token gets properly deleted. + */ + public function testStorageClears() + { + // arrange + $service = 'Facebook'; + $token = new StdOAuth2Token('access', 'refresh', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service, $token); + $this->storage->clearToken($service); + + // assert + $this->setExpectedException('OAuth\Common\Storage\Exception\TokenNotFoundException'); + $this->storage->retrieveAccessToken($service); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SymfonySessionTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SymfonySessionTest.php new file mode 100644 index 00000000..c6434612 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Storage/SymfonySessionTest.php @@ -0,0 +1,111 @@ + + * @copyright Copyright (c) 2012 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ + +namespace OAuth\Unit\Common\Storage; + +use OAuth\Common\Storage\SymfonySession; +use OAuth\OAuth2\Token\StdOAuth2Token; +use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; + +class SymfonySessionTest extends \PHPUnit_Framework_TestCase +{ + protected $session; + + protected $storage; + + public function setUp() + { + // set it + $this->session = new Session(new MockArraySessionStorage()); + $this->storage = new SymfonySession($this->session); + } + + public function tearDown() + { + // delete + $this->storage->getSession()->clear(); + unset($this->storage); + } + + /** + * Check that the token survives the constructor + */ + public function testStorageSurvivesConstructor() + { + $service = 'Facebook'; + $token = new StdOAuth2Token('access', 'refresh', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service, $token); + $this->storage = null; + $this->storage = new SymfonySession($this->session); + + // assert + $extraParams = $this->storage->retrieveAccessToken($service)->getExtraParams(); + $this->assertEquals('param', $extraParams['extra']); + $this->assertEquals($token, $this->storage->retrieveAccessToken($service)); + } + + /** + * Check that the token gets properly stored. + */ + public function testStorage() + { + // arrange + $service_1 = 'Facebook'; + $service_2 = 'Foursquare'; + + $token_1 = new StdOAuth2Token('access_1', 'refresh_1', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + $token_2 = new StdOAuth2Token('access_2', 'refresh_2', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service_1, $token_1); + $this->storage->storeAccessToken($service_2, $token_2); + + // assert + $extraParams = $this->storage->retrieveAccessToken($service_1)->getExtraParams(); + $this->assertEquals('param', $extraParams['extra']); + $this->assertEquals($token_1, $this->storage->retrieveAccessToken($service_1)); + $this->assertEquals($token_2, $this->storage->retrieveAccessToken($service_2)); + } + + /** + * Test hasAccessToken. + */ + public function testHasAccessToken() + { + // arrange + $service = 'Facebook'; + $this->storage->clearToken($service); + + // act + // assert + $this->assertFalse($this->storage->hasAccessToken($service)); + } + + /** + * Check that the token gets properly deleted. + */ + public function testStorageClears() + { + // arrange + $service = 'Facebook'; + $token = new StdOAuth2Token('access', 'refresh', StdOAuth2Token::EOL_NEVER_EXPIRES, array('extra' => 'param')); + + // act + $this->storage->storeAccessToken($service, $token); + $this->storage->clearToken($service); + + // assert + $this->setExpectedException('OAuth\Common\Storage\Exception\TokenNotFoundException'); + $this->storage->retrieveAccessToken($service); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/Common/Token/AbstractTokenTest.php b/vendor/lusitanian/oauth/tests/Unit/Common/Token/AbstractTokenTest.php new file mode 100644 index 00000000..54b3bb63 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/Common/Token/AbstractTokenTest.php @@ -0,0 +1,189 @@ +getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $this->assertInstanceOf('\\OAuth\\Common\\Token\\TokenInterface', $token); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getAccessToken + */ + public function testGetAccessTokenNotSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $this->assertNull($token->getAccessToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getAccessToken + */ + public function testGetAccessTokenSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo')); + + $this->assertSame('foo', $token->getAccessToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getAccessToken + * @covers OAuth\Common\Token\AbstractToken::setAccessToken + */ + public function testSetAccessToken() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $token->setAccessToken('foo'); + + $this->assertSame('foo', $token->getAccessToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getRefreshToken + */ + public function testGetRefreshToken() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $this->assertNull($token->getRefreshToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getRefreshToken + */ + public function testGetRefreshTokenSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo', 'bar')); + + $this->assertSame('bar', $token->getRefreshToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getRefreshToken + * @covers OAuth\Common\Token\AbstractToken::setRefreshToken + */ + public function testSetRefreshToken() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $token->setRefreshToken('foo'); + + $this->assertSame('foo', $token->getRefreshToken()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getExtraParams + */ + public function testGetExtraParamsNotSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $this->assertSame(array(), $token->getExtraParams()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::getExtraParams + */ + public function testGetExtraParamsSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo', 'bar', null, array('foo', 'bar'))); + + $this->assertEquals(array('foo', 'bar'), $token->getExtraParams()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setExtraParams + * @covers OAuth\Common\Token\AbstractToken::getExtraParams + */ + public function testSetExtraParams() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $token->setExtraParams(array('foo', 'bar')); + + $this->assertSame(array('foo', 'bar'), $token->getExtraParams()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setLifetime + * @covers OAuth\Common\Token\AbstractToken::getEndOfLife + */ + public function testGetEndOfLifeNotSet() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $this->assertSame(AbstractToken::EOL_UNKNOWN, $token->getEndOfLife()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setLifetime + * @covers OAuth\Common\Token\AbstractToken::getEndOfLife + */ + public function testGetEndOfLifeZero() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo', 'bar', 0)); + + $this->assertSame(AbstractToken::EOL_NEVER_EXPIRES, $token->getEndOfLife()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setLifetime + * @covers OAuth\Common\Token\AbstractToken::getEndOfLife + */ + public function testGetEndOfLifeNeverExpires() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo', 'bar', AbstractToken::EOL_NEVER_EXPIRES)); + + $this->assertSame(AbstractToken::EOL_NEVER_EXPIRES, $token->getEndOfLife()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setLifetime + * @covers OAuth\Common\Token\AbstractToken::getEndOfLife + */ + public function testGetEndOfLifeNeverExpiresFiveMinutes() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken', array('foo', 'bar', 5 * 60)); + + $this->assertSame(time() + (5*60), $token->getEndOfLife()); + } + + /** + * @covers OAuth\Common\Token\AbstractToken::__construct + * @covers OAuth\Common\Token\AbstractToken::setLifetime + * @covers OAuth\Common\Token\AbstractToken::getEndOfLife + * @covers OAuth\Common\Token\AbstractToken::setEndOfLife + */ + public function testSetEndOfLife() + { + $token = $this->getMockForAbstractClass('\\OAuth\\Common\\Token\\AbstractToken'); + + $token->setEndOfLife(10); + + $this->assertSame(10, $token->getEndOfLife()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/AbstractServiceTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/AbstractServiceTest.php new file mode 100644 index 00000000..ab5417b2 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/AbstractServiceTest.php @@ -0,0 +1,215 @@ +getMockForAbstractClass( + '\\OAuth\\OAuth1\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + ) + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::__construct + */ + public function testConstructCorrectParent() + { + $service = $this->getMockForAbstractClass( + '\\OAuth\\OAuth1\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + ) + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::requestRequestToken + * @covers OAuth\OAuth1\Service\AbstractService::buildAuthorizationHeaderForTokenRequest + * @covers OAuth\OAuth1\Service\AbstractService::getBasicAuthorizationHeaderInfo + * @covers OAuth\OAuth1\Service\AbstractService::generateNonce + * @covers OAuth\OAuth1\Service\AbstractService::getSignatureMethod + * @covers OAuth\OAuth1\Service\AbstractService::getVersion + * @covers OAuth\OAuth1\Service\AbstractService::getExtraOAuthHeaders + * @covers OAuth\OAuth1\Service\AbstractService::parseRequestTokenResponse + */ + public function testRequestRequestTokenBuildAuthHeaderTokenRequestWithoutParams() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($endpoint, $array, $headers) { + \PHPUnit_Framework_Assert::assertSame('http://pieterhordijk.com/token', $endpoint->getAbsoluteUri()); + })); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::getAuthorizationUri + * @covers OAuth\OAuth1\Service\AbstractService::getAuthorizationEndpoint + */ + public function testGetAuthorizationUriWithoutParameters() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('http://pieterhordijk.com/auth', $service->getAuthorizationUri()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::getAuthorizationUri + * @covers OAuth\OAuth1\Service\AbstractService::getAuthorizationEndpoint + */ + public function testGetAuthorizationUriWithParameters() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('http://pieterhordijk.com/auth?foo=bar&baz=beer', $service->getAuthorizationUri(array( + 'foo' => 'bar', + 'baz' => 'beer', + ))->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::requestAccessToken + * @covers OAuth\OAuth1\Service\AbstractService::service + * @covers OAuth\OAuth1\Service\AbstractService::buildAuthorizationHeaderForAPIRequest + * @covers OAuth\OAuth1\Service\AbstractService::getBasicAuthorizationHeaderInfo + * @covers OAuth\OAuth1\Service\AbstractService::generateNonce + * @covers OAuth\OAuth1\Service\AbstractService::getSignatureMethod + * @covers OAuth\OAuth1\Service\AbstractService::getVersion + * @covers OAuth\OAuth1\Service\AbstractService::getAccessTokenEndpoint + * @covers OAuth\OAuth1\Service\AbstractService::getExtraOAuthHeaders + * @covers OAuth\OAuth1\Service\AbstractService::parseAccessTokenResponse + */ + public function testRequestAccessTokenWithoutSecret() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($endpoint, $array, $headers) { + \PHPUnit_Framework_Assert::assertSame('http://pieterhordijk.com/access', $endpoint->getAbsoluteUri()); + })); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + $token->expects($this->once())->method('getRequestTokenSecret')->will($this->returnValue('baz')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar')); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::requestAccessToken + * @covers OAuth\OAuth1\Service\AbstractService::service + * @covers OAuth\OAuth1\Service\AbstractService::buildAuthorizationHeaderForAPIRequest + * @covers OAuth\OAuth1\Service\AbstractService::getBasicAuthorizationHeaderInfo + * @covers OAuth\OAuth1\Service\AbstractService::generateNonce + * @covers OAuth\OAuth1\Service\AbstractService::getSignatureMethod + * @covers OAuth\OAuth1\Service\AbstractService::getVersion + * @covers OAuth\OAuth1\Service\AbstractService::getAccessTokenEndpoint + * @covers OAuth\OAuth1\Service\AbstractService::getExtraOAuthHeaders + * @covers OAuth\OAuth1\Service\AbstractService::parseAccessTokenResponse + */ + public function testRequestAccessTokenWithSecret() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($endpoint, $array, $headers) { + \PHPUnit_Framework_Assert::assertSame('http://pieterhordijk.com/access', $endpoint->getAbsoluteUri()); + })); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } + + /** + * @covers OAuth\OAuth1\Service\AbstractService::request + * @covers OAuth\OAuth1\Service\AbstractService::determineRequestUriFromPath + * @covers OAuth\OAuth1\Service\AbstractService::service + * @covers OAuth\OAuth1\Service\AbstractService::getExtraApiHeaders + * @covers OAuth\OAuth1\Service\AbstractService::buildAuthorizationHeaderForAPIRequest + * @covers OAuth\OAuth1\Service\AbstractService::getBasicAuthorizationHeaderInfo + * @covers OAuth\OAuth1\Service\AbstractService::generateNonce + * @covers OAuth\OAuth1\Service\AbstractService::getSignatureMethod + * @covers OAuth\OAuth1\Service\AbstractService::getVersion + */ + public function testRequest() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('response!')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + //$token->expects($this->once())->method('getRequestTokenSecret')->will($this->returnValue('baz')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('response!', $service->request('/my/awesome/path')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/BitBucketTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/BitBucketTest.php new file mode 100644 index 00000000..87be98b1 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/BitBucketTest.php @@ -0,0 +1,278 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://bitbucket.org/!api/1.0/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://bitbucket.org/!api/1.0/oauth/authenticate', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://bitbucket.org/!api/1.0/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\BitBucket::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\BitBucket::__construct + * @covers OAuth\OAuth1\Service\BitBucket::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\BitBucket::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new BitBucket( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/EtsyTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/EtsyTest.php new file mode 100644 index 00000000..97ad3cdd --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/EtsyTest.php @@ -0,0 +1,286 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://openapi.etsy.com/v2/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + + $service->setScopes(array('email_r', 'cart_rw')); + + $this->assertSame( + 'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20cart_rw', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://openapi.etsy.com/v2/', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://openapi.etsy.com/v2/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Etsy::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Etsy::__construct + * @covers OAuth\OAuth1\Service\Etsy::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Etsy::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Etsy( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FitBitTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FitBitTest.php new file mode 100644 index 00000000..a8b7ae2d --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FitBitTest.php @@ -0,0 +1,278 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.fitbit.com/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.fitbit.com/oauth/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.fitbit.com/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\FitBit::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\FitBit::__construct + * @covers OAuth\OAuth1\Service\FitBit::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\FitBit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new FitBit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FlickrTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FlickrTest.php new file mode 100644 index 00000000..ee88f714 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/FlickrTest.php @@ -0,0 +1,302 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.flickr.com/services/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.flickr.com/services/oauth/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.flickr.com/services/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Flickr::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::__construct + * @covers OAuth\OAuth1\Service\Flickr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Flickr::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } + + /** + * @covers OAuth\OAuth1\Service\Flickr::request + */ + public function testRequest() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('response!')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Flickr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('response!', $service->request('/my/awesome/path')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/ScoopItTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/ScoopItTest.php new file mode 100644 index 00000000..4ba83fa6 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/ScoopItTest.php @@ -0,0 +1,302 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.scoop.it/oauth/request', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.scoop.it/oauth/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.scoop.it/oauth/access', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\ScoopIt::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::__construct + * @covers OAuth\OAuth1\Service\ScoopIt::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\ScoopIt::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } + + /** + * @covers OAuth\OAuth1\Service\ScoopIt::request + */ + public function testRequest() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('response!')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new ScoopIt( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('response!', $service->request('/my/awesome/path')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TumblrTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TumblrTest.php new file mode 100644 index 00000000..f1467ad6 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TumblrTest.php @@ -0,0 +1,278 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.tumblr.com/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.tumblr.com/oauth/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://www.tumblr.com/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Tumblr::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Tumblr::__construct + * @covers OAuth\OAuth1\Service\Tumblr::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Tumblr::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Tumblr( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TwitterTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TwitterTest.php new file mode 100644 index 00000000..bb31fa29 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/TwitterTest.php @@ -0,0 +1,307 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.twitter.com/oauth/request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertTrue( + in_array( + strtolower($service->getAuthorizationEndpoint()->getAbsoluteUri()), + array(\OAuth\OAuth1\Service\Twitter::ENDPOINT_AUTHENTICATE, \OAuth\OAuth1\Service\Twitter::ENDPOINT_AUTHORIZE) + ) + ); + + $service->setAuthorizationEndpoint( \OAuth\OAuth1\Service\Twitter::ENDPOINT_AUTHORIZE ); + + $this->assertTrue( + in_array( + strtolower($service->getAuthorizationEndpoint()->getAbsoluteUri()), + array(\OAuth\OAuth1\Service\Twitter::ENDPOINT_AUTHENTICATE, \OAuth\OAuth1\Service\Twitter::ENDPOINT_AUTHORIZE) + ) + ); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::setAuthorizationEndpoint + */ + public function testSetAuthorizationEndpoint() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Exception\\Exception'); + + $service->setAuthorizationEndpoint('foo'); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.twitter.com/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Twitter::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Twitter::__construct + * @covers OAuth\OAuth1\Service\Twitter::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Twitter::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Twitter( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/XingTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/XingTest.php new file mode 100644 index 00000000..d3a5f4ae --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/XingTest.php @@ -0,0 +1,239 @@ +client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $this->storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + + $this->xing = new Xing( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->client, + $this->storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + */ + public function testConstructCorrectInterfaceWithoutCustomUri() + { + $this->assertInstanceOf( + '\\OAuth\\OAuth1\\Service\\ServiceInterface', $this->xing + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $this->assertInstanceOf( + '\\OAuth\\OAuth1\\Service\\AbstractService', $this->xing + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Xing( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->client, + $this->storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $this->assertSame( + 'https://api.xing.com/v1/request_token', + $this->xing->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $this->assertSame( + 'https://api.xing.com/v1/authorize', + $this->xing->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $this->assertSame( + 'https://api.xing.com/v1/access_token', + $this->xing->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue(null)); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $this->xing->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue('notanarray')); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $this->xing->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue('foo=bar')); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $this->xing->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue('oauth_callback_confirmed=false')); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $this->xing->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Xing::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $this->assertInstanceOf( + '\\OAuth\\OAuth1\\Token\\StdOAuth1Token', + $this->xing->requestRequestToken() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $this->storage + ->expects($this->any()) + ->method('retrieveAccessToken') + ->will($this->returnValue($token)); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $this->xing->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Xing::__construct + * @covers OAuth\OAuth1\Service\Xing::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Xing::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $this->client + ->expects($this->once()) + ->method('retrieveResponse') + ->will($this->returnValue('oauth_token=foo&oauth_token_secret=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $this->storage + ->expects($this->any()) + ->method('retrieveAccessToken') + ->will($this->returnValue($token)); + + + $this->assertInstanceOf( + '\\OAuth\\OAuth1\\Token\\StdOAuth1Token', + $this->xing->requestAccessToken('foo', 'bar', $token) + ); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/YahooTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/YahooTest.php new file mode 100644 index 00000000..e8feb5dc --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Service/YahooTest.php @@ -0,0 +1,302 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + */ + public function testGetRequestTokenEndpoint() + { + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.login.yahoo.com/oauth/v2/get_request_token', + $service->getRequestTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.login.yahoo.com/oauth/v2/request_auth', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertSame( + 'https://api.login.yahoo.com/oauth/v2/get_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseNotAnArray() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('notanarray')); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotSet() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('foo=bar')); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseRequestTokenResponse + */ + public function testParseRequestTokenResponseThrowsExceptionOnResponseCallbackNotTrue() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=false' + )); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestRequestToken(); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseRequestTokenResponse + * @covers OAuth\OAuth1\Service\Yahoo::parseAccessTokenResponse + */ + public function testParseRequestTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_callback_confirmed=true&oauth_token=foo&oauth_token_secret=bar' + )); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=bar')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo', 'bar', $token); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::__construct + * @covers OAuth\OAuth1\Service\Yahoo::getRequestTokenEndpoint + * @covers OAuth\OAuth1\Service\Yahoo::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue( + 'oauth_token=foo&oauth_token_secret=bar' + )); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Token\\StdOAuth1Token', $service->requestAccessToken('foo', 'bar', $token)); + } + + /** + * @covers OAuth\OAuth1\Service\Yahoo::request + */ + public function testRequest() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('response!')); + + $token = $this->getMock('\\OAuth\\OAuth1\\Token\\TokenInterface'); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->any())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Yahoo( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + $this->getMock('\\OAuth\\OAuth1\\Signature\\SignatureInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertSame('response!', $service->request('/my/awesome/path')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Signature/SignatureTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Signature/SignatureTest.php new file mode 100644 index 00000000..44c731f5 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Signature/SignatureTest.php @@ -0,0 +1,325 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface')); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Signature\\SignatureInterface', $signature); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + */ + public function testSetHashingAlgorithm() + { + $signature = new Signature($this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface')); + + $this->assertNull($signature->setHashingAlgorithm('foo')); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + */ + public function testSetTokenSecret() + { + $signature = new Signature($this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface')); + + $this->assertNull($signature->setTokenSecret('foo')); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureBareUri() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + $signature->setTokenSecret('foo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/foo')); + + $this->assertSame('uoCpiII/Lg/cPiF0XrU2pj4eGFQ=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureWithQueryString() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + $signature->setTokenSecret('foo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/foo')); + + $this->assertSame('LxtD+WjJBRppIUvEI79iQ7I0hSo=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureWithAuthority() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + $signature->setTokenSecret('foo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('peehaa:pass')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/foo')); + + $this->assertSame('MHvkRndIntLrxiPkjkiCNsMEqv4=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureWithBarePathNonExplicitTrailingHostSlash() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + $signature->setTokenSecret('foo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('peehaa:pass')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/')); + $uri->expects($this->any()) + ->method('hasExplicitTrailingHostSlash') + ->will($this->returnValue(false)); + + $this->assertSame('iFELDoiI5Oj9ixB3kHzoPvBpq0w=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureWithBarePathWithExplicitTrailingHostSlash() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + $signature->setTokenSecret('foo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('peehaa:pass')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/')); + $uri->expects($this->any()) + ->method('hasExplicitTrailingHostSlash') + ->will($this->returnValue(true)); + + $this->assertSame('IEhUsArSTLvbQ3QYr0zzn+Rxpjg=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureNoTokenSecretSet() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('HMAC-SHA1'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('peehaa:pass')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/')); + $uri->expects($this->any()) + ->method('hasExplicitTrailingHostSlash') + ->will($this->returnValue(true)); + + $this->assertSame('YMHF7FYmLq7wzGnnHWYtd1VoBBE=', $signature->getSignature($uri, array('pee' => 'haa'))); + } + + /** + * @covers OAuth\OAuth1\Signature\Signature::__construct + * @covers OAuth\OAuth1\Signature\Signature::setHashingAlgorithm + * @covers OAuth\OAuth1\Signature\Signature::setTokenSecret + * @covers OAuth\OAuth1\Signature\Signature::getSignature + * @covers OAuth\OAuth1\Signature\Signature::buildSignatureDataString + * @covers OAuth\OAuth1\Signature\Signature::hash + * @covers OAuth\OAuth1\Signature\Signature::getSigningKey + */ + public function testGetSignatureThrowsExceptionOnUnsupportedAlgo() + { + $this->setExpectedException('\\OAuth\\OAuth1\\Signature\\Exception\\UnsupportedHashAlgorithmException'); + + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any()) + ->method('getConsumerSecret') + ->will($this->returnValue('foo')); + + + $signature = new Signature($credentials); + + $signature->setHashingAlgorithm('UnsupportedAlgo'); + + $uri = $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'); + $uri->expects($this->any()) + ->method('getQuery') + ->will($this->returnValue('param1=value1')); + $uri->expects($this->any()) + ->method('getScheme') + ->will($this->returnValue('http')); + $uri->expects($this->any()) + ->method('getRawAuthority') + ->will($this->returnValue('peehaa:pass')); + $uri->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/')); + $uri->expects($this->any()) + ->method('hasExplicitTrailingHostSlash') + ->will($this->returnValue(true)); + + $signature->getSignature($uri, array('pee' => 'haa')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth1/Token/StdOAuth1TokenTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Token/StdOAuth1TokenTest.php new file mode 100644 index 00000000..9b065b1e --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth1/Token/StdOAuth1TokenTest.php @@ -0,0 +1,85 @@ +assertInstanceOf('\\OAuth\\OAuth1\\Token\\TokenInterface', $token); + $this->assertInstanceOf('\\OAuth\\Common\\Token\\AbstractToken', $token); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setRequestToken + */ + public function testSetRequestToken() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setRequestToken('foo')); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setRequestToken + * @covers OAuth\OAuth1\Token\StdOAuth1Token::getRequestToken + */ + public function testGetRequestToken() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setRequestToken('foo')); + $this->assertSame('foo', $token->getRequestToken()); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setRequestTokenSecret + */ + public function testSetRequestTokenSecret() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setRequestTokenSecret('foo')); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setRequestTokenSecret + * @covers OAuth\OAuth1\Token\StdOAuth1Token::getRequestTokenSecret + */ + public function testGetRequestTokenSecret() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setRequestTokenSecret('foo')); + $this->assertSame('foo', $token->getRequestTokenSecret()); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setAccessTokenSecret + */ + public function testSetAccessTokenSecret() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setAccessTokenSecret('foo')); + } + + /** + * @covers OAuth\OAuth1\Token\StdOAuth1Token::setAccessTokenSecret + * @covers OAuth\OAuth1\Token\StdOAuth1Token::getAccessTokenSecret + */ + public function testGetAccessTokenSecret() + { + $token = new StdOAuth1Token(); + + $this->assertNull($token->setAccessTokenSecret('foo')); + $this->assertSame('foo', $token->getAccessTokenSecret()); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AbstractServiceTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AbstractServiceTest.php new file mode 100644 index 00000000..595db2a3 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AbstractServiceTest.php @@ -0,0 +1,401 @@ +getMockForAbstractClass( + '\\OAuth\\OAuth2\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + ) + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + */ + public function testConstructCorrectParent() + { + $service = $this->getMockForAbstractClass( + '\\OAuth\\OAuth2\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + ) + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + */ + public function testConstructCorrectParentCustomUri() + { + $service = $this->getMockForAbstractClass( + '\\OAuth\\OAuth2\\Service\\AbstractService', + array( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface'), + ) + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::isValidScope + */ + public function testConstructThrowsExceptionOnInvalidScope() + { + $this->setExpectedException('\\OAuth\\OAuth2\\Service\\Exception\\InvalidScopeException'); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array('invalidscope') + ); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationUri + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationEndpoint + */ + public function testGetAuthorizationUriWithoutParametersOrScopes() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo')); + $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar')); + + $service = new Mock( + $credentials, + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'http://pieterhordijk.com/auth?type=web_server&client_id=foo&redirect_uri=bar&response_type=code&scope=', + $service->getAuthorizationUri()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationUri + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationEndpoint + */ + public function testGetAuthorizationUriWithParametersWithoutScopes() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo')); + $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar')); + + $service = new Mock( + $credentials, + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'http://pieterhordijk.com/auth?foo=bar&baz=beer&type=web_server&client_id=foo&redirect_uri=bar&response_type=code&scope=', + $service->getAuthorizationUri(array('foo' => 'bar', 'baz' => 'beer'))->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::isValidScope + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationUri + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationEndpoint + */ + public function testGetAuthorizationUriWithParametersAndScopes() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo')); + $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar')); + + $service = new Mock( + $credentials, + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array('mock', 'mock2') + ); + + $this->assertSame( + 'http://pieterhordijk.com/auth?foo=bar&baz=beer&type=web_server&client_id=foo&redirect_uri=bar&response_type=code&scope=mock+mock2', + $service->getAuthorizationUri(array('foo' => 'bar', 'baz' => 'beer'))->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::requestAccessToken + * @covers OAuth\OAuth2\Service\AbstractService::getAccessTokenEndpoint + * @covers OAuth\OAuth2\Service\AbstractService::getExtraOAuthHeaders + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\AbstractService::service + */ + public function testRequestAccessToken() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceof('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('code')); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::request + * @covers OAuth\OAuth2\Service\AbstractService::determineRequestUriFromPath + */ + public function testRequestThrowsExceptionWhenTokenIsExpired() + { + $tokenExpiration = new \DateTime('26-03-1984 00:00:00'); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->any())->method('getEndOfLife')->will($this->returnValue($tokenExpiration->format('U'))); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $storage + ); + + $this->setExpectedException('\\OAuth\\Common\\Token\\Exception\\ExpiredTokenException', 'Token expired on 03/26/1984 at 12:00:00 AM'); + + $service->request('https://pieterhordijk.com/my/awesome/path'); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::request + * @covers OAuth\OAuth2\Service\AbstractService::determineRequestUriFromPath + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationMethod + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\AbstractService::service + * @covers OAuth\OAuth2\Service\AbstractService::getExtraApiHeaders + */ + public function testRequestOauthAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('OAuth foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::request + * @covers OAuth\OAuth2\Service\AbstractService::determineRequestUriFromPath + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationMethod + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\AbstractService::service + * @covers OAuth\OAuth2\Service\AbstractService::getExtraApiHeaders + */ + public function testRequestQueryStringMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $service->setAuthorizationMethod('querystring'); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::request + * @covers OAuth\OAuth2\Service\AbstractService::determineRequestUriFromPath + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationMethod + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\AbstractService::service + * @covers OAuth\OAuth2\Service\AbstractService::getExtraApiHeaders + */ + public function testRequestQueryStringTwoMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $service->setAuthorizationMethod('querystring2'); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('oauth2_access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::request + * @covers OAuth\OAuth2\Service\AbstractService::determineRequestUriFromPath + * @covers OAuth\OAuth2\Service\AbstractService::getAuthorizationMethod + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\AbstractService::service + * @covers OAuth\OAuth2\Service\AbstractService::getExtraApiHeaders + */ + public function testRequestBearerMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $service->setAuthorizationMethod('bearer'); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::getStorage + */ + public function testGetStorage() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\Common\\Storage\\TokenStorageInterface', $service->getStorage()); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::refreshAccessToken + * @covers OAuth\OAuth2\Service\AbstractService::getAccessTokenEndpoint + * @covers OAuth\OAuth2\Service\AbstractService::getExtraOAuthHeaders + * @covers OAuth\OAuth2\Service\AbstractService::parseAccessTokenResponse + */ + public function testRefreshAccessTokenSuccess() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\StdOAuth2Token'); + $token->expects($this->once())->method('getRefreshToken')->will($this->returnValue('foo')); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->refreshAccessToken($token)); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::isValidScope + */ + public function testIsValidScopeTrue() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertTrue($service->isValidScope('mock')); + } + + /** + * @covers OAuth\OAuth2\Service\AbstractService::__construct + * @covers OAuth\OAuth2\Service\AbstractService::isValidScope + */ + public function testIsValidScopeFalse() + { + $service = new Mock( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertFalse($service->isValidScope('invalid')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AmazonTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AmazonTest.php new file mode 100644 index 00000000..f70fe401 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/AmazonTest.php @@ -0,0 +1,207 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.amazon.com/ap/oa', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.amazon.com/ap/oatoken', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Amazon::__construct + * @covers OAuth\OAuth2\Service\Amazon::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Amazon( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BitlyTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BitlyTest.php new file mode 100644 index 00000000..9944b260 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BitlyTest.php @@ -0,0 +1,150 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + * @covers OAuth\OAuth2\Service\Bitly::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://bitly.com/oauth/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + * @covers OAuth\OAuth2\Service\Bitly::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api-ssl.bitly.com/oauth/access_token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + * @covers OAuth\OAuth2\Service\Bitly::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + * @covers OAuth\OAuth2\Service\Bitly::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Bitly::__construct + * @covers OAuth\OAuth2\Service\Bitly::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\Bitly::requestAccessToken + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('access_token=foo')); + + $service = new Bitly( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BoxTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BoxTest.php new file mode 100644 index 00000000..b5b2a789 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BoxTest.php @@ -0,0 +1,207 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.box.com/api/oauth2/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.box.com/api/oauth2/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Box::__construct + * @covers OAuth\OAuth2\Service\Box::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Box( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BufferTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BufferTest.php new file mode 100644 index 00000000..29726d0a --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/BufferTest.php @@ -0,0 +1,150 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + * @covers OAuth\OAuth2\Service\Buffer::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://bufferapp.com/oauth2/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + * @covers OAuth\OAuth2\Service\Buffer::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api.bufferapp.com/1/oauth2/token.json', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + * @covers OAuth\OAuth2\Service\Buffer::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + * @covers OAuth\OAuth2\Service\Buffer::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Buffer::__construct + * @covers OAuth\OAuth2\Service\Buffer::parseAccessTokenResponse + * @covers OAuth\OAuth2\Service\Buffer::requestAccessToken + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo"}')); + + $service = new Buffer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} \ No newline at end of file diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DailymotionTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DailymotionTest.php new file mode 100644 index 00000000..f3fbaa8e --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DailymotionTest.php @@ -0,0 +1,230 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api.dailymotion.com/oauth/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api.dailymotion.com/oauth/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('OAuth foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Dailymotion::__construct + * @covers OAuth\OAuth2\Service\Dailymotion::getExtraOAuthHeaders + */ + public function testGetExtraOAuthHeaders() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($uri, $params, $extraHeaders) { + \PHPUnit_Framework_Assert::assertTrue(array_key_exists('Accept', $extraHeaders)); + \PHPUnit_Framework_Assert::assertTrue(in_array('application/json', $extraHeaders, true)); + + return '{"access_token":"foo","expires_in":"bar"}'; + })); + + $service = new Dailymotion( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DropboxTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DropboxTest.php new file mode 100644 index 00000000..8f052c6b --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/DropboxTest.php @@ -0,0 +1,231 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationUri + */ + public function testGetAuthorizationUriWithoutAdditionalParams() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo')); + $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar')); + + $service = new Dropbox( + $credentials, + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.dropbox.com/1/oauth2/authorize?client_id=foo&redirect_uri=bar&response_type=code&scope=', + $service->getAuthorizationUri()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationUri + */ + public function testGetAuthorizationUriWithAdditionalParams() + { + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->once())->method('getConsumerId')->will($this->returnValue('foo')); + $credentials->expects($this->once())->method('getCallbackUrl')->will($this->returnValue('bar')); + + $service = new Dropbox( + $credentials, + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.dropbox.com/1/oauth2/authorize?client_id=foo&redirect_uri=bar&response_type=code&scope=', + $service->getAuthorizationUri()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.dropbox.com/1/oauth2/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api.dropbox.com/1/oauth2/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Dropbox::__construct + * @covers OAuth\OAuth2\Service\Dropbox::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Dropbox( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FacebookTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FacebookTest.php new file mode 100644 index 00000000..f2fed463 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FacebookTest.php @@ -0,0 +1,242 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.facebook.com/dialog/oauth', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://graph.facebook.com/oauth/access_token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('OAuth foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('access_token=foo&expires=bar')); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('access_token=foo&expires=bar&refresh_token=baz')); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::getDialogUri + */ + public function testGetDialogUriRedirectUriMissing() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Exception\\Exception'); + + $service->getDialogUri('feed', array()); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::getDialogUri + */ + public function testGetDialogUriInstanceofUri() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + + $service = new Facebook( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $dialogUri = $service->getDialogUri( + 'feed', + array( + 'redirect_uri' => 'http://www.facebook.com', + 'state' => 'Random state' + ) + ); + $this->assertInstanceOf('\\OAuth\\Common\\Http\\Uri\\Uri',$dialogUri); + } + + /** + * @covers OAuth\OAuth2\Service\Facebook::__construct + * @covers OAuth\OAuth2\Service\Facebook::getDialogUri + */ + public function testGetDialogUriContainsAppIdAndOtherParameters() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $credentials = $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'); + $credentials->expects($this->any())->method('getConsumerId')->will($this->returnValue('application_id')); + + + $service = new Facebook( + $credentials, + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $dialogUri = $service->getDialogUri( + 'feed', + array( + 'redirect_uri' => 'http://www.facebook.com', + 'state' => 'Random state' + ) + ); + + $queryString = $dialogUri->getQuery(); + parse_str($queryString, $queryArray); + + $this->assertArrayHasKey('app_id', $queryArray); + $this->assertArrayHasKey('redirect_uri', $queryArray); + $this->assertArrayHasKey('state', $queryArray); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FoursquareTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FoursquareTest.php new file mode 100644 index 00000000..96356ec5 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/FoursquareTest.php @@ -0,0 +1,197 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://foursquare.com/oauth2/authenticate', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://foursquare.com/oauth2/access_token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('OAuth foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"error":"some_error"}')); + + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Foursquare::__construct + * @covers OAuth\OAuth2\Service\Foursquare::request + */ + public function testRequest() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Foursquare( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $this->assertSame( + 'https://api.foursquare.com/v2/https://pieterhordijk.com/my/awesome/path?v=20130829', + $service->request('https://pieterhordijk.com/my/awesome/path')->getAbsoluteUri() + ); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GitHubTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GitHubTest.php new file mode 100644 index 00000000..edb0fee3 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GitHubTest.php @@ -0,0 +1,220 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://github.com/login/oauth/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://github.com/login/oauth/access_token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"error":"some_error"}')); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::getExtraOAuthHeaders + */ + public function testGetExtraOAuthHeaders() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($uri, $params, $extraHeaders) { + \PHPUnit_Framework_Assert::assertTrue(array_key_exists('Accept', $extraHeaders)); + \PHPUnit_Framework_Assert::assertTrue(in_array('application/json', $extraHeaders, true)); + + return '{"access_token":"foo","expires_in":"bar"}'; + })); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\GitHub::__construct + * @covers OAuth\OAuth2\Service\GitHub::getExtraApiHeaders + */ + public function testGetExtraApiHeaders() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new GitHub( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Accept', $headers)); + $this->assertSame('application/vnd.github.beta+json', $headers['Accept']); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GoogleTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GoogleTest.php new file mode 100644 index 00000000..b55808d2 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/GoogleTest.php @@ -0,0 +1,195 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://accounts.google.com/o/oauth2/auth?access_type=online', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + + // Verify that 'offine' works + $service->setAccessType('offline'); + $this->assertSame( + 'https://accounts.google.com/o/oauth2/auth?access_type=offline', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpointException() + { + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('OAuth\OAuth2\Service\Exception\InvalidAccessTypeException'); + + try { + $service->setAccessType('invalid'); + } catch (InvalidAccessTypeException $e) { + return; + } + $this->fail('Expected InvalidAccessTypeException not thrown'); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://accounts.google.com/o/oauth2/token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Google::__construct + * @covers OAuth\OAuth2\Service\Google::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Google( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/HerokuTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/HerokuTest.php new file mode 100644 index 00000000..cc2c0f69 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/HerokuTest.php @@ -0,0 +1,261 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://id.heroku.com/oauth/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://id.heroku.com/oauth/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::getExtraOAuthHeaders + */ + public function testGetExtraOAuthHeaders() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnCallback(function($uri, $params, $extraHeaders) { + \PHPUnit_Framework_Assert::assertTrue(array_key_exists('Accept', $extraHeaders)); + \PHPUnit_Framework_Assert::assertTrue(in_array('application/vnd.heroku+json; version=3', $extraHeaders, true)); + + return '{"access_token":"foo","expires_in":"bar"}'; + })); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Heroku::__construct + * @covers OAuth\OAuth2\Service\Heroku::getExtraApiHeaders + */ + public function testGetExtraApiHeaders() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Heroku( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Accept', $headers)); + $this->assertSame('application/vnd.heroku+json; version=3', $headers['Accept']); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/InstagramTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/InstagramTest.php new file mode 100644 index 00000000..bf9d764c --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/InstagramTest.php @@ -0,0 +1,193 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://api.instagram.com/oauth/authorize/', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://api.instagram.com/oauth/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Instagram::__construct + * @covers OAuth\OAuth2\Service\Instagram::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Instagram( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/LinkedinTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/LinkedinTest.php new file mode 100644 index 00000000..c7f5c76e --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/LinkedinTest.php @@ -0,0 +1,213 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.linkedin.com/uas/oauth2/authorization', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.linkedin.com/uas/oauth2/accessToken', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('oauth2_access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Linkedin::__construct + * @covers OAuth\OAuth2\Service\Linkedin::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Linkedin( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MailchimpTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MailchimpTest.php new file mode 100644 index 00000000..e7f955e1 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MailchimpTest.php @@ -0,0 +1,179 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://login.mailchimp.com/oauth2/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://login.mailchimp.com/oauth2/token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\StdOAuth2Token'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage, + array(), + new Uri('https://us1.api.mailchimp.com/2.0/') + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('apikey=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Mailchimp::__construct + * @covers OAuth\OAuth2\Service\Mailchimp::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValid() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->at(0))->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + $client->expects($this->at(1))->method('retrieveResponse')->will($this->returnValue('{"dc": "us7"}')); + + $service = new Mailchimp( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MicrosoftTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MicrosoftTest.php new file mode 100644 index 00000000..4001e1e4 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/MicrosoftTest.php @@ -0,0 +1,193 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://login.live.com/oauth20_authorize.srf', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://login.live.com/oauth20_token.srf', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(0)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $uri = $service->request('https://pieterhordijk.com/my/awesome/path'); + $absoluteUri = parse_url($uri->getAbsoluteUri()); + + $this->assertSame('access_token=foo', $absoluteUri['query']); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Microsoft::__construct + * @covers OAuth\OAuth2\Service\Microsoft::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Microsoft( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/PaypalTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/PaypalTest.php new file mode 100644 index 00000000..5396326f --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/PaypalTest.php @@ -0,0 +1,213 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://api.paypal.com/v1/identity/openidconnect/tokenservice', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnMessage() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('message=some_error')); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnName() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('name=some_error')); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Paypal::__construct + * @covers OAuth\OAuth2\Service\Paypal::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Paypal( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RedditTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RedditTest.php new file mode 100644 index 00000000..e8741e6f --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RedditTest.php @@ -0,0 +1,193 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://ssl.reddit.com/api/v1/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://ssl.reddit.com/api/v1/access_token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Reddit::__construct + * @covers OAuth\OAuth2\Service\Reddit::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Reddit( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RunKeeperTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RunKeeperTest.php new file mode 100644 index 00000000..671bd0cf --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/RunKeeperTest.php @@ -0,0 +1,207 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://runkeeper.com/apps/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://runkeeper.com/apps/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('/user'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error_description=some_error')); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\RunKeeper::__construct + * @covers OAuth\OAuth2\Service\RunKeeper::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new RunKeeper( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/SoundCloudTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/SoundCloudTest.php new file mode 100644 index 00000000..ac988ba2 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/SoundCloudTest.php @@ -0,0 +1,159 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://soundcloud.com/connect', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://api.soundcloud.com/oauth2/token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\SoundCloud::__construct + * @covers OAuth\OAuth2\Service\SoundCloud::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new SoundCloud( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/UstreamTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/UstreamTest.php new file mode 100644 index 00000000..48965ae0 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/UstreamTest.php @@ -0,0 +1,193 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.ustream.tv/oauth2/authorize', + $service->getAuthorizationEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame( + 'https://www.ustream.tv/oauth2/token', + $service->getAccessTokenEndpoint()->getAbsoluteUri() + ); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Ustream::__construct + * @covers OAuth\OAuth2\Service\Ustream::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Ustream( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/VkontakteTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/VkontakteTest.php new file mode 100644 index 00000000..7a8279b2 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/VkontakteTest.php @@ -0,0 +1,159 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://oauth.vk.com/authorize', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://oauth.vk.com/access_token', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}')); + + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Vkontakte::__construct + * @covers OAuth\OAuth2\Service\Vkontakte::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}')); + + $service = new Vkontakte( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/YammerTest.php b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/YammerTest.php new file mode 100644 index 00000000..86440395 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/OAuth2/Service/YammerTest.php @@ -0,0 +1,187 @@ +getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + */ + public function testConstructCorrectInstanceWithoutCustomUri() + { + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + */ + public function testConstructCorrectInstanceWithCustomUri() + { + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array(), + $this->getMock('\\OAuth\\Common\\Http\\Uri\\UriInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::getAuthorizationEndpoint + */ + public function testGetAuthorizationEndpoint() + { + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.yammer.com/dialog/oauth', $service->getAuthorizationEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::getAccessTokenEndpoint + */ + public function testGetAccessTokenEndpoint() + { + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertSame('https://www.yammer.com/oauth2/access_token.json', $service->getAccessTokenEndpoint()->getAbsoluteUri()); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::getAuthorizationMethod + */ + public function testGetAuthorizationMethod() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnArgument(2)); + + $token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface'); + $token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES)); + $token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo')); + + $storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'); + $storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token)); + + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $storage + ); + + $headers = $service->request('https://pieterhordijk.com/my/awesome/path'); + + $this->assertTrue(array_key_exists('Authorization', $headers)); + $this->assertTrue(in_array('Bearer foo', $headers, true)); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue(null)); + + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseThrowsExceptionOnError() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('error=some_error')); + + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException'); + + $service->requestAccessToken('foo'); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithoutRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":{"token":"foo", "expires_at":null}}')); + + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } + + /** + * @covers OAuth\OAuth2\Service\Yammer::__construct + * @covers OAuth\OAuth2\Service\Yammer::parseAccessTokenResponse + */ + public function testParseAccessTokenResponseValidWithRefreshToken() + { + $client = $this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface'); + $client->expects($this->once())->method('retrieveResponse')->will($this->returnValue('{"access_token":{"token":"foo", "expires_at":null},"refresh_token":"baz"}')); + + $service = new Yammer( + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $client, + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo')); + } +} diff --git a/vendor/lusitanian/oauth/tests/Unit/ServiceFactoryTest.php b/vendor/lusitanian/oauth/tests/Unit/ServiceFactoryTest.php new file mode 100644 index 00000000..26588dc0 --- /dev/null +++ b/vendor/lusitanian/oauth/tests/Unit/ServiceFactoryTest.php @@ -0,0 +1,311 @@ + + * @author Chris Heng + * @author Pieter Hordijk + * @copyright Copyright (c) 2013 The authors + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ +namespace OAuth\Unit; + +use OAuth\ServiceFactory; + +class ServiceFactoryTest extends \PHPUnit_Framework_TestCase +{ + /** + * @covers OAuth\ServiceFactory::setHttpClient + */ + public function testSetHttpClient() + { + $factory = new ServiceFactory(); + + $this->assertInstanceOf( + '\\OAuth\\ServiceFactory', + $factory->setHttpClient($this->getMock('\\OAuth\\Common\\Http\\Client\\ClientInterface')) + ); + } + + /** + * @covers OAuth\ServiceFactory::registerService + */ + public function testRegisterServiceThrowsExceptionNonExistentClass() + { + $this->setExpectedException('\\OAuth\Common\Exception\Exception'); + + $factory = new ServiceFactory(); + $factory->registerService('foo', 'bar'); + } + + /** + * @covers OAuth\ServiceFactory::registerService + */ + public function testRegisterServiceThrowsExceptionWithClassIncorrectImplementation() + { + $this->setExpectedException('\\OAuth\Common\Exception\Exception'); + + $factory = new ServiceFactory(); + $factory->registerService('foo', 'OAuth\\ServiceFactory'); + } + + /** + * @covers OAuth\ServiceFactory::registerService + */ + public function testRegisterServiceSuccessOAuth1() + { + $factory = new ServiceFactory(); + + $this->assertInstanceOf( + '\\OAuth\\ServiceFactory', + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake') + ); + } + + /** + * @covers OAuth\ServiceFactory::registerService + */ + public function testRegisterServiceSuccessOAuth2() + { + $factory = new ServiceFactory(); + + $this->assertInstanceOf( + '\\OAuth\\ServiceFactory', + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake') + ); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV1Service + */ + public function testCreateServiceOAuth1NonRegistered() + { + $factory = new ServiceFactory(); + + $service = $factory->createService( + 'twitter', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth1\\Service\\Twitter', $service); + } + + /** + * @covers OAuth\ServiceFactory::registerService + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV1Service + */ + public function testCreateServiceOAuth1Registered() + { + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\OAuth1\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::registerService + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV1Service + */ + public function testCreateServiceOAuth1RegisteredAndNonRegisteredSameName() + { + $factory = new ServiceFactory(); + + $factory->registerService('twitter', '\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake'); + + $service = $factory->createService( + 'twitter', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\OAuth1\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServiceOAuth2NonRegistered() + { + $factory = new ServiceFactory(); + + $service = $factory->createService( + 'facebook', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\Facebook', $service); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServiceOAuth2Registered() + { + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\OAuth2\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServiceOAuth2RegisteredAndNonRegisteredSameName() + { + $factory = new ServiceFactory(); + + $factory->registerService('facebook', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake'); + + $service = $factory->createService( + 'facebook', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\OAuth2\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::registerService + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV1Service + */ + public function testCreateServiceThrowsExceptionOnPassingScopesToV1Service() + { + $this->setExpectedException('\\OAuth\Common\Exception\Exception'); + + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array('bar') + ); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + */ + public function testCreateServiceNonExistentService() + { + $factory = new ServiceFactory(); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertNull($service); + } + + /** + * @covers OAuth\ServiceFactory::registerService + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServicePrefersOauth2() + { + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth1\\Service\\Fake'); + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface') + ); + + $this->assertInstanceOf('\\OAuth\OAuth2\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServiceOAuth2RegisteredWithClassConstantsAsScope() + { + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array('FOO') + ); + + $this->assertInstanceOf('\\OAuth\OAuth2\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake', $service); + } + + /** + * @covers OAuth\ServiceFactory::createService + * @covers OAuth\ServiceFactory::getFullyQualifiedServiceName + * @covers OAuth\ServiceFactory::buildV2Service + * @covers OAuth\ServiceFactory::resolveScopes + */ + public function testCreateServiceOAuth2RegisteredWithCustomScope() + { + $factory = new ServiceFactory(); + + $factory->registerService('foo', '\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake'); + + $service = $factory->createService( + 'foo', + $this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'), + $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'), + array('custom') + ); + + $this->assertInstanceOf('\\OAuth\OAuth2\Service\\ServiceInterface', $service); + $this->assertInstanceOf('\\OAuthTest\\Mocks\\OAuth2\\Service\\Fake', $service); + } +} diff --git a/vendor/lusitanian/oauth/tests/bootstrap.php b/vendor/lusitanian/oauth/tests/bootstrap.php new file mode 100644 index 00000000..193b857a --- /dev/null +++ b/vendor/lusitanian/oauth/tests/bootstrap.php @@ -0,0 +1,42 @@ + + * @author David Desberg + * @copyright Copyright (c) 2012 Pieter Hordijk + * @license http://www.opensource.org/licenses/mit-license.html MIT License + */ +namespace OAuthTest; + +/** + * Setting up the default timezone. because well... PHP sucks + */ +date_default_timezone_set('Europe/Amsterdam'); + +/** + * Simple SPL autoloader for the OAuthTest mocks + * + * @param string $class The class name to load + * + * @return void + */ +spl_autoload_register(function ($class) { + $nslen = strlen(__NAMESPACE__); + if (substr($class, 0, $nslen) !== __NAMESPACE__) { + return; + } + $path = substr(str_replace('\\', '/', $class), $nslen); + $path = __DIR__ . $path . '.php'; + if (file_exists($path)) { + require $path; + } +}); + +/** + * Fire up the autoloader + */ +require_once __DIR__ . '/../vendor/autoload.php'; diff --git a/vendor/swiftmailer/swiftmailer/.gitattributes b/vendor/swiftmailer/swiftmailer/.gitattributes new file mode 100644 index 00000000..5568ef09 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/.gitattributes @@ -0,0 +1,6 @@ +*.crt -crlf +*.key -crlf +*.srl -crlf +*.pub -crlf +*.priv -crlf +*.txt -crlf diff --git a/vendor/swiftmailer/swiftmailer/.gitignore b/vendor/swiftmailer/swiftmailer/.gitignore new file mode 100644 index 00000000..9a23ffe6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/.gitignore @@ -0,0 +1,4 @@ +/tests/acceptance.conf.php +/tests/smoke.conf.php +/build/* +/vendor/ diff --git a/vendor/swiftmailer/swiftmailer/.travis.yml b/vendor/swiftmailer/swiftmailer/.travis.yml new file mode 100644 index 00000000..cadee014 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/.travis.yml @@ -0,0 +1,25 @@ +language: php + +php: + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm-nightly + +before_script: + - cp tests/acceptance.conf.php.default tests/acceptance.conf.php + - cp tests/smoke.conf.php.default tests/smoke.conf.php + - composer self-update + - composer update --no-interaction --prefer-source + - gem install mailcatcher + - mailcatcher --smtp-port 4456 + +script: + - phpunit --verbose + +matrix: + allow_failures: + - php: 5.6 + - php: hhvm-nightly + fast_finish: true diff --git a/vendor/swiftmailer/swiftmailer/CHANGES b/vendor/swiftmailer/swiftmailer/CHANGES new file mode 100644 index 00000000..177766fa --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/CHANGES @@ -0,0 +1,186 @@ +Changelog +========= + +5.3.0 (2014-10-04) +------------------ + + * fixed cloning when using signers + * reverted removal of Swift_Encoding + * drop support for PHP 5.2.x + +5.2.2 (2014-09-20) +------------------ + + * fixed Japanese support + * fixed the memory spool when the message changes when in the pool + * added support for cloning messages + * fixed PHP warning in the redirect plugin + * changed the way to and cc-ed email are sent to only use one transaction + +5.2.1 (2014-06-13) +------------------ + + * SECURITY FIX: fixed CLI escaping when using sendmail as a transport + + Prior to 5.2.1, the sendmail transport (Swift_Transport_SendmailTransport) + was vulnerable to an arbitrary shell execution if the "From" header came + from a non-trusted source and no "Return-Path" is configured. + + * fixed parameter in DKIMSigner + * fixed compatibility with PHP < 5.4 + +5.2.0 (2014-05-08) +------------------ + + * fixed Swift_ByteStream_FileByteStream::read() to match to the specification + * fixed from-charset and to-charset arguments in mbstring_convert_encoding() usages + * fixed infinite loop in StreamBuffer + * fixed NullTransport to return the number of ignored emails instead of 0 + * Use phpunit and mockery for unit testing (realityking) + +5.1.0 (2014-03-18) +------------------ + + * fixed data writing to stream when sending large messages + * added support for libopendkim (https://github.com/xdecock/php-opendkim) + * merged SignedMessage and Message + * added Gmail XOAuth2 authentication + * updated the list of known mime types + * added NTLM authentication + +5.0.3 (2013-12-03) +------------------ + + * fixed double-dot bug + * fixed DKIM signer + +5.0.2 (2013-08-30) +------------------ + + * handled correct exception type while reading IoBuffer output + +5.0.1 (2013-06-17) +------------------ + + * changed the spool to only start the transport when a mail has to be sent + * fixed compatibility with PHP 5.2 + * fixed LICENSE file + +5.0.0 (2013-04-30) +------------------ + + * changed the license from LGPL to MIT + +4.3.1 (2013-04-11) +------------------ + + * removed usage of the native QP encoder when the charset is not UTF-8 + * fixed usage of uniqid to avoid collisions + * made a performance improvement when tokenizing large headers + * fixed usage of the PHP native QP encoder on PHP 5.4.7+ + +4.3.0 (2013-01-08) +------------------ + + * made the temporary directory configurable via the TMPDIR env variable + * added S/MIME signer and encryption support + +4.2.2 (2012-10-25) +------------------ + + * added the possibility to throttle messages per second in ThrottlerPlugin (mostly for Amazon SES) + * switched mime.qpcontentencoder to automatically use the PHP native encoder on PHP 5.4.7+ + * allowed specifying a whitelist with regular expressions in RedirectingPlugin + +4.2.1 (2012-07-13) +------------------ + + * changed the coding standards to PSR-1/2 + * fixed issue with autoloading + * added NativeQpContentEncoder to enhance performance (for PHP 5.3+) + +4.2.0 (2012-06-29) +------------------ + + * added documentation about how to use the Japanese support introduced in 4.1.8 + * added a way to override the default configuration in a lazy way + * changed the PEAR init script to lazy-load the initialization + * fixed a bug when calling Swift_Preferences before anything else (regression introduced in 4.1.8) + +4.1.8 (2012-06-17) +------------------ + + * added Japanese iso-2022-jp support + * changed the init script to lazy-load the initialization + * fixed docblocks (@id) which caused some problems with libraries parsing the dobclocks + * fixed Swift_Mime_Headers_IdentificationHeader::setId() when passed an array of ids + * fixed encoding of email addresses in headers + * added replacements setter to the Decorator plugin + +4.1.7 (2012-04-26) +------------------ + + * fixed QpEncoder safeMapShareId property + +4.1.6 (2012-03-23) +------------------ + + * reduced the size of serialized Messages + +4.1.5 (2012-01-04) +------------------ + + * enforced Swift_Spool::queueMessage() to return a Boolean + * made an optimization to the memory spool: start the transport only when required + * prevented stream_socket_client() from generating an error and throw a Swift_TransportException instead + * fixed a PHP warning when calling to mail() when safe_mode is off + * many doc tweaks + +4.1.4 (2011-12-16) +------------------ + + * added a memory spool (Swift_MemorySpool) + * fixed too many opened files when sending emails with attachments + +4.1.3 (2011-10-27) +------------------ + + * added STARTTLS support + * added missing @return tags on fluent methods + * added a MessageLogger plugin that logs all sent messages + * added composer.json + +4.1.2 (2011-09-13) +------------------ + + * fixed wrong detection of magic_quotes_runtime + * fixed fatal errors when no To or Subject header has been set + * fixed charset on parameter header continuations + * added documentation about how to install Swiftmailer from the PEAR channel + * fixed various typos and markup problem in the documentation + * fixed warning when cache directory does not exist + * fixed "slashes are escaped" bug + * changed require_once() to require() in autoload + +4.1.1 (2011-07-04) +------------------ + + * added missing file in PEAR package + +4.1.0 (2011-06-30) +------------------ + + * documentation has been converted to ReST + +4.1.0 RC1 (2011-06-17) +---------------------- + +New features: + + * changed the Decorator Plugin to allow replacements in all headers + * added Swift_Mime_Grammar and Swift_Validate to validate an email address + * modified the autoloader to lazy-initialize Swiftmailer + * removed Swift_Mailer::batchSend() + * added NullTransport + * added new plugins: RedirectingPlugin and ImpersonatePlugin + * added a way to send messages asynchronously (Spool) diff --git a/vendor/swiftmailer/swiftmailer/LICENSE b/vendor/swiftmailer/swiftmailer/LICENSE new file mode 100644 index 00000000..674bb2a6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/swiftmailer/swiftmailer/README b/vendor/swiftmailer/swiftmailer/README new file mode 100644 index 00000000..eb5f8bcf --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/README @@ -0,0 +1,16 @@ +Swift Mailer +------------ + +Swift Mailer is a component based mailing solution for PHP 5. +It is released under the MIT license. + +Homepage: http://swiftmailer.org +Documentation: http://swiftmailer.org/docs +Mailing List: http://groups.google.com/group/swiftmailer +Bugs: https://github.com/swiftmailer/swiftmailer/issues +Repository: https://github.com/swiftmailer/swiftmailer + +Swift Mailer is highly object-oriented by design and lends itself +to use in complex web application with a great deal of flexibility. + +For full details on usage, see the documentation. diff --git a/vendor/swiftmailer/swiftmailer/VERSION b/vendor/swiftmailer/swiftmailer/VERSION new file mode 100644 index 00000000..97a04ab9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/VERSION @@ -0,0 +1 @@ +Swift-5.3.0 diff --git a/vendor/swiftmailer/swiftmailer/composer.json b/vendor/swiftmailer/swiftmailer/composer.json new file mode 100644 index 00000000..ccc66326 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/composer.json @@ -0,0 +1,31 @@ +{ + "name": "swiftmailer/swiftmailer", + "type": "library", + "description": "Swiftmailer, free feature-rich PHP mailer", + "keywords": ["mail","mailer"], + "homepage": "http://swiftmailer.org", + "license": "MIT", + "authors": [ + { + "name": "Chris Corbyn" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "mockery/mockery": "~0.9.1" + }, + "autoload": { + "files": ["lib/swift_required.php"] + }, + "extra": { + "branch-alias": { + "dev-master": "5.3-dev" + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/doc/headers.rst b/vendor/swiftmailer/swiftmailer/doc/headers.rst new file mode 100644 index 00000000..6aec23ff --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/headers.rst @@ -0,0 +1,742 @@ +Message Headers +=============== + +Sometimes you'll want to add your own headers to a message or modify/remove +headers that are already present. You work with the message's HeaderSet to do +this. + +Header Basics +------------- + +All MIME entities in Swift Mailer -- including the message itself -- +store their headers in a single object called a HeaderSet. This HeaderSet is +retrieved with the ``getHeaders()`` method. + +As mentioned in the previous chapter, everything that forms a part of a message +in Swift Mailer is a MIME entity that is represented by an instance of +``Swift_Mime_MimeEntity``. This includes -- most notably -- the message object +itself, attachments, MIME parts and embedded images. Each of these MIME entities +consists of a body and a set of headers that describe the body. + +For all of the "standard" headers in these MIME entities, such as the +``Content-Type``, there are named methods for working with them, such as +``setContentType()`` and ``getContentType()``. This is because headers are a +moderately complex area of the library. Each header has a slightly different +required structure that it must meet in order to comply with the standards that +govern email (and that are checked by spam blockers etc). + +You fetch the HeaderSet from a MIME entity like so: + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + // Fetch the HeaderSet from a Message object + $headers = $message->getHeaders(); + + $attachment = Swift_Attachment::fromPath('document.pdf'); + + // Fetch the HeaderSet from an attachment object + $headers = $attachment->getHeaders(); + +The job of the HeaderSet is to contain and manage instances of Header objects. +Depending upon the MIME entity the HeaderSet came from, the contents of the +HeaderSet will be different, since an attachment for example has a different +set of headers to those in a message. + +You can find out what the HeaderSet contains with a quick loop, dumping out +the names of the headers: + +.. code-block:: php + + foreach ($headers->getAll() as $header) { + printf("%s
\n", $header->getFieldName()); + } + + /* + Content-Transfer-Encoding + Content-Type + MIME-Version + Date + Message-ID + From + Subject + To + */ + +You can also dump out the rendered HeaderSet by calling its ``toString()`` +method: + +.. code-block:: php + + echo $headers->toString(); + + /* + Message-ID: <1234869991.499a9ee7f1d5e@swift.generated> + Date: Tue, 17 Feb 2009 22:26:31 +1100 + Subject: Awesome subject! + From: sender@example.org + To: recipient@example.org + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: quoted-printable + */ + +Where the complexity comes in is when you want to modify an existing header. +This complexity comes from the fact that each header can be of a slightly +different type (such as a Date header, or a header that contains email +addresses, or a header that has key-value parameters on it!). Each header in the +HeaderSet is an instance of ``Swift_Mime_Header``. They all have common +functionality, but knowing exactly what type of header you're working with will +allow you a little more control. + +You can determine the type of header by comparing the return value of its +``getFieldType()`` method with the constants ``TYPE_TEXT``, +``TYPE_PARAMETERIZED``, ``TYPE_DATE``, ``TYPE_MAILBOX``, ``TYPE_ID`` and +``TYPE_PATH`` which are defined in ``Swift_Mime_Header``. + + +.. code-block:: php + + foreach ($headers->getAll() as $header) { + switch ($header->getFieldType()) { + case Swift_Mime_Header::TYPE_TEXT: $type = 'text'; + break; + case Swift_Mime_Header::TYPE_PARAMETERIZED: $type = 'parameterized'; + break; + case Swift_Mime_Header::TYPE_MAILBOX: $type = 'mailbox'; + break; + case Swift_Mime_Header::TYPE_DATE: $type = 'date'; + break; + case Swift_Mime_Header::TYPE_ID: $type = 'ID'; + break; + case Swift_Mime_Header::TYPE_PATH: $type = 'path'; + break; + } + printf("%s: is a %s header
\n", $header->getFieldName(), $type); + } + + /* + Content-Transfer-Encoding: is a text header + Content-Type: is a parameterized header + MIME-Version: is a text header + Date: is a date header + Message-ID: is a ID header + From: is a mailbox header + Subject: is a text header + To: is a mailbox header + */ + +Headers can be removed from the set, modified within the set, or added to the +set. + +The following sections show you how to work with the HeaderSet and explain the +details of each implementation of ``Swift_Mime_Header`` that may +exist within the HeaderSet. + +Header Types +------------ + +Because all headers are modeled on different data (dates, addresses, text!) +there are different types of Header in Swift Mailer. Swift Mailer attempts to +categorize all possible MIME headers into more general groups, defined by a +small number of classes. + +Text Headers +~~~~~~~~~~~~ + +Text headers are the simplest type of Header. They contain textual information +with no special information included within it -- for example the Subject +header in a message. + +There's nothing particularly interesting about a text header, though it is +probably the one you'd opt to use if you need to add a custom header to a +message. It represents text just like you'd think it does. If the text +contains characters that are not permitted in a message header (such as new +lines, or non-ascii characters) then the header takes care of encoding the +text so that it can be used. + +No header -- including text headers -- in Swift Mailer is vulnerable to +header-injection attacks. Swift Mailer breaks any attempt at header injection by +encoding the dangerous data into a non-dangerous form. + +It's easy to add a new text header to a HeaderSet. You do this by calling the +HeaderSet's ``addTextHeader()`` method. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addTextHeader('Your-Header-Name', 'the header value'); + +Changing the value of an existing text header is done by calling it's +``setValue()`` method. + +.. code-block:: php + + $subject = $message->getHeaders()->get('Subject'); + + $subject->setValue('new subject'); + +When output via ``toString()``, a text header produces something like the +following: + +.. code-block:: php + + $subject = $message->getHeaders()->get('Subject'); + + $subject->setValue('amazing subject line'); + + echo $subject->toString(); + + /* + + Subject: amazing subject line + + */ + +If the header contains any characters that are outside of the US-ASCII range +however, they will be encoded. This is nothing to be concerned about since +mail clients will decode them back. + +.. code-block:: php + + $subject = $message->getHeaders()->get('Subject'); + + $subject->setValue('contains – dash'); + + echo $subject->toString(); + + /* + + Subject: contains =?utf-8?Q?=E2=80=93?= dash + + */ + +Parameterized Headers +~~~~~~~~~~~~~~~~~~~~~ + +Parameterized headers are text headers that contain key-value parameters +following the textual content. The Content-Type header of a message is a +parameterized header since it contains charset information after the content +type. + +The parameterized header type is a special type of text header. It extends the +text header by allowing additional information to follow it. All of the methods +from text headers are available in addition to the methods described here. + +Adding a parameterized header to a HeaderSet is done by using the +``addParameterizedHeader()`` method which takes a text value like +``addTextHeader()`` but it also accepts an associative array of +key-value parameters. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addParameterizedHeader( + 'Header-Name', 'header value', + array('foo' => 'bar') + ); + +To change the text value of the header, call it's ``setValue()`` method just as +you do with text headers. + +To change the parameters in the header, call the header's ``setParameters()`` +method or the ``setParameter()`` method (note the pluralization). + +.. code-block:: php + + $type = $message->getHeaders()->get('Content-Type'); + + // setParameters() takes an associative array + $type->setParameters(array( + 'name' => 'file.txt', + 'charset' => 'iso-8859-1' + )); + + // setParameter() takes two args for $key and $value + $type->setParameter('charset', 'iso-8859-1'); + +When output via ``toString()``, a parameterized header produces something like +the following: + +.. code-block:: php + + $type = $message->getHeaders()->get('Content-Type'); + + $type->setValue('text/html'); + $type->setParameter('charset', 'utf-8'); + + echo $type->toString(); + + /* + + Content-Type: text/html; charset=utf-8 + + */ + +If the header contains any characters that are outside of the US-ASCII range +however, they will be encoded, just like they are for text headers. This is +nothing to be concerned about since mail clients will decode them back. +Likewise, if the parameters contain any non-ascii characters they will be +encoded so that they can be transmitted safely. + +.. code-block:: php + + $attachment = Swift_Attachment::newInstance(); + + $disp = $attachment->getHeaders()->get('Content-Disposition'); + + $disp->setValue('attachment'); + $disp->setParameter('filename', 'report–may.pdf'); + + echo $disp->toString(); + + /* + + Content-Disposition: attachment; filename*=utf-8''report%E2%80%93may.pdf + + */ + +Date Headers +~~~~~~~~~~~~ + +Date headers contains an RFC 2822 formatted date (i.e. what PHP's ``date('r')`` +returns). They are used anywhere a date or time is needed to be presented as a +message header. + +The data on which a date header is modeled is simply a UNIX timestamp such as +that returned by ``time()`` or ``strtotime()``. The timestamp is used to create +a correctly structured RFC 2822 formatted date such as +``Tue, 17 Feb 2009 22:26:31 +1100``. + +The obvious place this header type is used is in the ``Date:`` header of the +message itself. + +It's easy to add a new date header to a HeaderSet. You do this by calling +the HeaderSet's ``addDateHeader()`` method. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addDateHeader('Your-Header-Name', strtotime('3 days ago')); + +Changing the value of an existing date header is done by calling it's +``setTimestamp()`` method. + +.. code-block:: php + + $date = $message->getHeaders()->get('Date'); + + $date->setTimestamp(time()); + +When output via ``toString()``, a date header produces something like the +following: + +.. code-block:: php + + $date = $message->getHeaders()->get('Date'); + + echo $date->toString(); + + /* + + Date: Wed, 18 Feb 2009 13:35:02 +1100 + + */ + +Mailbox (e-mail address) Headers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Mailbox headers contain one or more email addresses, possibly with +personalized names attached to them. The data on which they are modeled is +represented by an associative array of email addresses and names. + +Mailbox headers are probably the most complex header type to understand in +Swift Mailer because they accept their input as an array which can take various +forms, as described in the previous chapter. + +All of the headers that contain e-mail addresses in a message -- with the +exception of ``Return-Path:`` which has a stricter syntax -- use this header +type. That is, ``To:``, ``From:`` etc. + +You add a new mailbox header to a HeaderSet by calling the HeaderSet's +``addMailboxHeader()`` method. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addMailboxHeader('Your-Header-Name', array( + 'person1@example.org' => 'Person Name One', + 'person2@example.org', + 'person3@example.org', + 'person4@example.org' => 'Another named person' + )); + +Changing the value of an existing mailbox header is done by calling it's +``setNameAddresses()`` method. + +.. code-block:: php + + $to = $message->getHeaders()->get('To'); + + $to->setNameAddresses(array( + 'joe@example.org' => 'Joe Bloggs', + 'john@example.org' => 'John Doe', + 'no-name@example.org' + )); + +If you don't wish to concern yourself with the complicated accepted input +formats accepted by ``setNameAddresses()`` as described in the previous chapter +and you only want to set one or more addresses (not names) then you can just +use the ``setAddresses()`` method instead. + +.. code-block:: php + + $to = $message->getHeaders()->get('To'); + + $to->setAddresses(array( + 'joe@example.org', + 'john@example.org', + 'no-name@example.org' + )); + +.. note:: + + Both methods will accept the above input format in practice. + +If all you want to do is set a single address in the header, you can use a +string as the input parameter to ``setAddresses()`` and/or +``setNameAddresses()``. + +.. code-block:: php + + $to = $message->getHeaders()->get('To'); + + $to->setAddresses('joe-bloggs@example.org'); + +When output via ``toString()``, a mailbox header produces something like the +following: + +.. code-block:: php + + $to = $message->getHeaders()->get('To'); + + $to->setNameAddresses(array( + 'person1@example.org' => 'Name of Person', + 'person2@example.org', + 'person3@example.org' => 'Another Person' + )); + + echo $to->toString(); + + /* + + To: Name of Person , person2@example.org, Another Person + + + */ + +ID Headers +~~~~~~~~~~ + +ID headers contain identifiers for the entity (or the message). The most +notable ID header is the Message-ID header on the message itself. + +An ID that exists inside an ID header looks more-or-less less like an email +address. For example, ``<1234955437.499becad62ec2@example.org>``. +The part to the left of the @ sign is usually unique, based on the current time +and some random factor. The part on the right is usually a domain name. + +Any ID passed to the header's ``setId()`` method absolutely MUST conform to +this structure, otherwise you'll get an Exception thrown at you by Swift Mailer +(a ``Swift_RfcComplianceException``). This is to ensure that the generated +email complies with relevant RFC documents and therefore is less likely to be +blocked as spam. + +It's easy to add a new ID header to a HeaderSet. You do this by calling +the HeaderSet's ``addIdHeader()`` method. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addIdHeader('Your-Header-Name', '123456.unqiue@example.org'); + +Changing the value of an existing date header is done by calling its +``setId()`` method. + +.. code-block:: php + + $msgId = $message->getHeaders()->get('Message-ID'); + + $msgId->setId(time() . '.' . uniqid('thing') . '@example.org'); + +When output via ``toString()``, an ID header produces something like the +following: + +.. code-block:: php + + $msgId = $message->getHeaders()->get('Message-ID'); + + echo $msgId->toString(); + + /* + + Message-ID: <1234955437.499becad62ec2@example.org> + + */ + +Path Headers +~~~~~~~~~~~~ + +Path headers are like very-restricted mailbox headers. They contain a single +email address with no associated name. The Return-Path header of a message is +a path header. + +You add a new path header to a HeaderSet by calling the HeaderSet's +``addPathHeader()`` method. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $headers = $message->getHeaders(); + + $headers->addPathHeader('Your-Header-Name', 'person@example.org'); + + +Changing the value of an existing path header is done by calling its +``setAddress()`` method. + +.. code-block:: php + + $return = $message->getHeaders()->get('Return-Path'); + + $return->setAddress('my-address@example.org'); + +When output via ``toString()``, a path header produces something like the +following: + +.. code-block:: php + + $return = $message->getHeaders()->get('Return-Path'); + + $return->setAddress('person@example.org'); + + echo $return->toString(); + + /* + + Return-Path: + + */ + +Header Operations +----------------- + +Working with the headers in a message involves knowing how to use the methods +on the HeaderSet and on the individual Headers within the HeaderSet. + +Adding new Headers +~~~~~~~~~~~~~~~~~~ + +New headers can be added to the HeaderSet by using one of the provided +``add..Header()`` methods. + +To add a header to a MIME entity (such as the message): + +Get the HeaderSet from the entity by via its ``getHeaders()`` method. + +* Add the header to the HeaderSet by calling one of the ``add..Header()`` + methods. + +The added header will appear in the message when it is sent. + +.. code-block:: php + + // Adding a custom header to a message + $message = Swift_Message::newInstance(); + $headers = $message->getHeaders(); + $headers->addTextHeader('X-Mine', 'something here'); + + // Adding a custom header to an attachment + $attachment = Swift_Attachment::fromPath('/path/to/doc.pdf'); + $attachment->getHeaders()->addDateHeader('X-Created-Time', time()); + +Retrieving Headers +~~~~~~~~~~~~~~~~~~ + +Headers are retrieved through the HeaderSet's ``get()`` and ``getAll()`` +methods. + +To get a header, or several headers from a MIME entity: + +* Get the HeaderSet from the entity by via its ``getHeaders()`` method. + +* Get the header(s) from the HeaderSet by calling either ``get()`` or + ``getAll()``. + +When using ``get()`` a single header is returned that matches the name (case +insensitive) that is passed to it. When using ``getAll()`` with a header name, +an array of headers with that name are returned. Calling ``getAll()`` with no +arguments returns an array of all headers present in the entity. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``getAll()`` exists to fetch all + headers with a specified name. In addition, ``get()`` accepts an optional + numerical index, starting from zero to specify which header you want more + specifically. + +.. note:: + + If you want to modify the contents of the header and you don't know for + sure what type of header it is then you may need to check the type by + calling its ``getFieldType()`` method. + + .. code-block:: php + + $headers = $message->getHeaders(); + + // Get the To: header + $toHeader = $headers->get('To'); + + // Get all headers named "X-Foo" + $fooHeaders = $headers->getAll('X-Foo'); + + // Get the second header named "X-Foo" + $foo = $headers->get('X-Foo', 1); + + // Get all headers that are present + $all = $headers->getAll(); + +Check if a Header Exists +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can check if a named header is present in a HeaderSet by calling its +``has()`` method. + +To check if a header exists: + +* Get the HeaderSet from the entity by via its ``getHeaders()`` method. + +* Call the HeaderSet's ``has()`` method specifying the header you're looking + for. + +If the header exists, ``true`` will be returned or ``false`` if not. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``has()`` accepts an optional + numerical index, starting from zero to specify which header you want to + check more specifically. + + .. code-block:: php + + $headers = $message->getHeaders(); + + // Check if the To: header exists + if ($headers->has('To')) { + echo 'To: exists'; + } + + // Check if an X-Foo header exists twice (i.e. check for the 2nd one) + if ($headers->has('X-Foo', 1)) { + echo 'Second X-Foo header exists'; + } + +Removing Headers +~~~~~~~~~~~~~~~~ + +Removing a Header from the HeaderSet is done by calling the HeaderSet's +``remove()`` or ``removeAll()`` methods. + +To remove an existing header: + +* Get the HeaderSet from the entity by via its ``getHeaders()`` method. + +* Call the HeaderSet's ``remove()`` or ``removeAll()`` methods specifying the + header you want to remove. + +When calling ``remove()`` a single header will be removed. When calling +``removeAll()`` all headers with the given name will be removed. If no headers +exist with the given name, no errors will occur. + +.. note:: + + It's valid for some headers to appear more than once in a message (e.g. + the Received header). For this reason ``remove()`` accepts an optional + numerical index, starting from zero to specify which header you want to + check more specifically. For the same reason, ``removeAll()`` exists to + remove all headers that have the given name. + + .. code-block:: php + + $headers = $message->getHeaders(); + + // Remove the Subject: header + $headers->remove('Subject'); + + // Remove all X-Foo headers + $headers->removeAll('X-Foo'); + + // Remove only the second X-Foo header + $headers->remove('X-Foo', 1); + +Modifying a Header's Content +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To change a Header's content you should know what type of header it is and then +call it's appropriate setter method. All headers also have a +``setFieldBodyModel()`` method that accepts a mixed parameter and delegates to +the correct setter. + +To modify an existing header: + +* Get the HeaderSet from the entity by via its ``getHeaders()`` method. + +* Get the Header by using the HeaderSet's ``get()``. + +* Call the Header's appropriate setter method or call the header's + ``setFieldBodyModel()`` method. + +The header will be updated inside the HeaderSet and the changes will be seen +when the message is sent. + +.. code-block:: php + + $headers = $message->getHeaders(); + + // Change the Subject: header + $subj = $headers->get('Subject'); + $subj->setValue('new subject here'); + + // Change the To: header + $to = $headers->get('To'); + $to->setNameAddresses(array( + 'person@example.org' => 'Person', + 'thing@example.org' + )); + + // Using the setFieldBodyModel() just delegates to the correct method + // So here to calls setNameAddresses() + $to->setFieldBodyModel(array( + 'person@example.org' => 'Person', + 'thing@example.org' + )); diff --git a/vendor/swiftmailer/swiftmailer/doc/help-resources.rst b/vendor/swiftmailer/swiftmailer/doc/help-resources.rst new file mode 100644 index 00000000..42089359 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/help-resources.rst @@ -0,0 +1,44 @@ +Getting Help +============ + +There are a number of ways you can get help when using Swift Mailer, depending +upon the nature of your problem. For bug reports and feature requests create a +new ticket in GitHub. For general advice ask on the Google Group +(swiftmailer). + +Submitting Bugs & Feature Requests +---------------------------------- + +Bugs and feature requests should be posted on GitHub. + +If you post a bug or request a feature in the forum, or on the Google Group +you will most likely be asked to create a ticket in `GitHub`_ since it is +simply not feasible to manage such requests from a number of a different +sources. + +When you go to GitHub you will be asked to create a username and password +before you can create a ticket. This is free and takes very little time. + +When you create your ticket, do not assign it to any milestones. A developer +will assess your ticket and re-assign it as needed. + +If your ticket is reporting a bug present in the current version, which was +not present in the previous version please include the tag "regression" in +your ticket. + +GitHub will update you when work is performed on your ticket. + +Ask on the Google Group +----------------------- + +You can seek advice at Google Groups, within the "swiftmailer" `group`_. + +You can post messages to this group if you want help, or there's something you +wish to discuss with the developers and with other users. + +This is probably the fastest way to get help since it is primarily email-based +for most users, though bug reports should not be posted here since they may +not be resolved. + +.. _`GitHub`: https://github.com/swiftmailer/swiftmailer/issues +.. _`group`: http://groups.google.com/group/swiftmailer diff --git a/vendor/swiftmailer/swiftmailer/doc/including-the-files.rst b/vendor/swiftmailer/swiftmailer/doc/including-the-files.rst new file mode 100644 index 00000000..978dca20 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/including-the-files.rst @@ -0,0 +1,46 @@ +Including Swift Mailer (Autoloading) +==================================== + +If you are using Composer, Swift Mailer will be automatically autoloaded. + +If not, you can use the built-in autoloader by requiring the +``swift_required.php`` file:: + + require_once '/path/to/swift-mailer/lib/swift_required.php'; + + /* rest of code goes here */ + +If you want to override the default Swift Mailer configuration, call the +``init()`` method on the ``Swift`` class and pass it a valid PHP callable (a +PHP function name, a PHP 5.3 anonymous function, ...):: + + require_once '/path/to/swift-mailer/lib/swift_required.php'; + + function swiftmailer_configurator() { + // configure Swift Mailer + + Swift_DependencyContainer::getInstance()->... + Swift_Preferences::getInstance()->... + } + + Swift::init('swiftmailer_configurator'); + + /* rest of code goes here */ + +The advantage of using the ``init()`` method is that your code will be +executed only if you use Swift Mailer in your script. + +.. note:: + + While Swift Mailer's autoloader is designed to play nicely with other + autoloaders, sometimes you may have a need to avoid using Swift Mailer's + autoloader and use your own instead. Include the ``swift_init.php`` + instead of the ``swift_required.php`` if you need to do this. The very + minimum include is the ``swift_init.php`` file since Swift Mailer will not + work without the dependency injection this file sets up: + + .. code-block:: php + + require_once '/path/to/swift-mailer/lib/swift_init.php'; + + /* rest of code goes here */ diff --git a/vendor/swiftmailer/swiftmailer/doc/index.rst b/vendor/swiftmailer/swiftmailer/doc/index.rst new file mode 100644 index 00000000..a1a0a924 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/index.rst @@ -0,0 +1,16 @@ +Swiftmailer +=========== + +.. toctree:: + :maxdepth: 2 + + introduction + overview + installing + help-resources + including-the-files + messages + headers + sending + plugins + japanese diff --git a/vendor/swiftmailer/swiftmailer/doc/installing.rst b/vendor/swiftmailer/swiftmailer/doc/installing.rst new file mode 100644 index 00000000..557211d4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/installing.rst @@ -0,0 +1,89 @@ +Installing the Library +====================== + +Installing with Composer +------------------------ + +The recommended way to install Swiftmailer is via Composer: + +.. code-block:: bash + + $ php composer.phar require swiftmailer/swiftmailer @stable + +Installing from Git +------------------- + +It's possible to download and install Swift Mailer directly from github.com if +you want to keep up-to-date with ease. + +Swift Mailer's source code is kept in a git repository at github.com so you +can get the source directly from the repository. + +.. note:: + + You do not need to have git installed to use Swift Mailer from GitHub. If + you don't have git installed, go to `GitHub`_ and click the "Download" + button. + +Cloning the Repository +~~~~~~~~~~~~~~~~~~~~~~ + +The repository can be cloned from git://github.com/swiftmailer/swiftmailer.git +using the ``git clone`` command. + +You will need to have ``git`` installed before you can use the +``git clone`` command. + +To clone the repository: + +* Open your favorite terminal environment (command line). + +* Move to the directory you want to clone to. + +* Run the command ``git clone git://github.com/swiftmailer/swiftmailer.git + swiftmailer``. + +The source code will be downloaded into a directory called "swiftmailer". + +The example shows the process on a UNIX-like system such as Linux, BSD or Mac +OS X. + +.. code-block:: bash + + $ cd source_code/ + $ git clone git://github.com/swiftmailer/swiftmailer.git swiftmailer + Initialized empty Git repository in /Users/chris/source_code/swiftmailer/.git/ + remote: Counting objects: 6815, done. + remote: Compressing objects: 100% (2761/2761), done. + remote: Total 6815 (delta 3641), reused 6326 (delta 3286) + Receiving objects: 100% (6815/6815), 4.35 MiB | 162 KiB/s, done. + Resolving deltas: 100% (3641/3641), done. + Checking out files: 100% (1847/1847), done. + $ cd swiftmailer/ + $ ls + CHANGES LICENSE ... + $ + +Troubleshooting +--------------- + +Swift Mailer does not work when used with function overloading as implemented +by ``mbstring`` (``mbstring.func_overload`` set to ``2``). A workaround is to +temporarily change the internal encoding to ``ASCII`` when sending an email: + +.. code-block:: php + + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) + { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('ASCII'); + } + + // Create your message and send it with Swift Mailer + + if (isset($mbEncoding)) + { + mb_internal_encoding($mbEncoding); + } + +.. _`GitHub`: http://github.com/swiftmailer/swiftmailer diff --git a/vendor/swiftmailer/swiftmailer/doc/introduction.rst b/vendor/swiftmailer/swiftmailer/doc/introduction.rst new file mode 100644 index 00000000..a85336b7 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/introduction.rst @@ -0,0 +1,135 @@ +Introduction +============ + +Swift Mailer is a component-based library for sending e-mails from PHP +applications. + +Organization of this Book +------------------------- + +This book has been written so that those who need information quickly are able +to find what they need, and those who wish to learn more advanced topics can +read deeper into each chapter. + +The book begins with an overview of Swift Mailer, discussing what's included +in the package and preparing you for the remainder of the book. + +It is possible to read this user guide just like any other book (from +beginning to end). Each chapter begins with a discussion of the contents it +contains, followed by a short code sample designed to give you a head start. +As you get further into a chapter you will learn more about Swift Mailer's +capabilities, but often you will be able to head directly to the topic you +wish to learn about. + +Throughout this book you will be presented with code samples, which most +people should find ample to implement Swift Mailer appropriately in their own +projects. We will also use diagrams where appropriate, and where we believe +readers may find it helpful we will discuss some related theory, including +reference to certain documents you are able to find online. + +Code Samples +------------ + +Code samples presented in this book will be displayed on a different colored +background in a monospaced font. Samples are not to be taken as copy & paste +code snippets. + +Code examples are used through the book to clarify what is written in text. +They will sometimes be usable as-is, but they should always be taken as +outline/pseudo code only. + +A code sample will look like this:: + + class AClass + { + ... + } + + // A Comment + $obj = new AClass($arg1, $arg2, ... ); + + /* A note about another way of doing something + $obj = AClass::newInstance($arg1, $arg2, ... ); + + */ + +The presence of 3 dots ``...`` in a code sample indicates that we have left +out a chunk of the code for brevity, they are not actually part of the code. + +We will often place multi-line comments ``/* ... */`` in the code so that we +can show alternative ways of achieving the same result. + +You should read the code examples given and try to understand them. They are +kept concise so that you are not overwhelmed with information. + +History of Swift Mailer +----------------------- + +Swift Mailer began back in 2005 as a one-class project for sending mail over +SMTP. It has since grown into the flexible component-based library that is in +development today. + +Chris Corbyn first posted Swift Mailer on a web forum asking for comments from +other developers. It was never intended as a fully supported open source +project, but members of the forum began to adopt it and make use of it. + +Very quickly feature requests were coming for the ability to add attachments +and use SMTP authentication, along with a number of other "obvious" missing +features. Considering the only alternative was PHPMailer it seemed like a good +time to bring some fresh tools to the table. Chris began working towards a +more component based, PHP5-like approach unlike the existing single-class, +legacy PHP4 approach taken by PHPMailer. + +Members of the forum offered a lot of advice and critique on the code as he +worked through this project and released versions 2 and 3 of the library in +2005 and 2006, which by then had been broken down into smaller classes +offering more flexibility and supporting plugins. To this day the Swift Mailer +team still receive a lot of feature requests from users both on the forum and +in by email. + +Until 2008 Chris was the sole developer of Swift Mailer, but entering 2009 he +gained the support of two experienced developers well-known to him: Paul +Annesley and Christopher Thompson. This has been an extremely welcome change. + +As of September 2009, Chris handed over the maintenance of Swift Mailer to +Fabien Potencier. + +Now 2009 and in its fourth major version Swift Mailer is more object-oriented +and flexible than ever, both from a usability standpoint and from a +development standpoint. + +By no means is Swift Mailer ready to call "finished". There are still many +features that can be added to the library along with the constant refactoring +that happens behind the scenes. + +It's a Library! +--------------- + +Swift Mailer is not an application - it's a library. + +To most experienced developers this is probably an obvious point to make, but +it's certainly worth mentioning. Many people often contact us having gotten +the completely wrong end of the stick in terms of what Swift Mailer is +actually for. + +It's not an application. It does not have a graphical user interface. It +cannot be opened in your web browser directly. + +It's a library (or a framework if you like). It provides a whole lot of +classes that do some very complicated things, so that you don't have to. You +"use" Swift Mailer within an application so that your application can have the +ability to send emails. + +The component-based structure of the library means that you are free to +implement it in a number of different ways and that you can pick and choose +what you want to use. + +An application on the other hand (such as a blog or a forum) is already "put +together" in a particular way, (usually) provides a graphical user interface +and most likely doesn't offer a great deal of integration with your own +application. + +Embrace the structure of the library and use the components it offers to your +advantage. Learning what the components do, rather than blindly copying and +pasting existing code will put you in a great position to build a powerful +application! diff --git a/vendor/swiftmailer/swiftmailer/doc/japanese.rst b/vendor/swiftmailer/swiftmailer/doc/japanese.rst new file mode 100644 index 00000000..34afa7b8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/japanese.rst @@ -0,0 +1,22 @@ +Using Swift Mailer for Japanese Emails +====================================== + +To send emails in Japanese, you need to tweak the default configuration. + +After requiring the Swift Mailer autoloader (by including the +``swift_required.php`` file), call the ``Swift::init()`` method with the +following code:: + + require_once '/path/to/swift-mailer/lib/swift_required.php'; + + Swift::init(function () { + Swift_DependencyContainer::getInstance() + ->register('mime.qpheaderencoder') + ->asAliasOf('mime.base64headerencoder'); + + Swift_Preferences::getInstance()->setCharset('iso-2022-jp'); + }); + + /* rest of code goes here */ + +That's all! diff --git a/vendor/swiftmailer/swiftmailer/doc/messages.rst b/vendor/swiftmailer/swiftmailer/doc/messages.rst new file mode 100644 index 00000000..7a192536 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/messages.rst @@ -0,0 +1,1057 @@ +Creating Messages +================= + +Creating messages in Swift Mailer is done by making use of the various MIME +entities provided with the library. Complex messages can be quickly created +with very little effort. + +Quick Reference for Creating a Message +--------------------------------------- + +You can think of creating a Message as being similar to the steps you perform +when you click the Compose button in your mail client. You give it a subject, +specify some recipients, add any attachments and write your message. + +To create a Message: + +* Call the ``newInstance()`` method of ``Swift_Message``. + +* Set your sender address (``From:``) with ``setFrom()`` or ``setSender()``. + +* Set a subject line with ``setSubject()``. + +* Set recipients with ``setTo()``, ``setCc()`` and/or ``setBcc()``. + +* Set a body with ``setBody()``. + +* Add attachments with ``attach()``. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the message + $message = Swift_Message::newInstance() + + // Give the message a subject + ->setSubject('Your subject') + + // Set the From address with an associative array + ->setFrom(array('john@doe.com' => 'John Doe')) + + // Set the To addresses with an associative array + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + + // Give it a body + ->setBody('Here is the message itself') + + // And optionally an alternative body + ->addPart('Here is the message itself', 'text/html') + + // Optionally add any attachments + ->attach(Swift_Attachment::fromPath('my-document.pdf')) + ; + +Message Basics +-------------- + +A message is a container for anything you want to send to somebody else. There +are several basic aspects of a message that you should know. + +An e-mail message is made up of several relatively simple entities that are +combined in different ways to achieve different results. All of these entities +have the same fundamental outline but serve a different purpose. The Message +itself can be defined as a MIME entity, an Attachment is a MIME entity, all +MIME parts are MIME entities -- and so on! + +The basic units of each MIME entity -- be it the Message itself, or an +Attachment -- are its Headers and its body: + +.. code-block:: text + + Header-Name: A header value + Other-Header: Another value + + The body content itself + +The Headers of a MIME entity, and its body must conform to some strict +standards defined by various RFC documents. Swift Mailer ensures that these +specifications are followed by using various types of object, including +Encoders and different Header types to generate the entity. + +The Structure of a Message +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Of all of the MIME entities, a message -- ``Swift_Message`` +is the largest and most complex. It has many properties that can be updated +and it can contain other MIME entities -- attachments for example -- +nested inside it. + +A Message has a lot of different Headers which are there to present +information about the message to the recipients' mail client. Most of these +headers will be familiar to the majority of users, but we'll list the basic +ones. Although it's possible to work directly with the Headers of a Message +(or other MIME entity), the standard Headers have accessor methods provided to +abstract away the complex details for you. For example, although the Date on a +message is written with a strict format, you only need to pass a UNIX +timestamp to ``setDate()``. + ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| Header | Description | Accessors | ++===============================+====================================================================================================================================+=============================================+ +| ``Message-ID`` | Identifies this message with a unique ID, usually containing the domain name and time generated | ``getId()`` / ``setId()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Return-Path`` | Specifies where bounces should go (Swift Mailer reads this for other uses) | ``getReturnPath()`` / ``setReturnPath()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``From`` | Specifies the address of the person who the message is from. This can be multiple addresses if multiple people wrote the message. | ``getFrom()`` / ``setFrom()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Sender`` | Specifies the address of the person who physically sent the message (higher precedence than ``From:``) | ``getSender()`` / ``setSender()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``To`` | Specifies the addresses of the intended recipients | ``getTo()`` / ``setTo()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Cc`` | Specifies the addresses of recipients who will be copied in on the message | ``getCc()`` / ``setCc()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Bcc`` | Specifies the addresses of recipients who the message will be blind-copied to. Other recipients will not be aware of these copies. | ``getBcc()`` / ``setBcc()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Reply-To`` | Specifies the address where replies are sent to | ``getReplyTo()`` / ``setReplyTo()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Subject`` | Specifies the subject line that is displayed in the recipients' mail client | ``getSubject()`` / ``setSubject()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Date`` | Specifies the date at which the message was sent | ``getDate()`` / ``setDate()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Content-Type`` | Specifies the format of the message (usually text/plain or text/html) | ``getContentType()`` / ``setContentType()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ +| ``Content-Transfer-Encoding`` | Specifies the encoding scheme in the message | ``getEncoder()`` / ``setEncoder()`` | ++-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+ + +Working with a Message Object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although there are a lot of available methods on a message object, you only +need to make use of a small subset of them. Usually you'll use +``setSubject()``, ``setTo()`` and +``setFrom()`` before setting the body of your message with +``setBody()``. + +Calling methods is simple. You just call them like functions, but using the +object operator "``->``" to do so. If you've created +a message object and called it ``$message`` then you'd set a +subject on it like so: + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + $message = Swift_Message::newInstance(); + $message->setSubject('My subject'); + +All MIME entities (including a message) have a ``toString()`` +method that you can call if you want to take a look at what is going to be +sent. For example, if you ``echo +$message->toString();`` you would see something like this: + +.. code-block:: bash + + Message-ID: <1230173678.4952f5eeb1432@swift.generated> + Date: Thu, 25 Dec 2008 13:54:38 +1100 + Subject: Example subject + From: Chris Corbyn + To: Receiver Name + MIME-Version: 1.0 + Content-Type: text/plain; charset=utf-8 + Content-Transfer-Encoding: quoted-printable + + Here is the message + +We'll take a closer look at the methods you use to create your message in the +following sections. + +Adding Content to Your Message +------------------------------ + +Rich content can be added to messages in Swift Mailer with relative ease by +calling methods such as ``setSubject()``, ``setBody()``, ``addPart()`` and +``attach()``. + +Setting the Subject Line +~~~~~~~~~~~~~~~~~~~~~~~~ + +The subject line, displayed in the recipients' mail client can be set with the +``setSubject()`` method, or as a parameter to ``Swift_Message::newInstance()``. + +To set the subject of your Message: + +* Call the ``setSubject()`` method of the Message, or specify it at the time + you create the message. + + .. code-block:: php + + // Pass it as a parameter when you create the message + $message = Swift_Message::newInstance('My amazing subject'); + + // Or set it after like this + $message->setSubject('My amazing subject'); + +Setting the Body Content +~~~~~~~~~~~~~~~~~~~~~~~~ + +The body of the message -- seen when the user opens the message -- +is specified by calling the ``setBody()`` method. If an alternative body is to +be included ``addPart()`` can be used. + +The body of a message is the main part that is read by the user. Often people +want to send a message in HTML format (``text/html``), other +times people want to send in plain text (``text/plain``), or +sometimes people want to send both versions and allow the recipient to choose +how they view the message. + +As a rule of thumb, if you're going to send a HTML email, always include a +plain-text equivalent of the same content so that users who prefer to read +plain text can do so. + +To set the body of your Message: + +* Call the ``setBody()`` method of the Message, or specify it at the time you + create the message. + +* Add any alternative bodies with ``addPart()``. + +If the recipient's mail client offers preferences for displaying text vs. HTML +then the mail client will present that part to the user where available. In +other cases the mail client will display the "best" part it can - usually HTML +if you've included HTML. + +.. code-block:: php + + // Pass it as a parameter when you create the message + $message = Swift_Message::newInstance('Subject here', 'My amazing body'); + + // Or set it after like this + $message->setBody('My amazing body', 'text/html'); + + // Add alternative parts with addPart() + $message->addPart('My amazing body in plain text', 'text/plain'); + +Attaching Files +--------------- + +Attachments are downloadable parts of a message and can be added by calling +the ``attach()`` method on the message. You can add attachments that exist on +disk, or you can create attachments on-the-fly. + +Attachments are actually an interesting area of Swift Mailer and something +that could put a lot of power at your fingertips if you grasp the concept +behind the way a message is held together. + +Although we refer to files sent over e-mails as "attachments" -- because +they're attached to the message -- lots of other parts of the message are +actually "attached" even if we don't refer to these parts as attachments. + +File attachments are created by the ``Swift_Attachment`` class +and then attached to the message via the ``attach()`` method on +it. For all of the "every day" MIME types such as all image formats, word +documents, PDFs and spreadsheets you don't need to explicitly set the +content-type of the attachment, though it would do no harm to do so. For less +common formats you should set the content-type -- which we'll cover in a +moment. + +Attaching Existing Files +~~~~~~~~~~~~~~~~~~~~~~~~ + +Files that already exist, either on disk or at a URL can be attached to a +message with just one line of code, using ``Swift_Attachment::fromPath()``. + +You can attach files that exist locally, or if your PHP installation has +``allow_url_fopen`` turned on you can attach files from other +websites. + +To attach an existing file: + +* Create an attachment with ``Swift_Attachment::fromPath()``. + +* Add the attachment to the message with ``attach()``. + +The attachment will be presented to the recipient as a downloadable file with +the same filename as the one you attached. + +.. code-block:: php + + // Create the attachment + // * Note that you can technically leave the content-type parameter out + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg'); + + // Attach it to the message + $message->attach($attachment); + + + // The two statements above could be written in one line instead + $message->attach(Swift_Attachment::fromPath('/path/to/image.jpg')); + + + // You can attach files from a URL if allow_url_fopen is on in php.ini + $message->attach(Swift_Attachment::fromPath('http://site.tld/logo.png')); + +Setting the Filename +~~~~~~~~~~~~~~~~~~~~ + +Usually you don't need to explicitly set the filename of an attachment because +the name of the attached file will be used by default, but if you want to set +the filename you use the ``setFilename()`` method of the Attachment. + +To change the filename of an attachment: + +* Call its ``setFilename()`` method. + +The attachment will be attached in the normal way, but meta-data sent inside +the email will rename the file to something else. + +.. code-block:: php + + // Create the attachment and call its setFilename() method + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') + ->setFilename('cool.jpg'); + + + // Because there's a fluid interface, you can do this in one statement + $message->attach( + Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('cool.jpg') + ); + +Attaching Dynamic Content +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Files that are generated at runtime, such as PDF documents or images created +via GD can be attached directly to a message without writing them out to disk. +Use the standard ``Swift_Attachment::newInstance()`` method. + +To attach dynamically created content: + +* Create your content as you normally would. + +* Create an attachment with ``Swift_Attachment::newInstance()``, specifying + the source data of your content along with a name and the content-type. + +* Add the attachment to the message with ``attach()``. + +The attachment will be presented to the recipient as a downloadable file +with the filename and content-type you specify. + +.. note:: + + If you would usually write the file to disk anyway you should just attach + it with ``Swift_Attachment::fromPath()`` since this will use less memory: + + .. code-block:: php + + // Create your file contents in the normal way, but don't write them to disk + $data = create_my_pdf_data(); + + // Create the attachment with your data + $attachment = Swift_Attachment::newInstance($data, 'my-file.pdf', 'application/pdf'); + + // Attach it to the message + $message->attach($attachment); + + + // You can alternatively use method chaining to build the attachment + $attachment = Swift_Attachment::newInstance() + ->setFilename('my-file.pdf') + ->setContentType('application/pdf') + ->setBody($data) + ; + +Changing the Disposition +~~~~~~~~~~~~~~~~~~~~~~~~ + +Attachments just appear as files that can be saved to the Desktop if desired. +You can make attachment appear inline where possible by using the +``setDisposition()`` method of an attachment. + +To make an attachment appear inline: + +* Call its ``setDisposition()`` method. + +The attachment will be displayed within the email viewing window if the mail +client knows how to display it. + +.. note:: + + If you try to create an inline attachment for a non-displayable file type + such as a ZIP file, the mail client should just present the attachment as + normal: + + .. code-block:: php + + // Create the attachment and call its setDisposition() method + $attachment = Swift_Attachment::fromPath('/path/to/image.jpg') + ->setDisposition('inline'); + + + // Because there's a fluid interface, you can do this in one statement + $message->attach( + Swift_Attachment::fromPath('/path/to/image.jpg')->setDisposition('inline') + ); + +Embedding Inline Media Files +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Often people want to include an image or other content inline with a HTML +message. It's easy to do this with HTML linking to remote resources, but this +approach is usually blocked by mail clients. Swift Mailer allows you to embed +your media directly into the message. + +Mail clients usually block downloads from remote resources because this +technique was often abused as a mean of tracking who opened an email. If +you're sending a HTML email and you want to include an image in the message +another approach you can take is to embed the image directly. + +Swift Mailer makes embedding files into messages extremely streamlined. You +embed a file by calling the ``embed()`` method of the message, +which returns a value you can use in a ``src`` or +``href`` attribute in your HTML. + +Just like with attachments, it's possible to embed dynamically generated +content without having an existing file available. + +The embedded files are sent in the email as a special type of attachment that +has a unique ID used to reference them within your HTML attributes. On mail +clients that do not support embedded files they may appear as attachments. + +Although this is commonly done for images, in theory it will work for any +displayable (or playable) media type. Support for other media types (such as +video) is dependent on the mail client however. + +Embedding Existing Files +........................ + +Files that already exist, either on disk or at a URL can be embedded in a +message with just one line of code, using ``Swift_EmbeddedFile::fromPath()``. + +You can embed files that exist locally, or if your PHP installation has +``allow_url_fopen`` turned on you can embed files from other websites. + +To embed an existing file: + +* Create a message object with ``Swift_Message::newInstance()``. + +* Set the body as HTML, and embed a file at the correct point in the message with ``embed()``. + +The file will be displayed with the message inline with the HTML wherever its ID +is used as a ``src`` attribute. + +.. note:: + + ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one + another. ``Swift_Image`` exists for semantic purposes. + +.. note:: + + You can embed files in two stages if you prefer. Just capture the return + value of ``embed()`` in a variable and use that as the ``src`` attribute. + + .. code-block:: php + + // Create the message + $message = Swift_Message::newInstance('My subject'); + + // Set the body + $message->setBody( + '' . + ' ' . + ' ' . + ' Here is an image Image' . + ' Rest of message' . + ' ' . + '', + 'text/html' // Mark the content-type as HTML + ); + + // You can embed files from a URL if allow_url_fopen is on in php.ini + $message->setBody( + '' . + ' ' . + ' ' . + ' Here is an image Image' . + ' Rest of message' . + ' ' . + '', + 'text/html' + ); + + + // If placing the embed() code inline becomes cumbersome + // it's easy to do this in two steps + $cid = $message->embed(Swift_Image::fromPath('image.png')); + + $message->setBody( + '' . + ' ' . + ' ' . + ' Here is an image Image' . + ' Rest of message' . + ' ' . + '', + 'text/html' // Mark the content-type as HTML + ); + +Embedding Dynamic Content +......................... + +Images that are generated at runtime, such as images created via GD can be +embedded directly to a message without writing them out to disk. Use the +standard ``Swift_Image::newInstance()`` method. + +To embed dynamically created content: + +* Create a message object with ``Swift_Message::newInstance()``. + +* Set the body as HTML, and embed a file at the correct point in the message + with ``embed()``. You will need to specify a filename and a content-type. + +The file will be displayed with the message inline with the HTML wherever its ID +is used as a ``src`` attribute. + +.. note:: + + ``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one + another. ``Swift_Image`` exists for semantic purposes. + +.. note:: + + You can embed files in two stages if you prefer. Just capture the return + value of ``embed()`` in a variable and use that as the ``src`` attribute. + + .. code-block:: php + + // Create your file contents in the normal way, but don't write them to disk + $img_data = create_my_image_data(); + + // Create the message + $message = Swift_Message::newInstance('My subject'); + + // Set the body + $message->setBody( + '' . + ' ' . + ' ' . + ' Here is an image Image' . + ' Rest of message' . + ' ' . + '', + 'text/html' // Mark the content-type as HTML + ); + + + // If placing the embed() code inline becomes cumbersome + // it's easy to do this in two steps + $cid = $message->embed(Swift_Image::newInstance($img_data, 'image.jpg', 'image/jpeg')); + + $message->setBody( + '' . + ' ' . + ' ' . + ' Here is an image Image' . + ' Rest of message' . + ' ' . + '', + 'text/html' // Mark the content-type as HTML + ); + +Adding Recipients to Your Message +--------------------------------- + +Recipients are specified within the message itself via ``setTo()``, ``setCc()`` +and ``setBcc()``. Swift Mailer reads these recipients from the message when it +gets sent so that it knows where to send the message to. + +Message recipients are one of three types: + +* ``To:`` recipients -- the primary recipients (required) + +* ``Cc:`` recipients -- receive a copy of the message (optional) + +* ``Bcc:`` recipients -- hidden from other recipients (optional) + +Each type can contain one, or several addresses. It's possible to list only +the addresses of the recipients, or you can personalize the address by +providing the real name of the recipient. + +Make sure to add only valid email addresses as recipients. If you try to add an +invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift +Mailer will throw a ``Swift_RfcComplianceException``. + +If you add recipients automatically based on a data source that may contain +invalid email addresses, you can prevent possible exceptions by validating the +addresses using ``Swift_Validate::email($email)`` and only adding addresses +that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and +``setBcc()`` calls in a try-catch block and handle the +``Swift_RfcComplianceException`` in the catch block. + +.. sidebar:: Syntax for Addresses + + If you only wish to refer to a single email address (for example your + ``From:`` address) then you can just use a string. + + .. code-block:: php + + $message->setFrom('some@address.tld'); + + If you want to include a name then you must use an associative array. + + .. code-block:: php + + $message->setFrom(array('some@address.tld' => 'The Name')); + + If you want to include multiple addresses then you must use an array. + + .. code-block:: php + + $message->setTo(array('some@address.tld', 'other@address.tld')); + + You can mix personalized (addresses with a name) and non-personalized + addresses in the same list by mixing the use of associative and + non-associative array syntax. + + .. code-block:: php + + $message->setTo(array( + 'recipient-with-name@example.org' => 'Recipient Name One', + 'no-name@example.org', // Note that this is not a key-value pair + 'named-recipient@example.org' => 'Recipient Name Two' + )); + +Setting ``To:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``To:`` recipients are required in a message and are set with the +``setTo()`` or ``addTo()`` methods of the message. + +To set ``To:`` recipients, create the message object using either +``new Swift_Message( ... )`` or ``Swift_Message::newInstance( ... )``, +then call the ``setTo()`` method with a complete array of addresses, or use the +``addTo()`` method to iteratively add recipients. + +The ``setTo()`` method accepts input in various formats as described earlier in +this chapter. The ``addTo()`` method takes either one or two parameters. The +first being the email address and the second optional parameter being the name +of the recipient. + +``To:`` recipients are visible in the message headers and will be +seen by the other recipients. + +.. note:: + + Multiple calls to ``setTo()`` will not add new recipients -- each + call overrides the previous calls. If you want to iteratively add + recipients, use the ``addTo()`` method. + + .. code-block:: php + + // Using setTo() to set all recipients in one go + $message->setTo(array( + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + )); + + // Using addTo() to add recipients iteratively + $message->addTo('person1@example.org'); + $message->addTo('person2@example.org', 'Person 2 Name'); + +Setting ``Cc:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Cc:`` recipients are set with the ``setCc()`` or ``addCc()`` methods of the +message. + +To set ``Cc:`` recipients, create the message object using either +``new Swift_Message( ... )`` or ``Swift_Message::newInstance( ... )``, then call +the ``setCc()`` method with a complete array of addresses, or use the +``addCc()`` method to iteratively add recipients. + +The ``setCc()`` method accepts input in various formats as described earlier in +this chapter. The ``addCc()`` method takes either one or two parameters. The +first being the email address and the second optional parameter being the name +of the recipient. + +``Cc:`` recipients are visible in the message headers and will be +seen by the other recipients. + +.. note:: + + Multiple calls to ``setCc()`` will not add new recipients -- each + call overrides the previous calls. If you want to iteratively add Cc: + recipients, use the ``addCc()`` method. + + .. code-block:: php + + // Using setCc() to set all recipients in one go + $message->setCc(array( + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + )); + + // Using addCc() to add recipients iteratively + $message->addCc('person1@example.org'); + $message->addCc('person2@example.org', 'Person 2 Name'); + +Setting ``Bcc:`` Recipients +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Bcc:`` recipients receive a copy of the message without anybody else knowing +it, and are set with the ``setBcc()`` or ``addBcc()`` methods of the message. + +To set ``Bcc:`` recipients, create the message object using either ``new +Swift_Message( ... )`` or ``Swift_Message::newInstance( ... )``, then call the +``setBcc()`` method with a complete array of addresses, or use +the ``addBcc()`` method to iteratively add recipients. + +The ``setBcc()`` method accepts input in various formats as described earlier in +this chapter. The ``addBcc()`` method takes either one or two parameters. The +first being the email address and the second optional parameter being the name +of the recipient. + +Only the individual ``Bcc:`` recipient will see their address in the message +headers. Other recipients (including other ``Bcc:`` recipients) will not see the +address. + +.. note:: + + Multiple calls to ``setBcc()`` will not add new recipients -- each + call overrides the previous calls. If you want to iteratively add Bcc: + recipients, use the ``addBcc()`` method. + + .. code-block:: php + + // Using setBcc() to set all recipients in one go + $message->setBcc(array( + 'person1@example.org', + 'person2@otherdomain.org' => 'Person 2 Name', + 'person3@example.org', + 'person4@example.org', + 'person5@example.org' => 'Person 5 Name' + )); + + // Using addBcc() to add recipients iteratively + $message->addBcc('person1@example.org'); + $message->addBcc('person2@example.org', 'Person 2 Name'); + +Specifying Sender Details +------------------------- + +An email must include information about who sent it. Usually this is managed +by the ``From:`` address, however there are other options. + +The sender information is contained in three possible places: + +* ``From:`` -- the address(es) of who wrote the message (required) + +* ``Sender:`` -- the address of the single person who sent the message + (optional) + +* ``Return-Path:`` -- the address where bounces should go to (optional) + +You must always include a ``From:`` address by using ``setFrom()`` on the +message. Swift Mailer will use this as the default ``Return-Path:`` unless +otherwise specified. + +The ``Sender:`` address exists because the person who actually sent the email +may not be the person who wrote the email. It has a higher precedence than the +``From:`` address and will be used as the ``Return-Path:`` unless otherwise +specified. + +Setting the ``From:`` Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``From:`` address is required and is set with the ``setFrom()`` method of the +message. ``From:`` addresses specify who actually wrote the email, and usually who sent it. + +What most people probably don't realise is that you can have more than one +``From:`` address if more than one person wrote the email -- for example if an +email was put together by a committee. + +To set the ``From:`` address(es): + +* Call the ``setFrom()`` method on the Message. + +The ``From:`` address(es) are visible in the message headers and +will be seen by the recipients. + +.. note:: + + If you set multiple ``From:`` addresses then you absolutely must set a + ``Sender:`` address to indicate who physically sent the message. + + .. code-block:: php + + // Set a single From: address + $message->setFrom('your@address.tld'); + + // Set a From: address including a name + $message->setFrom(array('your@address.tld' => 'Your Name')); + + // Set multiple From: addresses if multiple people wrote the email + $message->setFrom(array( + 'person1@example.org' => 'Sender One', + 'person2@example.org' => 'Sender Two' + )); + +Setting the ``Sender:`` Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``Sender:`` address specifies who sent the message and is set with the +``setSender()`` method of the message. + +To set the ``Sender:`` address: + +* Call the ``setSender()`` method on the Message. + +The ``Sender:`` address is visible in the message headers and will be seen by +the recipients. + +This address will be used as the ``Return-Path:`` unless otherwise specified. + +.. note:: + + If you set multiple ``From:`` addresses then you absolutely must set a + ``Sender:`` address to indicate who physically sent the message. + +You must not set more than one sender address on a message because it's not +possible for more than one person to send a single message. + +.. code-block:: php + + $message->setSender('your@address.tld'); + +Setting the ``Return-Path:`` (Bounce) Address +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Return-Path:`` address specifies where bounce notifications should +be sent and is set with the ``setReturnPath()`` method of the message. + +You can only have one ``Return-Path:`` and it must not include +a personal name. + +To set the ``Return-Path:`` address: + +* Call the ``setReturnPath()`` method on the Message. + +Bounce notifications will be sent to this address. + +.. code-block:: php + + $message->setReturnPath('bounces@address.tld'); + + +Signed/Encrypted Message +------------------------ + +To increase the integrity/security of a message it is possible to sign and/or +encrypt an message using one or multiple signers. + +S/MIME +~~~~~~ + +S/MIME can sign and/or encrypt a message using the OpenSSL extension. + +When signing a message, the signer creates a signature of the entire content of the message (including attachments). + +The certificate and private key must be PEM encoded, and can be either created using for example OpenSSL or +obtained at an official Certificate Authority (CA). + +**The recipient must have the CA certificate in the list of trusted issuers in order to verify the signature.** + +**Make sure the certificate supports emailProtection.** + +When using OpenSSL this can done by the including the *-addtrust emailProtection* parameter when creating the certificate. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $smimeSigner = Swift_Signers_SMimeSigner::newInstance(); + $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem'); + $message->attachSigner($smimeSigner); + +When the private key is secured using a passphrase use the following instead. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $smimeSigner = Swift_Signers_SMimeSigner::newInstance(); + $smimeSigner->setSignCertificate('/path/to/certificate.pem', array('/path/to/private-key.pem', 'passphrase')); + $message->attachSigner($smimeSigner); + +By default the signature is added as attachment, +making the message still readable for mailing agents not supporting signed messages. + +Storing the message as binary is also possible but not recommended. + +.. code-block:: php + + $smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem', PKCS7_BINARY); + +When encrypting the message (also known as enveloping), the entire message (including attachments) +is encrypted using a certificate, and the recipient can then decrypt the message using corresponding private key. + +Encrypting ensures nobody can read the contents of the message without the private key. + +Normally the recipient provides a certificate for encrypting and keeping the decryption key private. + +Using both signing and encrypting is also possible. + +.. code-block:: php + + $message = Swift_Message::newInstance(); + + $smimeSigner = Swift_Signers_SMimeSigner::newInstance(); + $smimeSigner->setSignCertificate('/path/to/sign-certificate.pem', '/path/to/private-key.pem'); + $smimeSigner->setEncryptCertificate('/path/to/encrypt-certificate.pem'); + $message->attachSigner($smimeSigner); + +The used encryption cipher can be set as the second parameter of setEncryptCertificate() + +See http://php.net/manual/openssl.ciphers for a list of supported ciphers. + +By default the message is first signed and then encrypted, this can be changed by adding. + +.. code-block:: php + + $smimeSigner->setSignThenEncrypt(false); + +**Changing this is not recommended as most mail agents don't support this none-standard way.** + +Only when having trouble with sign then encrypt method, this should be changed. + +Requesting a Read Receipt +------------------------- + +It is possible to request a read-receipt to be sent to an address when the +email is opened. To request a read receipt set the address with +``setReadReceiptTo()``. + +To request a read receipt: + +* Set the address you want the receipt to be sent to with the + ``setReadReceiptTo()`` method on the Message. + +When the email is opened, if the mail client supports it a notification will be sent to this address. + +.. note:: + + Read receipts won't work for the majority of recipients since many mail + clients auto-disable them. Those clients that will send a read receipt + will make the user aware that one has been requested. + + .. code-block:: php + + $message->setReadReceiptTo('your@address.tld'); + +Setting the Character Set +------------------------- + +The character set of the message (and it's MIME parts) is set with the +``setCharset()`` method. You can also change the global default of UTF-8 by +working with the ``Swift_Preferences`` class. + +Swift Mailer will default to the UTF-8 character set unless otherwise +overridden. UTF-8 will work in most instances since it includes all of the +standard US keyboard characters in addition to most international characters. + +It is absolutely vital however that you know what character set your message +(or it's MIME parts) are written in otherwise your message may be received +completely garbled. + +There are two places in Swift Mailer where you can change the character set: + +* In the ``Swift_Preferences`` class + +* On each individual message and/or MIME part + +To set the character set of your Message: + +* Change the global UTF-8 setting by calling + ``Swift_Preferences::setCharset()``; or + +* Call the ``setCharset()`` method on the message or the MIME part. + + .. code-block:: php + + // Approach 1: Change the global setting (suggested) + Swift_Preferences::getInstance()->setCharset('iso-8859-2'); + + // Approach 2: Call the setCharset() method of the message + $message = Swift_Message::newInstance() + ->setCharset('iso-8859-2'); + + // Approach 3: Specify the charset when setting the body + $message->setBody('My body', 'text/html', 'iso-8859-2'); + + // Approach 4: Specify the charset for each part added + $message->addPart('My part', 'text/plain', 'iso-8859-2'); + +Setting the Line Length +----------------------- + +The length of lines in a message can be changed by using the ``setMaxLineLength()`` method on the message. It should be kept to less than +1000 characters. + +Swift Mailer defaults to using 78 characters per line in a message. This is +done for historical reasons and so that the message can be easily viewed in +plain-text terminals. + +To change the maximum length of lines in your Message: + +* Call the ``setMaxLineLength()`` method on the Message. + +Lines that are longer than the line length specified will be wrapped between +words. + +.. note:: + + You should never set a maximum length longer than 1000 characters + according to RFC 2822. Doing so could have unspecified side-effects such + as truncating parts of your message when it is transported between SMTP + servers. + + .. code-block:: php + + $message->setMaxLineLength(1000); + +Setting the Message Priority +---------------------------- + +You can change the priority of the message with ``setPriority()``. Setting the +priority will not change the way your email is sent -- it is purely an +indicative setting for the recipient. + +The priority of a message is an indication to the recipient what significance +it has. Swift Mailer allows you to set the priority by calling the ``setPriority`` method. This method takes an integer value between 1 and 5: + +* Highest +* High +* Normal +* Low +* Lowest + +To set the message priority: + +* Set the priority as an integer between 1 and 5 with the ``setPriority()`` + method on the Message. + +.. code-block:: php + + // Indicate "High" priority + $message->setPriority(2); diff --git a/vendor/swiftmailer/swiftmailer/doc/overview.rst b/vendor/swiftmailer/swiftmailer/doc/overview.rst new file mode 100644 index 00000000..c9126173 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/overview.rst @@ -0,0 +1,161 @@ +Library Overview +================ + +Most features (and more) of your every day mail client software are provided +by Swift Mailer, using object-oriented PHP code as the interface. + +In this chapter we will take a short tour of the various components, which put +together form the Swift Mailer library as a whole. You will learn key +terminology used throughout the rest of this book and you will gain a little +understanding of the classes you will work with as you integrate Swift Mailer +into your application. + +This chapter is intended to prepare you for the information contained in the +subsequent chapters of this book. You may choose to skip this chapter if you +are fairly technically minded, though it is likely to save you some time in +the long run if you at least read between the lines here. + +System Requirements +------------------- + +The basic requirements to operate Swift Mailer are extremely minimal and +easily achieved. Historically, Swift Mailer has supported both PHP 4 and PHP 5 +by following a parallel development workflow. Now in it's fourth major +version, and Swift Mailer operates on servers running PHP 5.2 or higher. + +The library aims to work with as many PHP 5 projects as possible: + +* PHP 5.2 or higher, with the SPL extension (standard) + +* Limited network access to connect to remote SMTP servers + +* 8 MB or more memory limit (Swift Mailer uses around 2 MB) + +Component Breakdown +------------------- + +Swift Mailer is made up of many classes. Each of these classes can be grouped +into a general "component" group which describes the task it is designed to +perform. + +We'll take a brief look at the components which form Swift Mailer in this +section of the book. + +The Mailer +~~~~~~~~~~ + +The mailer class, ``Swift_Mailer`` is the central class in the library where +all of the other components meet one another. ``Swift_Mailer`` acts as a sort +of message dispatcher, communicating with the underlying Transport to deliver +your Message to all intended recipients. + +If you were to dig around in the source code for Swift Mailer you'd notice +that ``Swift_Mailer`` itself is pretty bare. It delegates to other objects for +most tasks and in theory, if you knew the internals of Swift Mailer well you +could by-pass this class entirely. We wouldn't advise doing such a thing +however -- there are reasons this class exists: + +* for consistency, regardless of the Transport used + +* to provide abstraction from the internals in the event internal API changes + are made + +* to provide convenience wrappers around aspects of the internal API + +An instance of ``Swift_Mailer`` is created by the developer before sending any +Messages. + +Transports +~~~~~~~~~~ + +Transports are the classes in Swift Mailer that are responsible for +communicating with a service in order to deliver a Message. There are several +types of Transport in Swift Mailer, all of which implement the Swift_Transport +interface and offer underlying start(), stop() and send() methods. + +Typically you will not need to know how a Transport works under-the-surface, +you will only need to know how to create an instance of one, and which one to +use for your environment. + ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ +| Class | Features | Pros/cons | ++=================================+=============================================================================================+===============================================================================================================================================+ +| ``Swift_SmtpTransport`` | Sends messages over SMTP; Supports Authentication; Supports Encryption | Very portable; Pleasingly predictable results; Provides good feedback | ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ +| ``Swift_SendmailTransport`` | Communicates with a locally installed ``sendmail`` executable (Linux/UNIX) | Quick time-to-run; Provides less-accurate feedback than SMTP; Requires ``sendmail`` installation | ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ +| ``Swift_MailTransport`` | Uses PHP's built-in ``mail()`` function | Very portable; Potentially unpredictable results; Provides extremely weak feedback | ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ +| ``Swift_LoadBalancedTransport`` | Cycles through a collection of the other Transports to manage load-reduction | Provides graceful fallback if one Transport fails (e.g. an SMTP server is down); Keeps the load on remote services down by spreading the work | ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ +| ``Swift_FailoverTransport`` | Works in conjunction with a collection of the other Transports to provide high-availability | Provides graceful fallback if one Transport fails (e.g. an SMTP server is down) | ++---------------------------------+---------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------+ + +MIME Entities +~~~~~~~~~~~~~ + +Everything that forms part of a Message is called a MIME Entity. All MIME +entities in Swift Mailer share a common set of features. There are various +types of MIME entity that serve different purposes such as Attachments and +MIME parts. + +An e-mail message is made up of several relatively simple entities that are +combined in different ways to achieve different results. All of these entities +have the same fundamental outline but serve a different purpose. The Message +itself can be defined as a MIME entity, an Attachment is a MIME entity, all +MIME parts are MIME entities -- and so on! + +The basic units of each MIME entity -- be it the Message itself, or an +Attachment -- are its Headers and its body: + +.. code-block:: text + + Other-Header: Another value + + The body content itself + +The Headers of a MIME entity, and its body must conform to some strict +standards defined by various RFC documents. Swift Mailer ensures that these +specifications are followed by using various types of object, including +Encoders and different Header types to generate the entity. + +Each MIME component implements the base ``Swift_Mime_MimeEntity`` interface, +which offers methods for retrieving Headers, adding new Headers, changing the +Encoder, updating the body and so on! + +All MIME entities have one Header in common -- the Content-Type Header, +updated with the entity's ``setContentType()`` method. + +Encoders +~~~~~~~~ + +Encoders are used to transform the content of Messages generated in Swift +Mailer into a format that is safe to send across the internet and that +conforms to RFC specifications. + +Generally speaking you will not need to interact with the Encoders in Swift +Mailer -- the correct settings will be handled by the library itself. +However they are probably worth a brief mention in the event that you do want +to play with them. + +Both the Headers and the body of all MIME entities (including the Message +itself) use Encoders to ensure the data they contain can be sent over the +internet without becoming corrupted or misinterpreted. + +There are two types of Encoder: Base64 and Quoted-Printable. + +Plugins +~~~~~~~ + +Plugins exist to extend, or modify the behaviour of Swift Mailer. They respond +to Events that are fired within the Transports during sending. + +There are a number of Plugins provided as part of the base Swift Mailer +package and they all follow a common interface to respond to Events fired +within the library. Interfaces are provided to "listen" to each type of Event +fired and to act as desired when a listened-to Event occurs. + +Although several plugins are provided with Swift Mailer out-of-the-box, the +Events system has been specifically designed to make it easy for experienced +object-oriented developers to write their own plugins in order to achieve +goals that may not be possible with the base library. diff --git a/vendor/swiftmailer/swiftmailer/doc/plugins.rst b/vendor/swiftmailer/swiftmailer/doc/plugins.rst new file mode 100644 index 00000000..16ae3356 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/plugins.rst @@ -0,0 +1,385 @@ +Plugins +======= + +Plugins are provided with Swift Mailer and can be used to extend the behavior +of the library in situations where using simple class inheritance would be more complex. + +AntiFlood Plugin +---------------- + +Many SMTP servers have limits on the number of messages that may be sent +during any single SMTP connection. The AntiFlood plugin provides a way to stay +within this limit while still managing a large number of emails. + +A typical limit for a single connection is 100 emails. If the server you +connect to imposes such a limit, it expects you to disconnect after that +number of emails has been sent. You could manage this manually within a loop, +but the AntiFlood plugin provides the necessary wrapper code so that you don't +need to worry about this logic. + +Regardless of limits imposed by the server, it's usually a good idea to be +conservative with the resources of the SMTP server. Sending will become +sluggish if the server is being over-used so using the AntiFlood plugin will +not be a bad idea even if no limits exist. + +The AntiFlood plugin's logic is basically to disconnect and the immediately +re-connect with the SMTP server every X number of emails sent, where X is a +number you specify to the plugin. + +You can also specify a time period in seconds that Swift Mailer should pause +for between the disconnect/re-connect process. It's a good idea to pause for a +short time (say 30 seconds every 100 emails) simply to give the SMTP server a +chance to process its queue and recover some resources. + +Using the AntiFlood Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The AntiFlood Plugin -- like all plugins -- is added with the Mailer class's +``registerPlugin()`` method. It takes two constructor parameters: the number of +emails to pause after, and optionally the number of seconds to pause for. + +To use the AntiFlood plugin: + +* Create an instance of the Mailer using any Transport you choose. + +* Create an instance of the ``Swift_Plugins_AntiFloodPlugin`` class, passing + in one or two constructor parameters. + +* Register the plugin using the Mailer's ``registerPlugin()`` method. + +* Continue using Swift Mailer to send messages as normal. + +When Swift Mailer sends messages it will count the number of messages that +have been sent since the last re-connect. Once the number hits your specified +threshold it will disconnect and re-connect, optionally pausing for a +specified amount of time. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Mailer using any Transport + $mailer = Swift_Mailer::newInstance( + Swift_SmtpTransport::newInstance('smtp.example.org', 25) + ); + + // Use AntiFlood to re-connect after 100 emails + $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100)); + + // And specify a time in seconds to pause for (30 secs) + $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100, 30)); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + +Throttler Plugin +---------------- + +If your SMTP server has restrictions in place to limit the rate at which you +send emails, then your code will need to be aware of this rate-limiting. The +Throttler plugin makes Swift Mailer run at a rate-limited speed. + +Many shared hosts don't open their SMTP servers as a free-for-all. Usually +they have policies in place (probably to discourage spammers) that only allow +you to send a fixed number of emails per-hour/day. + +The Throttler plugin supports two modes of rate-limiting and with each, you +will need to do that math to figure out the values you want. The plugin can +limit based on the number of emails per minute, or the number of +bytes-transferred per-minute. + +Using the Throttler Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Throttler Plugin -- like all plugins -- is added with the Mailer class' +``registerPlugin()`` method. It has two required constructor parameters that +tell it how to do its rate-limiting. + +To use the Throttler plugin: + +* Create an instance of the Mailer using any Transport you choose. + +* Create an instance of the ``Swift_Plugins_ThrottlerPlugin`` class, passing + the number of emails, or bytes you wish to limit by, along with the mode + you're using. + +* Register the plugin using the Mailer's ``registerPlugin()`` method. + +* Continue using Swift Mailer to send messages as normal. + +When Swift Mailer sends messages it will keep track of the rate at which sending +messages is occurring. If it realises that sending is happening too fast, it +will cause your program to ``sleep()`` for enough time to average out the rate. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Mailer using any Transport + $mailer = Swift_Mailer::newInstance( + Swift_SmtpTransport::newInstance('smtp.example.org', 25) + ); + + // Rate limit to 100 emails per-minute + $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( + 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE + )); + + // Rate limit to 10MB per-minute + $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( + 1024 * 1024 * 10, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE + )); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + +Logger Plugin +------------- + +The Logger plugins helps with debugging during the process of sending. It can +help to identify why an SMTP server is rejecting addresses, or any other +hard-to-find problems that may arise. + +The Logger plugin comes in two parts. There's the plugin itself, along with +one of a number of possible Loggers that you may choose to use. For example, +the logger may output messages directly in realtime, or it may capture +messages in an array. + +One other notable feature is the way in which the Logger plugin changes +Exception messages. If Exceptions are being thrown but the error message does +not provide conclusive information as to the source of the problem (such as an +ambiguous SMTP error) the Logger plugin includes the entire SMTP transcript in +the error message so that debugging becomes a simpler task. + +There are a few available Loggers included with Swift Mailer, but writing your +own implementation is incredibly simple and is achieved by creating a short +class that implements the ``Swift_Plugins_Logger`` interface. + +* ``Swift_Plugins_Loggers_ArrayLogger``: Keeps a collection of log messages + inside an array. The array content can be cleared or dumped out to the + screen. + +* ``Swift_Plugins_Loggers_EchoLogger``: Prints output to the screen in + realtime. Handy for very rudimentary debug output. + +Using the Logger Plugin +~~~~~~~~~~~~~~~~~~~~~~~ + +The Logger Plugin -- like all plugins -- is added with the Mailer class' +``registerPlugin()`` method. It accepts an instance of ``Swift_Plugins_Logger`` +in its constructor. + +To use the Logger plugin: + +* Create an instance of the Mailer using any Transport you choose. + +* Create an instance of the a Logger implementation of + ``Swift_Plugins_Logger``. + +* Create an instance of the ``Swift_Plugins_LoggerPlugin`` class, passing the + created Logger instance to its constructor. + +* Register the plugin using the Mailer's ``registerPlugin()`` method. + +* Continue using Swift Mailer to send messages as normal. + +* Dump the contents of the log with the logger's ``dump()`` method. + +When Swift Mailer sends messages it will keep a log of all the interactions +with the underlying Transport being used. Depending upon the Logger that has +been used the behaviour will differ, but all implementations offer a way to +get the contents of the log. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Mailer using any Transport + $mailer = Swift_Mailer::newInstance( + Swift_SmtpTransport::newInstance('smtp.example.org', 25) + ); + + // To use the ArrayLogger + $logger = new Swift_Plugins_Loggers_ArrayLogger(); + $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger)); + + // Or to use the Echo Logger + $logger = new Swift_Plugins_Loggers_EchoLogger(); + $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger)); + + // Continue sending as normal + for ($lotsOfRecipients as $recipient) { + ... + + $mailer->send( ... ); + } + + // Dump the log contents + // NOTE: The EchoLogger dumps in realtime so dump() does nothing for it + echo $logger->dump(); + +Decorator Plugin +---------------- + +Often there's a need to send the same message to multiple recipients, but with +tiny variations such as the recipient's name being used inside the message +body. The Decorator plugin aims to provide a solution for allowing these small +differences. + +The decorator plugin works by intercepting the sending process of Swift +Mailer, reading the email address in the To: field and then looking up a set +of replacements for a template. + +While the use of this plugin is simple, it is probably the most commonly +misunderstood plugin due to the way in which it works. The typical mistake +users make is to try registering the plugin multiple times (once for each +recipient) -- inside a loop for example. This is incorrect. + +The Decorator plugin should be registered just once, but containing the list +of all recipients prior to sending. It will use this list of recipients to +find the required replacements during sending. + +Using the Decorator Plugin +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use the Decorator plugin, simply create an associative array of replacements +based on email addresses and then use the mailer's ``registerPlugin()`` method +to add the plugin. + +First create an associative array of replacements based on the email addresses +you'll be sending the message to. + +.. note:: + + The replacements array becomes a 2-dimensional array whose keys are the + email addresses and whose values are an associative array of replacements + for that email address. The curly braces used in this example can be any + type of syntax you choose, provided they match the placeholders in your + email template. + + .. code-block:: php + + $replacements = array(); + foreach ($users as $user) { + $replacements[$user['email']] = array( + '{username}'=>$user['username'], + '{password}'=>$user['password'] + ); + } + +Now create an instance of the Decorator plugin using this array of replacements +and then register it with the Mailer. Do this only once! + +.. code-block:: php + + $decorator = new Swift_Plugins_DecoratorPlugin($replacements); + + $mailer->registerPlugin($decorator); + +When you create your message, replace elements in the body (and/or the subject +line) with your placeholders. + +.. code-block:: php + + $message = Swift_Message::newInstance() + ->setSubject('Important notice for {username}') + ->setBody( + "Hello {username}, we have reset your password to {password}\n" . + "Please log in and change it at your earliest convenience." + ) + ; + + foreach ($users as $user) { + $message->addTo($user['email']); + } + +When you send this message to each of your recipients listed in your +``$replacements`` array they will receive a message customized for just +themselves. For example, the message used above when received may appear like +this to one user: + +.. code-block:: text + + Subject: Important notice for smilingsunshine2009 + + Hello smilingsunshine2009, we have reset your password to rainyDays + Please log in and change it at your earliest convenience. + +While another use may receive the message as: + +.. code-block:: text + + Subject: Important notice for billy-bo-bob + + Hello billy-bo-bob, we have reset your password to dancingOctopus + Please log in and change it at your earliest convenience. + +While the decorator plugin provides a means to solve this problem, there are +various ways you could tackle this problem without the need for a plugin. +We're trying to come up with a better way ourselves and while we have several +(obvious) ideas we don't quite have the perfect solution to go ahead and +implement it. Watch this space. + +Providing Your Own Replacements Lookup for the Decorator +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Filling an array with replacements may not be the best solution for providing +replacement information to the decorator. If you have a more elegant algorithm +that performs replacement lookups on-the-fly you may provide your own +implementation. + +Providing your own replacements lookup implementation for the Decorator is +simply a matter of passing an instance of ``Swift_Plugins_Decorator_Replacements`` to the decorator plugin's constructor, +rather than passing in an array. + +The Replacements interface is very simple to implement since it has just one +method: ``getReplacementsFor($address)``. + +Imagine you want to look up replacements from a database on-the-fly, you might +provide an implementation that does this. You need to create a small class. + +.. code-block:: php + + class DbReplacements implements Swift_Plugins_Decorator_Replacements { + public function getReplacementsFor($address) { + $sql = sprintf( + "SELECT * FROM user WHERE email = '%s'", + mysql_real_escape_string($address) + ); + + $result = mysql_query($sql); + + if ($row = mysql_fetch_assoc($result)) { + return array( + '{username}'=>$row['username'], + '{password}'=>$row['password'] + ); + } + } + } + +Now all you need to do is pass an instance of your class into the Decorator +plugin's constructor instead of passing an array. + +.. code-block:: php + + $decorator = new Swift_Plugins_DecoratorPlugin(new DbReplacements()); + + $mailer->registerPlugin($decorator); + +For each message sent, the plugin will call your class' ``getReplacementsFor()`` +method to find the array of replacements it needs. + +.. note:: + + If your lookup algorithm is case sensitive, you should transform the + ``$address`` argument as appropriate -- for example by passing it + through ``strtolower()``. diff --git a/vendor/swiftmailer/swiftmailer/doc/sending.rst b/vendor/swiftmailer/swiftmailer/doc/sending.rst new file mode 100644 index 00000000..3e9c3a8d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/doc/sending.rst @@ -0,0 +1,607 @@ +Sending Messages +================ + +Quick Reference for Sending a Message +------------------------------------- + +Sending a message is very straightforward. You create a Transport, use it to +create the Mailer, then you use the Mailer to send the message. + +To send a Message: + +* Create a Transport from one of the provided Transports -- + ``Swift_SmtpTransport``, ``Swift_SendmailTransport``, ``Swift_MailTransport`` + or one of the aggregate Transports. + +* Create an instance of the ``Swift_Mailer`` class, using the Transport as + it's constructor parameter. + +* Create a Message. + +* Send the message via the ``send()`` method on the Mailer object. + +.. caution:: + + The ``Swift_SmtpTransport`` and ``Swift_SendmailTransport`` transports use + ``proc_*`` PHP functions, which might not be available on your PHP + installation. You can easily check if that's the case by running the + following PHP script: ``setUsername('your username') + ->setPassword('your password') + ; + + /* + You could alternatively use a different transport such as Sendmail or Mail: + + // Sendmail + $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); + + // Mail + $transport = Swift_MailTransport::newInstance(); + */ + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + + // Create a message + $message = Swift_Message::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself') + ; + + // Send the message + $result = $mailer->send($message); + +Transport Types +~~~~~~~~~~~~~~~ + +A Transport is the component which actually does the sending. You need to +provide a Transport object to the Mailer class and there are several possible +options. + +Typically you will not need to know how a Transport works under-the-surface, +you will only need to know how to create an instance of one, and which one to +use for your environment. + +The SMTP Transport +.................. + +The SMTP Transport sends messages over the (standardized) Simple Message +Transfer Protocol. It can deal with encryption and authentication. + +The SMTP Transport, ``Swift_SmtpTransport`` is without doubt the most commonly +used Transport because it will work on 99% of web servers (I just made that +number up, but you get the idea). All the server needs is the ability to +connect to a remote (or even local) SMTP server on the correct port number +(usually 25). + +SMTP servers often require users to authenticate with a username and password +before any mail can be sent to other domains. This is easily achieved using +Swift Mailer with the SMTP Transport. + +SMTP is a protocol -- in other words it's a "way" of communicating a job +to be done (i.e. sending a message). The SMTP protocol is the fundamental +basis on which messages are delivered all over the internet 7 days a week, 365 +days a year. For this reason it's the most "direct" method of sending messages +you can use and it's the one that will give you the most power and feedback +(such as delivery failures) when using Swift Mailer. + +Because SMTP is generally run as a remote service (i.e. you connect to it over +the network/internet) it's extremely portable from server-to-server. You can +easily store the SMTP server address and port number in a configuration file +within your application and adjust the settings accordingly if the code is +moved or if the SMTP server is changed. + +Some SMTP servers -- Google for example -- use encryption for security reasons. +Swift Mailer supports using both SSL and TLS encryption settings. + +Using the SMTP Transport +^^^^^^^^^^^^^^^^^^^^^^^^ + +The SMTP Transport is easy to use. Most configuration options can be set with +the constructor. + +To use the SMTP Transport you need to know which SMTP server your code needs +to connect to. Ask your web host if you're not sure. Lots of people ask me who +to connect to -- I really can't answer that since it's a setting that's +extremely specific to your hosting environment. + +To use the SMTP Transport: + +* Call ``Swift_SmtpTransport::newInstance()`` with the SMTP server name and + optionally with a port number (defaults to 25). + +* Use the returned object to create the Mailer. + +A connection to the SMTP server will be established upon the first call to +``send()``. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + + /* + It's also possible to use multiple method calls + + $transport = Swift_SmtpTransport::newInstance() + ->setHost('smtp.example.org') + ->setPort(25) + ; + */ + +Encrypted SMTP +^^^^^^^^^^^^^^ + +You can use SSL or TLS encryption with the SMTP Transport by specifying it as +a parameter or with a method call. + +To use encryption with the SMTP Transport: + +* Pass the encryption setting as a third parameter to + ``Swift_SmtpTransport::newInstance()``; or + +* Call the ``setEncryption()`` method on the Transport. + +A connection to the SMTP server will be established upon the first call to +``send()``. The connection will be initiated with the correct encryption +settings. + +.. note:: + + For SSL or TLS encryption to work your PHP installation must have + appropriate OpenSSL transports wrappers. You can check if "tls" and/or + "ssl" are present in your PHP installation by using the PHP function + ``stream_get_transports()`` + + .. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 587, 'ssl'); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + + /* + It's also possible to use multiple method calls + + $transport = Swift_SmtpTransport::newInstance() + ->setHost('smtp.example.org') + ->setPort(587) + ->setEncryption('ssl') + ; + */ + +SMTP with a Username and Password +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Some servers require authentication. You can provide a username and password +with ``setUsername()`` and ``setPassword()`` methods. + +To use a username and password with the SMTP Transport: + +* Create the Transport with ``Swift_SmtpTransport::newInstance()``. + +* Call the ``setUsername()`` and ``setPassword()`` methods on the Transport. + +Your username and password will be used to authenticate upon first connect +when ``send()`` are first used on the Mailer. + +If authentication fails, an Exception of type ``Swift_TransportException`` will +be thrown. + +.. note:: + + If you need to know early whether or not authentication has failed and an + Exception is going to be thrown, call the ``start()`` method on the + created Transport. + + .. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport the call setUsername() and setPassword() + $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25) + ->setUsername('username') + ->setPassword('password') + ; + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + +The Sendmail Transport +...................... + +The Sendmail Transport sends messages by communicating with a locally +installed MTA -- such as ``sendmail``. + +The Sendmail Transport, ``Swift_SendmailTransport`` does not directly connect to +any remote services. It is designed for Linux servers that have ``sendmail`` +installed. The Transport starts a local ``sendmail`` process and sends messages +to it. Usually the ``sendmail`` process will respond quickly as it spools your +messages to disk before sending them. + +The Transport is named the Sendmail Transport for historical reasons +(``sendmail`` was the "standard" UNIX tool for sending e-mail for years). It +will send messages using other transfer agents such as Exim or Postfix despite +its name, provided they have the relevant sendmail wrappers so that they can be +started with the correct command-line flags. + +It's a common misconception that because the Sendmail Transport returns a +result very quickly it must therefore deliver messages to recipients quickly +-- this is not true. It's not slow by any means, but it's certainly not +faster than SMTP when it comes to getting messages to the intended recipients. +This is because sendmail itself sends the messages over SMTP once they have +been quickly spooled to disk. + +The Sendmail Transport has the potential to be just as smart of the SMTP +Transport when it comes to notifying Swift Mailer about which recipients were +rejected, but in reality the majority of locally installed ``sendmail`` +instances are not configured well enough to provide any useful feedback. As such +Swift Mailer may report successful deliveries where they did in fact fail before +they even left your server. + +You can run the Sendmail Transport in two different modes specified by command +line flags: + +* "``-bs``" runs in SMTP mode so theoretically it will act like the SMTP + Transport + +* "``-t``" runs in piped mode with no feedback, but theoretically faster, + though not advised + +You can think of the Sendmail Transport as a sort of asynchronous SMTP Transport +-- though if you have problems with delivery failures you should try using the +SMTP Transport instead. Swift Mailer isn't doing the work here, it's simply +passing the work to somebody else (i.e. ``sendmail``). + +Using the Sendmail Transport +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To use the Sendmail Transport you simply need to call +``Swift_SendmailTransport::newInstance()`` with the command as a parameter. + +To use the Sendmail Transport you need to know where ``sendmail`` or another MTA +exists on the server. Swift Mailer uses a default value of +``/usr/sbin/sendmail``, which should work on most systems. + +You specify the entire command as a parameter (i.e. including the command line +flags). Swift Mailer supports operational modes of "``-bs``" (default) and +"``-t``". + +.. note:: + + If you run sendmail in "``-t``" mode you will get no feedback as to whether + or not sending has succeeded. Use "``-bs``" unless you have a reason not to. + +To use the Sendmail Transport: + +* Call ``Swift_SendmailTransport::newInstance()`` with the command, including + the correct command line flags. The default is to use ``/usr/sbin/sendmail + -bs`` if this is not specified. + +* Use the returned object to create the Mailer. + +A sendmail process will be started upon the first call to ``send()``. If the +process cannot be started successfully an Exception of type +``Swift_TransportException`` will be thrown. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_SendmailTransport::newInstance('/usr/sbin/exim -bs'); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + +The Mail Transport +.................. + +The Mail Transport sends messages by delegating to PHP's internal +``mail()`` function. + +In my experience -- and others' -- the ``mail()`` function is not particularly +predictable, or helpful. + +Quite notably, the ``mail()`` function behaves entirely differently between +Linux and Windows servers. On linux it uses ``sendmail``, but on Windows it uses +SMTP. + +In order for the ``mail()`` function to even work at all ``php.ini`` needs to be +configured correctly, specifying the location of sendmail or of an SMTP server. + +The problem with ``mail()`` is that it "tries" to simplify things to the point +that it actually makes things more complex due to poor interface design. The +developers of Swift Mailer have gone to a lot of effort to make the Mail +Transport work with a reasonable degree of consistency. + +Serious drawbacks when using this Transport are: + +* Unpredictable message headers + +* Lack of feedback regarding delivery failures + +* Lack of support for several plugins that require real-time delivery feedback + +It's a last resort, and we say that with a passion! + +Using the Mail Transport +^^^^^^^^^^^^^^^^^^^^^^^^ + +To use the Mail Transport you simply need to call +``Swift_MailTransport::newInstance()``. It's unlikely you'll need to configure +the Transport. + +To use the Mail Transport: + +* Call ``Swift_MailTransport::newInstance()``. + +* Use the returned object to create the Mailer. + +Messages will be sent using the ``mail()`` function. + +.. note:: + + The ``mail()`` function can take a ``$additional_parameters`` parameter. + Swift Mailer sets this to "``-f%s``" by default, where the "%s" is + substituted with the address of the sender (via a ``sprintf()``) at send + time. You may override this default by passing an argument to + ``newInstance()``. + + .. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_MailTransport::newInstance(); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + +Available Methods for Sending Messages +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Mailer class offers two methods for sending Messages -- ``send()``. +Each behaves in a slightly different way. + +When a message is sent in Swift Mailer, the Mailer class communicates with +whichever Transport class you have chosen to use. + +Each recipient in the message should either be accepted or rejected by the +Transport. For example, if the domain name on the email address is not +reachable the SMTP Transport may reject the address because it cannot process +it. Whichever method you use -- ``send()`` -- Swift Mailer will return +an integer indicating the number of accepted recipients. + +.. note:: + + It's possible to find out which recipients were rejected -- we'll cover that + later in this chapter. + +Using the ``send()`` Method +........................... + +The ``send()`` method of the ``Swift_Mailer`` class sends a message using +exactly the same logic as your Desktop mail client would use. Just pass it a +Message and get a result. + +To send a Message with ``send()``: + +* Create a Transport from one of the provided Transports -- + ``Swift_SmtpTransport``, ``Swift_SendmailTransport``, + ``Swift_MailTransport`` or one of the aggregate Transports. + +* Create an instance of the ``Swift_Mailer`` class, using the Transport as + it's constructor parameter. + +* Create a Message. + +* Send the message via the ``send()`` method on the Mailer object. + +The message will be sent just like it would be sent if you used your mail +client. An integer is returned which includes the number of successful +recipients. If none of the recipients could be sent to then zero will be +returned, which equates to a boolean ``false``. If you set two +``To:`` recipients and three ``Bcc:`` recipients in the message and all of the +recipients are delivered to successfully then the value 5 will be returned. + +.. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_SmtpTransport::newInstance('localhost', 25); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + + // Create a message + $message = Swift_Message::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself') + ; + + // Send the message + $numSent = $mailer->send($message); + + printf("Sent %d messages\n", $numSent); + + /* Note that often that only the boolean equivalent of the + return value is of concern (zero indicates FALSE) + + if ($mailer->send($message)) + { + echo "Sent\n"; + } + else + { + echo "Failed\n"; + } + + */ + +Sending Emails in Batch +....................... + +If you want to send a separate message to each recipient so that only their +own address shows up in the ``To:`` field, follow the following recipe: + +* Create a Transport from one of the provided Transports -- + ``Swift_SmtpTransport``, ``Swift_SendmailTransport``, + ``Swift_MailTransport`` or one of the aggregate Transports. + +* Create an instance of the ``Swift_Mailer`` class, using the Transport as + it's constructor parameter. + +* Create a Message. + +* Iterate over the recipients and send message via the ``send()`` method on + the Mailer object. + +Each recipient of the messages receives a different copy with only their own +email address on the ``To:`` field. + +Make sure to add only valid email addresses as recipients. If you try to add an +invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift +Mailer will throw a ``Swift_RfcComplianceException``. + +If you add recipients automatically based on a data source that may contain +invalid email addresses, you can prevent possible exceptions by validating the +addresses using ``Swift_Validate::email($email)`` and only adding addresses +that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and +``setBcc()`` calls in a try-catch block and handle the +``Swift_RfcComplianceException`` in the catch block. + +Handling invalid addresses properly is especially important when sending emails +in large batches since a single invalid address might cause an unhandled +exception and stop the execution or your script early. + +.. note:: + + In the following example, two emails are sent. One to each of + ``receiver@domain.org`` and ``other@domain.org``. These recipients will + not be aware of each other. + + .. code-block:: php + + require_once 'lib/swift_required.php'; + + // Create the Transport + $transport = Swift_SmtpTransport::newInstance('localhost', 25); + + // Create the Mailer using your created Transport + $mailer = Swift_Mailer::newInstance($transport); + + // Create a message + $message = Swift_Message::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setBody('Here is the message itself') + ; + + // Send the message + $failedRecipients = array(); + $numSent = 0; + $to = array('receiver@domain.org', 'other@domain.org' => 'A name'); + + foreach ($to as $address => $name) + { + if (is_int($address)) { + $message->setTo($name); + } else { + $message->setTo(array($address => $name)); + } + + $numSent += $mailer->send($message, $failedRecipients); + } + + printf("Sent %d messages\n", $numSent); + +Finding out Rejected Addresses +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It's possible to get a list of addresses that were rejected by the Transport +by using a by-reference parameter to ``send()``. + +As Swift Mailer attempts to send the message to each address given to it, if a +recipient is rejected it will be added to the array. You can pass an existing +array, otherwise one will be created by-reference. + +Collecting the list of recipients that were rejected can be useful in +circumstances where you need to "prune" a mailing list for example when some +addresses cannot be delivered to. + +Getting Failures By-reference +............................. + +Collecting delivery failures by-reference with the ``send()`` method is as +simple as passing a variable name to the method call. + +To get failed recipients by-reference: + +* Pass a by-reference variable name to the ``send()`` method of the Mailer + class. + +If the Transport rejects any of the recipients, the culprit addresses will be +added to the array provided by-reference. + +.. note:: + + If the variable name does not yet exist, it will be initialized as an + empty array and then failures will be added to that array. If the variable + already exists it will be type-cast to an array and failures will be added + to it. + + .. code-block:: php + + $mailer = Swift_Mailer::newInstance( ... ); + + $message = Swift_Message::newInstance( ... ) + ->setFrom( ... ) + ->setTo(array( + 'receiver@bad-domain.org' => 'Receiver Name', + 'other@domain.org' => 'A name', + 'other-receiver@bad-domain.org' => 'Other Name' + )) + ->setBody( ... ) + ; + + // Pass a variable name to the send() method + if (!$mailer->send($message, $failures)) + { + echo "Failures:"; + print_r($failures); + } + + /* + Failures: + Array ( + 0 => receiver@bad-domain.org, + 1 => other-receiver@bad-domain.org + ) + */ diff --git a/vendor/swiftmailer/swiftmailer/doc/uml/Encoders.graffle b/vendor/swiftmailer/swiftmailer/doc/uml/Encoders.graffle new file mode 100644 index 00000000..f895752b Binary files /dev/null and b/vendor/swiftmailer/swiftmailer/doc/uml/Encoders.graffle differ diff --git a/vendor/swiftmailer/swiftmailer/doc/uml/Mime.graffle b/vendor/swiftmailer/swiftmailer/doc/uml/Mime.graffle new file mode 100644 index 00000000..e1e33cbf Binary files /dev/null and b/vendor/swiftmailer/swiftmailer/doc/uml/Mime.graffle differ diff --git a/vendor/swiftmailer/swiftmailer/doc/uml/Transports.graffle b/vendor/swiftmailer/swiftmailer/doc/uml/Transports.graffle new file mode 100644 index 00000000..5670e2b6 Binary files /dev/null and b/vendor/swiftmailer/swiftmailer/doc/uml/Transports.graffle differ diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php new file mode 100644 index 00000000..729b9bb2 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift.php @@ -0,0 +1,80 @@ +createDependenciesFor('mime.attachment') + ); + + $this->setBody($data); + $this->setFilename($filename); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Create a new Attachment. + * + * @param string|Swift_OutputByteStream $data + * @param string $filename + * @param string $contentType + * + * @return Swift_Mime_Attachment + */ + public static function newInstance($data = null, $filename = null, $contentType = null) + { + return new self($data, $filename, $contentType); + } + + /** + * Create a new Attachment from a filesystem path. + * + * @param string $path + * @param string $contentType optional + * + * @return Swift_Mime_Attachment + */ + public static function fromPath($path, $contentType = null) + { + return self::newInstance()->setFile( + new Swift_ByteStream_FileByteStream($path), + $contentType + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php new file mode 100644 index 00000000..3e597d17 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/AbstractFilterableInputStream.php @@ -0,0 +1,179 @@ +_filters[$key] = $filter; + } + + /** + * Remove an already present StreamFilter based on its $key. + * + * @param string $key + */ + public function removeFilter($key) + { + unset($this->_filters[$key]); + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + * + * @return int + * + * @throws Swift_IoException + */ + public function write($bytes) + { + $this->_writeBuffer .= $bytes; + foreach ($this->_filters as $filter) { + if ($filter->shouldBuffer($this->_writeBuffer)) { + return; + } + } + $this->_doWrite($this->_writeBuffer); + + return ++$this->_sequence; + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + */ + public function commit() + { + $this->_doWrite($this->_writeBuffer); + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + */ + public function bind(Swift_InputByteStream $is) + { + $this->_mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->_mirrors as $k => $stream) { + if ($is === $stream) { + if ($this->_writeBuffer !== '') { + $stream->write($this->_writeBuffer); + } + unset($this->_mirrors[$k]); + } + } + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + */ + public function flushBuffers() + { + if ($this->_writeBuffer !== '') { + $this->_doWrite($this->_writeBuffer); + } + $this->_flush(); + + foreach ($this->_mirrors as $stream) { + $stream->flushBuffers(); + } + } + + /** Run $bytes through all filters */ + private function _filter($bytes) + { + foreach ($this->_filters as $filter) { + $bytes = $filter->filter($bytes); + } + + return $bytes; + } + + /** Just write the bytes to the stream */ + private function _doWrite($bytes) + { + $this->_commit($this->_filter($bytes)); + + foreach ($this->_mirrors as $stream) { + $stream->write($bytes); + } + + $this->_writeBuffer = ''; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php new file mode 100644 index 00000000..186a7c28 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/ArrayByteStream.php @@ -0,0 +1,184 @@ +_array = $stack; + $this->_arraySize = count($stack); + } elseif (is_string($stack)) { + $this->write($stack); + } else { + $this->_array = array(); + } + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the + * remaining bytes are given instead. If no bytes are remaining at all, boolean + * false is returned. + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->_offset == $this->_arraySize) { + return false; + } + + // Don't use array slice + $end = $length + $this->_offset; + $end = $this->_arraySize<$end + ? $this->_arraySize + : $end; + $ret = ''; + for (; $this->_offset < $end; ++$this->_offset) { + $ret .= $this->_array[$this->_offset]; + } + + return $ret; + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + */ + public function write($bytes) + { + $to_add = str_split($bytes); + foreach ($to_add as $value) { + $this->_array[] = $value; + } + $this->_arraySize = count($this->_array); + + foreach ($this->_mirrors as $stream) { + $stream->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + */ + public function bind(Swift_InputByteStream $is) + { + $this->_mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->_mirrors as $k => $stream) { + if ($is === $stream) { + unset($this->_mirrors[$k]); + } + } + } + + /** + * Move the internal read pointer to $byteOffset in the stream. + * + * @param int $byteOffset + * + * @return bool + */ + public function setReadPointer($byteOffset) + { + if ($byteOffset > $this->_arraySize) { + $byteOffset = $this->_arraySize; + } elseif ($byteOffset < 0) { + $byteOffset = 0; + } + + $this->_offset = $byteOffset; + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + */ + public function flushBuffers() + { + $this->_offset = 0; + $this->_array = array(); + $this->_arraySize = 0; + + foreach ($this->_mirrors as $stream) { + $stream->flushBuffers(); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php new file mode 100644 index 00000000..6c144623 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/FileByteStream.php @@ -0,0 +1,229 @@ +_path = $path; + $this->_mode = $writable ? 'w+b' : 'rb'; + + if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { + $this->_quotes = true; + } + } + + /** + * Get the complete path to the file. + * + * @return string + */ + public function getPath() + { + return $this->_path; + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the + * remaining bytes are given instead. If no bytes are remaining at all, boolean + * false is returned. + * + * @param int $length + * + * @return string|bool + * + * @throws Swift_IoException + */ + public function read($length) + { + $fp = $this->_getReadHandle(); + if (!feof($fp)) { + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 0); + } + $bytes = fread($fp, $length); + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 1); + } + $this->_offset = ftell($fp); + + // If we read one byte after reaching the end of the file + // feof() will return false and an empty string is returned + if ($bytes === '' && feof($fp)) { + $this->_resetReadHandle(); + + return false; + } + + return $bytes; + } + + $this->_resetReadHandle(); + + return false; + } + + /** + * Move the internal read pointer to $byteOffset in the stream. + * + * @param int $byteOffset + * + * @return bool + */ + public function setReadPointer($byteOffset) + { + if (isset($this->_reader)) { + $this->_seekReadStreamToPosition($byteOffset); + } + $this->_offset = $byteOffset; + } + + /** Just write the bytes to the file */ + protected function _commit($bytes) + { + fwrite($this->_getWriteHandle(), $bytes); + $this->_resetReadHandle(); + } + + /** Not used */ + protected function _flush() + { + } + + /** Get the resource for reading */ + private function _getReadHandle() + { + if (!isset($this->_reader)) { + if (!$this->_reader = fopen($this->_path, 'rb')) { + throw new Swift_IoException( + 'Unable to open file for reading ['.$this->_path.']' + ); + } + if ($this->_offset != 0) { + $this->_getReadStreamSeekableStatus(); + $this->_seekReadStreamToPosition($this->_offset); + } + } + + return $this->_reader; + } + + /** Get the resource for writing */ + private function _getWriteHandle() + { + if (!isset($this->_writer)) { + if (!$this->_writer = fopen($this->_path, $this->_mode)) { + throw new Swift_IoException( + 'Unable to open file for writing ['.$this->_path.']' + ); + } + } + + return $this->_writer; + } + + /** Force a reload of the resource for reading */ + private function _resetReadHandle() + { + if (isset($this->_reader)) { + fclose($this->_reader); + $this->_reader = null; + } + } + + /** Check if ReadOnly Stream is seekable */ + private function _getReadStreamSeekableStatus() + { + $metas = stream_get_meta_data($this->_reader); + $this->_seekable = $metas['seekable']; + } + + /** Streams in a readOnly stream ensuring copy if needed */ + private function _seekReadStreamToPosition($offset) + { + if ($this->_seekable === null) { + $this->_getReadStreamSeekableStatus(); + } + if ($this->_seekable === false) { + $currentPos = ftell($this->_reader); + if ($currentPos<$offset) { + $toDiscard = $offset-$currentPos; + fread($this->_reader, $toDiscard); + + return; + } + $this->_copyReadStream(); + } + fseek($this->_reader, $offset, SEEK_SET); + } + + /** Copy a readOnly Stream to ensure seekability */ + private function _copyReadStream() + { + if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { + /* We have opened a php:// Stream Should work without problem */ + } elseif (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) { + /* We have opened a tmpfile */ + } else { + throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); + } + $currentPos = ftell($this->_reader); + fclose($this->_reader); + $source = fopen($this->_path, 'rb'); + if (!$source) { + throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']'); + } + fseek($tmpFile, 0, SEEK_SET); + while (!feof($source)) { + fwrite($tmpFile, fread($source, 4096)); + } + fseek($tmpFile, $currentPos, SEEK_SET); + fclose($source); + $this->_reader = $tmpFile; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php new file mode 100644 index 00000000..eb33151b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ByteStream/TemporaryFileByteStream.php @@ -0,0 +1,42 @@ +getPath())) === false) { + throw new Swift_IoException('Failed to get temporary file content.'); + } + + return $content; + } + + public function __destruct() + { + if (file_exists($this->getPath())) { + @unlink($this->getPath()); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php new file mode 100644 index 00000000..febd77eb --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader.php @@ -0,0 +1,67 @@ + + */ +interface Swift_CharacterReader +{ + const MAP_TYPE_INVALID = 0x01; + const MAP_TYPE_FIXED_LEN = 0x02; + const MAP_TYPE_POSITIONS = 0x03; + + /** + * Returns the complete character map + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars); + + /** + * Returns the mapType, see constants. + * + * @return int + */ + public function getMapType(); + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param integer[] $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size); + + /** + * Returns the number of bytes which should be read to start each character. + * + * For fixed width character sets this should be the number of octets-per-character. + * For multibyte character sets this will probably be 1. + * + * @return int + */ + public function getInitialByteSize(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php new file mode 100644 index 00000000..d0c8698d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/GenericFixedWidthReader.php @@ -0,0 +1,97 @@ + + */ +class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader +{ + /** + * The number of bytes in a single character. + * + * @var int + */ + private $_width; + + /** + * Creates a new GenericFixedWidthReader using $width bytes per character. + * + * @param int $width + */ + public function __construct($width) + { + $this->_width = $width; + } + + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) + { + $strlen = strlen($string); + // % and / are CPU intensive, so, maybe find a better way + $ignored = $strlen % $this->_width; + $ignoredChars = substr($string, - $ignored); + $currentMap = $this->_width; + + return ($strlen - $ignored) / $this->_width; + } + + /** + * Returns the mapType. + * + * @return int + */ + public function getMapType() + { + return self::MAP_TYPE_FIXED_LEN; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + $needed = $this->_width - $size; + + return ($needed > -1) ? $needed : -1; + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return $this->_width; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php new file mode 100644 index 00000000..229c567f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/UsAsciiReader.php @@ -0,0 +1,84 @@ +"\x07F") { + // Invalid char + $currentMap[$i+$startOffset] = $string[$i]; + } + } + + return $strlen; + } + + /** + * Returns mapType + * + * @return int mapType + */ + public function getMapType() + { + return self::MAP_TYPE_INVALID; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + $byte = reset($bytes); + if (1 == count($bytes) && $byte >= 0x00 && $byte <= 0x7F) { + return 0; + } else { + return -1; + } + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return 1; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php new file mode 100644 index 00000000..aebbecf6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReader/Utf8Reader.php @@ -0,0 +1,179 @@ + + */ +class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader +{ + /** Pre-computed for optimization */ + private static $length_map = array( + // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN + 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN + 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN + ); + + private static $s_length_map = array( + "\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1, + "\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1, + "\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1, + "\x18" => 1, "\x19" => 1, "\x1a" => 1, "\x1b" => 1, "\x1c" => 1, "\x1d" => 1, "\x1e" => 1, "\x1f" => 1, + "\x20" => 1, "\x21" => 1, "\x22" => 1, "\x23" => 1, "\x24" => 1, "\x25" => 1, "\x26" => 1, "\x27" => 1, + "\x28" => 1, "\x29" => 1, "\x2a" => 1, "\x2b" => 1, "\x2c" => 1, "\x2d" => 1, "\x2e" => 1, "\x2f" => 1, + "\x30" => 1, "\x31" => 1, "\x32" => 1, "\x33" => 1, "\x34" => 1, "\x35" => 1, "\x36" => 1, "\x37" => 1, + "\x38" => 1, "\x39" => 1, "\x3a" => 1, "\x3b" => 1, "\x3c" => 1, "\x3d" => 1, "\x3e" => 1, "\x3f" => 1, + "\x40" => 1, "\x41" => 1, "\x42" => 1, "\x43" => 1, "\x44" => 1, "\x45" => 1, "\x46" => 1, "\x47" => 1, + "\x48" => 1, "\x49" => 1, "\x4a" => 1, "\x4b" => 1, "\x4c" => 1, "\x4d" => 1, "\x4e" => 1, "\x4f" => 1, + "\x50" => 1, "\x51" => 1, "\x52" => 1, "\x53" => 1, "\x54" => 1, "\x55" => 1, "\x56" => 1, "\x57" => 1, + "\x58" => 1, "\x59" => 1, "\x5a" => 1, "\x5b" => 1, "\x5c" => 1, "\x5d" => 1, "\x5e" => 1, "\x5f" => 1, + "\x60" => 1, "\x61" => 1, "\x62" => 1, "\x63" => 1, "\x64" => 1, "\x65" => 1, "\x66" => 1, "\x67" => 1, + "\x68" => 1, "\x69" => 1, "\x6a" => 1, "\x6b" => 1, "\x6c" => 1, "\x6d" => 1, "\x6e" => 1, "\x6f" => 1, + "\x70" => 1, "\x71" => 1, "\x72" => 1, "\x73" => 1, "\x74" => 1, "\x75" => 1, "\x76" => 1, "\x77" => 1, + "\x78" => 1, "\x79" => 1, "\x7a" => 1, "\x7b" => 1, "\x7c" => 1, "\x7d" => 1, "\x7e" => 1, "\x7f" => 1, + "\x80" => 0, "\x81" => 0, "\x82" => 0, "\x83" => 0, "\x84" => 0, "\x85" => 0, "\x86" => 0, "\x87" => 0, + "\x88" => 0, "\x89" => 0, "\x8a" => 0, "\x8b" => 0, "\x8c" => 0, "\x8d" => 0, "\x8e" => 0, "\x8f" => 0, + "\x90" => 0, "\x91" => 0, "\x92" => 0, "\x93" => 0, "\x94" => 0, "\x95" => 0, "\x96" => 0, "\x97" => 0, + "\x98" => 0, "\x99" => 0, "\x9a" => 0, "\x9b" => 0, "\x9c" => 0, "\x9d" => 0, "\x9e" => 0, "\x9f" => 0, + "\xa0" => 0, "\xa1" => 0, "\xa2" => 0, "\xa3" => 0, "\xa4" => 0, "\xa5" => 0, "\xa6" => 0, "\xa7" => 0, + "\xa8" => 0, "\xa9" => 0, "\xaa" => 0, "\xab" => 0, "\xac" => 0, "\xad" => 0, "\xae" => 0, "\xaf" => 0, + "\xb0" => 0, "\xb1" => 0, "\xb2" => 0, "\xb3" => 0, "\xb4" => 0, "\xb5" => 0, "\xb6" => 0, "\xb7" => 0, + "\xb8" => 0, "\xb9" => 0, "\xba" => 0, "\xbb" => 0, "\xbc" => 0, "\xbd" => 0, "\xbe" => 0, "\xbf" => 0, + "\xc0" => 2, "\xc1" => 2, "\xc2" => 2, "\xc3" => 2, "\xc4" => 2, "\xc5" => 2, "\xc6" => 2, "\xc7" => 2, + "\xc8" => 2, "\xc9" => 2, "\xca" => 2, "\xcb" => 2, "\xcc" => 2, "\xcd" => 2, "\xce" => 2, "\xcf" => 2, + "\xd0" => 2, "\xd1" => 2, "\xd2" => 2, "\xd3" => 2, "\xd4" => 2, "\xd5" => 2, "\xd6" => 2, "\xd7" => 2, + "\xd8" => 2, "\xd9" => 2, "\xda" => 2, "\xdb" => 2, "\xdc" => 2, "\xdd" => 2, "\xde" => 2, "\xdf" => 2, + "\xe0" => 3, "\xe1" => 3, "\xe2" => 3, "\xe3" => 3, "\xe4" => 3, "\xe5" => 3, "\xe6" => 3, "\xe7" => 3, + "\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3, + "\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4, + "\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0, + ); + + /** + * Returns the complete character map. + * + * @param string $string + * @param int $startOffset + * @param array $currentMap + * @param mixed $ignoredChars + * + * @return int + */ + public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) + { + if (!isset($currentMap['i']) || ! isset($currentMap['p'])) { + $currentMap['p'] = $currentMap['i'] = array(); + } + + $strlen = strlen($string); + $charPos = count($currentMap['p']); + $foundChars = 0; + $invalid = false; + for ($i = 0; $i < $strlen; ++$i) { + $char = $string[$i]; + $size = self::$s_length_map[$char]; + if ($size == 0) { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue; + } else { + if ($invalid == true) { + /* We mark the chars as invalid and start a new char */ + $currentMap['p'][$charPos + $foundChars] = $startOffset + $i; + $currentMap['i'][$charPos + $foundChars] = true; + ++$foundChars; + $invalid = false; + } + if (($i + $size) > $strlen) { + $ignoredChars = substr($string, $i); + break; + } + for ($j = 1; $j < $size; ++$j) { + $char = $string[$i + $j]; + if ($char > "\x7F" && $char < "\xC0") { + // Valid - continue parsing + } else { + /* char is invalid, we must wait for a resync */ + $invalid = true; + continue 2; + } + } + /* Ok we got a complete char here */ + $currentMap['p'][$charPos + $foundChars] = $startOffset + $i + $size; + $i += $j - 1; + ++$foundChars; + } + } + + return $foundChars; + } + + /** + * Returns mapType. + * + * @return int mapType + */ + public function getMapType() + { + return self::MAP_TYPE_POSITIONS; + } + + /** + * Returns an integer which specifies how many more bytes to read. + * + * A positive integer indicates the number of more bytes to fetch before invoking + * this method again. + * A value of zero means this is already a valid character. + * A value of -1 means this cannot possibly be a valid character. + * + * @param string $bytes + * @param int $size + * + * @return int + */ + public function validateByteSequence($bytes, $size) + { + if ($size<1) { + return -1; + } + $needed = self::$length_map[$bytes[0]] - $size; + + return ($needed > -1) + ? $needed + : -1 + ; + } + + /** + * Returns the number of bytes which should be read to start each character. + * + * @return int + */ + public function getInitialByteSize() + { + return 1; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php new file mode 100644 index 00000000..5bf38b8b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterReaderFactory.php @@ -0,0 +1,26 @@ +init(); + } + + public function __wakeup() + { + $this->init(); + } + + public function init() + { + if (count(self::$_map) > 0) { + return; + } + + $prefix = 'Swift_CharacterReader_'; + + $singleByte = array( + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => array(1), + ); + + $doubleByte = array( + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => array(2), + ); + + $fourBytes = array( + 'class' => $prefix.'GenericFixedWidthReader', + 'constructor' => array(4), + ); + + // Utf-8 + self::$_map['utf-?8'] = array( + 'class' => $prefix.'Utf8Reader', + 'constructor' => array(), + ); + + //7-8 bit charsets + self::$_map['(us-)?ascii'] = $singleByte; + self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; + self::$_map['windows-?125[0-9]'] = $singleByte; + self::$_map['cp-?[0-9]+'] = $singleByte; + self::$_map['ansi'] = $singleByte; + self::$_map['macintosh'] = $singleByte; + self::$_map['koi-?7'] = $singleByte; + self::$_map['koi-?8-?.+'] = $singleByte; + self::$_map['mik'] = $singleByte; + self::$_map['(cork|t1)'] = $singleByte; + self::$_map['v?iscii'] = $singleByte; + + //16 bits + self::$_map['(ucs-?2|utf-?16)'] = $doubleByte; + + //32 bits + self::$_map['(ucs-?4|utf-?32)'] = $fourBytes; + + // Fallback + self::$_map['.*'] = $singleByte; + } + + /** + * Returns a CharacterReader suitable for the charset applied. + * + * @param string $charset + * + * @return Swift_CharacterReader + */ + public function getReaderFor($charset) + { + $charset = trim(strtolower($charset)); + foreach (self::$_map as $pattern => $spec) { + $re = '/^'.$pattern.'$/D'; + if (preg_match($re, $charset)) { + if (!array_key_exists($pattern, self::$_loaded)) { + $reflector = new ReflectionClass($spec['class']); + if ($reflector->getConstructor()) { + $reader = $reflector->newInstanceArgs($spec['constructor']); + } else { + $reader = $reflector->newInstance(); + } + self::$_loaded[$pattern] = $reader; + } + + return self::$_loaded[$pattern]; + } + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php new file mode 100644 index 00000000..aa46779e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream.php @@ -0,0 +1,89 @@ +setCharacterReaderFactory($factory); + $this->setCharacterSet($charset); + } + + /** + * Set the character set used in this CharacterStream. + * + * @param string $charset + */ + public function setCharacterSet($charset) + { + $this->_charset = $charset; + $this->_charReader = null; + } + + /** + * Set the CharacterReaderFactory for multi charset support. + * + * @param Swift_CharacterReaderFactory $factory + */ + public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) + { + $this->_charReaderFactory = $factory; + } + + /** + * Overwrite this character stream using the byte sequence in the byte stream. + * + * @param Swift_OutputByteStream $os output stream to read from + */ + public function importByteStream(Swift_OutputByteStream $os) + { + if (!isset($this->_charReader)) { + $this->_charReader = $this->_charReaderFactory + ->getReaderFor($this->_charset); + } + + $startLength = $this->_charReader->getInitialByteSize(); + while (false !== $bytes = $os->read($startLength)) { + $c = array(); + for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { + $c[] = self::$_byteMap[$bytes[$i]]; + } + $size = count($c); + $need = $this->_charReader + ->validateByteSequence($c, $size); + if ($need > 0 && + false !== $bytes = $os->read($need)) { + for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { + $c[] = self::$_byteMap[$bytes[$i]]; + } + } + $this->_array[] = $c; + ++$this->_array_size; + } + } + + /** + * Import a string a bytes into this CharacterStream, overwriting any existing + * data in the stream. + * + * @param string $string + */ + public function importString($string) + { + $this->flushContents(); + $this->write($string); + } + + /** + * Read $length characters from the stream and move the internal pointer + * $length further into the stream. + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->_offset == $this->_array_size) { + return false; + } + + // Don't use array slice + $arrays = array(); + $end = $length + $this->_offset; + for ($i = $this->_offset; $i < $end; ++$i) { + if (!isset($this->_array[$i])) { + break; + } + $arrays[] = $this->_array[$i]; + } + $this->_offset += $i - $this->_offset; // Limit function calls + $chars = false; + foreach ($arrays as $array) { + $chars .= implode('', array_map('chr', $array)); + } + + return $chars; + } + + /** + * Read $length characters from the stream and return a 1-dimensional array + * containing there octet values. + * + * @param int $length + * + * @return integer[] + */ + public function readBytes($length) + { + if ($this->_offset == $this->_array_size) { + return false; + } + $arrays = array(); + $end = $length + $this->_offset; + for ($i = $this->_offset; $i < $end; ++$i) { + if (!isset($this->_array[$i])) { + break; + } + $arrays[] = $this->_array[$i]; + } + $this->_offset += ($i - $this->_offset); // Limit function calls + + return call_user_func_array('array_merge', $arrays); + } + + /** + * Write $chars to the end of the stream. + * + * @param string $chars + */ + public function write($chars) + { + if (!isset($this->_charReader)) { + $this->_charReader = $this->_charReaderFactory->getReaderFor( + $this->_charset); + } + + $startLength = $this->_charReader->getInitialByteSize(); + + $fp = fopen('php://memory', 'w+b'); + fwrite($fp, $chars); + unset($chars); + fseek($fp, 0, SEEK_SET); + + $buffer = array(0); + $buf_pos = 1; + $buf_len = 1; + $has_datas = true; + do { + $bytes = array(); + // Buffer Filing + if ($buf_len - $buf_pos < $startLength) { + $buf = array_splice($buffer, $buf_pos); + $new = $this->_reloadBuffer($fp, 100); + if ($new) { + $buffer = array_merge($buf, $new); + $buf_len = count($buffer); + $buf_pos = 0; + } else { + $has_datas = false; + } + } + if ($buf_len - $buf_pos > 0) { + $size = 0; + for ($i = 0; $i < $startLength && isset($buffer[$buf_pos]); ++$i) { + ++$size; + $bytes[] = $buffer[$buf_pos++]; + } + $need = $this->_charReader->validateByteSequence( + $bytes, $size); + if ($need > 0) { + if ($buf_len - $buf_pos < $need) { + $new = $this->_reloadBuffer($fp, $need); + + if ($new) { + $buffer = array_merge($buffer, $new); + $buf_len = count($buffer); + } + } + for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) { + $bytes[] = $buffer[$buf_pos++]; + } + } + $this->_array[] = $bytes; + ++$this->_array_size; + } + } while ($has_datas); + + fclose($fp); + } + + /** + * Move the internal pointer to $charOffset in the stream. + * + * @param int $charOffset + */ + public function setPointer($charOffset) + { + if ($charOffset > $this->_array_size) { + $charOffset = $this->_array_size; + } elseif ($charOffset < 0) { + $charOffset = 0; + } + $this->_offset = $charOffset; + } + + /** + * Empty the stream and reset the internal pointer. + */ + public function flushContents() + { + $this->_offset = 0; + $this->_array = array(); + $this->_array_size = 0; + } + + private function _reloadBuffer($fp, $len) + { + if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) { + $buf = array(); + for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { + $buf[] = self::$_byteMap[$bytes[$i]]; + } + + return $buf; + } + + return false; + } + + private static function _initializeMaps() + { + if (!isset(self::$_charMap)) { + self::$_charMap = array(); + for ($byte = 0; $byte < 256; ++$byte) { + self::$_charMap[$byte] = chr($byte); + } + self::$_byteMap = array_flip(self::$_charMap); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php new file mode 100644 index 00000000..b962e403 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/CharacterStream/NgCharacterStream.php @@ -0,0 +1,276 @@ + + */ + +class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream +{ + /** + * The char reader (lazy-loaded) for the current charset. + * + * @var Swift_CharacterReader + */ + private $_charReader; + + /** + * A factory for creating CharacterReader instances. + * + * @var Swift_CharacterReaderFactory + */ + private $_charReaderFactory; + + /** + * The character set this stream is using. + * + * @var string + */ + private $_charset; + + /** + * The data's stored as-is. + * + * @var string + */ + private $_datas = ''; + + /** + * Number of bytes in the stream + * + * @var int + */ + private $_datasSize = 0; + + /** + * Map. + * + * @var mixed + */ + private $_map; + + /** + * Map Type. + * + * @var int + */ + private $_mapType = 0; + + /** + * Number of characters in the stream. + * + * @var int + */ + private $_charCount = 0; + + /** + * Position in the stream. + * + * @var int + */ + private $_currentPos = 0; + + /** + * Constructor. + * + * @param Swift_CharacterReaderFactory $factory + * @param string $charset + */ + public function __construct(Swift_CharacterReaderFactory $factory, $charset) + { + $this->setCharacterReaderFactory($factory); + $this->setCharacterSet($charset); + } + + /* -- Changing parameters of the stream -- */ + + /** + * Set the character set used in this CharacterStream. + * + * @param string $charset + */ + public function setCharacterSet($charset) + { + $this->_charset = $charset; + $this->_charReader = null; + $this->_mapType = 0; + } + + /** + * Set the CharacterReaderFactory for multi charset support. + * + * @param Swift_CharacterReaderFactory $factory + */ + public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) + { + $this->_charReaderFactory = $factory; + } + + /** + * @see Swift_CharacterStream::flushContents() + */ + public function flushContents() + { + $this->_datas = null; + $this->_map = null; + $this->_charCount = 0; + $this->_currentPos = 0; + $this->_datasSize = 0; + } + + /** + * @see Swift_CharacterStream::importByteStream() + * + * @param Swift_OutputByteStream $os + */ + public function importByteStream(Swift_OutputByteStream $os) + { + $this->flushContents(); + $blocks = 512; + $os->setReadPointer(0); + while (false !== ($read = $os->read($blocks))) { + $this->write($read); + } + } + + /** + * @see Swift_CharacterStream::importString() + * + * @param string $string + */ + public function importString($string) + { + $this->flushContents(); + $this->write($string); + } + + /** + * @see Swift_CharacterStream::read() + * + * @param int $length + * + * @return string + */ + public function read($length) + { + if ($this->_currentPos >= $this->_charCount) { + return false; + } + $ret = false; + $length = ($this->_currentPos+$length > $this->_charCount) + ? $this->_charCount - $this->_currentPos + : $length; + switch ($this->_mapType) { + case Swift_CharacterReader::MAP_TYPE_FIXED_LEN: + $len = $length*$this->_map; + $ret = substr($this->_datas, + $this->_currentPos * $this->_map, + $len); + $this->_currentPos += $length; + break; + + case Swift_CharacterReader::MAP_TYPE_INVALID: + $end = $this->_currentPos + $length; + $end = $end > $this->_charCount + ? $this->_charCount + : $end; + $ret = ''; + for (; $this->_currentPos < $length; ++$this->_currentPos) { + if (isset ($this->_map[$this->_currentPos])) { + $ret .= '?'; + } else { + $ret .= $this->_datas[$this->_currentPos]; + } + } + break; + + case Swift_CharacterReader::MAP_TYPE_POSITIONS: + $end = $this->_currentPos + $length; + $end = $end > $this->_charCount + ? $this->_charCount + : $end; + $ret = ''; + $start = 0; + if ($this->_currentPos>0) { + $start = $this->_map['p'][$this->_currentPos-1]; + } + $to = $start; + for (; $this->_currentPos < $end; ++$this->_currentPos) { + if (isset($this->_map['i'][$this->_currentPos])) { + $ret .= substr($this->_datas, $start, $to - $start).'?'; + $start = $this->_map['p'][$this->_currentPos]; + } else { + $to = $this->_map['p'][$this->_currentPos]; + } + } + $ret .= substr($this->_datas, $start, $to - $start); + break; + } + + return $ret; + } + + /** + * @see Swift_CharacterStream::readBytes() + * + * @param int $length + * + * @return integer[] + */ + public function readBytes($length) + { + $read = $this->read($length); + if ($read !== false) { + $ret = array_map('ord', str_split($read, 1)); + + return $ret; + } + + return false; + } + + /** + * @see Swift_CharacterStream::setPointer() + * + * @param int $charOffset + */ + public function setPointer($charOffset) + { + if ($this->_charCount<$charOffset) { + $charOffset = $this->_charCount; + } + $this->_currentPos = $charOffset; + } + + /** + * @see Swift_CharacterStream::write() + * + * @param string $chars + */ + public function write($chars) + { + if (!isset($this->_charReader)) { + $this->_charReader = $this->_charReaderFactory->getReaderFor( + $this->_charset); + $this->_map = array(); + $this->_mapType = $this->_charReader->getMapType(); + } + $ignored = ''; + $this->_datas .= $chars; + $this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored); + if ($ignored !== false) { + $this->_datasSize = strlen($this->_datas)-strlen($ignored); + } else { + $this->_datasSize = strlen($this->_datas); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php new file mode 100644 index 00000000..df87527f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ConfigurableSpool.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Base class for Spools (implements time and message limits). + * + * @author Fabien Potencier + */ +abstract class Swift_ConfigurableSpool implements Swift_Spool +{ + /** The maximum number of messages to send per flush */ + private $_message_limit; + + /** The time limit per flush */ + private $_time_limit; + + /** + * Sets the maximum number of messages to send per flush. + * + * @param int $limit + */ + public function setMessageLimit($limit) + { + $this->_message_limit = (int) $limit; + } + + /** + * Gets the maximum number of messages to send per flush. + * + * @return int The limit + */ + public function getMessageLimit() + { + return $this->_message_limit; + } + + /** + * Sets the time limit (in seconds) per flush. + * + * @param int $limit The limit + */ + public function setTimeLimit($limit) + { + $this->_time_limit = (int) $limit; + } + + /** + * Gets the time limit (in seconds) per flush. + * + * @return int The limit + */ + public function getTimeLimit() + { + return $this->_time_limit; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php new file mode 100644 index 00000000..1d8cb3a3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyContainer.php @@ -0,0 +1,372 @@ +_store); + } + + /** + * Test if an item is registered in this container with the given name. + * + * @see register() + * + * @param string $itemName + * + * @return bool + */ + public function has($itemName) + { + return array_key_exists($itemName, $this->_store) + && isset($this->_store[$itemName]['lookupType']); + } + + /** + * Lookup the item with the given $itemName. + * + * @see register() + * + * @param string $itemName + * + * @return mixed + * + * @throws Swift_DependencyException If the dependency is not found + */ + public function lookup($itemName) + { + if (!$this->has($itemName)) { + throw new Swift_DependencyException( + 'Cannot lookup dependency "'.$itemName.'" since it is not registered.' + ); + } + + switch ($this->_store[$itemName]['lookupType']) { + case self::TYPE_ALIAS: + return $this->_createAlias($itemName); + case self::TYPE_VALUE: + return $this->_getValue($itemName); + case self::TYPE_INSTANCE: + return $this->_createNewInstance($itemName); + case self::TYPE_SHARED: + return $this->_createSharedInstance($itemName); + } + } + + /** + * Create an array of arguments passed to the constructor of $itemName. + * + * @param string $itemName + * + * @return array + */ + public function createDependenciesFor($itemName) + { + $args = array(); + if (isset($this->_store[$itemName]['args'])) { + $args = $this->_resolveArgs($this->_store[$itemName]['args']); + } + + return $args; + } + + /** + * Register a new dependency with $itemName. + * + * This method returns the current DependencyContainer instance because it + * requires the use of the fluid interface to set the specific details for the + * dependency. + * @see asNewInstanceOf(), asSharedInstanceOf(), asValue() + * + * @param string $itemName + * + * @return Swift_DependencyContainer + */ + public function register($itemName) + { + $this->_store[$itemName] = array(); + $this->_endPoint = & $this->_store[$itemName]; + + return $this; + } + + /** + * Specify the previously registered item as a literal value. + * + * {@link register()} must be called before this will work. + * + * @param mixed $value + * + * @return Swift_DependencyContainer + */ + public function asValue($value) + { + $endPoint = & $this->_getEndPoint(); + $endPoint['lookupType'] = self::TYPE_VALUE; + $endPoint['value'] = $value; + + return $this; + } + + /** + * Specify the previously registered item as an alias of another item. + * + * @param string $lookup + * + * @return Swift_DependencyContainer + */ + public function asAliasOf($lookup) + { + $endPoint = & $this->_getEndPoint(); + $endPoint['lookupType'] = self::TYPE_ALIAS; + $endPoint['ref'] = $lookup; + + return $this; + } + + /** + * Specify the previously registered item as a new instance of $className. + * + * {@link register()} must be called before this will work. + * Any arguments can be set with {@link withDependencies()}, + * {@link addConstructorValue()} or {@link addConstructorLookup()}. + * + * @see withDependencies(), addConstructorValue(), addConstructorLookup() + * + * @param string $className + * + * @return Swift_DependencyContainer + */ + public function asNewInstanceOf($className) + { + $endPoint = & $this->_getEndPoint(); + $endPoint['lookupType'] = self::TYPE_INSTANCE; + $endPoint['className'] = $className; + + return $this; + } + + /** + * Specify the previously registered item as a shared instance of $className. + * + * {@link register()} must be called before this will work. + * + * @param string $className + * + * @return Swift_DependencyContainer + */ + public function asSharedInstanceOf($className) + { + $endPoint = & $this->_getEndPoint(); + $endPoint['lookupType'] = self::TYPE_SHARED; + $endPoint['className'] = $className; + + return $this; + } + + /** + * Specify a list of injected dependencies for the previously registered item. + * + * This method takes an array of lookup names. + * + * @see addConstructorValue(), addConstructorLookup() + * + * @param array $lookups + * + * @return Swift_DependencyContainer + */ + public function withDependencies(array $lookups) + { + $endPoint = & $this->_getEndPoint(); + $endPoint['args'] = array(); + foreach ($lookups as $lookup) { + $this->addConstructorLookup($lookup); + } + + return $this; + } + + /** + * Specify a literal (non looked up) value for the constructor of the + * previously registered item. + * + * @see withDependencies(), addConstructorLookup() + * + * @param mixed $value + * + * @return Swift_DependencyContainer + */ + public function addConstructorValue($value) + { + $endPoint = & $this->_getEndPoint(); + if (!isset($endPoint['args'])) { + $endPoint['args'] = array(); + } + $endPoint['args'][] = array('type' => 'value', 'item' => $value); + + return $this; + } + + /** + * Specify a dependency lookup for the constructor of the previously + * registered item. + * + * @see withDependencies(), addConstructorValue() + * + * @param string $lookup + * + * @return Swift_DependencyContainer + */ + public function addConstructorLookup($lookup) + { + $endPoint = & $this->_getEndPoint(); + if (!isset($this->_endPoint['args'])) { + $endPoint['args'] = array(); + } + $endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup); + + return $this; + } + + /** Get the literal value with $itemName */ + private function _getValue($itemName) + { + return $this->_store[$itemName]['value']; + } + + /** Resolve an alias to another item */ + private function _createAlias($itemName) + { + return $this->lookup($this->_store[$itemName]['ref']); + } + + /** Create a fresh instance of $itemName */ + private function _createNewInstance($itemName) + { + $reflector = new ReflectionClass($this->_store[$itemName]['className']); + if ($reflector->getConstructor()) { + return $reflector->newInstanceArgs( + $this->createDependenciesFor($itemName) + ); + } else { + return $reflector->newInstance(); + } + } + + /** Create and register a shared instance of $itemName */ + private function _createSharedInstance($itemName) + { + if (!isset($this->_store[$itemName]['instance'])) { + $this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName); + } + + return $this->_store[$itemName]['instance']; + } + + /** Get the current endpoint in the store */ + private function &_getEndPoint() + { + if (!isset($this->_endPoint)) { + throw new BadMethodCallException( + 'Component must first be registered by calling register()' + ); + } + + return $this->_endPoint; + } + + /** Get an argument list with dependencies resolved */ + private function _resolveArgs(array $args) + { + $resolved = array(); + foreach ($args as $argDefinition) { + switch ($argDefinition['type']) { + case 'lookup': + $resolved[] = $this->_lookupRecursive($argDefinition['item']); + break; + case 'value': + $resolved[] = $argDefinition['item']; + break; + } + } + + return $resolved; + } + + /** Resolve a single dependency with an collections */ + private function _lookupRecursive($item) + { + if (is_array($item)) { + $collection = array(); + foreach ($item as $k => $v) { + $collection[$k] = $this->_lookupRecursive($v); + } + + return $collection; + } else { + return $this->lookup($item); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php new file mode 100644 index 00000000..0a96232e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/DependencyException.php @@ -0,0 +1,27 @@ +createDependenciesFor('mime.embeddedfile') + ); + + $this->setBody($data); + $this->setFilename($filename); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Create a new EmbeddedFile. + * + * @param string|Swift_OutputByteStream $data + * @param string $filename + * @param string $contentType + * + * @return Swift_Mime_EmbeddedFile + */ + public static function newInstance($data = null, $filename = null, $contentType = null) + { + return new self($data, $filename, $contentType); + } + + /** + * Create a new EmbeddedFile from a filesystem path. + * + * @param string $path + * + * @return Swift_Mime_EmbeddedFile + */ + public static function fromPath($path) + { + return self::newInstance()->setFile( + new Swift_ByteStream_FileByteStream($path) + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php new file mode 100644 index 00000000..7c656424 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder.php @@ -0,0 +1,27 @@ += $maxLineLength || 76 < $maxLineLength) { + $maxLineLength = 76; + } + + $encodedString = base64_encode($string); + $firstLine = ''; + + if (0 != $firstLineOffset) { + $firstLine = substr( + $encodedString, 0, $maxLineLength - $firstLineOffset + )."\r\n"; + $encodedString = substr( + $encodedString, $maxLineLength - $firstLineOffset + ); + } + + return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n")); + } + + /** + * Does nothing. + */ + public function charsetChanged($charset) + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php new file mode 100644 index 00000000..81836f77 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/QpEncoder.php @@ -0,0 +1,289 @@ + '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', + 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', + 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', + 15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13', + 20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18', + 25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D', + 30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22', + 35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27', + 40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C', + 45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31', + 50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36', + 55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B', + 60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40', + 65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45', + 70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A', + 75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F', + 80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54', + 85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59', + 90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E', + 95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63', + 100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68', + 105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D', + 110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72', + 115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77', + 120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C', + 125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81', + 130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86', + 135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B', + 140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90', + 145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95', + 150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A', + 155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F', + 160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4', + 165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9', + 170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE', + 175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3', + 180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8', + 185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD', + 190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2', + 195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7', + 200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC', + 205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1', + 210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6', + 215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB', + 220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0', + 225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5', + 230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA', + 235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF', + 240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4', + 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', + 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', + 255 => '=FF', + ); + + protected static $_safeMapShare = array(); + + /** + * A map of non-encoded ascii characters. + * + * @var string[] + */ + protected $_safeMap = array(); + + /** + * Creates a new QpEncoder for the given CharacterStream. + * + * @param Swift_CharacterStream $charStream to use for reading characters + * @param Swift_StreamFilter $filter if input should be canonicalized + */ + public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) + { + $this->_charStream = $charStream; + if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + $this->initSafeMap(); + self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + } else { + $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + } + $this->_filter = $filter; + } + + public function __sleep() + { + return array('_charStream', '_filter'); + } + + public function __wakeup() + { + if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { + $this->initSafeMap(); + self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; + } else { + $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; + } + } + + protected function getSafeMapShareId() + { + return get_class($this); + } + + protected function initSafeMap() + { + foreach (array_merge( + array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { + $this->_safeMap[$byte] = chr($byte); + } + } + + /** + * Takes an unencoded string and produces a QP encoded string from it. + * + * QP encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + * + * @param string $string to encode + * @param int $firstLineOffset, optional + * @param int $maxLineLength, optional 0 indicates the default of 76 chars + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($maxLineLength > 76 || $maxLineLength <= 0) { + $maxLineLength = 76; + } + + $thisLineLength = $maxLineLength - $firstLineOffset; + + $lines = array(); + $lNo = 0; + $lines[$lNo] = ''; + $currentLine = & $lines[$lNo++]; + $size = $lineLen = 0; + + $this->_charStream->flushContents(); + $this->_charStream->importString($string); + + // Fetching more than 4 chars at one is slower, as is fetching fewer bytes + // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 + // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes + while (false !== $bytes = $this->_nextSequence()) { + // If we're filtering the input + if (isset($this->_filter)) { + // If we can't filter because we need more bytes + while ($this->_filter->shouldBuffer($bytes)) { + // Then collect bytes into the buffer + if (false === $moreBytes = $this->_nextSequence(1)) { + break; + } + + foreach ($moreBytes as $b) { + $bytes[] = $b; + } + } + // And filter them + $bytes = $this->_filter->filter($bytes); + } + + $enc = $this->_encodeByteSequence($bytes, $size); + if ($currentLine && $lineLen+$size >= $thisLineLength) { + $lines[$lNo] = ''; + $currentLine = & $lines[$lNo++]; + $thisLineLength = $maxLineLength; + $lineLen = 0; + } + $lineLen += $size; + $currentLine .= $enc; + } + + return $this->_standardize(implode("=\r\n", $lines)); + } + + /** + * Updates the charset used. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->_charStream->setCharacterSet($charset); + } + + /** + * Encode the given byte array into a verbatim QP form. + * + * @param integer[] $bytes + * @param int $size + * + * @return string + */ + protected function _encodeByteSequence(array $bytes, &$size) + { + $ret = ''; + $size = 0; + foreach ($bytes as $b) { + if (isset($this->_safeMap[$b])) { + $ret .= $this->_safeMap[$b]; + ++$size; + } else { + $ret .= self::$_qpMap[$b]; + $size += 3; + } + } + + return $ret; + } + + /** + * Get the next sequence of bytes to read from the char stream. + * + * @param int $size number of bytes to read + * + * @return integer[] + */ + protected function _nextSequence($size = 4) + { + return $this->_charStream->readBytes($size); + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + * + * @param string $string + * + * @return string + */ + protected function _standardize($string) + { + $string = str_replace(array("\t=0D=0A", " =0D=0A", "=0D=0A"), + array("=09\r\n", "=20\r\n", "\r\n"), $string + ); + switch ($end = ord(substr($string, -1))) { + case 0x09: + case 0x20: + $string = substr_replace($string, self::$_qpMap[$end], -1); + } + + return $string; + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->_charStream = clone $this->_charStream; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php new file mode 100644 index 00000000..1a7e21eb --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoder/Rfc2231Encoder.php @@ -0,0 +1,92 @@ +_charStream = $charStream; + } + + /** + * Takes an unencoded string and produces a string encoded according to + * RFC 2231 from it. + * + * @param string $string + * @param int $firstLineOffset + * @param int $maxLineLength optional, 0 indicates the default of 75 bytes + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + $lines = array(); + $lineCount = 0; + $lines[] = ''; + $currentLine = & $lines[$lineCount++]; + + if (0 >= $maxLineLength) { + $maxLineLength = 75; + } + + $this->_charStream->flushContents(); + $this->_charStream->importString($string); + + $thisLineLength = $maxLineLength - $firstLineOffset; + + while (false !== $char = $this->_charStream->read(4)) { + $encodedChar = rawurlencode($char); + if (0 != strlen($currentLine) + && strlen($currentLine.$encodedChar) > $thisLineLength) { + $lines[] = ''; + $currentLine = & $lines[$lineCount++]; + $thisLineLength = $maxLineLength; + } + $currentLine .= $encodedChar; + } + + return implode("\r\n", $lines); + } + + /** + * Updates the charset used. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->_charStream->setCharacterSet($charset); + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->_charStream = clone $this->_charStream; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoding.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoding.php new file mode 100644 index 00000000..5cbb20fc --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Encoding.php @@ -0,0 +1,64 @@ +lookup($key); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php new file mode 100644 index 00000000..670f4d3d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandEvent.php @@ -0,0 +1,65 @@ +_command = $command; + $this->_successCodes = $successCodes; + } + + /** + * Get the command which was sent to the server. + * + * @return string + */ + public function getCommand() + { + return $this->_command; + } + + /** + * Get the numeric response codes which indicate success for this command. + * + * @return integer[] + */ + public function getSuccessCodes() + { + return $this->_successCodes; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php new file mode 100644 index 00000000..3465c8d6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/CommandListener.php @@ -0,0 +1,24 @@ +_source = $source; + } + + /** + * Get the source object of this event. + * + * @return object + */ + public function getSource() + { + return $this->_source; + } + + /** + * Prevent this Event from bubbling any further up the stack. + * + * @param bool $cancel, optional + */ + public function cancelBubble($cancel = true) + { + $this->_bubbleCancelled = $cancel; + } + + /** + * Returns true if this Event will not bubble any further up the stack. + * + * @return bool + */ + public function bubbleCancelled() + { + return $this->_bubbleCancelled; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php new file mode 100644 index 00000000..b0ac1a8f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseEvent.php @@ -0,0 +1,65 @@ +_response = $response; + $this->_valid = $valid; + } + + /** + * Get the response which was received from the server. + * + * @return string + */ + public function getResponse() + { + return $this->_response; + } + + /** + * Get the success status of this Event. + * + * @return bool + */ + public function isValid() + { + return $this->_valid; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php new file mode 100644 index 00000000..9629f1e5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/ResponseListener.php @@ -0,0 +1,24 @@ +_message = $message; + $this->_result = self::RESULT_PENDING; + } + + /** + * Get the Transport used to send the Message. + * + * @return Swift_Transport + */ + public function getTransport() + { + return $this->getSource(); + } + + /** + * Get the Message being sent. + * + * @return Swift_Mime_Message + */ + public function getMessage() + { + return $this->_message; + } + + /** + * Set the array of addresses that failed in sending. + * + * @param array $recipients + */ + public function setFailedRecipients($recipients) + { + $this->_failedRecipients = $recipients; + } + + /** + * Get an recipient addresses which were not accepted for delivery. + * + * @return string[] + */ + public function getFailedRecipients() + { + return $this->_failedRecipients; + } + + /** + * Set the result of sending. + * + * @param int $result + */ + public function setResult($result) + { + $this->_result = $result; + } + + /** + * Get the result of this Event. + * + * The return value is a bitmask from + * {@see RESULT_PENDING, RESULT_SUCCESS, RESULT_TENTATIVE, RESULT_FAILED} + * + * @return int + */ + public function getResult() + { + return $this->_result; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php new file mode 100644 index 00000000..7d35f18e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/SendListener.php @@ -0,0 +1,31 @@ +_eventMap = array( + 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', + 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', + 'Swift_Events_SendEvent' => 'Swift_Events_SendListener', + 'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener', + 'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener', + ); + } + + /** + * Create a new SendEvent for $source and $message. + * + * @param Swift_Transport $source + * @param Swift_Mime_Message + * + * @return Swift_Events_SendEvent + */ + public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message) + { + return new Swift_Events_SendEvent($source, $message); + } + + /** + * Create a new CommandEvent for $source and $command. + * + * @param Swift_Transport $source + * @param string $command That will be executed + * @param array $successCodes That are needed + * + * @return Swift_Events_CommandEvent + */ + public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array()) + { + return new Swift_Events_CommandEvent($source, $command, $successCodes); + } + + /** + * Create a new ResponseEvent for $source and $response. + * + * @param Swift_Transport $source + * @param string $response + * @param bool $valid If the response is valid + * + * @return Swift_Events_ResponseEvent + */ + public function createResponseEvent(Swift_Transport $source, $response, $valid) + { + return new Swift_Events_ResponseEvent($source, $response, $valid); + } + + /** + * Create a new TransportChangeEvent for $source. + * + * @param Swift_Transport $source + * + * @return Swift_Events_TransportChangeEvent + */ + public function createTransportChangeEvent(Swift_Transport $source) + { + return new Swift_Events_TransportChangeEvent($source); + } + + /** + * Create a new TransportExceptionEvent for $source. + * + * @param Swift_Transport $source + * @param Swift_TransportException $ex + * + * @return Swift_Events_TransportExceptionEvent + */ + public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex) + { + return new Swift_Events_TransportExceptionEvent($source, $ex); + } + + /** + * Bind an event listener to this dispatcher. + * + * @param Swift_Events_EventListener $listener + */ + public function bindEventListener(Swift_Events_EventListener $listener) + { + foreach ($this->_listeners as $l) { + // Already loaded + if ($l === $listener) { + return; + } + } + $this->_listeners[] = $listener; + } + + /** + * Dispatch the given Event to all suitable listeners. + * + * @param Swift_Events_EventObject $evt + * @param string $target method + */ + public function dispatchEvent(Swift_Events_EventObject $evt, $target) + { + $this->_prepareBubbleQueue($evt); + $this->_bubble($evt, $target); + } + + /** Queue listeners on a stack ready for $evt to be bubbled up it */ + private function _prepareBubbleQueue(Swift_Events_EventObject $evt) + { + $this->_bubbleQueue = array(); + $evtClass = get_class($evt); + foreach ($this->_listeners as $listener) { + if (array_key_exists($evtClass, $this->_eventMap) + && ($listener instanceof $this->_eventMap[$evtClass])) { + $this->_bubbleQueue[] = $listener; + } + } + } + + /** Bubble $evt up the stack calling $target() on each listener */ + private function _bubble(Swift_Events_EventObject $evt, $target) + { + if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) { + $listener->$target($evt); + $this->_bubble($evt, $target); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php new file mode 100644 index 00000000..23c82970 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeEvent.php @@ -0,0 +1,27 @@ +getSource(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php new file mode 100644 index 00000000..0edfe377 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportChangeListener.php @@ -0,0 +1,45 @@ +_exception = $ex; + } + + /** + * Get the TransportException thrown. + * + * @return Swift_TransportException + */ + public function getException() + { + return $this->_exception; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php new file mode 100644 index 00000000..f153742c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Events/TransportExceptionListener.php @@ -0,0 +1,24 @@ +createDependenciesFor('transport.failover') + ); + + $this->setTransports($transports); + } + + /** + * Create a new FailoverTransport instance. + * + * @param Swift_Transport[] $transports + * + * @return Swift_FailoverTransport + */ + public static function newInstance($transports = array()) + { + return new self($transports); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php new file mode 100644 index 00000000..b30f9f85 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileSpool.php @@ -0,0 +1,208 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages on the filesystem. + * + * @author Fabien Potencier + * @author Xavier De Cock + */ +class Swift_FileSpool extends Swift_ConfigurableSpool +{ + /** The spool directory */ + private $_path; + + /** + * File WriteRetry Limit + * + * @var int + */ + private $_retryLimit = 10; + + /** + * Create a new FileSpool. + * + * @param string $path + * + * @throws Swift_IoException + */ + public function __construct($path) + { + $this->_path = $path; + + if (!file_exists($this->_path)) { + if (!mkdir($this->_path, 0777, true)) { + throw new Swift_IoException('Unable to create Path ['.$this->_path.']'); + } + } + } + + /** + * Tests if this Spool mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Spool mechanism. + */ + public function start() + { + } + + /** + * Stops this Spool mechanism. + */ + public function stop() + { + } + + /** + * Allow to manage the enqueuing retry limit. + * + * Default, is ten and allows over 64^20 different fileNames + * + * @param int $limit + */ + public function setRetryLimit($limit) + { + $this->_retryLimit = $limit; + } + + /** + * Queues a message. + * + * @param Swift_Mime_Message $message The message to store + * + * @return bool + * + * @throws Swift_IoException + */ + public function queueMessage(Swift_Mime_Message $message) + { + $ser = serialize($message); + $fileName = $this->_path.'/'.$this->getRandomString(10); + for ($i = 0; $i < $this->_retryLimit; ++$i) { + /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ + $fp = @fopen($fileName.'.message', 'x'); + if (false !== $fp) { + if (false === fwrite($fp, $ser)) { + return false; + } + + return fclose($fp); + } else { + /* The file already exists, we try a longer fileName */ + $fileName .= $this->getRandomString(1); + } + } + + throw new Swift_IoException('Unable to create a file for enqueuing Message'); + } + + /** + * Execute a recovery if for any reason a process is sending for too long. + * + * @param int $timeout in second Defaults is for very slow smtp responses + */ + public function recover($timeout = 900) + { + foreach (new DirectoryIterator($this->_path) as $file) { + $file = $file->getRealPath(); + + if (substr($file, - 16) == '.message.sending') { + $lockedtime = filectime($file); + if ((time() - $lockedtime) > $timeout) { + rename($file, substr($file, 0, - 8)); + } + } + } + } + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent e-mail's + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) + { + $directoryIterator = new DirectoryIterator($this->_path); + + /* Start the transport only if there are queued files to send */ + if (!$transport->isStarted()) { + foreach ($directoryIterator as $file) { + if (substr($file->getRealPath(), -8) == '.message') { + $transport->start(); + break; + } + } + } + + $failedRecipients = (array) $failedRecipients; + $count = 0; + $time = time(); + foreach ($directoryIterator as $file) { + $file = $file->getRealPath(); + + if (substr($file, -8) != '.message') { + continue; + } + + /* We try a rename, it's an atomic operation, and avoid locking the file */ + if (rename($file, $file.'.sending')) { + $message = unserialize(file_get_contents($file.'.sending')); + + $count += $transport->send($message, $failedRecipients); + + unlink($file.'.sending'); + } else { + /* This message has just been catched by another process */ + continue; + } + + if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) { + break; + } + + if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) { + break; + } + } + + return $count; + } + + /** + * Returns a random string needed to generate a fileName for the queue. + * + * @param int $count + * + * @return string + */ + protected function getRandomString($count) + { + // This string MUST stay FS safe, avoid special chars + $base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-."; + $ret = ''; + $strlen = strlen($base); + for ($i = 0; $i < $count; ++$i) { + $ret .= $base[((int) rand(0, $strlen - 1))]; + } + + return $ret; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php new file mode 100644 index 00000000..802cb430 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/FileStream.php @@ -0,0 +1,24 @@ +setFile( + new Swift_ByteStream_FileByteStream($path) + ); + + return $image; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php new file mode 100644 index 00000000..fd45ab93 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/InputByteStream.php @@ -0,0 +1,75 @@ +_stream = $stream; + } + + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + */ + public function setString($nsKey, $itemKey, $string, $mode) + { + $this->_prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $this->_contents[$nsKey][$itemKey] = $string; + break; + case self::MODE_APPEND: + if (!$this->hasKey($nsKey, $itemKey)) { + $this->_contents[$nsKey][$itemKey] = ''; + } + $this->_contents[$nsKey][$itemKey] .= $string; + break; + default: + throw new Swift_SwiftException( + 'Invalid mode ['.$mode.'] used to set nsKey='. + $nsKey.', itemKey='.$itemKey + ); + } + } + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_OutputByteStream $os + * @param int $mode + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) + { + $this->_prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $this->clearKey($nsKey, $itemKey); + case self::MODE_APPEND: + if (!$this->hasKey($nsKey, $itemKey)) { + $this->_contents[$nsKey][$itemKey] = ''; + } + while (false !== $bytes = $os->read(8192)) { + $this->_contents[$nsKey][$itemKey] .= $bytes; + } + break; + default: + throw new Swift_SwiftException( + 'Invalid mode ['.$mode.'] used to set nsKey='. + $nsKey.', itemKey='.$itemKey + ); + } + } + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $writeThrough + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) + { + $is = clone $this->_stream; + $is->setKeyCache($this); + $is->setNsKey($nsKey); + $is->setItemKey($itemKey); + if (isset($writeThrough)) { + $is->setWriteThroughStream($writeThrough); + } + + return $is; + } + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @return string + */ + public function getString($nsKey, $itemKey) + { + $this->_prepareCache($nsKey); + if ($this->hasKey($nsKey, $itemKey)) { + return $this->_contents[$nsKey][$itemKey]; + } + } + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) + { + $this->_prepareCache($nsKey); + $is->write($this->getString($nsKey, $itemKey)); + } + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey) + { + $this->_prepareCache($nsKey); + + return array_key_exists($itemKey, $this->_contents[$nsKey]); + } + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey) + { + unset($this->_contents[$nsKey][$itemKey]); + } + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey) + { + unset($this->_contents[$nsKey]); + } + + /** + * Initialize the namespace of $nsKey if needed. + * + * @param string $nsKey + */ + private function _prepareCache($nsKey) + { + if (!array_key_exists($nsKey, $this->_contents)) { + $this->_contents[$nsKey] = array(); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php new file mode 100644 index 00000000..5a709625 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/DiskKeyCache.php @@ -0,0 +1,324 @@ +_stream = $stream; + $this->_path = $path; + + if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { + $this->_quotes = true; + } + } + + /** + * Set a string into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param string $string + * @param int $mode + * + * @throws Swift_IoException + */ + public function setString($nsKey, $itemKey, $string, $mode) + { + $this->_prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + break; + case self::MODE_APPEND: + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + break; + default: + throw new Swift_SwiftException( + 'Invalid mode ['.$mode.'] used to set nsKey='. + $nsKey.', itemKey='.$itemKey + ); + break; + } + fwrite($fp, $string); + $this->_freeHandle($nsKey, $itemKey); + } + + /** + * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. + * + * @see MODE_WRITE, MODE_APPEND + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_OutputByteStream $os + * @param int $mode + * + * @throws Swift_IoException + */ + public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) + { + $this->_prepareCache($nsKey); + switch ($mode) { + case self::MODE_WRITE: + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + break; + case self::MODE_APPEND: + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); + break; + default: + throw new Swift_SwiftException( + 'Invalid mode ['.$mode.'] used to set nsKey='. + $nsKey.', itemKey='.$itemKey + ); + break; + } + while (false !== $bytes = $os->read(8192)) { + fwrite($fp, $bytes); + } + $this->_freeHandle($nsKey, $itemKey); + } + + /** + * Provides a ByteStream which when written to, writes data to $itemKey. + * + * NOTE: The stream will always write in append mode. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $writeThrough + * + * @return Swift_InputByteStream + */ + public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) + { + $is = clone $this->_stream; + $is->setKeyCache($this); + $is->setNsKey($nsKey); + $is->setItemKey($itemKey); + if (isset($writeThrough)) { + $is->setWriteThroughStream($writeThrough); + } + + return $is; + } + + /** + * Get data back out of the cache as a string. + * + * @param string $nsKey + * @param string $itemKey + * + * @return string + * + * @throws Swift_IoException + */ + public function getString($nsKey, $itemKey) + { + $this->_prepareCache($nsKey); + if ($this->hasKey($nsKey, $itemKey)) { + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 0); + } + $str = ''; + while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { + $str .= $bytes; + } + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 1); + } + $this->_freeHandle($nsKey, $itemKey); + + return $str; + } + } + + /** + * Get data back out of the cache as a ByteStream. + * + * @param string $nsKey + * @param string $itemKey + * @param Swift_InputByteStream $is to write the data to + */ + public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) + { + if ($this->hasKey($nsKey, $itemKey)) { + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 0); + } + while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { + $is->write($bytes); + } + if ($this->_quotes) { + ini_set('magic_quotes_runtime', 1); + } + $this->_freeHandle($nsKey, $itemKey); + } + } + + /** + * Check if the given $itemKey exists in the namespace $nsKey. + * + * @param string $nsKey + * @param string $itemKey + * + * @return bool + */ + public function hasKey($nsKey, $itemKey) + { + return is_file($this->_path.'/'.$nsKey.'/'.$itemKey); + } + + /** + * Clear data for $itemKey in the namespace $nsKey if it exists. + * + * @param string $nsKey + * @param string $itemKey + */ + public function clearKey($nsKey, $itemKey) + { + if ($this->hasKey($nsKey, $itemKey)) { + $this->_freeHandle($nsKey, $itemKey); + unlink($this->_path.'/'.$nsKey.'/'.$itemKey); + } + } + + /** + * Clear all data in the namespace $nsKey if it exists. + * + * @param string $nsKey + */ + public function clearAll($nsKey) + { + if (array_key_exists($nsKey, $this->_keys)) { + foreach ($this->_keys[$nsKey] as $itemKey => $null) { + $this->clearKey($nsKey, $itemKey); + } + if (is_dir($this->_path.'/'.$nsKey)) { + rmdir($this->_path.'/'.$nsKey); + } + unset($this->_keys[$nsKey]); + } + } + + /** + * Initialize the namespace of $nsKey if needed. + * + * @param string $nsKey + */ + private function _prepareCache($nsKey) + { + $cacheDir = $this->_path.'/'.$nsKey; + if (!is_dir($cacheDir)) { + if (!mkdir($cacheDir)) { + throw new Swift_IoException('Failed to create cache directory '.$cacheDir); + } + $this->_keys[$nsKey] = array(); + } + } + + /** + * Get a file handle on the cache item. + * + * @param string $nsKey + * @param string $itemKey + * @param int $position + * + * @return resource + */ + private function _getHandle($nsKey, $itemKey, $position) + { + if (!isset($this->_keys[$nsKey][$itemKey])) { + $openMode = $this->hasKey($nsKey, $itemKey) + ? 'r+b' + : 'w+b' + ; + $fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode); + $this->_keys[$nsKey][$itemKey] = $fp; + } + if (self::POSITION_START == $position) { + fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET); + } elseif (self::POSITION_END == $position) { + fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END); + } + + return $this->_keys[$nsKey][$itemKey]; + } + + private function _freeHandle($nsKey, $itemKey) + { + $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT); + fclose($fp); + $this->_keys[$nsKey][$itemKey] = null; + } + + /** + * Destructor. + */ + public function __destruct() + { + foreach ($this->_keys as $nsKey => $null) { + $this->clearAll($nsKey); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php new file mode 100644 index 00000000..76039d8a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/KeyCache/KeyCacheInputStream.php @@ -0,0 +1,51 @@ +_keyCache = $keyCache; + } + + /** + * Specify a stream to write through for each write(). + * + * @param Swift_InputByteStream $is + */ + public function setWriteThroughStream(Swift_InputByteStream $is) + { + $this->_writeThrough = $is; + } + + /** + * Writes $bytes to the end of the stream. + * + * @param string $bytes + * @param Swift_InputByteStream $is optional + */ + public function write($bytes, Swift_InputByteStream $is = null) + { + $this->_keyCache->setString( + $this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND + ); + if (isset($is)) { + $is->write($bytes); + } + if (isset($this->_writeThrough)) { + $this->_writeThrough->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Not used. + */ + public function bind(Swift_InputByteStream $is) + { + } + + /** + * Not used. + */ + public function unbind(Swift_InputByteStream $is) + { + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + */ + public function flushBuffers() + { + $this->_keyCache->clearKey($this->_nsKey, $this->_itemKey); + } + + /** + * Set the nsKey which will be written to. + * + * @param string $nsKey + */ + public function setNsKey($nsKey) + { + $this->_nsKey = $nsKey; + } + + /** + * Set the itemKey which will be written to. + * + * @param string $itemKey + */ + public function setItemKey($itemKey) + { + $this->_itemKey = $itemKey; + } + + /** + * Any implementation should be cloneable, allowing the clone to access a + * separate $nsKey and $itemKey. + */ + public function __clone() + { + $this->_writeThrough = null; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php new file mode 100644 index 00000000..6e1080b9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/LoadBalancedTransport.php @@ -0,0 +1,45 @@ +createDependenciesFor('transport.loadbalanced') + ); + + $this->setTransports($transports); + } + + /** + * Create a new LoadBalancedTransport instance. + * + * @param array $transports + * + * @return Swift_LoadBalancedTransport + */ + public static function newInstance($transports = array()) + { + return new self($transports); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MailTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MailTransport.php new file mode 100644 index 00000000..a6d3340d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MailTransport.php @@ -0,0 +1,45 @@ +createDependenciesFor('transport.mail') + ); + + $this->setExtraParams($extraParams); + } + + /** + * Create a new MailTransport instance. + * + * @param string $extraParams To be passed to mail() + * + * @return Swift_MailTransport + */ + public static function newInstance($extraParams = '-f%s') + { + return new self($extraParams); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php new file mode 100644 index 00000000..5677fcb4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php @@ -0,0 +1,114 @@ +_transport = $transport; + } + + /** + * Create a new Mailer instance. + * + * @param Swift_Transport $transport + * + * @return Swift_Mailer + */ + public static function newInstance(Swift_Transport $transport) + { + return new self($transport); + } + + /** + * Create a new class instance of one of the message services. + * + * For example 'mimepart' would create a 'message.mimepart' instance + * + * @param string $service + * + * @return object + */ + public function createMessage($service = 'message') + { + return Swift_DependencyContainer::getInstance() + ->lookup('message.'.$service); + } + + /** + * Send the given Message like it would be sent in a mail client. + * + * All recipients (with the exception of Bcc) will be able to see the other + * recipients this message was sent to. + * + * Recipient/sender data will be retrieved from the Message object. + * + * The return value is the number of recipients who were accepted for + * delivery. + * + * @param Swift_Mime_Message $message + * @param array $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + $failedRecipients = (array) $failedRecipients; + + if (!$this->_transport->isStarted()) { + $this->_transport->start(); + } + + $sent = 0; + + try { + $sent = $this->_transport->send($message, $failedRecipients); + } catch (Swift_RfcComplianceException $e) { + foreach ($message->getTo() as $address => $name) { + $failedRecipients[] = $address; + } + } + + return $sent; + } + + /** + * Register a plugin using a known unique key (e.g. myPlugin). + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->_transport->registerPlugin($plugin); + } + + /** + * The Transport used to send messages. + * + * @return Swift_Transport + */ + public function getTransport() + { + return $this->_transport; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php new file mode 100644 index 00000000..d02e1846 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/ArrayRecipientIterator.php @@ -0,0 +1,55 @@ +_recipients = $recipients; + } + + /** + * Returns true only if there are more recipients to send to. + * + * @return bool + */ + public function hasNext() + { + return !empty($this->_recipients); + } + + /** + * Returns an array where the keys are the addresses of recipients and the + * values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL) + * + * @return array + */ + public function nextRecipient() + { + return array_splice($this->_recipients, 0, 1); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php new file mode 100644 index 00000000..a935c563 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer/RecipientIterator.php @@ -0,0 +1,32 @@ + 'Foo') or ('foo@bar' => NULL) + * + * @return array + */ + public function nextRecipient(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php new file mode 100644 index 00000000..590fc488 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MemorySpool.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in memory. + * + * @author Fabien Potencier + */ +class Swift_MemorySpool implements Swift_Spool +{ + protected $messages = array(); + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * Stores a message in the queue. + * + * @param Swift_Mime_Message $message The message to store + * + * @return bool Whether the operation has succeeded + */ + public function queueMessage(Swift_Mime_Message $message) + { + //clone the message to make sure it is not changed while in the queue + $this->messages[] = clone $message; + + return true; + } + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) + { + if (!$this->messages) { + return 0; + } + + if (!$transport->isStarted()) { + $transport->start(); + } + + $count = 0; + while ($message = array_pop($this->messages)) { + $count += $transport->send($message, $failedRecipients); + } + + return $count; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php new file mode 100644 index 00000000..6887a075 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Message.php @@ -0,0 +1,287 @@ +createDependenciesFor('mime.message') + ); + + if (!isset($charset)) { + $charset = Swift_DependencyContainer::getInstance() + ->lookup('properties.charset'); + } + $this->setSubject($subject); + $this->setBody($body); + $this->setCharset($charset); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Create a new Message. + * + * @param string $subject + * @param string $body + * @param string $contentType + * @param string $charset + * + * @return Swift_Message + */ + public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null) + { + return new self($subject, $body, $contentType, $charset); + } + + /** + * Add a MimePart to this Message. + * + * @param string|Swift_OutputByteStream $body + * @param string $contentType + * @param string $charset + * + * @return Swift_Mime_SimpleMessage + */ + public function addPart($body, $contentType = null, $charset = null) + { + return $this->attach(Swift_MimePart::newInstance( + $body, $contentType, $charset + )); + } + + /** + * Attach a new signature handler to the message. + * + * @param Swift_Signer $signer + * @return Swift_Message + */ + public function attachSigner(Swift_Signer $signer) + { + if ($signer instanceof Swift_Signers_HeaderSigner) { + $this->headerSigners[] = $signer; + } elseif ($signer instanceof Swift_Signers_BodySigner) { + $this->bodySigners[] = $signer; + } + + return $this; + } + + /** + * Attach a new signature handler to the message. + * + * @param Swift_Signer $signer + * @return Swift_Message + */ + public function detachSigner(Swift_Signer $signer) + { + if ($signer instanceof Swift_Signers_HeaderSigner) { + foreach ($this->headerSigners as $k => $headerSigner) { + if ($headerSigner === $signer) { + unset($this->headerSigners[$k]); + + return $this; + } + } + } elseif ($signer instanceof Swift_Signers_BodySigner) { + foreach ($this->bodySigners as $k => $bodySigner) { + if ($bodySigner === $signer) { + unset($this->bodySigners[$k]); + + return $this; + } + } + } + + return $this; + } + + /** + * Get this message as a complete string. + * + * @return string + */ + public function toString() + { + if (empty($this->headerSigners) && empty($this->bodySigners)) { + return parent::toString(); + } + + $this->saveMessage(); + + $this->doSign(); + + $string = parent::toString(); + + $this->restoreMessage(); + + return $string; + } + + /** + * Write this message to a {@link Swift_InputByteStream}. + * + * @param Swift_InputByteStream $is + */ + public function toByteStream(Swift_InputByteStream $is) + { + if (empty($this->headerSigners) && empty($this->bodySigners)) { + parent::toByteStream($is); + + return; + } + + $this->saveMessage(); + + $this->doSign(); + + parent::toByteStream($is); + + $this->restoreMessage(); + } + + public function __wakeup() + { + Swift_DependencyContainer::getInstance()->createDependenciesFor('mime.message'); + } + + /** + * loops through signers and apply the signatures + */ + protected function doSign() + { + foreach ($this->bodySigners as $signer) { + $altered = $signer->getAlteredHeaders(); + $this->saveHeaders($altered); + $signer->signMessage($this); + } + + foreach ($this->headerSigners as $signer) { + $altered = $signer->getAlteredHeaders(); + $this->saveHeaders($altered); + $signer->reset(); + + $signer->setHeaders($this->getHeaders()); + + $signer->startBody(); + $this->_bodyToByteStream($signer); + $signer->endBody(); + + $signer->addSignature($this->getHeaders()); + } + } + + /** + * save the message before any signature is applied + */ + protected function saveMessage() + { + $this->savedMessage = array('headers' => array()); + $this->savedMessage['body'] = $this->getBody(); + $this->savedMessage['children'] = $this->getChildren(); + if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') { + $this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children'])); + $this->setBody(''); + } + } + + /** + * save the original headers + * @param array $altered + */ + protected function saveHeaders(array $altered) + { + foreach ($altered as $head) { + $lc = strtolower($head); + + if (!isset($this->savedMessage['headers'][$lc])) { + $this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head); + } + } + } + + /** + * Remove or restore altered headers + */ + protected function restoreHeaders() + { + foreach ($this->savedMessage['headers'] as $name => $savedValue) { + $headers = $this->getHeaders()->getAll($name); + + foreach ($headers as $key => $value) { + if (!isset($savedValue[$key])) { + $this->getHeaders()->remove($name, $key); + } + } + } + } + + /** + * Restore message body + */ + protected function restoreMessage() + { + $this->setBody($this->savedMessage['body']); + $this->setChildren($this->savedMessage['children']); + + $this->restoreHeaders(); + $this->savedMessage = array(); + } + + /** + * Clone Message Signers + * @see Swift_Mime_SimpleMimeEntity::__clone() + */ + public function __clone() + { + parent::__clone(); + foreach ($this->bodySigners as $key => $bodySigner) { + $this->bodySigners[$key] = clone($bodySigner); + } + + foreach ($this->headerSigners as $key => $headerSigner) { + $this->headerSigners[$key] = clone($headerSigner); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php new file mode 100644 index 00000000..d9d96529 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Attachment.php @@ -0,0 +1,153 @@ +setDisposition('attachment'); + $this->setContentType('application/octet-stream'); + $this->_mimeTypes = $mimeTypes; + } + + /** + * Get the nesting level used for this attachment. + * + * Always returns {@link LEVEL_MIXED}. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_MIXED; + } + + /** + * Get the Content-Disposition of this attachment. + * + * By default attachments have a disposition of "attachment". + * + * @return string + */ + public function getDisposition() + { + return $this->_getHeaderFieldModel('Content-Disposition'); + } + + /** + * Set the Content-Disposition of this attachment. + * + * @param string $disposition + * + * @return Swift_Mime_Attachment + */ + public function setDisposition($disposition) + { + if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) { + $this->getHeaders()->addParameterizedHeader( + 'Content-Disposition', $disposition + ); + } + + return $this; + } + + /** + * Get the filename of this attachment when downloaded. + * + * @return string + */ + public function getFilename() + { + return $this->_getHeaderParameter('Content-Disposition', 'filename'); + } + + /** + * Set the filename of this attachment. + * + * @param string $filename + * + * @return Swift_Mime_Attachment + */ + public function setFilename($filename) + { + $this->_setHeaderParameter('Content-Disposition', 'filename', $filename); + $this->_setHeaderParameter('Content-Type', 'name', $filename); + + return $this; + } + + /** + * Get the file size of this attachment. + * + * @return int + */ + public function getSize() + { + return $this->_getHeaderParameter('Content-Disposition', 'size'); + } + + /** + * Set the file size of this attachment. + * + * @param int $size + * + * @return Swift_Mime_Attachment + */ + public function setSize($size) + { + $this->_setHeaderParameter('Content-Disposition', 'size', $size); + + return $this; + } + + /** + * Set the file that this attachment is for. + * + * @param Swift_FileStream $file + * @param string $contentType optional + * + * @return Swift_Mime_Attachment + */ + public function setFile(Swift_FileStream $file, $contentType = null) + { + $this->setFilename(basename($file->getPath())); + $this->setBody($file, $contentType); + if (!isset($contentType)) { + $extension = strtolower(substr( + $file->getPath(), strrpos($file->getPath(), '.') + 1 + )); + + if (array_key_exists($extension, $this->_mimeTypes)) { + $this->setContentType($this->_mimeTypes[$extension]); + } + } + + return $this; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php new file mode 100644 index 00000000..57d8bc46 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/CharsetObserver.php @@ -0,0 +1,24 @@ += $maxLineLength || 76 < $maxLineLength) { + $maxLineLength = 76; + } + + $remainder = 0; + + while (false !== $bytes = $os->read(8190)) { + $encoded = base64_encode($bytes); + $encodedTransformed = ''; + $thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset; + + while ($thisMaxLineLength < strlen($encoded)) { + $encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n"; + $firstLineOffset = 0; + $encoded = substr($encoded, $thisMaxLineLength); + $thisMaxLineLength = $maxLineLength; + $remainder = 0; + } + + if (0 < $remainingLength = strlen($encoded)) { + $remainder += $remainingLength; + $encodedTransformed .= $encoded; + $encoded = null; + } + + $is->write($encodedTransformed); + } + } + + /** + * Get the name of this encoding scheme. + * Returns the string 'base64'. + * + * @return string + */ + public function getName() + { + return 'base64'; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php new file mode 100644 index 00000000..e97195a5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php @@ -0,0 +1,123 @@ +charset = $charset ? $charset : 'utf-8'; + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->charset = $charset; + } + + /** + * Encode $in to $out. + * + * @param Swift_OutputByteStream $os to read from + * @param Swift_InputByteStream $is to write to + * @param int $firstLineOffset + * @param int $maxLineLength 0 indicates the default length for this encoding + * + * @throws RuntimeException + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($this->charset !== 'utf-8') { + throw new RuntimeException( + sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); + } + + $string = ''; + + while (false !== $bytes = $os->read(8192)) { + $string .= $bytes; + } + + $is->write($this->encodeString($string)); + } + + /** + * Get the MIME name of this content encoding scheme. + * + * @return string + */ + public function getName() + { + return 'quoted-printable'; + } + + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset if first line needs to be shorter + * @param int $maxLineLength 0 indicates the default length for this encoding + * + * @return string + * + * @throws RuntimeException + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($this->charset !== 'utf-8') { + throw new RuntimeException( + sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); + } + + return $this->_standardize(quoted_printable_encode($string)); + } + + /** + * Make sure CRLF is correct and HT/SPACE are in valid places. + * + * @param string $string + * + * @return string + */ + protected function _standardize($string) + { + // transform CR or LF to CRLF + $string = preg_replace('~=0D(?!=0A)|(?_name = $name; + $this->_canonical = $canonical; + } + + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset ignored + * @param int $maxLineLength - 0 means no wrapping will occur + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($this->_canonical) { + $string = $this->_canonicalize($string); + } + + return $this->_safeWordWrap($string, $maxLineLength, "\r\n"); + } + + /** + * Encode stream $in to stream $out. + * + * @param Swift_OutputByteStream $os + * @param Swift_InputByteStream $is + * @param int $firstLineOffset ignored + * @param int $maxLineLength optional, 0 means no wrapping will occur + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + $leftOver = ''; + while (false !== $bytes = $os->read(8192)) { + $toencode = $leftOver.$bytes; + if ($this->_canonical) { + $toencode = $this->_canonicalize($toencode); + } + $wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n"); + $lastLinePos = strrpos($wrapped, "\r\n"); + $leftOver = substr($wrapped, $lastLinePos); + $wrapped = substr($wrapped, 0, $lastLinePos); + + $is->write($wrapped); + } + if (strlen($leftOver)) { + $is->write($leftOver); + } + } + + /** + * Get the name of this encoding scheme. + * + * @return string + */ + public function getName() + { + return $this->_name; + } + + /** + * Not used. + */ + public function charsetChanged($charset) + { + } + + /** + * A safer (but weaker) wordwrap for unicode. + * + * @param string $string + * @param int $length + * @param string $le + * + * @return string + */ + private function _safeWordwrap($string, $length = 75, $le = "\r\n") + { + if (0 >= $length) { + return $string; + } + + $originalLines = explode($le, $string); + + $lines = array(); + $lineCount = 0; + + foreach ($originalLines as $originalLine) { + $lines[] = ''; + $currentLine = & $lines[$lineCount++]; + + //$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine); + $chunks = preg_split('/(?<=\s)/', $originalLine); + + foreach ($chunks as $chunk) { + if (0 != strlen($currentLine) + && strlen($currentLine.$chunk) > $length) { + $lines[] = ''; + $currentLine = & $lines[$lineCount++]; + } + $currentLine .= $chunk; + } + } + + return implode("\r\n", $lines); + } + + /** + * Canonicalize string input (fix CRLF). + * + * @param string $string + * + * @return string + */ + private function _canonicalize($string) + { + return str_replace( + array("\r\n", "\r", "\n"), + array("\n", "\n", "\r\n"), + $string + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php new file mode 100644 index 00000000..58f05a10 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php @@ -0,0 +1,123 @@ +_dotEscape = $dotEscape; + parent::__construct($charStream, $filter); + } + + public function __sleep() + { + return array('_charStream', '_filter', '_dotEscape'); + } + + protected function getSafeMapShareId() + { + return get_class($this).($this->_dotEscape ? '.dotEscape' : ''); + } + + protected function initSafeMap() + { + parent::initSafeMap(); + if ($this->_dotEscape) { + /* Encode . as =2e for buggy remote servers */ + unset($this->_safeMap[0x2e]); + } + } + + /** + * Encode stream $in to stream $out. + * + * QP encoded strings have a maximum line length of 76 characters. + * If the first line needs to be shorter, indicate the difference with + * $firstLineOffset. + * + * @param Swift_OutputByteStream $os output stream + * @param Swift_InputByteStream $is input stream + * @param int $firstLineOffset + * @param int $maxLineLength + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + if ($maxLineLength > 76 || $maxLineLength <= 0) { + $maxLineLength = 76; + } + + $thisLineLength = $maxLineLength - $firstLineOffset; + + $this->_charStream->flushContents(); + $this->_charStream->importByteStream($os); + + $currentLine = ''; + $prepend = ''; + $size = $lineLen = 0; + + while (false !== $bytes = $this->_nextSequence()) { + // If we're filtering the input + if (isset($this->_filter)) { + // If we can't filter because we need more bytes + while ($this->_filter->shouldBuffer($bytes)) { + // Then collect bytes into the buffer + if (false === $moreBytes = $this->_nextSequence(1)) { + break; + } + + foreach ($moreBytes as $b) { + $bytes[] = $b; + } + } + // And filter them + $bytes = $this->_filter->filter($bytes); + } + + $enc = $this->_encodeByteSequence($bytes, $size); + if ($currentLine && $lineLen+$size >= $thisLineLength) { + $is->write($prepend.$this->_standardize($currentLine)); + $currentLine = ''; + $prepend = "=\r\n"; + $thisLineLength = $maxLineLength; + $lineLen = 0; + } + $lineLen += $size; + $currentLine .= $enc; + } + if (strlen($currentLine)) { + $is->write($prepend.$this->_standardize($currentLine)); + } + } + + /** + * Get the name of this encoding scheme. + * Returns the string 'quoted-printable'. + * + * @return string + */ + public function getName() + { + return 'quoted-printable'; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php new file mode 100644 index 00000000..d6e8d7c3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php @@ -0,0 +1,97 @@ + + */ +class Swift_Mime_ContentEncoder_QpContentEncoderProxy implements Swift_Mime_ContentEncoder +{ + /** + * @var Swift_Mime_ContentEncoder_QpContentEncoder + */ + private $safeEncoder; + + /** + * @var Swift_Mime_ContentEncoder_NativeQpContentEncoder + */ + private $nativeEncoder; + + /** + * @var null|string + */ + private $charset; + + /** + * Constructor. + * + * @param Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder + * @param Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder + * @param string|null $charset + */ + public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset) + { + $this->safeEncoder = $safeEncoder; + $this->nativeEncoder = $nativeEncoder; + $this->charset = $charset; + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->safeEncoder = clone $this->safeEncoder; + $this->nativeEncoder = clone $this->nativeEncoder; + } + + /** + * {@inheritdoc} + */ + public function charsetChanged($charset) + { + $this->charset = $charset; + } + + /** + * {@inheritdoc} + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + $this->getEncoder()->encodeByteStream($os, $is, $firstLineOffset, $maxLineLength); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return 'quoted-printable'; + } + + /** + * {@inheritdoc} + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return $this->getEncoder()->encodeString($string, $firstLineOffset, $maxLineLength); + } + + /** + * @return Swift_Mime_ContentEncoder + */ + private function getEncoder() + { + return 'utf-8' === $this->charset ? $this->nativeEncoder : $this->safeEncoder; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php new file mode 100644 index 00000000..f717dc78 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php @@ -0,0 +1,63 @@ + + */ +class Swift_Mime_ContentEncoder_RawContentEncoder implements Swift_Mime_ContentEncoder +{ + /** + * Encode a given string to produce an encoded string. + * + * @param string $string + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return $string; + } + + /** + * Encode stream $in to stream $out. + * + * @param Swift_OutputByteStream $in + * @param Swift_InputByteStream $out + * @param int $firstLineOffset ignored + * @param int $maxLineLength ignored + */ + public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) + { + while (false !== ($bytes = $os->read(8192))) { + $is->write($bytes); + } + } + + /** + * Get the name of this encoding scheme. + * + * @return string + */ + public function getName() + { + return 'raw'; + } + + /** + * Not used. + */ + public function charsetChanged($charset) + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php new file mode 100644 index 00000000..ec1ef535 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EmbeddedFile.php @@ -0,0 +1,45 @@ +setDisposition('inline'); + $this->setId($this->getId()); + } + + /** + * Get the nesting level of this EmbeddedFile. + * + * Returns {@see LEVEL_RELATED}. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_RELATED; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php new file mode 100644 index 00000000..e262974b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/EncodingObserver.php @@ -0,0 +1,24 @@ +init(); + } + + public function __wakeup() + { + $this->init(); + } + + protected function init() + { + if (count(self::$_specials) > 0) { + return; + } + + self::$_specials = array( + '(', ')', '<', '>', '[', ']', + ':', ';', '@', ',', '.', '"', + ); + + /*** Refer to RFC 2822 for ABNF grammar ***/ + + // All basic building blocks + self::$_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]'; + self::$_grammar['WSP'] = '[ \t]'; + self::$_grammar['CRLF'] = '(?:\r\n)'; + self::$_grammar['FWS'] = '(?:(?:'.self::$_grammar['WSP'].'*'. + self::$_grammar['CRLF'].')?'.self::$_grammar['WSP'].')'; + self::$_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]'; + self::$_grammar['quoted-pair'] = '(?:\\\\'.self::$_grammar['text'].')'; + self::$_grammar['ctext'] = '(?:'.self::$_grammar['NO-WS-CTL']. + '|[\x21-\x27\x2A-\x5B\x5D-\x7E])'; + // Uses recursive PCRE (?1) -- could be a weak point?? + self::$_grammar['ccontent'] = '(?:'.self::$_grammar['ctext'].'|'. + self::$_grammar['quoted-pair'].'|(?1))'; + self::$_grammar['comment'] = '(\((?:'.self::$_grammar['FWS'].'|'. + self::$_grammar['ccontent'].')*'.self::$_grammar['FWS'].'?\))'; + self::$_grammar['CFWS'] = '(?:(?:'.self::$_grammar['FWS'].'?'. + self::$_grammar['comment'].')*(?:(?:'.self::$_grammar['FWS'].'?'. + self::$_grammar['comment'].')|'.self::$_grammar['FWS'].'))'; + self::$_grammar['qtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. + '|[\x21\x23-\x5B\x5D-\x7E])'; + self::$_grammar['qcontent'] = '(?:'.self::$_grammar['qtext'].'|'. + self::$_grammar['quoted-pair'].')'; + self::$_grammar['quoted-string'] = '(?:'.self::$_grammar['CFWS'].'?"'. + '('.self::$_grammar['FWS'].'?'.self::$_grammar['qcontent'].')*'. + self::$_grammar['FWS'].'?"'.self::$_grammar['CFWS'].'?)'; + self::$_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]'; + self::$_grammar['atom'] = '(?:'.self::$_grammar['CFWS'].'?'. + self::$_grammar['atext'].'+'.self::$_grammar['CFWS'].'?)'; + self::$_grammar['dot-atom-text'] = '(?:'.self::$_grammar['atext'].'+'. + '(\.'.self::$_grammar['atext'].'+)*)'; + self::$_grammar['dot-atom'] = '(?:'.self::$_grammar['CFWS'].'?'. + self::$_grammar['dot-atom-text'].'+'.self::$_grammar['CFWS'].'?)'; + self::$_grammar['word'] = '(?:'.self::$_grammar['atom'].'|'. + self::$_grammar['quoted-string'].')'; + self::$_grammar['phrase'] = '(?:'.self::$_grammar['word'].'+?)'; + self::$_grammar['no-fold-quote'] = '(?:"(?:'.self::$_grammar['qtext']. + '|'.self::$_grammar['quoted-pair'].')*")'; + self::$_grammar['dtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. + '|[\x21-\x5A\x5E-\x7E])'; + self::$_grammar['no-fold-literal'] = '(?:\[(?:'.self::$_grammar['dtext']. + '|'.self::$_grammar['quoted-pair'].')*\])'; + + // Message IDs + self::$_grammar['id-left'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. + self::$_grammar['no-fold-quote'].')'; + self::$_grammar['id-right'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. + self::$_grammar['no-fold-literal'].')'; + + // Addresses, mailboxes and paths + self::$_grammar['local-part'] = '(?:'.self::$_grammar['dot-atom'].'|'. + self::$_grammar['quoted-string'].')'; + self::$_grammar['dcontent'] = '(?:'.self::$_grammar['dtext'].'|'. + self::$_grammar['quoted-pair'].')'; + self::$_grammar['domain-literal'] = '(?:'.self::$_grammar['CFWS'].'?\[('. + self::$_grammar['FWS'].'?'.self::$_grammar['dcontent'].')*?'. + self::$_grammar['FWS'].'?\]'.self::$_grammar['CFWS'].'?)'; + self::$_grammar['domain'] = '(?:'.self::$_grammar['dot-atom'].'|'. + self::$_grammar['domain-literal'].')'; + self::$_grammar['addr-spec'] = '(?:'.self::$_grammar['local-part'].'@'. + self::$_grammar['domain'].')'; + } + + /** + * Get the grammar defined for $name token. + * + * @param string $name exactly as written in the RFC + * + * @return string + */ + public function getDefinition($name) + { + if (array_key_exists($name, self::$_grammar)) { + return self::$_grammar[$name]; + } else { + throw new Swift_RfcComplianceException( + "No such grammar '".$name."' defined." + ); + } + } + + /** + * Returns the tokens defined in RFC 2822 (and some related RFCs). + * + * @return array + */ + public function getGrammarDefinitions() + { + return self::$_grammar; + } + + /** + * Returns the current special characters used in the syntax which need to be escaped. + * + * @return array + */ + public function getSpecials() + { + return self::$_specials; + } + + /** + * Escape special characters in a string (convert to quoted-pairs). + * + * @param string $token + * @param string[] $include additional chars to escape + * @param string[] $exclude chars from escaping + * + * @return string + */ + public function escapeSpecials($token, $include = array(), $exclude = array()) + { + foreach (array_merge(array('\\'), array_diff(self::$_specials, $exclude), $include) as $char) { + $token = str_replace($char, '\\'.$char, $token); + } + + return $token; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php new file mode 100644 index 00000000..7074c4f6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Header.php @@ -0,0 +1,93 @@ +getName(), "\r\n"); + mb_internal_encoding($old); + + return $newstring; + } + + return parent::encodeString($string, $firstLineOffset, $maxLineLength); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php new file mode 100644 index 00000000..dd8ff382 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php @@ -0,0 +1,65 @@ +_safeMap[$byte] = chr($byte); + } + } + + /** + * Get the name of this encoding scheme. + * + * Returns the string 'Q'. + * + * @return string + */ + public function getName() + { + return 'Q'; + } + + /** + * Takes an unencoded string and produces a QP encoded string from it. + * + * @param string $string string to encode + * @param int $firstLineOffset optional + * @param int $maxLineLength optional, 0 indicates the default of 76 chars + * + * @return string + */ + public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) + { + return str_replace(array(' ', '=20', "=\r\n"), array('_', '_', "\r\n"), + parent::encodeString($string, $firstLineOffset, $maxLineLength) + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php new file mode 100644 index 00000000..423cebcf --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/HeaderFactory.php @@ -0,0 +1,78 @@ +setGrammar($grammar); + } + + /** + * Set the character set used in this Header. + * + * @param string $charset + */ + public function setCharset($charset) + { + $this->clearCachedValueIf($charset != $this->_charset); + $this->_charset = $charset; + if (isset($this->_encoder)) { + $this->_encoder->charsetChanged($charset); + } + } + + /** + * Get the character set used in this Header. + * + * @return string + */ + public function getCharset() + { + return $this->_charset; + } + + /** + * Set the language used in this Header. + * + * For example, for US English, 'en-us'. + * This can be unspecified. + * + * @param string $lang + */ + public function setLanguage($lang) + { + $this->clearCachedValueIf($this->_lang != $lang); + $this->_lang = $lang; + } + + /** + * Get the language used in this Header. + * + * @return string + */ + public function getLanguage() + { + return $this->_lang; + } + + /** + * Set the encoder used for encoding the header. + * + * @param Swift_Mime_HeaderEncoder $encoder + */ + public function setEncoder(Swift_Mime_HeaderEncoder $encoder) + { + $this->_encoder = $encoder; + $this->setCachedValue(null); + } + + /** + * Get the encoder used for encoding this Header. + * + * @return Swift_Mime_HeaderEncoder + */ + public function getEncoder() + { + return $this->_encoder; + } + + /** + * Set the grammar used for the header. + * + * @param Swift_Mime_Grammar $grammar + */ + public function setGrammar(Swift_Mime_Grammar $grammar) + { + $this->_grammar = $grammar; + $this->setCachedValue(null); + } + + /** + * Get the grammar used for this Header. + * + * @return Swift_Mime_Grammar + */ + public function getGrammar() + { + return $this->_grammar; + } + + /** + * Get the name of this header (e.g. charset). + * + * @return string + */ + public function getFieldName() + { + return $this->_name; + } + + /** + * Set the maximum length of lines in the header (excluding EOL). + * + * @param int $lineLength + */ + public function setMaxLineLength($lineLength) + { + $this->clearCachedValueIf($this->_lineLength != $lineLength); + $this->_lineLength = $lineLength; + } + + /** + * Get the maximum permitted length of lines in this Header. + * + * @return int + */ + public function getMaxLineLength() + { + return $this->_lineLength; + } + + /** + * Get this Header rendered as a RFC 2822 compliant string. + * + * @return string + * + * @throws Swift_RfcComplianceException + */ + public function toString() + { + return $this->_tokensToString($this->toTokens()); + } + + /** + * Returns a string representation of this object. + * + * @return string + * + * @see toString() + */ + public function __toString() + { + return $this->toString(); + } + + // -- Points of extension + + /** + * Set the name of this Header field. + * + * @param string $name + */ + protected function setFieldName($name) + { + $this->_name = $name; + } + + /** + * Produces a compliant, formatted RFC 2822 'phrase' based on the string given. + * + * @param Swift_Mime_Header $header + * @param string $string as displayed + * @param string $charset of the text + * @param Swift_Mime_HeaderEncoder $encoder + * @param bool $shorten the first line to make remove for header name + * + * @return string + */ + protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false) + { + // Treat token as exactly what was given + $phraseStr = $string; + // If it's not valid + if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) { + // .. but it is just ascii text, try escaping some characters + // and make it a quoted-string + if (preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) { + $phraseStr = $this->getGrammar()->escapeSpecials( + $phraseStr, array('"'), $this->getGrammar()->getSpecials() + ); + $phraseStr = '"'.$phraseStr.'"'; + } else { + // ... otherwise it needs encoding + // Determine space remaining on line if first line + if ($shorten) { + $usedLength = strlen($header->getFieldName().': '); + } else { + $usedLength = 0; + } + $phraseStr = $this->encodeWords($header, $string, $usedLength); + } + } + + return $phraseStr; + } + + /** + * Encode needed word tokens within a string of input. + * + * @param Swift_Mime_Header $header + * @param string $input + * @param string $usedLength optional + * + * @return string + */ + protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1) + { + $value = ''; + + $tokens = $this->getEncodableWordTokens($input); + + foreach ($tokens as $token) { + // See RFC 2822, Sect 2.2 (really 2.2 ??) + if ($this->tokenNeedsEncoding($token)) { + // Don't encode starting WSP + $firstChar = substr($token, 0, 1); + switch ($firstChar) { + case ' ': + case "\t": + $value .= $firstChar; + $token = substr($token, 1); + } + + if (-1 == $usedLength) { + $usedLength = strlen($header->getFieldName().': ') + strlen($value); + } + $value .= $this->getTokenAsEncodedWord($token, $usedLength); + + $header->setMaxLineLength(76); // Forcefully override + } else { + $value .= $token; + } + } + + return $value; + } + + /** + * Test if a token needs to be encoded or not. + * + * @param string $token + * + * @return bool + */ + protected function tokenNeedsEncoding($token) + { + return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token); + } + + /** + * Splits a string into tokens in blocks of words which can be encoded quickly. + * + * @param string $string + * + * @return string[] + */ + protected function getEncodableWordTokens($string) + { + $tokens = array(); + + $encodedToken = ''; + // Split at all whitespace boundaries + foreach (preg_split('~(?=[\t ])~', $string) as $token) { + if ($this->tokenNeedsEncoding($token)) { + $encodedToken .= $token; + } else { + if (strlen($encodedToken) > 0) { + $tokens[] = $encodedToken; + $encodedToken = ''; + } + $tokens[] = $token; + } + } + if (strlen($encodedToken)) { + $tokens[] = $encodedToken; + } + + return $tokens; + } + + /** + * Get a token as an encoded word for safe insertion into headers. + * + * @param string $token token to encode + * @param int $firstLineOffset optional + * + * @return string + */ + protected function getTokenAsEncodedWord($token, $firstLineOffset = 0) + { + // Adjust $firstLineOffset to account for space needed for syntax + $charsetDecl = $this->_charset; + if (isset($this->_lang)) { + $charsetDecl .= '*'.$this->_lang; + } + $encodingWrapperLength = strlen( + '=?'.$charsetDecl.'?'.$this->_encoder->getName().'??=' + ); + + if ($firstLineOffset >= 75) { + //Does this logic need to be here? + $firstLineOffset = 0; + } + + $encodedTextLines = explode("\r\n", + $this->_encoder->encodeString( + $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset + ) + ); + + if (strtolower($this->_charset) !== 'iso-2022-jp') { + // special encoding for iso-2022-jp using mb_encode_mimeheader + foreach ($encodedTextLines as $lineNum => $line) { + $encodedTextLines[$lineNum] = '=?'.$charsetDecl. + '?'.$this->_encoder->getName(). + '?'.$line.'?='; + } + } + + return implode("\r\n ", $encodedTextLines); + } + + /** + * Generates tokens from the given string which include CRLF as individual tokens. + * + * @param string $token + * + * @return string[] + */ + protected function generateTokenLines($token) + { + return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE); + } + + /** + * Set a value into the cache. + * + * @param string $value + */ + protected function setCachedValue($value) + { + $this->_cachedValue = $value; + } + + /** + * Get the value in the cache. + * + * @return string + */ + protected function getCachedValue() + { + return $this->_cachedValue; + } + + /** + * Clear the cached value if $condition is met. + * + * @param bool $condition + */ + protected function clearCachedValueIf($condition) + { + if ($condition) { + $this->setCachedValue(null); + } + } + + /** + * Generate a list of all tokens in the final header. + * + * @param string $string The string to tokenize + * + * @return array An array of tokens as strings + */ + protected function toTokens($string = null) + { + if (is_null($string)) { + $string = $this->getFieldBody(); + } + + $tokens = array(); + + // Generate atoms; split at all invisible boundaries followed by WSP + foreach (preg_split('~(?=[ \t])~', $string) as $token) { + $newTokens = $this->generateTokenLines($token); + foreach ($newTokens as $newToken) { + $tokens[] = $newToken; + } + } + + return $tokens; + } + + /** + * Takes an array of tokens which appear in the header and turns them into + * an RFC 2822 compliant string, adding FWSP where needed. + * + * @param string[] $tokens + * + * @return string + */ + private function _tokensToString(array $tokens) + { + $lineCount = 0; + $headerLines = array(); + $headerLines[] = $this->_name.': '; + $currentLine = & $headerLines[$lineCount++]; + + // Build all tokens back into compliant header + foreach ($tokens as $i => $token) { + // Line longer than specified maximum or token was just a new line + if (("\r\n" == $token) || + ($i > 0 && strlen($currentLine.$token) > $this->_lineLength) + && 0 < strlen($currentLine)) { + $headerLines[] = ''; + $currentLine = & $headerLines[$lineCount++]; + } + + // Append token to the line + if ("\r\n" != $token) { + $currentLine .= $token; + } + } + + // Implode with FWS (RFC 2822, 2.2.3) + return implode("\r\n", $headerLines)."\r\n"; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php new file mode 100644 index 00000000..a1093fb0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/DateHeader.php @@ -0,0 +1,125 @@ + + * + * + * + * @param string $name of Header + * @param Swift_Mime_Grammar $grammar + */ + public function __construct($name, Swift_Mime_Grammar $grammar) + { + $this->setFieldName($name); + parent::__construct($grammar); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_DATE; + } + + /** + * Set the model for the field body. + * + * This method takes a UNIX timestamp. + * + * @param int $model + */ + public function setFieldBodyModel($model) + { + $this->setTimestamp($model); + } + + /** + * Get the model for the field body. + * + * This method returns a UNIX timestamp. + * + * @return mixed + */ + public function getFieldBodyModel() + { + return $this->getTimestamp(); + } + + /** + * Get the UNIX timestamp of the Date in this Header. + * + * @return int + */ + public function getTimestamp() + { + return $this->_timestamp; + } + + /** + * Set the UNIX timestamp of the Date in this Header. + * + * @param int $timestamp + */ + public function setTimestamp($timestamp) + { + if (!is_null($timestamp)) { + $timestamp = (int) $timestamp; + } + $this->clearCachedValueIf($this->_timestamp != $timestamp); + $this->_timestamp = $timestamp; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + if (isset($this->_timestamp)) { + $this->setCachedValue(date('r', $this->_timestamp)); + } + } + + return $this->getCachedValue(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php new file mode 100644 index 00000000..1a5a3dd9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/IdentificationHeader.php @@ -0,0 +1,180 @@ +setFieldName($name); + parent::__construct($grammar); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_ID; + } + + /** + * Set the model for the field body. + * + * This method takes a string ID, or an array of IDs. + * + * @param mixed $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setId($model); + } + + /** + * Get the model for the field body. + * + * This method returns an array of IDs + * + * @return array + */ + public function getFieldBodyModel() + { + return $this->getIds(); + } + + /** + * Set the ID used in the value of this header. + * + * @param string|array $id + * + * @throws Swift_RfcComplianceException + */ + public function setId($id) + { + $this->setIds(is_array($id) ? $id : array($id)); + } + + /** + * Get the ID used in the value of this Header. + * + * If multiple IDs are set only the first is returned. + * + * @return string + */ + public function getId() + { + if (count($this->_ids) > 0) { + return $this->_ids[0]; + } + } + + /** + * Set a collection of IDs to use in the value of this Header. + * + * @param string[] $ids + * + * @throws Swift_RfcComplianceException + */ + public function setIds(array $ids) + { + $actualIds = array(); + + foreach ($ids as $id) { + $this->_assertValidId($id); + $actualIds[] = $id; + } + + $this->clearCachedValueIf($this->_ids != $actualIds); + $this->_ids = $actualIds; + } + + /** + * Get the list of IDs used in this Header. + * + * @return string[] + */ + public function getIds() + { + return $this->_ids; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@see toString()} for that). + * + * @see toString() + * + * @return string + * + * @throws Swift_RfcComplianceException + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + $angleAddrs = array(); + + foreach ($this->_ids as $id) { + $angleAddrs[] = '<'.$id.'>'; + } + + $this->setCachedValue(implode(' ', $angleAddrs)); + } + + return $this->getCachedValue(); + } + + /** + * Throws an Exception if the id passed does not comply with RFC 2822. + * + * @param string $id + * + * @throws Swift_RfcComplianceException + */ + private function _assertValidId($id) + { + if (!preg_match( + '/^'.$this->getGrammar()->getDefinition('id-left').'@'. + $this->getGrammar()->getDefinition('id-right').'$/D', + $id + )) { + throw new Swift_RfcComplianceException( + 'Invalid ID given <'.$id.'>' + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php new file mode 100644 index 00000000..165b8619 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php @@ -0,0 +1,354 @@ +setFieldName($name); + $this->setEncoder($encoder); + parent::__construct($grammar); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_MAILBOX; + } + + /** + * Set the model for the field body. + * + * This method takes a string, or an array of addresses. + * + * @param mixed $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setNameAddresses($model); + } + + /** + * Get the model for the field body. + * + * This method returns an associative array like {@link getNameAddresses()} + * + * @return array + * + * @throws Swift_RfcComplianceException + */ + public function getFieldBodyModel() + { + return $this->getNameAddresses(); + } + + /** + * Set a list of mailboxes to be shown in this Header. + * + * The mailboxes can be a simple array of addresses, or an array of + * key=>value pairs where (email => personalName). + * Example: + * + * setNameAddresses(array( + * 'chris@swiftmailer.org' => 'Chris Corbyn', + * 'mark@swiftmailer.org' //No associated personal name + * )); + * ?> + * + * + * @see __construct() + * @see setAddresses() + * @see setValue() + * + * @param string|string[] $mailboxes + * + * @throws Swift_RfcComplianceException + */ + public function setNameAddresses($mailboxes) + { + $this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes); + $this->setCachedValue(null); //Clear any cached value + } + + /** + * Get the full mailbox list of this Header as an array of valid RFC 2822 strings. + * + * Example: + * + * 'Chris Corbyn', + * 'mark@swiftmailer.org' => 'Mark Corbyn') + * ); + * print_r($header->getNameAddressStrings()); + * // array ( + * // 0 => Chris Corbyn , + * // 1 => Mark Corbyn + * // ) + * ?> + * + * + * @see getNameAddresses() + * @see toString() + * + * @return string[] + * + * @throws Swift_RfcComplianceException + */ + public function getNameAddressStrings() + { + return $this->_createNameAddressStrings($this->getNameAddresses()); + } + + /** + * Get all mailboxes in this Header as key=>value pairs. + * + * The key is the address and the value is the name (or null if none set). + * Example: + * + * 'Chris Corbyn', + * 'mark@swiftmailer.org' => 'Mark Corbyn') + * ); + * print_r($header->getNameAddresses()); + * // array ( + * // chris@swiftmailer.org => Chris Corbyn, + * // mark@swiftmailer.org => Mark Corbyn + * // ) + * ?> + * + * + * @see getAddresses() + * @see getNameAddressStrings() + * + * @return string[] + */ + public function getNameAddresses() + { + return $this->_mailboxes; + } + + /** + * Makes this Header represent a list of plain email addresses with no names. + * + * Example: + * + * setAddresses( + * array('one@domain.tld', 'two@domain.tld', 'three@domain.tld') + * ); + * ?> + * + * + * @see setNameAddresses() + * @see setValue() + * + * @param string[] $addresses + * + * @throws Swift_RfcComplianceException + */ + public function setAddresses($addresses) + { + $this->setNameAddresses(array_values((array) $addresses)); + } + + /** + * Get all email addresses in this Header. + * + * @see getNameAddresses() + * + * @return string[] + */ + public function getAddresses() + { + return array_keys($this->_mailboxes); + } + + /** + * Remove one or more addresses from this Header. + * + * @param string|string[] $addresses + */ + public function removeAddresses($addresses) + { + $this->setCachedValue(null); + foreach ((array) $addresses as $address) { + unset($this->_mailboxes[$address]); + } + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @return string + * + * @throws Swift_RfcComplianceException + */ + public function getFieldBody() + { + // Compute the string value of the header only if needed + if (is_null($this->getCachedValue())) { + $this->setCachedValue($this->createMailboxListString($this->_mailboxes)); + } + + return $this->getCachedValue(); + } + + // -- Points of extension + + /** + * Normalizes a user-input list of mailboxes into consistent key=>value pairs. + * + * @param string[] $mailboxes + * + * @return string[] + */ + protected function normalizeMailboxes(array $mailboxes) + { + $actualMailboxes = array(); + + foreach ($mailboxes as $key => $value) { + if (is_string($key)) { + //key is email addr + $address = $key; + $name = $value; + } else { + $address = $value; + $name = null; + } + $this->_assertValidAddress($address); + $actualMailboxes[$address] = $name; + } + + return $actualMailboxes; + } + + /** + * Produces a compliant, formatted display-name based on the string given. + * + * @param string $displayName as displayed + * @param bool $shorten the first line to make remove for header name + * + * @return string + */ + protected function createDisplayNameString($displayName, $shorten = false) + { + return $this->createPhrase($this, $displayName, + $this->getCharset(), $this->getEncoder(), $shorten + ); + } + + /** + * Creates a string form of all the mailboxes in the passed array. + * + * @param string[] $mailboxes + * + * @return string + * + * @throws Swift_RfcComplianceException + */ + protected function createMailboxListString(array $mailboxes) + { + return implode(', ', $this->_createNameAddressStrings($mailboxes)); + } + + /** + * Redefine the encoding requirements for mailboxes. + * + * Commas and semicolons are used to separate + * multiple addresses, and should therefore be encoded + * + * @param string $token + * + * @return bool + */ + protected function tokenNeedsEncoding($token) + { + return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token); + } + + /** + * Return an array of strings conforming the the name-addr spec of RFC 2822. + * + * @param string[] $mailboxes + * + * @return string[] + */ + private function _createNameAddressStrings(array $mailboxes) + { + $strings = array(); + + foreach ($mailboxes as $email => $name) { + $mailboxStr = $email; + if (!is_null($name)) { + $nameStr = $this->createDisplayNameString($name, empty($strings)); + $mailboxStr = $nameStr.' <'.$mailboxStr.'>'; + } + $strings[] = $mailboxStr; + } + + return $strings; + } + + /** + * Throws an Exception if the address passed does not comply with RFC 2822. + * + * @param string $address + * + * @throws Swift_RfcComplianceException If invalid. + */ + private function _assertValidAddress($address) + { + if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', + $address)) { + throw new Swift_RfcComplianceException( + 'Address in mailbox given ['.$address. + '] does not comply with RFC 2822, 3.6.2.' + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php new file mode 100644 index 00000000..b55d4609 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/OpenDKIMHeader.php @@ -0,0 +1,135 @@ + + */ +class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header +{ + /** + * The value of this Header. + * + * @var string + */ + private $_value; + + /** + * The name of this Header + * @var string + */ + private $_fieldName; + + /** + * Creates a new SimpleHeader with $name. + * + * @param string $name + * @param Swift_Mime_HeaderEncoder $encoder + * @param Swift_Mime_Grammar $grammar + */ + public function __construct($name) + { + $this->_fieldName = $name; + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_TEXT; + } + + /** + * Set the model for the field body. + * + * This method takes a string for the field value. + * + * @param string $model + */ + public function setFieldBodyModel($model) + { + $this->setValue($model); + } + + /** + * Get the model for the field body. + * + * This method returns a string. + * + * @return string + */ + public function getFieldBodyModel() + { + return $this->getValue(); + } + + /** + * Get the (unencoded) value of this header. + * + * @return string + */ + public function getValue() + { + return $this->_value; + } + + /** + * Set the (unencoded) value of this header. + * + * @param string $value + */ + public function setValue($value) + { + $this->_value = $value; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() + { + return $this->_value; + } + + /** + * Get this Header rendered as a RFC 2822 compliant string. + * + * @return string + */ + public function toString() + { + return $this->_fieldName.': '.$this->_value; + } + + /** + * Set the Header FieldName + * @see Swift_Mime_Header::getFieldName() + */ + public function getFieldName() + { + return $this->_fieldName; + } + + /** + * Ignored + */ + public function setCharset($charset) + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php new file mode 100644 index 00000000..994fc940 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/ParameterizedHeader.php @@ -0,0 +1,260 @@ +_paramEncoder = $paramEncoder; + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_PARAMETERIZED; + } + + /** + * Set the character set used in this Header. + * + * @param string $charset + */ + public function setCharset($charset) + { + parent::setCharset($charset); + if (isset($this->_paramEncoder)) { + $this->_paramEncoder->charsetChanged($charset); + } + } + + /** + * Set the value of $parameter. + * + * @param string $parameter + * @param string $value + */ + public function setParameter($parameter, $value) + { + $this->setParameters(array_merge($this->getParameters(), array($parameter => $value))); + } + + /** + * Get the value of $parameter. + * + * @param string $parameter + * + * @return string + */ + public function getParameter($parameter) + { + $params = $this->getParameters(); + + return array_key_exists($parameter, $params) + ? $params[$parameter] + : null; + } + + /** + * Set an associative array of parameter names mapped to values. + * + * @param string[] $parameters + */ + public function setParameters(array $parameters) + { + $this->clearCachedValueIf($this->_params != $parameters); + $this->_params = $parameters; + } + + /** + * Returns an associative array of parameter names mapped to values. + * + * @return string[] + */ + public function getParameters() + { + return $this->_params; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() //TODO: Check caching here + { + $body = parent::getFieldBody(); + foreach ($this->_params as $name => $value) { + if (!is_null($value)) { + // Add the parameter + $body .= '; '.$this->_createParameter($name, $value); + } + } + + return $body; + } + + /** + * Generate a list of all tokens in the final header. + * + * This doesn't need to be overridden in theory, but it is for implementation + * reasons to prevent potential breakage of attributes. + * + * @param string $string The string to tokenize + * + * @return array An array of tokens as strings + */ + protected function toTokens($string = null) + { + $tokens = parent::toTokens(parent::getFieldBody()); + + // Try creating any parameters + foreach ($this->_params as $name => $value) { + if (!is_null($value)) { + // Add the semi-colon separator + $tokens[count($tokens)-1] .= ';'; + $tokens = array_merge($tokens, $this->generateTokenLines( + ' '.$this->_createParameter($name, $value) + )); + } + } + + return $tokens; + } + + /** + * Render a RFC 2047 compliant header parameter from the $name and $value. + * + * @param string $name + * @param string $value + * + * @return string + */ + private function _createParameter($name, $value) + { + $origValue = $value; + + $encoded = false; + // Allow room for parameter name, indices, "=" and DQUOTEs + $maxValueLength = $this->getMaxLineLength() - strlen($name.'=*N"";') - 1; + $firstLineOffset = 0; + + // If it's not already a valid parameter value... + if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + // TODO: text, or something else?? + // ... and it's not ascii + if (!preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $value)) { + $encoded = true; + // Allow space for the indices, charset and language + $maxValueLength = $this->getMaxLineLength() - strlen($name.'*N*="";') - 1; + $firstLineOffset = strlen( + $this->getCharset()."'".$this->getLanguage()."'" + ); + } + } + + // Encode if we need to + if ($encoded || strlen($value) > $maxValueLength) { + if (isset($this->_paramEncoder)) { + $value = $this->_paramEncoder->encodeString( + $origValue, $firstLineOffset, $maxValueLength, $this->getCharset() + ); + } else { + // We have to go against RFC 2183/2231 in some areas for interoperability + $value = $this->getTokenAsEncodedWord($origValue); + $encoded = false; + } + } + + $valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value); + + // Need to add indices + if (count($valueLines) > 1) { + $paramLines = array(); + foreach ($valueLines as $i => $line) { + $paramLines[] = $name.'*'.$i. + $this->_getEndOfParameterValue($line, true, $i == 0); + } + + return implode(";\r\n ", $paramLines); + } else { + return $name.$this->_getEndOfParameterValue( + $valueLines[0], $encoded, true + ); + } + } + + /** + * Returns the parameter value from the "=" and beyond. + * + * @param string $value to append + * @param bool $encoded + * @param bool $firstLine + * + * @return string + */ + private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false) + { + if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { + $value = '"'.$value.'"'; + } + $prepend = '='; + if ($encoded) { + $prepend = '*='; + if ($firstLine) { + $prepend = '*='.$this->getCharset()."'".$this->getLanguage(). + "'"; + } + } + + return $prepend.$value; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php new file mode 100644 index 00000000..eea9a9ee --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/PathHeader.php @@ -0,0 +1,143 @@ +setFieldName($name); + parent::__construct($grammar); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_PATH; + } + + /** + * Set the model for the field body. + * This method takes a string for an address. + * + * @param string $model + * + * @throws Swift_RfcComplianceException + */ + public function setFieldBodyModel($model) + { + $this->setAddress($model); + } + + /** + * Get the model for the field body. + * This method returns a string email address. + * + * @return mixed + */ + public function getFieldBodyModel() + { + return $this->getAddress(); + } + + /** + * Set the Address which should appear in this Header. + * + * @param string $address + * + * @throws Swift_RfcComplianceException + */ + public function setAddress($address) + { + if (is_null($address)) { + $this->_address = null; + } elseif ('' == $address) { + $this->_address = ''; + } else { + $this->_assertValidAddress($address); + $this->_address = $address; + } + $this->setCachedValue(null); + } + + /** + * Get the address which is used in this Header (if any). + * + * Null is returned if no address is set. + * + * @return string + */ + public function getAddress() + { + return $this->_address; + } + + /** + * Get the string value of the body in this Header. + * + * This is not necessarily RFC 2822 compliant since folding white space will + * not be added at this stage (see {@link toString()} for that). + * + * @see toString() + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + if (isset($this->_address)) { + $this->setCachedValue('<'.$this->_address.'>'); + } + } + + return $this->getCachedValue(); + } + + /** + * Throws an Exception if the address passed does not comply with RFC 2822. + * + * @param string $address + * + * @throws Swift_RfcComplianceException If address is invalid + */ + private function _assertValidAddress($address) + { + if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', + $address)) { + throw new Swift_RfcComplianceException( + 'Address set in PathHeader does not comply with addr-spec of RFC 2822.' + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php new file mode 100644 index 00000000..41d4e63d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/UnstructuredHeader.php @@ -0,0 +1,112 @@ +setFieldName($name); + $this->setEncoder($encoder); + parent::__construct($grammar); + } + + /** + * Get the type of Header that this instance represents. + * + * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX + * @see TYPE_DATE, TYPE_ID, TYPE_PATH + * + * @return int + */ + public function getFieldType() + { + return self::TYPE_TEXT; + } + + /** + * Set the model for the field body. + * + * This method takes a string for the field value. + * + * @param string $model + */ + public function setFieldBodyModel($model) + { + $this->setValue($model); + } + + /** + * Get the model for the field body. + * + * This method returns a string. + * + * @return string + */ + public function getFieldBodyModel() + { + return $this->getValue(); + } + + /** + * Get the (unencoded) value of this header. + * + * @return string + */ + public function getValue() + { + return $this->_value; + } + + /** + * Set the (unencoded) value of this header. + * + * @param string $value + */ + public function setValue($value) + { + $this->clearCachedValueIf($this->_value != $value); + $this->_value = $value; + } + + /** + * Get the value of this header prepared for rendering. + * + * @return string + */ + public function getFieldBody() + { + if (!$this->getCachedValue()) { + $this->setCachedValue( + $this->encodeWords($this, $this->_value) + ); + } + + return $this->getCachedValue(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Message.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Message.php new file mode 100644 index 00000000..29bc4b33 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Message.php @@ -0,0 +1,223 @@ + 'Real Name'). + * + * If the second parameter is provided and the first is a string, then $name + * is associated with the address. + * + * @param mixed $address + * @param string $name optional + */ + public function setSender($address, $name = null); + + /** + * Get the sender address for this message. + * + * This has a higher significance than the From address. + * + * @return string + */ + public function getSender(); + + /** + * Set the From address of this message. + * + * It is permissible for multiple From addresses to be set using an array. + * + * If multiple From addresses are used, you SHOULD set the Sender address and + * according to RFC 2822, MUST set the sender address. + * + * An array can be used if display names are to be provided: i.e. + * array('email@address.com' => 'Real Name'). + * + * If the second parameter is provided and the first is a string, then $name + * is associated with the address. + * + * @param mixed $addresses + * @param string $name optional + */ + public function setFrom($addresses, $name = null); + + /** + * Get the From address(es) of this message. + * + * This method always returns an associative array where the keys are the + * addresses. + * + * @return string[] + */ + public function getFrom(); + + /** + * Set the Reply-To address(es). + * + * Any replies from the receiver will be sent to this address. + * + * It is permissible for multiple reply-to addresses to be set using an array. + * + * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. + * + * If the second parameter is provided and the first is a string, then $name + * is associated with the address. + * + * @param mixed $addresses + * @param string $name optional + */ + public function setReplyTo($addresses, $name = null); + + /** + * Get the Reply-To addresses for this message. + * + * This method always returns an associative array where the keys provide the + * email addresses. + * + * @return string[] + */ + public function getReplyTo(); + + /** + * Set the To address(es). + * + * Recipients set in this field will receive a copy of this message. + * + * This method has the same synopsis as {@link setFrom()} and {@link setCc()}. + * + * If the second parameter is provided and the first is a string, then $name + * is associated with the address. + * + * @param mixed $addresses + * @param string $name optional + */ + public function setTo($addresses, $name = null); + + /** + * Get the To addresses for this message. + * + * This method always returns an associative array, whereby the keys provide + * the actual email addresses. + * + * @return string[] + */ + public function getTo(); + + /** + * Set the Cc address(es). + * + * Recipients set in this field will receive a 'carbon-copy' of this message. + * + * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. + * + * @param mixed $addresses + * @param string $name optional + */ + public function setCc($addresses, $name = null); + + /** + * Get the Cc addresses for this message. + * + * This method always returns an associative array, whereby the keys provide + * the actual email addresses. + * + * @return string[] + */ + public function getCc(); + + /** + * Set the Bcc address(es). + * + * Recipients set in this field will receive a 'blind-carbon-copy' of this + * message. + * + * In other words, they will get the message, but any other recipients of the + * message will have no such knowledge of their receipt of it. + * + * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. + * + * @param mixed $addresses + * @param string $name optional + */ + public function setBcc($addresses, $name = null); + + /** + * Get the Bcc addresses for this message. + * + * This method always returns an associative array, whereby the keys provide + * the actual email addresses. + * + * @return string[] + */ + public function getBcc(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php new file mode 100644 index 00000000..cd8b8a2b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/MimeEntity.php @@ -0,0 +1,115 @@ +setContentType('text/plain'); + if (!is_null($charset)) { + $this->setCharset($charset); + } + } + + /** + * Set the body of this entity, either as a string, or as an instance of + * {@link Swift_OutputByteStream}. + * + * @param mixed $body + * @param string $contentType optional + * @param string $charset optional + * + * @return Swift_Mime_MimePart + */ + public function setBody($body, $contentType = null, $charset = null) + { + if (isset($charset)) { + $this->setCharset($charset); + } + $body = $this->_convertString($body); + + parent::setBody($body, $contentType); + + return $this; + } + + /** + * Get the character set of this entity. + * + * @return string + */ + public function getCharset() + { + return $this->_getHeaderParameter('Content-Type', 'charset'); + } + + /** + * Set the character set of this entity. + * + * @param string $charset + * + * @return Swift_Mime_MimePart + */ + public function setCharset($charset) + { + $this->_setHeaderParameter('Content-Type', 'charset', $charset); + if ($charset !== $this->_userCharset) { + $this->_clearCache(); + } + $this->_userCharset = $charset; + parent::charsetChanged($charset); + + return $this; + } + + /** + * Get the format of this entity (i.e. flowed or fixed). + * + * @return string + */ + public function getFormat() + { + return $this->_getHeaderParameter('Content-Type', 'format'); + } + + /** + * Set the format of this entity (flowed or fixed). + * + * @param string $format + * + * @return Swift_Mime_MimePart + */ + public function setFormat($format) + { + $this->_setHeaderParameter('Content-Type', 'format', $format); + $this->_userFormat = $format; + + return $this; + } + + /** + * Test if delsp is being used for this entity. + * + * @return bool + */ + public function getDelSp() + { + return ($this->_getHeaderParameter('Content-Type', 'delsp') == 'yes') + ? true + : false; + } + + /** + * Turn delsp on or off for this entity. + * + * @param bool $delsp + * + * @return Swift_Mime_MimePart + */ + public function setDelSp($delsp = true) + { + $this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); + $this->_userDelSp = $delsp; + + return $this; + } + + /** + * Get the nesting level of this entity. + * + * @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED + * + * @return int + */ + public function getNestingLevel() + { + return $this->_nestingLevel; + } + + /** + * Receive notification that the charset has changed on this document, or a + * parent document. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->setCharset($charset); + } + + /** Fix the content-type and encoding of this entity */ + protected function _fixHeaders() + { + parent::_fixHeaders(); + if (count($this->getChildren())) { + $this->_setHeaderParameter('Content-Type', 'charset', null); + $this->_setHeaderParameter('Content-Type', 'format', null); + $this->_setHeaderParameter('Content-Type', 'delsp', null); + } else { + $this->setCharset($this->_userCharset); + $this->setFormat($this->_userFormat); + $this->setDelSp($this->_userDelSp); + } + } + + /** Set the nesting level of this entity */ + protected function _setNestingLevel($level) + { + $this->_nestingLevel = $level; + } + + /** Encode charset when charset is not utf-8 */ + protected function _convertString($string) + { + $charset = strtolower($this->getCharset()); + if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) { + // mb_convert_encoding must be the first one to check, since iconv cannot convert some words. + if (function_exists('mb_convert_encoding')) { + $string = mb_convert_encoding($string, $charset, 'utf-8'); + } elseif (function_exists('iconv')) { + $string = iconv('utf-8//TRANSLIT//IGNORE', $charset, $string); + } else { + throw new Swift_SwiftException('No suitable convert encoding function (use UTF-8 as your charset or install the mbstring or iconv extension).'); + } + + return $string; + } + + return $string; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php new file mode 100644 index 00000000..ea793201 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ParameterizedHeader.php @@ -0,0 +1,34 @@ +_encoder = $encoder; + $this->_paramEncoder = $paramEncoder; + $this->_grammar = $grammar; + $this->_charset = $charset; + } + + /** + * Create a new Mailbox Header with a list of $addresses. + * + * @param string $name + * @param array|string|null $addresses + * + * @return Swift_Mime_Header + */ + public function createMailboxHeader($name, $addresses = null) + { + $header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar); + if (isset($addresses)) { + $header->setFieldBodyModel($addresses); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Create a new Date header using $timestamp (UNIX time). + * @param string $name + * @param int|null $timestamp + * + * @return Swift_Mime_Header + */ + public function createDateHeader($name, $timestamp = null) + { + $header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar); + if (isset($timestamp)) { + $header->setFieldBodyModel($timestamp); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Create a new basic text header with $name and $value. + * + * @param string $name + * @param string $value + * + * @return Swift_Mime_Header + */ + public function createTextHeader($name, $value = null) + { + $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar); + if (isset($value)) { + $header->setFieldBodyModel($value); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Create a new ParameterizedHeader with $name, $value and $params. + * + * @param string $name + * @param string $value + * @param array $params + * + * @return Swift_Mime_ParameterizedHeader + */ + public function createParameterizedHeader($name, $value = null, + $params = array()) + { + $header = new Swift_Mime_Headers_ParameterizedHeader($name, + $this->_encoder, (strtolower($name) == 'content-disposition') + ? $this->_paramEncoder + : null, + $this->_grammar + ); + if (isset($value)) { + $header->setFieldBodyModel($value); + } + foreach ($params as $k => $v) { + $header->setParameter($k, $v); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Create a new ID header for Message-ID or Content-ID. + * + * @param string $name + * @param string|array $ids + * + * @return Swift_Mime_Header + */ + public function createIdHeader($name, $ids = null) + { + $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar); + if (isset($ids)) { + $header->setFieldBodyModel($ids); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Create a new Path header with an address (path) in it. + * + * @param string $name + * @param string $path + * + * @return Swift_Mime_Header + */ + public function createPathHeader($name, $path = null) + { + $header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar); + if (isset($path)) { + $header->setFieldBodyModel($path); + } + $this->_setHeaderCharset($header); + + return $header; + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->_charset = $charset; + $this->_encoder->charsetChanged($charset); + $this->_paramEncoder->charsetChanged($charset); + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->_encoder = clone $this->_encoder; + $this->_paramEncoder = clone $this->_paramEncoder; + } + + /** Apply the charset to the Header */ + private function _setHeaderCharset(Swift_Mime_Header $header) + { + if (isset($this->_charset)) { + $header->setCharset($this->_charset); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php new file mode 100644 index 00000000..b44a02ca --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleHeaderSet.php @@ -0,0 +1,396 @@ +_factory = $factory; + if (isset($charset)) { + $this->setCharset($charset); + } + } + + /** + * Set the charset used by these headers. + * + * @param string $charset + */ + public function setCharset($charset) + { + $this->_charset = $charset; + $this->_factory->charsetChanged($charset); + $this->_notifyHeadersOfCharset($charset); + } + + /** + * Add a new Mailbox Header with a list of $addresses. + * + * @param string $name + * @param array|string $addresses + */ + public function addMailboxHeader($name, $addresses = null) + { + $this->_storeHeader($name, + $this->_factory->createMailboxHeader($name, $addresses)); + } + + /** + * Add a new Date header using $timestamp (UNIX time). + * + * @param string $name + * @param int $timestamp + */ + public function addDateHeader($name, $timestamp = null) + { + $this->_storeHeader($name, + $this->_factory->createDateHeader($name, $timestamp)); + } + + /** + * Add a new basic text header with $name and $value. + * + * @param string $name + * @param string $value + */ + public function addTextHeader($name, $value = null) + { + $this->_storeHeader($name, + $this->_factory->createTextHeader($name, $value)); + } + + /** + * Add a new ParameterizedHeader with $name, $value and $params. + * + * @param string $name + * @param string $value + * @param array $params + */ + public function addParameterizedHeader($name, $value = null, $params = array()) + { + $this->_storeHeader($name, $this->_factory->createParameterizedHeader($name, $value, $params)); + } + + /** + * Add a new ID header for Message-ID or Content-ID. + * + * @param string $name + * @param string|array $ids + */ + public function addIdHeader($name, $ids = null) + { + $this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids)); + } + + /** + * Add a new Path header with an address (path) in it. + * + * @param string $name + * @param string $path + */ + public function addPathHeader($name, $path = null) + { + $this->_storeHeader($name, $this->_factory->createPathHeader($name, $path)); + } + + /** + * Returns true if at least one header with the given $name exists. + * + * If multiple headers match, the actual one may be specified by $index. + * + * @param string $name + * @param int $index + * + * @return bool + */ + public function has($name, $index = 0) + { + $lowerName = strtolower($name); + + return array_key_exists($lowerName, $this->_headers) && array_key_exists($index, $this->_headers[$lowerName]); + } + + /** + * Set a header in the HeaderSet. + * + * The header may be a previously fetched header via {@link get()} or it may + * be one that has been created separately. + * + * If $index is specified, the header will be inserted into the set at this + * offset. + * + * @param Swift_Mime_Header $header + * @param int $index + */ + public function set(Swift_Mime_Header $header, $index = 0) + { + $this->_storeHeader($header->getFieldName(), $header, $index); + } + + /** + * Get the header with the given $name. + * + * If multiple headers match, the actual one may be specified by $index. + * Returns NULL if none present. + * + * @param string $name + * @param int $index + * + * @return Swift_Mime_Header + */ + public function get($name, $index = 0) + { + if ($this->has($name, $index)) { + $lowerName = strtolower($name); + + return $this->_headers[$lowerName][$index]; + } + } + + /** + * Get all headers with the given $name. + * + * @param string $name + * + * @return array + */ + public function getAll($name = null) + { + if (!isset($name)) { + $headers = array(); + foreach ($this->_headers as $collection) { + $headers = array_merge($headers, $collection); + } + + return $headers; + } + + $lowerName = strtolower($name); + if (!array_key_exists($lowerName, $this->_headers)) { + return array(); + } + + return $this->_headers[$lowerName]; + } + + /** + * Return the name of all Headers + * + * @return array + */ + public function listAll() + { + $headers = $this->_headers; + if ($this->_canSort()) { + uksort($headers, array($this, '_sortHeaders')); + } + + return array_keys($headers); + } + + /** + * Remove the header with the given $name if it's set. + * + * If multiple headers match, the actual one may be specified by $index. + * + * @param string $name + * @param int $index + */ + public function remove($name, $index = 0) + { + $lowerName = strtolower($name); + unset($this->_headers[$lowerName][$index]); + } + + /** + * Remove all headers with the given $name. + * + * @param string $name + */ + public function removeAll($name) + { + $lowerName = strtolower($name); + unset($this->_headers[$lowerName]); + } + + /** + * Create a new instance of this HeaderSet. + * + * @return Swift_Mime_HeaderSet + */ + public function newInstance() + { + return new self($this->_factory); + } + + /** + * Define a list of Header names as an array in the correct order. + * + * These Headers will be output in the given order where present. + * + * @param array $sequence + */ + public function defineOrdering(array $sequence) + { + $this->_order = array_flip(array_map('strtolower', $sequence)); + } + + /** + * Set a list of header names which must always be displayed when set. + * + * Usually headers without a field value won't be output unless set here. + * + * @param array $names + */ + public function setAlwaysDisplayed(array $names) + { + $this->_required = array_flip(array_map('strtolower', $names)); + } + + /** + * Notify this observer that the entity's charset has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->setCharset($charset); + } + + /** + * Returns a string with a representation of all headers. + * + * @return string + */ + public function toString() + { + $string = ''; + $headers = $this->_headers; + if ($this->_canSort()) { + uksort($headers, array($this, '_sortHeaders')); + } + foreach ($headers as $collection) { + foreach ($collection as $header) { + if ($this->_isDisplayed($header) || $header->getFieldBody() != '') { + $string .= $header->toString(); + } + } + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @return string + * + * @see toString() + */ + public function __toString() + { + return $this->toString(); + } + + /** Save a Header to the internal collection */ + private function _storeHeader($name, Swift_Mime_Header $header, $offset = null) + { + if (!isset($this->_headers[strtolower($name)])) { + $this->_headers[strtolower($name)] = array(); + } + if (!isset($offset)) { + $this->_headers[strtolower($name)][] = $header; + } else { + $this->_headers[strtolower($name)][$offset] = $header; + } + } + + /** Test if the headers can be sorted */ + private function _canSort() + { + return count($this->_order) > 0; + } + + /** uksort() algorithm for Header ordering */ + private function _sortHeaders($a, $b) + { + $lowerA = strtolower($a); + $lowerB = strtolower($b); + $aPos = array_key_exists($lowerA, $this->_order) + ? $this->_order[$lowerA] + : -1; + $bPos = array_key_exists($lowerB, $this->_order) + ? $this->_order[$lowerB] + : -1; + + if ($aPos == -1) { + return 1; + } elseif ($bPos == -1) { + return -1; + } + + return ($aPos < $bPos) ? -1 : 1; + } + + /** Test if the given Header is always displayed */ + private function _isDisplayed(Swift_Mime_Header $header) + { + return array_key_exists(strtolower($header->getFieldName()), $this->_required); + } + + /** Notify all Headers of the new charset */ + private function _notifyHeadersOfCharset($charset) + { + foreach ($this->_headers as $headerGroup) { + foreach ($headerGroup as $header) { + $header->setCharset($charset); + } + } + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->_factory = clone $this->_factory; + foreach ($this->_headers as $groupKey => $headerGroup) { + foreach ($headerGroup as $key => $header) { + $this->_headers[$groupKey][$key] = clone $header; + } + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php new file mode 100644 index 00000000..16d8d091 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMessage.php @@ -0,0 +1,649 @@ +getHeaders()->defineOrdering(array( + 'Return-Path', + 'Received', + 'DKIM-Signature', + 'DomainKey-Signature', + 'Sender', + 'Message-ID', + 'Date', + 'Subject', + 'From', + 'Reply-To', + 'To', + 'Cc', + 'Bcc', + 'MIME-Version', + 'Content-Type', + 'Content-Transfer-Encoding', + )); + $this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From')); + $this->getHeaders()->addTextHeader('MIME-Version', '1.0'); + $this->setDate(time()); + $this->setId($this->getId()); + $this->getHeaders()->addMailboxHeader('From'); + } + + /** + * Always returns {@link LEVEL_TOP} for a message instance. + * + * @return int + */ + public function getNestingLevel() + { + return self::LEVEL_TOP; + } + + /** + * Set the subject of this message. + * + * @param string $subject + * + * @return Swift_Mime_SimpleMessage + */ + public function setSubject($subject) + { + if (!$this->_setHeaderFieldModel('Subject', $subject)) { + $this->getHeaders()->addTextHeader('Subject', $subject); + } + + return $this; + } + + /** + * Get the subject of this message. + * + * @return string + */ + public function getSubject() + { + return $this->_getHeaderFieldModel('Subject'); + } + + /** + * Set the date at which this message was created. + * + * @param int $date + * + * @return Swift_Mime_SimpleMessage + */ + public function setDate($date) + { + if (!$this->_setHeaderFieldModel('Date', $date)) { + $this->getHeaders()->addDateHeader('Date', $date); + } + + return $this; + } + + /** + * Get the date at which this message was created. + * + * @return int + */ + public function getDate() + { + return $this->_getHeaderFieldModel('Date'); + } + + /** + * Set the return-path (the bounce address) of this message. + * + * @param string $address + * + * @return Swift_Mime_SimpleMessage + */ + public function setReturnPath($address) + { + if (!$this->_setHeaderFieldModel('Return-Path', $address)) { + $this->getHeaders()->addPathHeader('Return-Path', $address); + } + + return $this; + } + + /** + * Get the return-path (bounce address) of this message. + * + * @return string + */ + public function getReturnPath() + { + return $this->_getHeaderFieldModel('Return-Path'); + } + + /** + * Set the sender of this message. + * + * This does not override the From field, but it has a higher significance. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setSender($address, $name = null) + { + if (!is_array($address) && isset($name)) { + $address = array($address => $name); + } + + if (!$this->_setHeaderFieldModel('Sender', (array) $address)) { + $this->getHeaders()->addMailboxHeader('Sender', (array) $address); + } + + return $this; + } + + /** + * Get the sender of this message. + * + * @return string + */ + public function getSender() + { + return $this->_getHeaderFieldModel('Sender'); + } + + /** + * Add a From: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function addFrom($address, $name = null) + { + $current = $this->getFrom(); + $current[$address] = $name; + + return $this->setFrom($current); + } + + /** + * Set the from address of this message. + * + * You may pass an array of addresses if this message is from multiple people. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param string $addresses + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setFrom($addresses, $name = null) + { + if (!is_array($addresses) && isset($name)) { + $addresses = array($addresses => $name); + } + + if (!$this->_setHeaderFieldModel('From', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('From', (array) $addresses); + } + + return $this; + } + + /** + * Get the from address of this message. + * + * @return mixed + */ + public function getFrom() + { + return $this->_getHeaderFieldModel('From'); + } + + /** + * Add a Reply-To: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function addReplyTo($address, $name = null) + { + $current = $this->getReplyTo(); + $current[$address] = $name; + + return $this->setReplyTo($current); + } + + /** + * Set the reply-to address of this message. + * + * You may pass an array of addresses if replies will go to multiple people. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param string $addresses + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setReplyTo($addresses, $name = null) + { + if (!is_array($addresses) && isset($name)) { + $addresses = array($addresses => $name); + } + + if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses); + } + + return $this; + } + + /** + * Get the reply-to address of this message. + * + * @return string + */ + public function getReplyTo() + { + return $this->_getHeaderFieldModel('Reply-To'); + } + + /** + * Add a To: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function addTo($address, $name = null) + { + $current = $this->getTo(); + $current[$address] = $name; + + return $this->setTo($current); + } + + /** + * Set the to addresses of this message. + * + * If multiple recipients will receive the message an array should be used. + * Example: array('receiver@domain.org', 'other@domain.org' => 'A name') + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setTo($addresses, $name = null) + { + if (!is_array($addresses) && isset($name)) { + $addresses = array($addresses => $name); + } + + if (!$this->_setHeaderFieldModel('To', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('To', (array) $addresses); + } + + return $this; + } + + /** + * Get the To addresses of this message. + * + * @return array + */ + public function getTo() + { + return $this->_getHeaderFieldModel('To'); + } + + /** + * Add a Cc: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function addCc($address, $name = null) + { + $current = $this->getCc(); + $current[$address] = $name; + + return $this->setCc($current); + } + + /** + * Set the Cc addresses of this message. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setCc($addresses, $name = null) + { + if (!is_array($addresses) && isset($name)) { + $addresses = array($addresses => $name); + } + + if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Cc', (array) $addresses); + } + + return $this; + } + + /** + * Get the Cc address of this message. + * + * @return array + */ + public function getCc() + { + return $this->_getHeaderFieldModel('Cc'); + } + + /** + * Add a Bcc: address to this message. + * + * If $name is passed this name will be associated with the address. + * + * @param string $address + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function addBcc($address, $name = null) + { + $current = $this->getBcc(); + $current[$address] = $name; + + return $this->setBcc($current); + } + + /** + * Set the Bcc addresses of this message. + * + * If $name is passed and the first parameter is a string, this name will be + * associated with the address. + * + * @param mixed $addresses + * @param string $name optional + * + * @return Swift_Mime_SimpleMessage + */ + public function setBcc($addresses, $name = null) + { + if (!is_array($addresses) && isset($name)) { + $addresses = array($addresses => $name); + } + + if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) { + $this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses); + } + + return $this; + } + + /** + * Get the Bcc addresses of this message. + * + * @return array + */ + public function getBcc() + { + return $this->_getHeaderFieldModel('Bcc'); + } + + /** + * Set the priority of this message. + * + * The value is an integer where 1 is the highest priority and 5 is the lowest. + * + * @param int $priority + * + * @return Swift_Mime_SimpleMessage + */ + public function setPriority($priority) + { + $priorityMap = array( + 1 => 'Highest', + 2 => 'High', + 3 => 'Normal', + 4 => 'Low', + 5 => 'Lowest', + ); + $pMapKeys = array_keys($priorityMap); + if ($priority > max($pMapKeys)) { + $priority = max($pMapKeys); + } elseif ($priority < min($pMapKeys)) { + $priority = min($pMapKeys); + } + if (!$this->_setHeaderFieldModel('X-Priority', + sprintf('%d (%s)', $priority, $priorityMap[$priority]))) { + $this->getHeaders()->addTextHeader('X-Priority', + sprintf('%d (%s)', $priority, $priorityMap[$priority])); + } + + return $this; + } + + /** + * Get the priority of this message. + * + * The returned value is an integer where 1 is the highest priority and 5 + * is the lowest. + * + * @return int + */ + public function getPriority() + { + list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'), + '%[1-5]' + ); + + return isset($priority) ? $priority : 3; + } + + /** + * Ask for a delivery receipt from the recipient to be sent to $addresses + * + * @param array $addresses + * + * @return Swift_Mime_SimpleMessage + */ + public function setReadReceiptTo($addresses) + { + if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) { + $this->getHeaders() + ->addMailboxHeader('Disposition-Notification-To', $addresses); + } + + return $this; + } + + /** + * Get the addresses to which a read-receipt will be sent. + * + * @return string + */ + public function getReadReceiptTo() + { + return $this->_getHeaderFieldModel('Disposition-Notification-To'); + } + + /** + * Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart. + * + * @param Swift_Mime_MimeEntity $entity + * + * @return Swift_Mime_SimpleMessage + */ + public function attach(Swift_Mime_MimeEntity $entity) + { + $this->setChildren(array_merge($this->getChildren(), array($entity))); + + return $this; + } + + /** + * Remove an already attached entity. + * + * @param Swift_Mime_MimeEntity $entity + * + * @return Swift_Mime_SimpleMessage + */ + public function detach(Swift_Mime_MimeEntity $entity) + { + $newChildren = array(); + foreach ($this->getChildren() as $child) { + if ($entity !== $child) { + $newChildren[] = $child; + } + } + $this->setChildren($newChildren); + + return $this; + } + + /** + * Attach a {@link Swift_Mime_MimeEntity} and return it's CID source. + * This method should be used when embedding images or other data in a message. + * + * @param Swift_Mime_MimeEntity $entity + * + * @return string + */ + public function embed(Swift_Mime_MimeEntity $entity) + { + $this->attach($entity); + + return 'cid:'.$entity->getId(); + } + + /** + * Get this message as a complete string. + * + * @return string + */ + public function toString() + { + if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { + $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + $string = parent::toString(); + $this->setChildren($children); + } else { + $string = parent::toString(); + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @see toString() + * + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Write this message to a {@link Swift_InputByteStream}. + * + * @param Swift_InputByteStream $is + */ + public function toByteStream(Swift_InputByteStream $is) + { + if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { + $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); + parent::toByteStream($is); + $this->setChildren($children); + } else { + parent::toByteStream($is); + } + } + + /** @see Swift_Mime_SimpleMimeEntity::_getIdField() */ + protected function _getIdField() + { + return 'Message-ID'; + } + + /** Turn the body of this message into a child of itself if needed */ + protected function _becomeMimePart() + { + $part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(), + $this->_getCache(), $this->_getGrammar(), $this->_userCharset + ); + $part->setContentType($this->_userContentType); + $part->setBody($this->getBody()); + $part->setFormat($this->_userFormat); + $part->setDelSp($this->_userDelSp); + $part->_setNestingLevel($this->_getTopNestingLevel()); + + return $part; + } + + /** Get the highest nesting level nested inside this message */ + private function _getTopNestingLevel() + { + $highestLevel = $this->getNestingLevel(); + foreach ($this->getChildren() as $child) { + $childLevel = $child->getNestingLevel(); + if ($highestLevel < $childLevel) { + $highestLevel = $childLevel; + } + } + + return $highestLevel; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php new file mode 100644 index 00000000..60492920 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/SimpleMimeEntity.php @@ -0,0 +1,866 @@ + array(self::LEVEL_TOP, self::LEVEL_MIXED), + 'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE), + 'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED), + ); + + /** A set of filter rules to define what level an entity should be nested at */ + private $_compoundLevelFilters = array(); + + /** The nesting level of this entity */ + private $_nestingLevel = self::LEVEL_ALTERNATIVE; + + /** A KeyCache instance used during encoding and streaming */ + private $_cache; + + /** Direct descendants of this entity */ + private $_immediateChildren = array(); + + /** All descendants of this entity */ + private $_children = array(); + + /** The maximum line length of the body of this entity */ + private $_maxLineLength = 78; + + /** The order in which alternative mime types should appear */ + private $_alternativePartOrder = array( + 'text/plain' => 1, + 'text/html' => 2, + 'multipart/related' => 3, + ); + + /** The CID of this entity */ + private $_id; + + /** The key used for accessing the cache */ + private $_cacheKey; + + protected $_userContentType; + + /** + * Create a new SimpleMimeEntity with $headers, $encoder and $cache. + * + * @param Swift_Mime_HeaderSet $headers + * @param Swift_Mime_ContentEncoder $encoder + * @param Swift_KeyCache $cache + * @param Swift_Mime_Grammar $grammar + */ + public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar) + { + $this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true)); + $this->_cache = $cache; + $this->_headers = $headers; + $this->_grammar = $grammar; + $this->setEncoder($encoder); + $this->_headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); + + // This array specifies that, when the entire MIME document contains + // $compoundLevel, then for each child within $level, if its Content-Type + // is $contentType then it should be treated as if it's level is + // $neededLevel instead. I tried to write that unambiguously! :-\ + // Data Structure: + // array ( + // $compoundLevel => array( + // $level => array( + // $contentType => $neededLevel + // ) + // ) + // ) + + $this->_compoundLevelFilters = array( + (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array( + self::LEVEL_ALTERNATIVE => array( + 'text/plain' => self::LEVEL_ALTERNATIVE, + 'text/html' => self::LEVEL_RELATED, + ), + ), + ); + + $this->_id = $this->getRandomId(); + } + + /** + * Generate a new Content-ID or Message-ID for this MIME entity. + * + * @return string + */ + public function generateId() + { + $this->setId($this->getRandomId()); + + return $this->_id; + } + + /** + * Get the {@link Swift_Mime_HeaderSet} for this entity. + * + * @return Swift_Mime_HeaderSet + */ + public function getHeaders() + { + return $this->_headers; + } + + /** + * Get the nesting level of this entity. + * + * @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE + * + * @return int + */ + public function getNestingLevel() + { + return $this->_nestingLevel; + } + + /** + * Get the Content-type of this entity. + * + * @return string + */ + public function getContentType() + { + return $this->_getHeaderFieldModel('Content-Type'); + } + + /** + * Set the Content-type of this entity. + * + * @param string $type + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setContentType($type) + { + $this->_setContentTypeInHeaders($type); + // Keep track of the value so that if the content-type changes automatically + // due to added child entities, it can be restored if they are later removed + $this->_userContentType = $type; + + return $this; + } + + /** + * Get the CID of this entity. + * + * The CID will only be present in headers if a Content-ID header is present. + * + * @return string + */ + public function getId() + { + $tmp = (array) $this->_getHeaderFieldModel($this->_getIdField()); + + return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id; + } + + /** + * Set the CID of this entity. + * + * @param string $id + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setId($id) + { + if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) { + $this->_headers->addIdHeader($this->_getIdField(), $id); + } + $this->_id = $id; + + return $this; + } + + /** + * Get the description of this entity. + * + * This value comes from the Content-Description header if set. + * + * @return string + */ + public function getDescription() + { + return $this->_getHeaderFieldModel('Content-Description'); + } + + /** + * Set the description of this entity. + * + * This method sets a value in the Content-ID header. + * + * @param string $description + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setDescription($description) + { + if (!$this->_setHeaderFieldModel('Content-Description', $description)) { + $this->_headers->addTextHeader('Content-Description', $description); + } + + return $this; + } + + /** + * Get the maximum line length of the body of this entity. + * + * @return int + */ + public function getMaxLineLength() + { + return $this->_maxLineLength; + } + + /** + * Set the maximum line length of lines in this body. + * + * Though not enforced by the library, lines should not exceed 1000 chars. + * + * @param int $length + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setMaxLineLength($length) + { + $this->_maxLineLength = $length; + + return $this; + } + + /** + * Get all children added to this entity. + * + * @return array of Swift_Mime_Entity + */ + public function getChildren() + { + return $this->_children; + } + + /** + * Set all children of this entity. + * + * @param array $children Swift_Mime_Entity instances + * @param int $compoundLevel For internal use only + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setChildren(array $children, $compoundLevel = null) + { + // TODO: Try to refactor this logic + + $compoundLevel = isset($compoundLevel) + ? $compoundLevel + : $this->_getCompoundLevel($children) + ; + + $immediateChildren = array(); + $grandchildren = array(); + $newContentType = $this->_userContentType; + + foreach ($children as $child) { + $level = $this->_getNeededChildLevel($child, $compoundLevel); + if (empty($immediateChildren)) { + //first iteration + $immediateChildren = array($child); + } else { + $nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + if ($nextLevel == $level) { + $immediateChildren[] = $child; + } elseif ($level < $nextLevel) { + // Re-assign immediateChildren to grandchildren + $grandchildren = array_merge($grandchildren, $immediateChildren); + // Set new children + $immediateChildren = array($child); + } else { + $grandchildren[] = $child; + } + } + } + + if (!empty($immediateChildren)) { + $lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); + + // Determine which composite media type is needed to accommodate the + // immediate children + foreach ($this->_compositeRanges as $mediaType => $range) { + if ($lowestLevel > $range[0] + && $lowestLevel <= $range[1]) { + $newContentType = $mediaType; + break; + } + } + + // Put any grandchildren in a subpart + if (!empty($grandchildren)) { + $subentity = $this->_createChild(); + $subentity->_setNestingLevel($lowestLevel); + $subentity->setChildren($grandchildren, $compoundLevel); + array_unshift($immediateChildren, $subentity); + } + } + + $this->_immediateChildren = $immediateChildren; + $this->_children = $children; + $this->_setContentTypeInHeaders($newContentType); + $this->_fixHeaders(); + $this->_sortChildren(); + + return $this; + } + + /** + * Get the body of this entity as a string. + * + * @return string + */ + public function getBody() + { + return ($this->_body instanceof Swift_OutputByteStream) + ? $this->_readStream($this->_body) + : $this->_body; + } + + /** + * Set the body of this entity, either as a string, or as an instance of + * {@link Swift_OutputByteStream}. + * + * @param mixed $body + * @param string $contentType optional + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setBody($body, $contentType = null) + { + if ($body !== $this->_body) { + $this->_clearCache(); + } + + $this->_body = $body; + if (isset($contentType)) { + $this->setContentType($contentType); + } + + return $this; + } + + /** + * Get the encoder used for the body of this entity. + * + * @return Swift_Mime_ContentEncoder + */ + public function getEncoder() + { + return $this->_encoder; + } + + /** + * Set the encoder used for the body of this entity. + * + * @param Swift_Mime_ContentEncoder $encoder + * + * @return Swift_Mime_SimpleMimeEntity + */ + public function setEncoder(Swift_Mime_ContentEncoder $encoder) + { + if ($encoder !== $this->_encoder) { + $this->_clearCache(); + } + + $this->_encoder = $encoder; + $this->_setEncoding($encoder->getName()); + $this->_notifyEncoderChanged($encoder); + + return $this; + } + + /** + * Get the boundary used to separate children in this entity. + * + * @return string + */ + public function getBoundary() + { + if (!isset($this->_boundary)) { + $this->_boundary = '_=_swift_v4_'.time().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_'; + } + + return $this->_boundary; + } + + /** + * Set the boundary used to separate children in this entity. + * + * @param string $boundary + * + * @return Swift_Mime_SimpleMimeEntity + * + * @throws Swift_RfcComplianceException + */ + public function setBoundary($boundary) + { + $this->_assertValidBoundary($boundary); + $this->_boundary = $boundary; + + return $this; + } + + /** + * Receive notification that the charset of this entity, or a parent entity + * has changed. + * + * @param string $charset + */ + public function charsetChanged($charset) + { + $this->_notifyCharsetChanged($charset); + } + + /** + * Receive notification that the encoder of this entity or a parent entity + * has changed. + * + * @param Swift_Mime_ContentEncoder $encoder + */ + public function encoderChanged(Swift_Mime_ContentEncoder $encoder) + { + $this->_notifyEncoderChanged($encoder); + } + + /** + * Get this entire entity as a string. + * + * @return string + */ + public function toString() + { + $string = $this->_headers->toString(); + $string .= $this->_bodyToString(); + + return $string; + } + + /** + * Get this entire entity as a string. + * + * @return string + */ + protected function _bodyToString() + { + $string = ''; + + if (isset($this->_body) && empty($this->_immediateChildren)) { + if ($this->_cache->hasKey($this->_cacheKey, 'body')) { + $body = $this->_cache->getString($this->_cacheKey, 'body'); + } else { + $body = "\r\n".$this->_encoder->encodeString($this->getBody(), 0, + $this->getMaxLineLength() + ); + $this->_cache->setString($this->_cacheKey, 'body', $body, + Swift_KeyCache::MODE_WRITE + ); + } + $string .= $body; + } + + if (!empty($this->_immediateChildren)) { + foreach ($this->_immediateChildren as $child) { + $string .= "\r\n\r\n--".$this->getBoundary()."\r\n"; + $string .= $child->toString(); + } + $string .= "\r\n\r\n--".$this->getBoundary()."--\r\n"; + } + + return $string; + } + + /** + * Returns a string representation of this object. + * + * @see toString() + * + * @return string + */ + public function __toString() + { + return $this->toString(); + } + + /** + * Write this entire entity to a {@see Swift_InputByteStream}. + * + * @param Swift_InputByteStream + */ + public function toByteStream(Swift_InputByteStream $is) + { + $is->write($this->_headers->toString()); + $is->commit(); + + $this->_bodyToByteStream($is); + } + + /** + * Write this entire entity to a {@link Swift_InputByteStream}. + * + * @param Swift_InputByteStream + */ + protected function _bodyToByteStream(Swift_InputByteStream $is) + { + if (empty($this->_immediateChildren)) { + if (isset($this->_body)) { + if ($this->_cache->hasKey($this->_cacheKey, 'body')) { + $this->_cache->exportToByteStream($this->_cacheKey, 'body', $is); + } else { + $cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body'); + if ($cacheIs) { + $is->bind($cacheIs); + } + + $is->write("\r\n"); + + if ($this->_body instanceof Swift_OutputByteStream) { + $this->_body->setReadPointer(0); + + $this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength()); + } else { + $is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); + } + + if ($cacheIs) { + $is->unbind($cacheIs); + } + } + } + } + + if (!empty($this->_immediateChildren)) { + foreach ($this->_immediateChildren as $child) { + $is->write("\r\n\r\n--".$this->getBoundary()."\r\n"); + $child->toByteStream($is); + } + $is->write("\r\n\r\n--".$this->getBoundary()."--\r\n"); + } + } + + /** + * Get the name of the header that provides the ID of this entity + */ + protected function _getIdField() + { + return 'Content-ID'; + } + + /** + * Get the model data (usually an array or a string) for $field. + */ + protected function _getHeaderFieldModel($field) + { + if ($this->_headers->has($field)) { + return $this->_headers->get($field)->getFieldBodyModel(); + } + } + + /** + * Set the model data for $field. + */ + protected function _setHeaderFieldModel($field, $model) + { + if ($this->_headers->has($field)) { + $this->_headers->get($field)->setFieldBodyModel($model); + + return true; + } else { + return false; + } + } + + /** + * Get the parameter value of $parameter on $field header. + */ + protected function _getHeaderParameter($field, $parameter) + { + if ($this->_headers->has($field)) { + return $this->_headers->get($field)->getParameter($parameter); + } + } + + /** + * Set the parameter value of $parameter on $field header. + */ + protected function _setHeaderParameter($field, $parameter, $value) + { + if ($this->_headers->has($field)) { + $this->_headers->get($field)->setParameter($parameter, $value); + + return true; + } else { + return false; + } + } + + /** + * Re-evaluate what content type and encoding should be used on this entity. + */ + protected function _fixHeaders() + { + if (count($this->_immediateChildren)) { + $this->_setHeaderParameter('Content-Type', 'boundary', + $this->getBoundary() + ); + $this->_headers->remove('Content-Transfer-Encoding'); + } else { + $this->_setHeaderParameter('Content-Type', 'boundary', null); + $this->_setEncoding($this->_encoder->getName()); + } + } + + /** + * Get the KeyCache used in this entity. + * + * @return Swift_KeyCache + */ + protected function _getCache() + { + return $this->_cache; + } + + /** + * Get the grammar used for validation. + * + * @return Swift_Mime_Grammar + */ + protected function _getGrammar() + { + return $this->_grammar; + } + + /** + * Empty the KeyCache for this entity. + */ + protected function _clearCache() + { + $this->_cache->clearKey($this->_cacheKey, 'body'); + } + + /** + * Returns a random Content-ID or Message-ID. + * + * @return string + */ + protected function getRandomId() + { + $idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); + $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated'; + $id = $idLeft.'@'.$idRight; + + try { + $this->_assertValidId($id); + } catch (Swift_RfcComplianceException $e) { + $id = $idLeft.'@swift.generated'; + } + + return $id; + } + + private function _readStream(Swift_OutputByteStream $os) + { + $string = ''; + while (false !== $bytes = $os->read(8192)) { + $string .= $bytes; + } + + return $string; + } + + private function _setEncoding($encoding) + { + if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { + $this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding); + } + } + + private function _assertValidBoundary($boundary) + { + if (!preg_match( + '/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', + $boundary)) { + throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.'); + } + } + + private function _setContentTypeInHeaders($type) + { + if (!$this->_setHeaderFieldModel('Content-Type', $type)) { + $this->_headers->addParameterizedHeader('Content-Type', $type); + } + } + + private function _setNestingLevel($level) + { + $this->_nestingLevel = $level; + } + + private function _getCompoundLevel($children) + { + $level = 0; + foreach ($children as $child) { + $level |= $child->getNestingLevel(); + } + + return $level; + } + + private function _getNeededChildLevel($child, $compoundLevel) + { + $filter = array(); + foreach ($this->_compoundLevelFilters as $bitmask => $rules) { + if (($compoundLevel & $bitmask) === $bitmask) { + $filter = $rules + $filter; + } + } + + $realLevel = $child->getNestingLevel(); + $lowercaseType = strtolower($child->getContentType()); + + if (isset($filter[$realLevel]) + && isset($filter[$realLevel][$lowercaseType])) { + return $filter[$realLevel][$lowercaseType]; + } else { + return $realLevel; + } + } + + private function _createChild() + { + return new self($this->_headers->newInstance(), + $this->_encoder, $this->_cache, $this->_grammar); + } + + private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) + { + foreach ($this->_immediateChildren as $child) { + $child->encoderChanged($encoder); + } + } + + private function _notifyCharsetChanged($charset) + { + $this->_encoder->charsetChanged($charset); + $this->_headers->charsetChanged($charset); + foreach ($this->_immediateChildren as $child) { + $child->charsetChanged($charset); + } + } + + private function _sortChildren() + { + $shouldSort = false; + foreach ($this->_immediateChildren as $child) { + // NOTE: This include alternative parts moved into a related part + if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) { + $shouldSort = true; + break; + } + } + + // Sort in order of preference, if there is one + if ($shouldSort) { + usort($this->_immediateChildren, array($this, '_childSortAlgorithm')); + } + } + + private function _childSortAlgorithm($a, $b) + { + $typePrefs = array(); + $types = array( + strtolower($a->getContentType()), + strtolower($b->getContentType()), + ); + foreach ($types as $type) { + $typePrefs[] = (array_key_exists($type, $this->_alternativePartOrder)) + ? $this->_alternativePartOrder[$type] + : (max($this->_alternativePartOrder) + 1); + } + + return ($typePrefs[0] >= $typePrefs[1]) ? 1 : -1; + } + + // -- Destructor + + /** + * Empties it's own contents from the cache. + */ + public function __destruct() + { + $this->_cache->clearAll($this->_cacheKey); + } + + /** + * Throws an Exception if the id passed does not comply with RFC 2822. + * + * @param string $id + * + * @throws Swift_RfcComplianceException + */ + private function _assertValidId($id) + { + if (!preg_match( + '/^'.$this->_grammar->getDefinition('id-left').'@'. + $this->_grammar->getDefinition('id-right').'$/D', + $id + )) { + throw new Swift_RfcComplianceException( + 'Invalid ID given <'.$id.'>' + ); + } + } + + /** + * Make a deep copy of object + */ + public function __clone() + { + $this->_headers = clone $this->_headers; + $this->_encoder = clone $this->_encoder; + $this->_cacheKey = uniqid(); + $this->generateId(); + $children = array(); + foreach ($this->_children as $pos => $child) { + $children[$pos] = clone $child; + } + $this->setChildren($children); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php new file mode 100644 index 00000000..5702d1c1 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/MimePart.php @@ -0,0 +1,59 @@ +createDependenciesFor('mime.part') + ); + + if (!isset($charset)) { + $charset = Swift_DependencyContainer::getInstance() + ->lookup('properties.charset'); + } + $this->setBody($body); + $this->setCharset($charset); + if ($contentType) { + $this->setContentType($contentType); + } + } + + /** + * Create a new MimePart. + * + * @param string $body + * @param string $contentType + * @param string $charset + * + * @return Swift_Mime_MimePart + */ + public static function newInstance($body = null, $contentType = null, $charset = null) + { + return new self($body, $contentType, $charset); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php new file mode 100644 index 00000000..726d83ca --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/NullTransport.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pretends messages have been sent, but just ignores them. + * + * @author Fabien Potencier + */ +class Swift_NullTransport extends Swift_Transport_NullTransport +{ + /** + * Create a new NullTransport. + */ + public function __construct() + { + call_user_func_array( + array($this, 'Swift_Transport_NullTransport::__construct'), + Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.null') + ); + } + + /** + * Create a new NullTransport instance. + * + * @return Swift_NullTransport + */ + public static function newInstance() + { + return new self(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php new file mode 100644 index 00000000..0c2783f0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/OutputByteStream.php @@ -0,0 +1,46 @@ +setThreshold($threshold); + $this->setSleepTime($sleep); + $this->_sleeper = $sleeper; + } + + /** + * Set the number of emails to send before restarting. + * + * @param int $threshold + */ + public function setThreshold($threshold) + { + $this->_threshold = $threshold; + } + + /** + * Get the number of emails to send before restarting. + * + * @return int + */ + public function getThreshold() + { + return $this->_threshold; + } + + /** + * Set the number of seconds to sleep for during a restart. + * + * @param int $sleep time + */ + public function setSleepTime($sleep) + { + $this->_sleep = $sleep; + } + + /** + * Get the number of seconds to sleep for during a restart. + * + * @return int + */ + public function getSleepTime() + { + return $this->_sleep; + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + ++$this->_counter; + if ($this->_counter >= $this->_threshold) { + $transport = $evt->getTransport(); + $transport->stop(); + if ($this->_sleep) { + $this->sleep($this->_sleep); + } + $transport->start(); + $this->_counter = 0; + } + } + + /** + * Sleep for $seconds. + * + * @param int $seconds + */ + public function sleep($seconds) + { + if (isset($this->_sleeper)) { + $this->_sleeper->sleep($seconds); + } else { + sleep($seconds); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php new file mode 100644 index 00000000..af1701a0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/BandwidthMonitorPlugin.php @@ -0,0 +1,164 @@ +getMessage(); + $message->toByteStream($this); + } + + /** + * Invoked immediately following a command being sent. + * + * @param Swift_Events_CommandEvent $evt + */ + public function commandSent(Swift_Events_CommandEvent $evt) + { + $command = $evt->getCommand(); + $this->_out += strlen($command); + } + + /** + * Invoked immediately following a response coming back. + * + * @param Swift_Events_ResponseEvent $evt + */ + public function responseReceived(Swift_Events_ResponseEvent $evt) + { + $response = $evt->getResponse(); + $this->_in += strlen($response); + } + + /** + * Called when a message is sent so that the outgoing counter can be increased. + * + * @param string $bytes + */ + public function write($bytes) + { + $this->_out += strlen($bytes); + foreach ($this->_mirrors as $stream) { + $stream->write($bytes); + } + } + + /** + * Not used. + */ + public function commit() + { + } + + /** + * Attach $is to this stream. + * + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + */ + public function bind(Swift_InputByteStream $is) + { + $this->_mirrors[] = $is; + } + + /** + * Remove an already bound stream. + * + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + */ + public function unbind(Swift_InputByteStream $is) + { + foreach ($this->_mirrors as $k => $stream) { + if ($is === $stream) { + unset($this->_mirrors[$k]); + } + } + } + + /** + * Not used. + */ + public function flushBuffers() + { + foreach ($this->_mirrors as $stream) { + $stream->flushBuffers(); + } + } + + /** + * Get the total number of bytes sent to the server. + * + * @return int + */ + public function getBytesOut() + { + return $this->_out; + } + + /** + * Get the total number of bytes received from the server. + * + * @return int + */ + public function getBytesIn() + { + return $this->_in; + } + + /** + * Reset the internal counters to zero. + */ + public function reset() + { + $this->_out = 0; + $this->_in = 0; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php new file mode 100644 index 00000000..86184339 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Decorator/Replacements.php @@ -0,0 +1,31 @@ + + * $replacements = array( + * "address1@domain.tld" => array("{a}" => "b", "{c}" => "d"), + * "address2@domain.tld" => array("{a}" => "x", "{c}" => "y") + * ) + * + * + * When using an instance of {@link Swift_Plugins_Decorator_Replacements}, + * the object should return just the array of replacements for the address + * given to {@link Swift_Plugins_Decorator_Replacements::getReplacementsFor()}. + * + * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements + */ + public function __construct($replacements) + { + $this->setReplacements($replacements); + } + + /** + * Sets replacements. + * + * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements + * + * @see __construct() + */ + public function setReplacements($replacements) + { + if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) { + $this->_replacements = (array) $replacements; + } else { + $this->_replacements = $replacements; + } + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $this->_restoreMessage($message); + $to = array_keys($message->getTo()); + $address = array_shift($to); + if ($replacements = $this->getReplacementsFor($address)) { + $body = $message->getBody(); + $search = array_keys($replacements); + $replace = array_values($replacements); + $bodyReplaced = str_replace( + $search, $replace, $body + ); + if ($body != $bodyReplaced) { + $this->_originalBody = $body; + $message->setBody($bodyReplaced); + } + + foreach ($message->getHeaders()->getAll() as $header) { + $body = $header->getFieldBodyModel(); + $count = 0; + if (is_array($body)) { + $bodyReplaced = array(); + foreach ($body as $key => $value) { + $count1 = 0; + $count2 = 0; + $key = is_string($key) ? str_replace($search, $replace, $key, $count1) : $key; + $value = is_string($value) ? str_replace($search, $replace, $value, $count2) : $value; + $bodyReplaced[$key] = $value; + + if (!$count && ($count1 || $count2)) { + $count = 1; + } + } + } else { + $bodyReplaced = str_replace($search, $replace, $body, $count); + } + + if ($count) { + $this->_originalHeaders[$header->getFieldName()] = $body; + $header->setFieldBodyModel($bodyReplaced); + } + } + + $children = (array) $message->getChildren(); + foreach ($children as $child) { + list($type, ) = sscanf($child->getContentType(), '%[^/]/%s'); + if ('text' == $type) { + $body = $child->getBody(); + $bodyReplaced = str_replace( + $search, $replace, $body + ); + if ($body != $bodyReplaced) { + $child->setBody($bodyReplaced); + $this->_originalChildBodies[$child->getId()] = $body; + } + } + } + $this->_lastMessage = $message; + } + } + + /** + * Find a map of replacements for the address. + * + * If this plugin was provided with a delegate instance of + * {@link Swift_Plugins_Decorator_Replacements} then the call will be + * delegated to it. Otherwise, it will attempt to find the replacements + * from the array provided in the constructor. + * + * If no replacements can be found, an empty value (NULL) is returned. + * + * @param string $address + * + * @return array + */ + public function getReplacementsFor($address) + { + if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) { + return $this->_replacements->getReplacementsFor($address); + } else { + return isset($this->_replacements[$address]) + ? $this->_replacements[$address] + : null + ; + } + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $this->_restoreMessage($evt->getMessage()); + } + + /** Restore a changed message back to its original state */ + private function _restoreMessage(Swift_Mime_Message $message) + { + if ($this->_lastMessage === $message) { + if (isset($this->_originalBody)) { + $message->setBody($this->_originalBody); + $this->_originalBody = null; + } + if (!empty($this->_originalHeaders)) { + foreach ($message->getHeaders()->getAll() as $header) { + if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) { + $header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]); + } + } + $this->_originalHeaders = array(); + } + if (!empty($this->_originalChildBodies)) { + $children = (array) $message->getChildren(); + foreach ($children as $child) { + $id = $child->getId(); + if (array_key_exists($id, $this->_originalChildBodies)) { + $child->setBody($this->_originalChildBodies[$id]); + } + } + $this->_originalChildBodies = array(); + } + $this->_lastMessage = null; + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php new file mode 100644 index 00000000..5bd0bbda --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/ImpersonatePlugin.php @@ -0,0 +1,68 @@ +_sender = $sender; + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $headers = $message->getHeaders(); + + // save current recipients + $headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath()); + + // replace them with the one to send to + $message->setReturnPath($this->_sender); + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + + // restore original headers + $headers = $message->getHeaders(); + + if ($headers->has('X-Swift-Return-Path')) { + $message->setReturnPath($headers->get('X-Swift-Return-Path')->getAddress()); + $headers->removeAll('X-Swift-Return-Path'); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php new file mode 100644 index 00000000..915e7206 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Logger.php @@ -0,0 +1,36 @@ +_logger = $logger; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + $this->_logger->add($entry); + } + + /** + * Clear the log contents. + */ + public function clear() + { + $this->_logger->clear(); + } + + /** + * Get this log as a string. + * + * @return string + */ + public function dump() + { + return $this->_logger->dump(); + } + + /** + * Invoked immediately following a command being sent. + * + * @param Swift_Events_CommandEvent $evt + */ + public function commandSent(Swift_Events_CommandEvent $evt) + { + $command = $evt->getCommand(); + $this->_logger->add(sprintf(">> %s", $command)); + } + + /** + * Invoked immediately following a response coming back. + * + * @param Swift_Events_ResponseEvent $evt + */ + public function responseReceived(Swift_Events_ResponseEvent $evt) + { + $response = $evt->getResponse(); + $this->_logger->add(sprintf("<< %s", $response)); + } + + /** + * Invoked just before a Transport is started. + * + * @param Swift_Events_TransportChangeEvent $evt + */ + public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) + { + $transportName = get_class($evt->getSource()); + $this->_logger->add(sprintf("++ Starting %s", $transportName)); + } + + /** + * Invoked immediately after the Transport is started. + * + * @param Swift_Events_TransportChangeEvent $evt + */ + public function transportStarted(Swift_Events_TransportChangeEvent $evt) + { + $transportName = get_class($evt->getSource()); + $this->_logger->add(sprintf("++ %s started", $transportName)); + } + + /** + * Invoked just before a Transport is stopped. + * + * @param Swift_Events_TransportChangeEvent $evt + */ + public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) + { + $transportName = get_class($evt->getSource()); + $this->_logger->add(sprintf("++ Stopping %s", $transportName)); + } + + /** + * Invoked immediately after the Transport is stopped. + * + * @param Swift_Events_TransportChangeEvent $evt + */ + public function transportStopped(Swift_Events_TransportChangeEvent $evt) + { + $transportName = get_class($evt->getSource()); + $this->_logger->add(sprintf("++ %s stopped", $transportName)); + } + + /** + * Invoked as a TransportException is thrown in the Transport system. + * + * @param Swift_Events_TransportExceptionEvent $evt + */ + public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt) + { + $e = $evt->getException(); + $message = $e->getMessage(); + $this->_logger->add(sprintf("!! %s", $message)); + $message .= PHP_EOL; + $message .= 'Log data:'.PHP_EOL; + $message .= $this->_logger->dump(); + $evt->cancelBubble(); + throw new Swift_TransportException($message); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php new file mode 100644 index 00000000..f1739e8e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/ArrayLogger.php @@ -0,0 +1,72 @@ +_size = $size; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + $this->_log[] = $entry; + while (count($this->_log) > $this->_size) { + array_shift($this->_log); + } + } + + /** + * Clear the log contents. + */ + public function clear() + { + $this->_log = array(); + } + + /** + * Get this log as a string. + * + * @return string + */ + public function dump() + { + return implode(PHP_EOL, $this->_log); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php new file mode 100644 index 00000000..e8b6c18a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Loggers/EchoLogger.php @@ -0,0 +1,58 @@ +_isHtml = $isHtml; + } + + /** + * Add a log entry. + * + * @param string $entry + */ + public function add($entry) + { + if ($this->_isHtml) { + printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '
', PHP_EOL); + } else { + printf('%s%s', $entry, PHP_EOL); + } + } + + /** + * Not implemented. + */ + public function clear() + { + } + + /** + * Not implemented. + */ + public function dump() + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php new file mode 100644 index 00000000..a02ad98e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/MessageLogger.php @@ -0,0 +1,75 @@ +messages = array(); + } + + /** + * Get the message list + * + * @return array + */ + public function getMessages() + { + return $this->messages; + } + + /** + * Get the message count + * + * @return int count + */ + public function countMessages() + { + return count($this->messages); + } + + /** + * Empty the message list + * + */ + public function clear() + { + $this->messages = array(); + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $this->messages[] = clone $evt->getMessage(); + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php new file mode 100644 index 00000000..1e18016a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Pop/Pop3Connection.php @@ -0,0 +1,31 @@ +_host = $host; + $this->_port = $port; + $this->_crypto = $crypto; + } + + /** + * Create a new PopBeforeSmtpPlugin for $host and $port. + * + * @param string $host + * @param int $port + * @param string $crypto as "tls" or "ssl" + * + * @return Swift_Plugins_PopBeforeSmtpPlugin + */ + public static function newInstance($host, $port = 110, $crypto = null) + { + return new self($host, $port, $crypto); + } + + /** + * Set a Pop3Connection to delegate to instead of connecting directly. + * + * @param Swift_Plugins_Pop_Pop3Connection $connection + * + * @return Swift_Plugins_PopBeforeSmtpPlugin + */ + public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection) + { + $this->_connection = $connection; + + return $this; + } + + /** + * Bind this plugin to a specific SMTP transport instance. + * + * @param Swift_Transport + */ + public function bindSmtp(Swift_Transport $smtp) + { + $this->_transport = $smtp; + } + + /** + * Set the connection timeout in seconds (default 10). + * + * @param int $timeout + * + * @return Swift_Plugins_PopBeforeSmtpPlugin + */ + public function setTimeout($timeout) + { + $this->_timeout = (int) $timeout; + + return $this; + } + + /** + * Set the username to use when connecting (if needed). + * + * @param string $username + * + * @return Swift_Plugins_PopBeforeSmtpPlugin + */ + public function setUsername($username) + { + $this->_username = $username; + + return $this; + } + + /** + * Set the password to use when connecting (if needed). + * + * @param string $password + * + * @return Swift_Plugins_PopBeforeSmtpPlugin + */ + public function setPassword($password) + { + $this->_password = $password; + + return $this; + } + + /** + * Connect to the POP3 host and authenticate. + * + * @throws Swift_Plugins_Pop_Pop3Exception if connection fails + */ + public function connect() + { + if (isset($this->_connection)) { + $this->_connection->connect(); + } else { + if (!isset($this->_socket)) { + if (!$socket = fsockopen( + $this->_getHostString(), $this->_port, $errno, $errstr, $this->_timeout)) { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('Failed to connect to POP3 host [%s]: %s', $this->_host, $errstr) + ); + } + $this->_socket = $socket; + + if (false === $greeting = fgets($this->_socket)) { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('Failed to connect to POP3 host [%s]', trim($greeting)) + ); + } + + $this->_assertOk($greeting); + + if ($this->_username) { + $this->_command(sprintf("USER %s\r\n", $this->_username)); + $this->_command(sprintf("PASS %s\r\n", $this->_password)); + } + } + } + } + + /** + * Disconnect from the POP3 host. + */ + public function disconnect() + { + if (isset($this->_connection)) { + $this->_connection->disconnect(); + } else { + $this->_command("QUIT\r\n"); + if (!fclose($this->_socket)) { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('POP3 host [%s] connection could not be stopped', $this->_host) + ); + } + $this->_socket = null; + } + } + + /** + * Invoked just before a Transport is started. + * + * @param Swift_Events_TransportChangeEvent $evt + */ + public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) + { + if (isset($this->_transport)) { + if ($this->_transport !== $evt->getTransport()) { + return; + } + } + + $this->connect(); + $this->disconnect(); + } + + /** + * Not used. + */ + public function transportStarted(Swift_Events_TransportChangeEvent $evt) + { + } + + /** + * Not used. + */ + public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) + { + } + + /** + * Not used. + */ + public function transportStopped(Swift_Events_TransportChangeEvent $evt) + { + } + + private function _command($command) + { + if (!fwrite($this->_socket, $command)) { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('Failed to write command [%s] to POP3 host', trim($command)) + ); + } + + if (false === $response = fgets($this->_socket)) { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('Failed to read from POP3 host after command [%s]', trim($command)) + ); + } + + $this->_assertOk($response); + + return $response; + } + + private function _assertOk($response) + { + if (substr($response, 0, 3) != '+OK') { + throw new Swift_Plugins_Pop_Pop3Exception( + sprintf('POP3 command failed [%s]', trim($response)) + ); + } + } + + private function _getHostString() + { + $host = $this->_host; + switch (strtolower($this->_crypto)) { + case 'ssl': + $host = 'ssl://'.$host; + break; + + case 'tls': + $host = 'tls://'.$host; + break; + } + + return $host; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php new file mode 100644 index 00000000..cc86134c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/RedirectingPlugin.php @@ -0,0 +1,211 @@ +_recipient = $recipient; + $this->_whitelist = $whitelist; + } + + /** + * Set the recipient of all messages. + * + * @param mixed $recipient + */ + public function setRecipient($recipient) + { + $this->_recipient = $recipient; + } + + /** + * Get the recipient of all messages. + * + * @return mixed + */ + public function getRecipient() + { + return $this->_recipient; + } + + /** + * Set a list of regular expressions to whitelist certain recipients + * + * @param array $whitelist + */ + public function setWhitelist(array $whitelist) + { + $this->_whitelist = $whitelist; + } + + /** + * Get the whitelist + * + * @return array + */ + public function getWhitelist() + { + return $this->_whitelist; + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $headers = $message->getHeaders(); + + // conditionally save current recipients + + if ($headers->has('to')) { + $headers->addMailboxHeader('X-Swift-To', $message->getTo()); + } + + if ($headers->has('cc')) { + $headers->addMailboxHeader('X-Swift-Cc', $message->getCc()); + } + + if ($headers->has('bcc')) { + $headers->addMailboxHeader('X-Swift-Bcc', $message->getBcc()); + } + + // Filter remaining headers against whitelist + $this->_filterHeaderSet($headers, 'To'); + $this->_filterHeaderSet($headers, 'Cc'); + $this->_filterHeaderSet($headers, 'Bcc'); + + // Add each hard coded recipient + $to = $message->getTo(); + if (null === $to) { + $to = array(); + } + + foreach ( (array) $this->_recipient as $recipient) { + if (!array_key_exists($recipient, $to)) { + $message->addTo($recipient); + } + } + } + + /** + * Filter header set against a whitelist of regular expressions + * + * @param Swift_Mime_HeaderSet $headerSet + * @param string $type + */ + private function _filterHeaderSet(Swift_Mime_HeaderSet $headerSet, $type) + { + foreach ($headerSet->getAll($type) as $headers) { + $headers->setNameAddresses($this->_filterNameAddresses($headers->getNameAddresses())); + } + } + + /** + * Filtered list of addresses => name pairs + * + * @param array $recipients + * @return array + */ + private function _filterNameAddresses(array $recipients) + { + $filtered = array(); + + foreach ($recipients as $address => $name) { + if ($this->_isWhitelisted($address)) { + $filtered[$address] = $name; + } + } + + return $filtered; + } + + /** + * Matches address against whitelist of regular expressions + * + * @param $recipient + * @return bool + */ + protected function _isWhitelisted($recipient) + { + if (in_array($recipient, (array) $this->_recipient)) { + return true; + } + + foreach ($this->_whitelist as $pattern) { + if (preg_match($pattern, $recipient)) { + return true; + } + } + + return false; + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $this->_restoreMessage($evt->getMessage()); + } + + private function _restoreMessage(Swift_Mime_Message $message) + { + // restore original headers + $headers = $message->getHeaders(); + + if ($headers->has('X-Swift-To')) { + $message->setTo($headers->get('X-Swift-To')->getNameAddresses()); + $headers->removeAll('X-Swift-To'); + } else { + $message->setTo(null); + } + + if ($headers->has('X-Swift-Cc')) { + $message->setCc($headers->get('X-Swift-Cc')->getNameAddresses()); + $headers->removeAll('X-Swift-Cc'); + } + + if ($headers->has('X-Swift-Bcc')) { + $message->setBcc($headers->get('X-Swift-Bcc')->getNameAddresses()); + $headers->removeAll('X-Swift-Bcc'); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php new file mode 100644 index 00000000..294b547d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporter.php @@ -0,0 +1,32 @@ +_reporter = $reporter; + } + + /** + * Not used. + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + } + + /** + * Invoked immediately after the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + $message = $evt->getMessage(); + $failures = array_flip($evt->getFailedRecipients()); + foreach ((array) $message->getTo() as $address => $null) { + $this->_reporter->notify( + $message, $address, (array_key_exists($address, $failures) + ? Swift_Plugins_Reporter::RESULT_FAIL + : Swift_Plugins_Reporter::RESULT_PASS) + ); + } + foreach ((array) $message->getCc() as $address => $null) { + $this->_reporter->notify( + $message, $address, (array_key_exists($address, $failures) + ? Swift_Plugins_Reporter::RESULT_FAIL + : Swift_Plugins_Reporter::RESULT_PASS) + ); + } + foreach ((array) $message->getBcc() as $address => $null) { + $this->_reporter->notify( + $message, $address, (array_key_exists($address, $failures) + ? Swift_Plugins_Reporter::RESULT_FAIL + : Swift_Plugins_Reporter::RESULT_PASS) + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php new file mode 100644 index 00000000..ea60f51d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HitReporter.php @@ -0,0 +1,59 @@ +_failures_cache[$address])) { + $this->_failures[] = $address; + $this->_failures_cache[$address] = true; + } + } + + /** + * Get an array of addresses for which delivery failed. + * + * @return array + */ + public function getFailedRecipients() + { + return $this->_failures; + } + + /** + * Clear the buffer (empty the list). + */ + public function clear() + { + $this->_failures = $this->_failures_cache = array(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php new file mode 100644 index 00000000..817e32f5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Reporters/HtmlReporter.php @@ -0,0 +1,39 @@ +".PHP_EOL; + echo "PASS ".$address.PHP_EOL; + echo "".PHP_EOL; + flush(); + } else { + echo "
".PHP_EOL; + echo "FAIL ".$address.PHP_EOL; + echo "
".PHP_EOL; + flush(); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php new file mode 100644 index 00000000..38727052 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Sleeper.php @@ -0,0 +1,24 @@ +_rate = $rate; + $this->_mode = $mode; + $this->_sleeper = $sleeper; + $this->_timer = $timer; + } + + /** + * Invoked immediately before the Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function beforeSendPerformed(Swift_Events_SendEvent $evt) + { + $time = $this->getTimestamp(); + if (!isset($this->_start)) { + $this->_start = $time; + } + $duration = $time - $this->_start; + + switch ($this->_mode) { + case self::BYTES_PER_MINUTE : + $sleep = $this->_throttleBytesPerMinute($duration); + break; + case self::MESSAGES_PER_SECOND : + $sleep = $this->_throttleMessagesPerSecond($duration); + break; + case self::MESSAGES_PER_MINUTE : + $sleep = $this->_throttleMessagesPerMinute($duration); + break; + default : + $sleep = 0; + break; + } + + if ($sleep > 0) { + $this->sleep($sleep); + } + } + + /** + * Invoked when a Message is sent. + * + * @param Swift_Events_SendEvent $evt + */ + public function sendPerformed(Swift_Events_SendEvent $evt) + { + parent::sendPerformed($evt); + ++$this->_messages; + } + + /** + * Sleep for $seconds. + * + * @param int $seconds + */ + public function sleep($seconds) + { + if (isset($this->_sleeper)) { + $this->_sleeper->sleep($seconds); + } else { + sleep($seconds); + } + } + + /** + * Get the current UNIX timestamp. + * + * @return int + */ + public function getTimestamp() + { + if (isset($this->_timer)) { + return $this->_timer->getTimestamp(); + } else { + return time(); + } + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function _throttleBytesPerMinute($timePassed) + { + $expectedDuration = $this->getBytesOut() / ($this->_rate / 60); + + return (int) ceil($expectedDuration - $timePassed); + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function _throttleMessagesPerSecond($timePassed) + { + $expectedDuration = $this->_messages / ($this->_rate); + + return (int) ceil($expectedDuration - $timePassed); + } + + /** + * Get a number of seconds to sleep for. + * + * @param int $timePassed + * + * @return int + */ + private function _throttleMessagesPerMinute($timePassed) + { + $expectedDuration = $this->_messages / ($this->_rate / 60); + + return (int) ceil($expectedDuration - $timePassed); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php new file mode 100644 index 00000000..a05e3181 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Plugins/Timer.php @@ -0,0 +1,24 @@ +register('properties.charset')->asValue($charset); + + return $this; + } + + /** + * Set the directory where temporary files can be saved. + * + * @param string $dir + * + * @return Swift_Preferences + */ + public function setTempDir($dir) + { + Swift_DependencyContainer::getInstance() + ->register('tempdir')->asValue($dir); + + return $this; + } + + /** + * Set the type of cache to use (i.e. "disk" or "array"). + * + * @param string $type + * + * @return Swift_Preferences + */ + public function setCacheType($type) + { + Swift_DependencyContainer::getInstance() + ->register('cache')->asAliasOf(sprintf('cache.%s', $type)); + + return $this; + } + + /** + * Set the QuotedPrintable dot escaper preference. + * + * @param bool $dotEscape + * + * @return Swift_Preferences + */ + public function setQPDotEscape($dotEscape) + { + $dotEscape = !empty($dotEscape); + Swift_DependencyContainer::getInstance() + ->register('mime.qpcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') + ->withDependencies(array('mime.charstream', 'mime.bytecanonicalizer')) + ->addConstructorValue($dotEscape); + + return $this; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php new file mode 100644 index 00000000..ca9e4f60 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/ReplacementFilterFactory.php @@ -0,0 +1,27 @@ +createDependenciesFor('transport.sendmail') + ); + + $this->setCommand($command); + } + + /** + * Create a new SendmailTransport instance. + * + * @param string $command + * + * @return Swift_SendmailTransport + */ + public static function newInstance($command = '/usr/sbin/sendmail -bs') + { + return new self($command); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SignedMessage.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SignedMessage.php new file mode 100644 index 00000000..66e1c68c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SignedMessage.php @@ -0,0 +1,22 @@ + + * @deprecated + */ +class Swift_SignedMessage extends Swift_Message +{ +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php new file mode 100644 index 00000000..7448179f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signer.php @@ -0,0 +1,20 @@ + + */ +interface Swift_Signer +{ + public function reset(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php new file mode 100644 index 00000000..93dc8ac7 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/BodySigner.php @@ -0,0 +1,33 @@ + + */ +interface Swift_Signers_BodySigner extends Swift_Signer +{ + /** + * Change the Swift_Signed_Message to apply the singing. + * + * @param Swift_Message $message + * + * @return Swift_Signers_BodySigner + */ + public function signMessage(Swift_Message $message); + + /** + * Return the list of header a signer might tamper + * + * @return array + */ + public function getAlteredHeaders(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php new file mode 100644 index 00000000..220c3ac9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php @@ -0,0 +1,688 @@ + + */ +class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner +{ + /** + * PrivateKey + * + * @var string + */ + protected $_privateKey; + + /** + * DomainName + * + * @var string + */ + protected $_domainName; + + /** + * Selector + * + * @var string + */ + protected $_selector; + + /** + * Hash algorithm used + * + * @var string + */ + protected $_hashAlgorithm = 'rsa-sha1'; + + /** + * Body canon method + * + * @var string + */ + protected $_bodyCanon = 'simple'; + + /** + * Header canon method + * + * @var string + */ + protected $_headerCanon = 'simple'; + + /** + * Headers not being signed + * + * @var array + */ + protected $_ignoredHeaders = array(); + + /** + * Signer identity + * + * @var unknown_type + */ + protected $_signerIdentity; + + /** + * BodyLength + * + * @var int + */ + protected $_bodyLen = 0; + + /** + * Maximum signedLen + * + * @var int + */ + protected $_maxLen = PHP_INT_MAX; + + /** + * Embbed bodyLen in signature + * + * @var bool + */ + protected $_showLen = false; + + /** + * When the signature has been applied (true means time()), false means not embedded + * + * @var mixed + */ + protected $_signatureTimestamp = true; + + /** + * When will the signature expires false means not embedded, if sigTimestamp is auto + * Expiration is relative, otherwhise it's absolute + * + * @var int + */ + protected $_signatureExpiration = false; + + /** + * Must we embed signed headers? + * + * @var bool + */ + protected $_debugHeaders = false; + + // work variables + /** + * Headers used to generate hash + * + * @var array + */ + protected $_signedHeaders = array(); + + /** + * If debugHeaders is set store debugDatas here + * + * @var string + */ + private $_debugHeadersData = ''; + + /** + * Stores the bodyHash + * + * @var string + */ + private $_bodyHash = ''; + + /** + * Stores the signature header + * + * @var Swift_Mime_Headers_ParameterizedHeader + */ + protected $_dkimHeader; + + /** + * Hash Handler + * + * @var hash_ressource + */ + private $_headerHashHandler; + + private $_bodyHashHandler; + + private $_headerHash; + + private $_headerCanonData = ''; + + private $_bodyCanonEmptyCounter = 0; + + private $_bodyCanonIgnoreStart = 2; + + private $_bodyCanonSpace = false; + + private $_bodyCanonLastChar = null; + + private $_bodyCanonLine = ''; + + private $_bound = array(); + + /** + * Constructor + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + */ + public function __construct($privateKey, $domainName, $selector) + { + $this->_privateKey = $privateKey; + $this->_domainName = $domainName; + $this->_signerIdentity = '@'.$domainName; + $this->_selector = $selector; + } + + /** + * Instanciate DKIMSigner + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + * @return Swift_Signers_DKIMSigner + */ + public static function newInstance($privateKey, $domainName, $selector) + { + return new static($privateKey, $domainName, $selector); + } + + /** + * Reset the Signer + * @see Swift_Signer::reset() + */ + public function reset() + { + $this->_headerHash = null; + $this->_signedHeaders = array(); + $this->_headerHashHandler = null; + $this->_bodyHash = null; + $this->_bodyHashHandler = null; + $this->_bodyCanonIgnoreStart = 2; + $this->_bodyCanonEmptyCounter = 0; + $this->_bodyCanonLastChar = null; + $this->_bodyCanonSpace = false; + } + + /** + * Writes $bytes to the end of the stream. + * + * Writing may not happen immediately if the stream chooses to buffer. If + * you want to write these bytes with immediate effect, call {@link commit()} + * after calling write(). + * + * This method returns the sequence ID of the write (i.e. 1 for first, 2 for + * second, etc etc). + * + * @param string $bytes + * @return int + * @throws Swift_IoException + */ + public function write($bytes) + { + $this->_canonicalizeBody($bytes); + foreach ($this->_bound as $is) { + $is->write($bytes); + } + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + */ + public function commit() + { + // Nothing to do + return; + } + + /** + * Attach $is to this stream. + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + */ + public function bind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + $this->_bound[] = $is; + + return; + } + + /** + * Remove an already bound stream. + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + */ + public function unbind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + foreach ($this->_bound as $k => $stream) { + if ($stream === $is) { + unset($this->_bound[$k]); + + return; + } + } + + return; + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + */ + public function flushBuffers() + { + $this->reset(); + } + + /** + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256 + * + * @param string $hash + * @return Swift_Signers_DKIMSigner + */ + public function setHashAlgorithm($hash) + { + // Unable to sign with rsa-sha256 + if ($hash == 'rsa-sha1') { + $this->_hashAlgorithm = 'rsa-sha1'; + } else { + $this->_hashAlgorithm = 'rsa-sha256'; + } + + return $this; + } + + /** + * Set the body canonicalization algorithm + * + * @param string $canon + * @return Swift_Signers_DKIMSigner + */ + public function setBodyCanon($canon) + { + if ($canon == 'relaxed') { + $this->_bodyCanon = 'relaxed'; + } else { + $this->_bodyCanon = 'simple'; + } + + return $this; + } + + /** + * Set the header canonicalization algorithm + * + * @param string $canon + * @return Swift_Signers_DKIMSigner + */ + public function setHeaderCanon($canon) + { + if ($canon == 'relaxed') { + $this->_headerCanon = 'relaxed'; + } else { + $this->_headerCanon = 'simple'; + } + + return $this; + } + + /** + * Set the signer identity + * + * @param string $identity + * @return Swift_Signers_DKIMSigner + */ + public function setSignerIdentity($identity) + { + $this->_signerIdentity = $identity; + + return $this; + } + + /** + * Set the length of the body to sign + * + * @param mixed $len (bool or int) + * @return Swift_Signers_DKIMSigner + */ + public function setBodySignedLen($len) + { + if ($len === true) { + $this->_showLen = true; + $this->_maxLen = PHP_INT_MAX; + } elseif ($len === false) { + $this->showLen = false; + $this->_maxLen = PHP_INT_MAX; + } else { + $this->_showLen = true; + $this->_maxLen = (int) $len; + } + + return $this; + } + + /** + * Set the signature timestamp + * + * @param timestamp $time + * @return Swift_Signers_DKIMSigner + */ + public function setSignatureTimestamp($time) + { + $this->_signatureTimestamp = $time; + + return $this; + } + + /** + * Set the signature expiration timestamp + * + * @param timestamp $time + * @return Swift_Signers_DKIMSigner + */ + public function setSignatureExpiration($time) + { + $this->_signatureExpiration = $time; + + return $this; + } + + /** + * Enable / disable the DebugHeaders + * + * @param bool $debug + * @return Swift_Signers_DKIMSigner + */ + public function setDebugHeaders($debug) + { + $this->_debugHeaders = (bool) $debug; + + return $this; + } + + /** + * Start Body + * + */ + public function startBody() + { + // Init + switch ($this->_hashAlgorithm) { + case 'rsa-sha256' : + $this->_bodyHashHandler = hash_init('sha256'); + break; + case 'rsa-sha1' : + $this->_bodyHashHandler = hash_init('sha1'); + break; + } + $this->_bodyCanonLine = ''; + } + + /** + * End Body + * + */ + public function endBody() + { + $this->_endOfBody(); + } + + /** + * Returns the list of Headers Tampered by this plugin + * + * @return array + */ + public function getAlteredHeaders() + { + if ($this->_debugHeaders) { + return array('DKIM-Signature', 'X-DebugHash'); + } else { + return array('DKIM-Signature'); + } + } + + /** + * Adds an ignored Header + * + * @param string $header_name + * @return Swift_Signers_DKIMSigner + */ + public function ignoreHeader($header_name) + { + $this->_ignoredHeaders[strtolower($header_name)] = true; + + return $this; + } + + /** + * Set the headers to sign + * + * @param Swift_Mime_HeaderSet $headers + * @return Swift_Signers_DKIMSigner + */ + public function setHeaders(Swift_Mime_HeaderSet $headers) + { + $this->_headerCanonData = ''; + // Loop through Headers + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (! isset($this->_ignoredHeaders[strtolower($hName)])) { + if ($headers->has($hName)) { + $tmp = $headers->getAll($hName); + foreach ($tmp as $header) { + if ($header->getFieldBody() != '') { + $this->_addHeader($header->toString()); + $this->_signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + + return $this; + } + + /** + * Add the signature to the given Headers + * + * @param Swift_Mime_HeaderSet $headers + * @return Swift_Signers_DKIMSigner + */ + public function addSignature(Swift_Mime_HeaderSet $headers) + { + // Prepare the DKIM-Signature + $params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector); + if ($this->_bodyCanon != 'simple') { + $params['c'] = $this->_headerCanon.'/'.$this->_bodyCanon; + } elseif ($this->_headerCanon != 'simple') { + $params['c'] = $this->_headerCanon; + } + if ($this->_showLen) { + $params['l'] = $this->_bodyLen; + } + if ($this->_signatureTimestamp === true) { + $params['t'] = time(); + if ($this->_signatureExpiration !== false) { + $params['x'] = $params['t'] + $this->_signatureExpiration; + } + } else { + if ($this->_signatureTimestamp !== false) { + $params['t'] = $this->_signatureTimestamp; + } + if ($this->_signatureExpiration !== false) { + $params['x'] = $this->_signatureExpiration; + } + } + if ($this->_debugHeaders) { + $params['z'] = implode('|', $this->_debugHeadersData); + } + $string = ''; + foreach ($params as $k => $v) { + $string .= $k.'='.$v.'; '; + } + $string = trim($string); + $headers->addTextHeader('DKIM-Signature', $string); + // Add the last DKIM-Signature + $tmp = $headers->getAll('DKIM-Signature'); + $this->_dkimHeader = end($tmp); + $this->_addHeader(trim($this->_dkimHeader->toString())."\r\n b=", true); + $this->_endOfHeaders(); + if ($this->_debugHeaders) { + $headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash)); + } + $this->_dkimHeader->setValue($string." b=".trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, " "))); + + return $this; + } + + /* Private helpers */ + + protected function _addHeader($header, $is_sig = false) + { + switch ($this->_headerCanon) { + case 'relaxed' : + // Prepare Header and cascade + $exploded = explode(':', $header, 2); + $name = strtolower(trim($exploded[0])); + $value = str_replace("\r\n", "", $exploded[1]); + $value = preg_replace("/[ \t][ \t]+/", " ", $value); + $header = $name.":".trim($value).($is_sig ? '' : "\r\n"); + case 'simple' : + // Nothing to do + } + $this->_addToHeaderHash($header); + } + + protected function _endOfHeaders() + { + //$this->_headerHash=hash_final($this->_headerHashHandler, true); + } + + protected function _canonicalizeBody($string) + { + $len = strlen($string); + $canon = ''; + $method = ($this->_bodyCanon == "relaxed"); + for ($i = 0; $i < $len; ++$i) { + if ($this->_bodyCanonIgnoreStart > 0) { + --$this->_bodyCanonIgnoreStart; + continue; + } + switch ($string[$i]) { + case "\r" : + $this->_bodyCanonLastChar = "\r"; + break; + case "\n" : + if ($this->_bodyCanonLastChar == "\r") { + if ($method) { + $this->_bodyCanonSpace = false; + } + if ($this->_bodyCanonLine == '') { + ++$this->_bodyCanonEmptyCounter; + } else { + $this->_bodyCanonLine = ''; + $canon .= "\r\n"; + } + } else { + // Wooops Error + // todo handle it but should never happen + } + break; + case " " : + case "\t" : + if ($method) { + $this->_bodyCanonSpace = true; + break; + } + default : + if ($this->_bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); + $this->_bodyCanonEmptyCounter = 0; + } + if ($this->_bodyCanonSpace) { + $this->_bodyCanonLine .= ' '; + $canon .= ' '; + $this->_bodyCanonSpace = false; + } + $this->_bodyCanonLine .= $string[$i]; + $canon .= $string[$i]; + } + } + $this->_addToBodyHash($canon); + } + + protected function _endOfBody() + { + // Add trailing Line return if last line is non empty + if (strlen($this->_bodyCanonLine) > 0) { + $this->_addToBodyHash("\r\n"); + } + $this->_bodyHash = hash_final($this->_bodyHashHandler, true); + } + + private function _addToBodyHash($string) + { + $len = strlen($string); + if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) { + $string = substr($string, 0, $new_len); + $len = $new_len; + } + hash_update($this->_bodyHashHandler, $string); + $this->_bodyLen += $len; + } + + private function _addToHeaderHash($header) + { + if ($this->_debugHeaders) { + $this->_debugHeadersData[] = trim($header); + } + $this->_headerCanonData .= $header; + } + + /** + * @throws Swift_SwiftException + * @return string + */ + private function _getEncryptedHash() + { + $signature = ''; + switch ($this->_hashAlgorithm) { + case 'rsa-sha1': + $algorithm = OPENSSL_ALGO_SHA1; + break; + case 'rsa-sha256': + $algorithm = OPENSSL_ALGO_SHA256; + break; + } + $pkeyId = openssl_get_privatekey($this->_privateKey); + if (!$pkeyId) { + throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']'); + } + if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) { + return $signature; + } + throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php new file mode 100644 index 00000000..b52ffdf4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/DomainKeySigner.php @@ -0,0 +1,512 @@ + + */ +class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner +{ + /** + * PrivateKey + * + * @var string + */ + protected $_privateKey; + + /** + * DomainName + * + * @var string + */ + protected $_domainName; + + /** + * Selector + * + * @var string + */ + protected $_selector; + + /** + * Hash algorithm used + * + * @var string + */ + protected $_hashAlgorithm = 'rsa-sha1'; + + /** + * Canonisation method + * + * @var string + */ + protected $_canon = 'simple'; + + /** + * Headers not being signed + * + * @var array + */ + protected $_ignoredHeaders = array(); + + /** + * Signer identity + * + * @var string + */ + protected $_signerIdentity; + + /** + * Must we embed signed headers? + * + * @var bool + */ + protected $_debugHeaders = false; + + // work variables + /** + * Headers used to generate hash + * + * @var array + */ + private $_signedHeaders = array(); + + /** + * Stores the signature header + * + * @var Swift_Mime_Headers_ParameterizedHeader + */ + protected $_domainKeyHeader; + + /** + * Hash Handler + * + * @var resource|null + */ + private $_hashHandler; + + private $_hash; + + private $_canonData = ''; + + private $_bodyCanonEmptyCounter = 0; + + private $_bodyCanonIgnoreStart = 2; + + private $_bodyCanonSpace = false; + + private $_bodyCanonLastChar = null; + + private $_bodyCanonLine = ''; + + private $_bound = array(); + + /** + * Constructor + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + */ + public function __construct($privateKey, $domainName, $selector) + { + $this->_privateKey = $privateKey; + $this->_domainName = $domainName; + $this->_signerIdentity = '@'.$domainName; + $this->_selector = $selector; + } + + /** + * Instanciate DomainKeySigner + * + * @param string $privateKey + * @param string $domainName + * @param string $selector + * @return Swift_Signers_DomainKeySigner + */ + public static function newInstance($privateKey, $domainName, $selector) + { + return new static($privateKey, $domainName, $selector); + } + + /** + * Resets internal states + * + * @return Swift_Signers_DomainKeysSigner + */ + public function reset() + { + $this->_hash = null; + $this->_hashHandler = null; + $this->_bodyCanonIgnoreStart = 2; + $this->_bodyCanonEmptyCounter = 0; + $this->_bodyCanonLastChar = null; + $this->_bodyCanonSpace = false; + + return $this; + } + + /** + * Writes $bytes to the end of the stream. + * + * Writing may not happen immediately if the stream chooses to buffer. If + * you want to write these bytes with immediate effect, call {@link commit()} + * after calling write(). + * + * This method returns the sequence ID of the write (i.e. 1 for first, 2 for + * second, etc etc). + * + * @param string $bytes + * @return int + * @throws Swift_IoException + * @return Swift_Signers_DomainKeysSigner + */ + public function write($bytes) + { + $this->_canonicalizeBody($bytes); + foreach ($this->_bound as $is) { + $is->write($bytes); + } + + return $this; + } + + /** + * For any bytes that are currently buffered inside the stream, force them + * off the buffer. + * + * @throws Swift_IoException + * @return Swift_Signers_DomainKeysSigner + */ + public function commit() + { + // Nothing to do + return $this; + } + + /** + * Attach $is to this stream. + * The stream acts as an observer, receiving all data that is written. + * All {@link write()} and {@link flushBuffers()} operations will be mirrored. + * + * @param Swift_InputByteStream $is + * @return Swift_Signers_DomainKeysSigner + */ + public function bind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + $this->_bound[] = $is; + + return $this; + } + + /** + * Remove an already bound stream. + * If $is is not bound, no errors will be raised. + * If the stream currently has any buffered data it will be written to $is + * before unbinding occurs. + * + * @param Swift_InputByteStream $is + * @return Swift_Signers_DomainKeysSigner + */ + public function unbind(Swift_InputByteStream $is) + { + // Don't have to mirror anything + foreach ($this->_bound as $k => $stream) { + if ($stream === $is) { + unset($this->_bound[$k]); + + return; + } + } + + return $this; + } + + /** + * Flush the contents of the stream (empty it) and set the internal pointer + * to the beginning. + * + * @throws Swift_IoException + * @return Swift_Signers_DomainKeysSigner + */ + public function flushBuffers() + { + $this->reset(); + + return $this; + } + + /** + * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256 + * + * @param string $hash + * @return Swift_Signers_DomainKeysSigner + */ + public function setHashAlgorithm($hash) + { + $this->_hashAlgorithm = 'rsa-sha1'; + + return $this; + } + + /** + * Set the canonicalization algorithm + * + * @param string $canon simple | nofws defaults to simple + * @return Swift_Signers_DomainKeysSigner + */ + public function setCanon($canon) + { + if ($canon == 'nofws') { + $this->_canon = 'nofws'; + } else { + $this->_canon = 'simple'; + } + + return $this; + } + + /** + * Set the signer identity + * + * @param string $identity + * @return Swift_Signers_DomainKeySigner + */ + public function setSignerIdentity($identity) + { + $this->_signerIdentity = $identity; + + return $this; + } + + /** + * Enable / disable the DebugHeaders + * + * @param bool $debug + * @return Swift_Signers_DomainKeySigner + */ + public function setDebugHeaders($debug) + { + $this->_debugHeaders = (bool) $debug; + + return $this; + } + + /** + * Start Body + * + */ + public function startBody() + { + } + + /** + * End Body + * + */ + public function endBody() + { + $this->_endOfBody(); + } + + /** + * Returns the list of Headers Tampered by this plugin + * + * @return array + */ + public function getAlteredHeaders() + { + if ($this->_debugHeaders) { + return array('DomainKey-Signature', 'X-DebugHash'); + } else { + return array('DomainKey-Signature'); + } + } + + /** + * Adds an ignored Header + * + * @param string $header_name + * @return Swift_Signers_DomainKeySigner + */ + public function ignoreHeader($header_name) + { + $this->_ignoredHeaders[strtolower($header_name)] = true; + + return $this; + } + + /** + * Set the headers to sign + * + * @param Swift_Mime_HeaderSet $headers + * @return Swift_Signers_DomainKeySigner + */ + public function setHeaders(Swift_Mime_HeaderSet $headers) + { + $this->_startHash(); + $this->_canonData = ''; + // Loop through Headers + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (! isset($this->_ignoredHeaders[strtolower($hName)])) { + if ($headers->has($hName)) { + $tmp = $headers->getAll($hName); + foreach ($tmp as $header) { + if ($header->getFieldBody() != '') { + $this->_addHeader($header->toString()); + $this->_signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + $this->_endOfHeaders(); + + return $this; + } + + /** + * Add the signature to the given Headers + * + * @param Swift_Mime_HeaderSet $headers + * @return Swift_Signers_DomainKeySigner + */ + public function addSignature(Swift_Mime_HeaderSet $headers) + { + // Prepare the DomainKey-Signature Header + $params = array('a' => $this->_hashAlgorithm, 'b' => chunk_split(base64_encode($this->_getEncryptedHash()), 73, " "), 'c' => $this->_canon, 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'q' => 'dns', 's' => $this->_selector); + $string = ''; + foreach ($params as $k => $v) { + $string .= $k.'='.$v.'; '; + } + $string = trim($string); + $headers->addTextHeader('DomainKey-Signature', $string); + + return $this; + } + + /* Private helpers */ + + protected function _addHeader($header) + { + switch ($this->_canon) { + case 'nofws' : + // Prepare Header and cascade + $exploded = explode(':', $header, 2); + $name = strtolower(trim($exploded[0])); + $value = str_replace("\r\n", "", $exploded[1]); + $value = preg_replace("/[ \t][ \t]+/", " ", $value); + $header = $name.":".trim($value)."\r\n"; + case 'simple' : + // Nothing to do + } + $this->_addToHash($header); + } + + protected function _endOfHeaders() + { + $this->_bodyCanonEmptyCounter = 1; + } + + protected function _canonicalizeBody($string) + { + $len = strlen($string); + $canon = ''; + $nofws = ($this->_canon == "nofws"); + for ($i = 0; $i < $len; ++$i) { + if ($this->_bodyCanonIgnoreStart > 0) { + --$this->_bodyCanonIgnoreStart; + continue; + } + switch ($string[$i]) { + case "\r" : + $this->_bodyCanonLastChar = "\r"; + break; + case "\n" : + if ($this->_bodyCanonLastChar == "\r") { + if ($nofws) { + $this->_bodyCanonSpace = false; + } + if ($this->_bodyCanonLine == '') { + ++$this->_bodyCanonEmptyCounter; + } else { + $this->_bodyCanonLine = ''; + $canon .= "\r\n"; + } + } else { + // Wooops Error + throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r'); + } + break; + case " " : + case "\t" : + case "\x09": //HTAB + if ($nofws) { + $this->_bodyCanonSpace = true; + break; + } + default : + if ($this->_bodyCanonEmptyCounter > 0) { + $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); + $this->_bodyCanonEmptyCounter = 0; + } + $this->_bodyCanonLine .= $string[$i]; + $canon .= $string[$i]; + } + } + $this->_addToHash($canon); + } + + protected function _endOfBody() + { + if (strlen($this->_bodyCanonLine) > 0) { + $this->_addToHash("\r\n"); + } + $this->_hash = hash_final($this->_hashHandler, true); + } + + private function _addToHash($string) + { + $this->_canonData .= $string; + hash_update($this->_hashHandler, $string); + } + + private function _startHash() + { + // Init + switch ($this->_hashAlgorithm) { + case 'rsa-sha1' : + $this->_hashHandler = hash_init('sha1'); + break; + } + $this->_canonLine = ''; + } + + /** + * @throws Swift_SwiftException + * @return string + */ + private function _getEncryptedHash() + { + $signature = ''; + $pkeyId = openssl_get_privatekey($this->_privateKey); + if (!$pkeyId) { + throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']'); + } + if (openssl_sign($this->_canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { + return $signature; + } + throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php new file mode 100644 index 00000000..67c79413 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php @@ -0,0 +1,65 @@ + + */ +interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream +{ + /** + * Exclude an header from the signed headers + * + * @param string $header_name + * + * @return Swift_Signers_HeaderSigner + */ + public function ignoreHeader($header_name); + + /** + * Prepare the Signer to get a new Body + * + * @return Swift_Signers_HeaderSigner + */ + public function startBody(); + + /** + * Give the signal that the body has finished streaming + * + * @return Swift_Signers_HeaderSigner + */ + public function endBody(); + + /** + * Give the headers already given + * + * @param Swift_Mime_SimpleHeaderSet $headers + * + * @return Swift_Signers_HeaderSigner + */ + public function setHeaders(Swift_Mime_HeaderSet $headers); + + /** + * Add the header(s) to the headerSet + * + * @param Swift_Mime_HeaderSet $headers + * + * @return Swift_Signers_HeaderSigner + */ + public function addSignature(Swift_Mime_HeaderSet $headers); + + /** + * Return the list of header a signer might tamper + * + * @return array + */ + public function getAlteredHeaders(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php new file mode 100644 index 00000000..b9738f42 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/OpenDKIMSigner.php @@ -0,0 +1,186 @@ + + */ +class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner +{ + private $_peclLoaded = false; + + private $_dkimHandler = null; + + private $dropFirstLF = true; + + const CANON_RELAXED = 1; + const CANON_SIMPLE = 2; + const SIG_RSA_SHA1 = 3; + const SIG_RSA_SHA256 = 4; + + public function __construct($privateKey, $domainName, $selector) + { + if (extension_loaded('opendkim')) { + $this->_peclLoaded = true; + } else { + throw new Swift_SwiftException('php-opendkim extension not found'); + } + parent::__construct($privateKey, $domainName, $selector); + } + + public static function newInstance($privateKey, $domainName, $selector) + { + return new static($privateKey, $domainName, $selector); + } + + public function addSignature(Swift_Mime_HeaderSet $headers) + { + $header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature'); + $headerVal = $this->_dkimHandler->getSignatureHeader(); + if (!$headerVal) { + throw new Swift_SwiftException('OpenDKIM Error: '.$this->_dkimHandler->getError()); + } + $header->setValue($headerVal); + $headers->set($header); + + return $this; + } + + public function setHeaders(Swift_Mime_HeaderSet $headers) + { + $bodyLen = $this->_bodyLen; + if (is_bool($bodyLen)) { + $bodyLen = - 1; + } + $hash = ($this->_hashAlgorithm == 'rsa-sha1') ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; + $bodyCanon = ($this->_bodyCanon == 'simple') ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $headerCanon = ($this->_headerCanon == 'simple') ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; + $this->_dkimHandler = new OpenDKIMSign($this->_privateKey, $this->_selector, $this->_domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); + // Hardcode signature Margin for now + $this->_dkimHandler->setMargin(78); + + if (!is_numeric($this->_signatureTimestamp)) { + OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time()); + } else { + if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->_signatureTimestamp)) { + throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']'); + } + } + if (isset($this->_signerIdentity)) { + $this->_dkimHandler->setSigner($this->_signerIdentity); + } + $listHeaders = $headers->listAll(); + foreach ($listHeaders as $hName) { + // Check if we need to ignore Header + if (! isset($this->_ignoredHeaders[strtolower($hName)])) { + $tmp = $headers->getAll($hName); + if ($headers->has($hName)) { + foreach ($tmp as $header) { + if ($header->getFieldBody() != '') { + $htosign = $header->toString(); + $this->_dkimHandler->header($htosign); + $this->_signedHeaders[] = $header->getFieldName(); + } + } + } + } + } + + return $this; + } + + public function startBody() + { + if (! $this->_peclLoaded) { + return parent::startBody(); + } + $this->dropFirstLF = true; + $this->_dkimHandler->eoh(); + + return $this; + } + + public function endBody() + { + if (! $this->_peclLoaded) { + return parent::endBody(); + } + $this->_dkimHandler->eom(); + + return $this; + } + + public function reset() + { + $this->_dkimHandler = null; + parent::reset(); + + return $this; + } + + /** + * Set the signature timestamp + * + * @param timestamp $time + * @return Swift_Signers_DKIMSigner + */ + public function setSignatureTimestamp($time) + { + $this->_signatureTimestamp = $time; + + return $this; + } + + /** + * Set the signature expiration timestamp + * + * @param timestamp $time + * @return Swift_Signers_DKIMSigner + */ + public function setSignatureExpiration($time) + { + $this->_signatureExpiration = $time; + + return $this; + } + + /** + * Enable / disable the DebugHeaders + * + * @param bool $debug + * @return Swift_Signers_DKIMSigner + */ + public function setDebugHeaders($debug) + { + $this->_debugHeaders = (bool) $debug; + + return $this; + } + + // Protected + + protected function _canonicalizeBody($string) + { + if (! $this->_peclLoaded) { + return parent::_canonicalizeBody($string); + } + if (false && $this->dropFirstLF === true) { + if ($string[0] == "\r" && $string[1] == "\n") { + $string = substr($string, 2); + } + } + $this->dropFirstLF = false; + if (strlen($string)) { + $this->_dkimHandler->body($string); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php new file mode 100644 index 00000000..42e294c6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/SMimeSigner.php @@ -0,0 +1,427 @@ + + */ +class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner +{ + protected $signCertificate; + protected $signPrivateKey; + protected $encryptCert; + protected $signThenEncrypt = true; + protected $signLevel; + protected $encryptLevel; + protected $signOptions; + protected $encryptOptions; + protected $encryptCipher; + + /** + * @var Swift_StreamFilters_StringReplacementFilterFactory + */ + protected $replacementFactory; + + /** + * @var Swift_Mime_HeaderFactory + */ + protected $headerFactory; + + /** + * Constructor. + * + * @param string $certificate + * @param string $privateKey + * @param string $encryptCertificate + */ + public function __construct($signCertificate = null, $signPrivateKey = null, $encryptCertificate = null) + { + if (null !== $signPrivateKey) { + $this->setSignCertificate($signCertificate, $signPrivateKey); + } + + if (null !== $encryptCertificate) { + $this->setEncryptCertificate($encryptCertificate); + } + + $this->replacementFactory = Swift_DependencyContainer::getInstance() + ->lookup('transport.replacementfactory'); + + $this->signOptions = PKCS7_DETACHED; + + // Supported since php5.4 + if (defined('OPENSSL_CIPHER_AES_128_CBC')) { + $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; + } else { + $this->encryptCipher = OPENSSL_CIPHER_RC2_128; + } + } + + /** + * Returns an new Swift_Signers_SMimeSigner instance. + * + * @param string $certificate + * @param string $privateKey + * + * @return Swift_Signers_SMimeSigner + */ + public static function newInstance($certificate = null, $privateKey = null) + { + return new self($certificate, $privateKey); + } + + /** + * Set the certificate location to use for signing. + * + * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php + * + * @param string $certificate + * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead + * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign() + * + * @return Swift_Signers_SMimeSigner + */ + public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED) + { + $this->signCertificate = 'file://'.str_replace('\\', '/', realpath($certificate)); + + if (null !== $privateKey) { + if (is_array($privateKey)) { + $this->signPrivateKey = $privateKey; + $this->signPrivateKey[0] = 'file://'.str_replace('\\', '/', realpath($privateKey[0])); + } else { + $this->signPrivateKey = 'file://'.str_replace('\\', '/', realpath($privateKey)); + } + } + + $this->signOptions = $signOptions; + + return $this; + } + + /** + * Set the certificate location to use for encryption. + * + * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php + * @link http://nl3.php.net/manual/en/openssl.ciphers.php + * + * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates. + * @param int $cipher + * + * @return Swift_Signers_SMimeSigner + */ + public function setEncryptCertificate($recipientCerts, $cipher = null) + { + if (is_array($recipientCerts)) { + $this->encryptCert = array(); + + foreach ($recipientCerts as $cert) { + $this->encryptCert[] = 'file://'.str_replace('\\', '/', realpath($cert)); + } + } else { + $this->encryptCert = 'file://'.str_replace('\\', '/', realpath($recipientCerts)); + } + + if (null !== $cipher) { + $this->encryptCipher = $cipher; + } + + return $this; + } + + /** + * @return string + */ + public function getSignCertificate() + { + return $this->signCertificate; + } + + /** + * @return string + */ + public function getSignPrivateKey() + { + return $this->signPrivateKey; + } + + /** + * Set perform signing before encryption. + * + * The default is to first sign the message and then encrypt. + * But some older mail clients, namely Microsoft Outlook 2000 will work when the message first encrypted. + * As this goes against the official specs, its recommended to only use 'encryption -> signing' when specifically targeting these 'broken' clients. + * + * @param string $signThenEncrypt + * + * @return Swift_Signers_SMimeSigner + */ + public function setSignThenEncrypt($signThenEncrypt = true) + { + $this->signThenEncrypt = $signThenEncrypt; + + return $this; + } + + /** + * @return bool + */ + public function isSignThenEncrypt() + { + return $this->signThenEncrypt; + } + + /** + * Resets internal states. + * + * @return Swift_Signers_SMimeSigner + */ + public function reset() + { + return $this; + } + + /** + * Change the Swift_Message to apply the signing. + * + * @param Swift_Message $message + * + * @return Swift_Signers_SMimeSigner + */ + public function signMessage(Swift_Message $message) + { + if (null === $this->signCertificate && null === $this->encryptCert) { + return $this; + } + + // Store the message using ByteStream to a file{1} + // Remove all Children + // Sign file{1}, parse the new MIME headers and set them on the primary MimeEntity + // Set the singed-body as the new body (without boundary) + + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $this->toSMimeByteStream($messageStream, $message); + $message->setEncoder(Swift_DependencyContainer::getInstance()->lookup('mime.rawcontentencoder')); + + $message->setChildren(array()); + $this->streamToMime($messageStream, $message); + } + + /** + * Return the list of header a signer might tamper. + * + * @return array + */ + public function getAlteredHeaders() + { + return array('Content-Type', 'Content-Transfer-Encoding', 'Content-Disposition'); + } + + /** + * @param Swift_InputByteStream $inputStream + * @param Swift_Message $mimeEntity + */ + protected function toSMimeByteStream(Swift_InputByteStream $inputStream, Swift_Message $message) + { + $mimeEntity = $this->createMessage($message); + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + $mimeEntity->toByteStream($messageStream); + $messageStream->commit(); + + if (null !== $this->signCertificate && null !== $this->encryptCert) { + $temporaryStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if ($this->signThenEncrypt) { + $this->messageStreamToSignedByteStream($messageStream, $temporaryStream); + $this->messageStreamToEncryptedByteStream($temporaryStream, $inputStream); + } else { + $this->messageStreamToEncryptedByteStream($messageStream, $temporaryStream); + $this->messageStreamToSignedByteStream($temporaryStream, $inputStream); + } + } elseif ($this->signCertificate !== null) { + $this->messageStreamToSignedByteStream($messageStream, $inputStream); + } else { + $this->messageStreamToEncryptedByteStream($messageStream, $inputStream); + } + } + + /** + * @param Swift_Message $message + * + * @return Swift_Message + */ + protected function createMessage(Swift_Message $message) + { + $mimeEntity = new Swift_Message('', $message->getBody(), $message->getContentType(), $message->getCharset()); + $mimeEntity->setChildren($message->getChildren()); + + $messageHeaders = $mimeEntity->getHeaders(); + $messageHeaders->remove('Message-ID'); + $messageHeaders->remove('Date'); + $messageHeaders->remove('Subject'); + $messageHeaders->remove('MIME-Version'); + $messageHeaders->remove('To'); + $messageHeaders->remove('From'); + + return $mimeEntity; + } + + /** + * @param Swift_FileStream $outputStream + * @param Swift_InputByteStream $inputStream + * + * @throws Swift_IoException + */ + protected function messageStreamToSignedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $inputStream) + { + $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_sign($outputStream->getPath(), $signedMessageStream->getPath(), $this->signCertificate, $this->signPrivateKey, array(), $this->signOptions)) { + throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); + } + + $this->copyFromOpenSSLOutput($signedMessageStream, $inputStream); + } + + /** + * @param Swift_FileStream $outputStream + * @param Swift_InputByteStream $is + * + * @throws Swift_IoException + */ + protected function messageStreamToEncryptedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $is) + { + $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_encrypt($outputStream->getPath(), $encryptedMessageStream->getPath(), $this->encryptCert, array(), 0, $this->encryptCipher)) { + throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string())); + } + + $this->copyFromOpenSSLOutput($encryptedMessageStream, $is); + } + + /** + * @param Swift_OutputByteStream $fromStream + * @param Swift_InputByteStream $toStream + */ + protected function copyFromOpenSSLOutput(Swift_OutputByteStream $fromStream, Swift_InputByteStream $toStream) + { + $bufferLength = 4096; + $filteredStream = new Swift_ByteStream_TemporaryFileByteStream(); + $filteredStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); + $filteredStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); + + while (false !== ($buffer = $fromStream->read($bufferLength))) { + $filteredStream->write($buffer); + } + + $filteredStream->flushBuffers(); + + while (false !== ($buffer = $filteredStream->read($bufferLength))) { + $toStream->write($buffer); + } + + $toStream->commit(); + } + + /** + * Merges an OutputByteStream to Swift_Message. + * + * @param Swift_OutputByteStream $fromStream + * @param Swift_Message $message + */ + protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message) + { + $bufferLength = 78; + $headerData = ''; + + $fromStream->setReadPointer(0); + + while (($buffer = $fromStream->read($bufferLength)) !== false) { + $headerData .= $buffer; + + if (false !== strpos($buffer, "\r\n\r\n")) { + break; + } + } + + $headersPosEnd = strpos($headerData, "\r\n\r\n"); + $headerData = trim($headerData); + $headerData = substr($headerData, 0, $headersPosEnd); + $headerLines = explode("\r\n", $headerData); + unset($headerData); + + $headers = array(); + $currentHeaderName = ''; + + foreach ($headerLines as $headerLine) { + // Line separated + if (ctype_space($headerLines[0]) || false === strpos($headerLine, ':')) { + $headers[$currentHeaderName] .= ' '.trim($headerLine); + continue; + } + + $header = explode(':', $headerLine, 2); + $currentHeaderName = strtolower($header[0]); + $headers[$currentHeaderName] = trim($header[1]); + } + + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $messageStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); + $messageStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); + + $messageHeaders = $message->getHeaders(); + + // No need to check for 'application/pkcs7-mime', as this is always base64 + if ('multipart/signed;' === substr($headers['content-type'], 0, 17)) { + if (!preg_match('/boundary=("[^"]+"|(?:[^\s]+|$))/is', $headers['content-type'], $contentTypeData)) { + throw new Swift_SwiftException('Failed to find Boundary parameter'); + } + + $boundary = trim($contentTypeData['1'], '"'); + $boundaryLen = strlen($boundary); + + // Skip the header and CRLF CRLF + $fromStream->setReadPointer($headersPosEnd + 4); + + while (false !== ($buffer = $fromStream->read($bufferLength))) { + $messageStream->write($buffer); + } + + $messageStream->commit(); + + $messageHeaders->remove('Content-Transfer-Encoding'); + $message->setContentType($headers['content-type']); + $message->setBoundary($boundary); + $message->setBody($messageStream); + } else { + $fromStream->setReadPointer($headersPosEnd + 4); + + if (null === $this->headerFactory) { + $this->headerFactory = Swift_DependencyContainer::getInstance()->lookup('mime.headerfactory'); + } + + $message->setContentType($headers['content-type']); + $messageHeaders->set($this->headerFactory->createTextHeader('Content-Transfer-Encoding', $headers['content-transfer-encoding'])); + $messageHeaders->set($this->headerFactory->createTextHeader('Content-Disposition', $headers['content-disposition'])); + + while (false !== ($buffer = $fromStream->read($bufferLength))) { + $messageStream->write($buffer); + } + + $messageStream->commit(); + $message->setBody($messageStream); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php new file mode 100644 index 00000000..5d4945e1 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php @@ -0,0 +1,57 @@ +createDependenciesFor('transport.smtp') + ); + + $this->setHost($host); + $this->setPort($port); + $this->setEncryption($security); + } + + /** + * Create a new SmtpTransport instance. + * + * @param string $host + * @param int $port + * @param string $security + * + * @return Swift_SmtpTransport + */ + public static function newInstance($host = 'localhost', $port = 25, $security = null) + { + return new self($host, $port, $security); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php new file mode 100644 index 00000000..afae5fac --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Spool.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Interface for spools. + * + * @author Fabien Potencier + */ +interface Swift_Spool +{ + /** + * Starts this Spool mechanism. + */ + public function start(); + + /** + * Stops this Spool mechanism. + */ + public function stop(); + + /** + * Tests if this Spool mechanism has started. + * + * @return bool + */ + public function isStarted(); + + /** + * Queues a message. + * + * @param Swift_Mime_Message $message The message to store + * + * @return bool Whether the operation has succeeded + */ + public function queueMessage(Swift_Mime_Message $message); + + /** + * Sends messages using the given transport instance. + * + * @param Swift_Transport $transport A transport instance + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function flushQueue(Swift_Transport $transport, &$failedRecipients = null); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php new file mode 100644 index 00000000..9351c40d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SpoolTransport.php @@ -0,0 +1,47 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in a queue. + * + * @author Fabien Potencier + */ +class Swift_SpoolTransport extends Swift_Transport_SpoolTransport +{ + /** + * Create a new SpoolTransport. + * + * @param Swift_Spool $spool + */ + public function __construct(Swift_Spool $spool) + { + $arguments = Swift_DependencyContainer::getInstance() + ->createDependenciesFor('transport.spool'); + + $arguments[] = $spool; + + call_user_func_array( + array($this, 'Swift_Transport_SpoolTransport::__construct'), + $arguments + ); + } + + /** + * Create a new SpoolTransport instance. + * + * @param Swift_Spool $spool + * + * @return Swift_SpoolTransport + */ + public static function newInstance(Swift_Spool $spool) + { + return new self($spool); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php new file mode 100644 index 00000000..1c3fd3a5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilter.php @@ -0,0 +1,35 @@ +_search = $search; + $this->_index = array(); + $this->_tree = array(); + $this->_replace = array(); + $this->_repSize = array(); + + $tree = null; + $i = null; + $last_size = $size = 0; + foreach ($search as $i => $search_element) { + if ($tree !== null) { + $tree[-1] = min (count($replace) - 1, $i - 1); + $tree[-2] = $last_size; + } + $tree = &$this->_tree; + if (is_array ($search_element)) { + foreach ($search_element as $k => $char) { + $this->_index[$char] = true; + if (!isset($tree[$char])) { + $tree[$char] = array(); + } + $tree = &$tree[$char]; + } + $last_size = $k+1; + $size = max($size, $last_size); + } else { + $last_size = 1; + if (!isset($tree[$search_element])) { + $tree[$search_element] = array(); + } + $tree = &$tree[$search_element]; + $size = max($last_size, $size); + $this->_index[$search_element] = true; + } + } + if ($i !== null) { + $tree[-1] = min (count ($replace) - 1, $i); + $tree[-2] = $last_size; + $this->_treeMaxLen = $size; + } + foreach ($replace as $rep) { + if (!is_array($rep)) { + $rep = array ($rep); + } + $this->_replace[] = $rep; + } + for ($i = count($this->_replace) - 1; $i >= 0; --$i) { + $this->_replace[$i] = $rep = $this->filter($this->_replace[$i], $i); + $this->_repSize[$i] = count($rep); + } + } + + /** + * Returns true if based on the buffer passed more bytes should be buffered. + * + * @param array $buffer + * + * @return bool + */ + public function shouldBuffer($buffer) + { + $endOfBuffer = end($buffer); + + return isset ($this->_index[$endOfBuffer]); + } + + /** + * Perform the actual replacements on $buffer and return the result. + * + * @param array $buffer + * @param int $_minReplaces + * + * @return array + */ + public function filter($buffer, $_minReplaces = -1) + { + if ($this->_treeMaxLen == 0) { + return $buffer; + } + + $newBuffer = array(); + $buf_size = count($buffer); + for ($i = 0; $i < $buf_size; ++$i) { + $search_pos = $this->_tree; + $last_found = PHP_INT_MAX; + // We try to find if the next byte is part of a search pattern + for ($j = 0; $j <= $this->_treeMaxLen; ++$j) { + // We have a new byte for a search pattern + if (isset ($buffer [$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { + $search_pos = $search_pos[$buffer[$p]]; + // We have a complete pattern, save, in case we don't find a better match later + if (isset($search_pos[- 1]) && $search_pos[-1] < $last_found + && $search_pos[-1] > $_minReplaces) { + $last_found = $search_pos[-1]; + $last_size = $search_pos[-2]; + } + } + // We got a complete pattern + elseif ($last_found !== PHP_INT_MAX) { + // Adding replacement datas to output buffer + $rep_size = $this->_repSize[$last_found]; + for ($j = 0; $j < $rep_size; ++$j) { + $newBuffer[] = $this->_replace[$last_found][$j]; + } + // We Move cursor forward + $i += $last_size - 1; + // Edge Case, last position in buffer + if ($i >= $buf_size) { + $newBuffer[] = $buffer[$i]; + } + + // We start the next loop + continue 2; + } else { + // this byte is not in a pattern and we haven't found another pattern + break; + } + } + // Normal byte, move it to output buffer + $newBuffer[] = $buffer[$i]; + } + + return $newBuffer; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php new file mode 100644 index 00000000..e6b9e7b8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilter.php @@ -0,0 +1,66 @@ +_search = $search; + $this->_replace = $replace; + } + + /** + * Returns true if based on the buffer passed more bytes should be buffered. + * + * @param string $buffer + * + * @return bool + */ + public function shouldBuffer($buffer) + { + $endOfBuffer = substr($buffer, -1); + foreach ((array) $this->_search as $needle) { + if (false !== strpos($needle, $endOfBuffer)) { + return true; + } + } + + return false; + } + + /** + * Perform the actual replacements on $buffer and return the result. + * + * @param string $buffer + * + * @return string + */ + public function filter($buffer) + { + return str_replace($this->_search, $this->_replace, $buffer); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php new file mode 100644 index 00000000..4b12cfff --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/StreamFilters/StringReplacementFilterFactory.php @@ -0,0 +1,45 @@ +_filters[$search][$replace])) { + if (!isset($this->_filters[$search])) { + $this->_filters[$search] = array(); + } + + if (!isset($this->_filters[$search][$replace])) { + $this->_filters[$search][$replace] = array(); + } + + $this->_filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); + } + + return $this->_filters[$search][$replace]; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php new file mode 100644 index 00000000..22ee3eb4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SwiftException.php @@ -0,0 +1,27 @@ +_eventDispatcher = $dispatcher; + $this->_buffer = $buf; + $this->_lookupHostname(); + } + + /** + * Set the name of the local domain which Swift will identify itself as. + * + * This should be a fully-qualified domain name and should be truly the domain + * you're using. + * + * If your server doesn't have a domain name, use the IP in square + * brackets (i.e. [127.0.0.1]). + * + * @param string $domain + * + * @return Swift_Transport_AbstractSmtpTransport + */ + public function setLocalDomain($domain) + { + $this->_domain = $domain; + + return $this; + } + + /** + * Get the name of the domain Swift will identify as. + * + * @return string + */ + public function getLocalDomain() + { + return $this->_domain; + } + + /** + * Sets the source IP. + * + * @param string $source + */ + public function setSourceIp($source) + { + $this->_sourceIp = $source; + } + + /** + * Returns the IP used to connect to the destination + * + * @return string + */ + public function getSourceIp() + { + return $this->_sourceIp; + } + + /** + * Start the SMTP connection. + */ + public function start() + { + if (!$this->_started) { + if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); + if ($evt->bubbleCancelled()) { + return; + } + } + + try { + $this->_buffer->initialize($this->_getBufferParams()); + } catch (Swift_TransportException $e) { + $this->_throwException($e); + } + $this->_readGreeting(); + $this->_doHeloCommand(); + + if ($evt) { + $this->_eventDispatcher->dispatchEvent($evt, 'transportStarted'); + } + + $this->_started = true; + } + } + + /** + * Test if an SMTP connection has been established. + * + * @return bool + */ + public function isStarted() + { + return $this->_started; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + $sent = 0; + $failedRecipients = (array) $failedRecipients; + + if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if (!$reversePath = $this->_getReversePath($message)) { + throw new Swift_TransportException( + 'Cannot send message without a sender address' + ); + } + + $to = (array) $message->getTo(); + $cc = (array) $message->getCc(); + $tos = array_merge($to, $cc); + $bcc = (array) $message->getBcc(); + + $message->setBcc(array()); + + try { + $sent += $this->_sendTo($message, $reversePath, $tos, $failedRecipients); + $sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients); + } catch (Exception $e) { + $message->setBcc($bcc); + throw $e; + } + + $message->setBcc($bcc); + + if ($evt) { + if ($sent == count($to) + count($cc) + count($bcc)) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + } elseif ($sent > 0) { + $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE); + } else { + $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); + } + $evt->setFailedRecipients($failedRecipients); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $message->generateId(); //Make sure a new Message ID is used + + return $sent; + } + + /** + * Stop the SMTP connection. + */ + public function stop() + { + if ($this->_started) { + if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); + if ($evt->bubbleCancelled()) { + return; + } + } + + try { + $this->executeCommand("QUIT\r\n", array(221)); + } catch (Swift_TransportException $e) { + } + + try { + $this->_buffer->terminate(); + + if ($evt) { + $this->_eventDispatcher->dispatchEvent($evt, 'transportStopped'); + } + } catch (Swift_TransportException $e) { + $this->_throwException($e); + } + } + $this->_started = false; + } + + /** + * Register a plugin. + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->_eventDispatcher->bindEventListener($plugin); + } + + /** + * Reset the current mail transaction. + */ + public function reset() + { + $this->executeCommand("RSET\r\n", array(250)); + } + + /** + * Get the IoBuffer where read/writes are occurring. + * + * @return Swift_Transport_IoBuffer + */ + public function getBuffer() + { + return $this->_buffer; + } + + /** + * Run a command against the buffer, expecting the given response codes. + * + * If no response codes are given, the response will not be validated. + * If codes are given, an exception will be thrown on an invalid response. + * + * @param string $command + * @param int[] $codes + * @param string[] $failures An array of failures by-reference + * + * @return string + */ + public function executeCommand($command, $codes = array(), &$failures = null) + { + $failures = (array) $failures; + $seq = $this->_buffer->write($command); + $response = $this->_getFullResponse($seq); + if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) { + $this->_eventDispatcher->dispatchEvent($evt, 'commandSent'); + } + $this->_assertResponseCode($response, $codes); + + return $response; + } + + /** Read the opening SMTP greeting */ + protected function _readGreeting() + { + $this->_assertResponseCode($this->_getFullResponse(0), array(220)); + } + + /** Send the HELO welcome */ + protected function _doHeloCommand() + { + $this->executeCommand( + sprintf("HELO %s\r\n", $this->_domain), array(250) + ); + } + + /** Send the MAIL FROM command */ + protected function _doMailFromCommand($address) + { + $this->executeCommand( + sprintf("MAIL FROM: <%s>\r\n", $address), array(250) + ); + } + + /** Send the RCPT TO command */ + protected function _doRcptToCommand($address) + { + $this->executeCommand( + sprintf("RCPT TO: <%s>\r\n", $address), array(250, 251, 252) + ); + } + + /** Send the DATA command */ + protected function _doDataCommand() + { + $this->executeCommand("DATA\r\n", array(354)); + } + + /** Stream the contents of the message over the buffer */ + protected function _streamMessage(Swift_Mime_Message $message) + { + $this->_buffer->setWriteTranslations(array("\r\n." => "\r\n..")); + try { + $message->toByteStream($this->_buffer); + $this->_buffer->flushBuffers(); + } catch (Swift_TransportException $e) { + $this->_throwException($e); + } + $this->_buffer->setWriteTranslations(array()); + $this->executeCommand("\r\n.\r\n", array(250)); + } + + /** Determine the best-use reverse path for this message */ + protected function _getReversePath(Swift_Mime_Message $message) + { + $return = $message->getReturnPath(); + $sender = $message->getSender(); + $from = $message->getFrom(); + $path = null; + if (!empty($return)) { + $path = $return; + } elseif (!empty($sender)) { + // Don't use array_keys + reset($sender); // Reset Pointer to first pos + $path = key($sender); // Get key + } elseif (!empty($from)) { + reset($from); // Reset Pointer to first pos + $path = key($from); // Get key + } + + return $path; + } + + /** Throw a TransportException, first sending it to any listeners */ + protected function _throwException(Swift_TransportException $e) + { + if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { + $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); + if (!$evt->bubbleCancelled()) { + throw $e; + } + } else { + throw $e; + } + } + + /** Throws an Exception if a response code is incorrect */ + protected function _assertResponseCode($response, $wanted) + { + list($code) = sscanf($response, '%3d'); + $valid = (empty($wanted) || in_array($code, $wanted)); + + if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response, + $valid)) { + $this->_eventDispatcher->dispatchEvent($evt, 'responseReceived'); + } + + if (!$valid) { + $this->_throwException( + new Swift_TransportException( + 'Expected response code '.implode('/', $wanted).' but got code '. + '"'.$code.'", with message "'.$response.'"', + $code) + ); + } + } + + /** Get an entire multi-line response using its sequence number */ + protected function _getFullResponse($seq) + { + $response = ''; + try { + do { + $line = $this->_buffer->readLine($seq); + $response .= $line; + } while (null !== $line && false !== $line && ' ' != $line{3}); + } catch (Swift_TransportException $e) { + $this->_throwException($e); + } catch (Swift_IoException $e) { + $this->_throwException( + new Swift_TransportException( + $e->getMessage()) + ); + } + + return $response; + } + + /** Send an email to the given recipients from the given reverse path */ + private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) + { + $sent = 0; + $this->_doMailFromCommand($reversePath); + foreach ($recipients as $forwardPath) { + try { + $this->_doRcptToCommand($forwardPath); + $sent++; + } catch (Swift_TransportException $e) { + $failedRecipients[] = $forwardPath; + } + } + + if ($sent != 0) { + $this->_doDataCommand(); + $this->_streamMessage($message); + } else { + $this->reset(); + } + + return $sent; + } + + /** Send a message to the given To: recipients */ + private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients) + { + if (empty($to)) { + return 0; + } + + return $this->_doMailTransaction($message, $reversePath, array_keys($to), + $failedRecipients); + } + + /** Send a message to all Bcc: recipients */ + private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients) + { + $sent = 0; + foreach ($bcc as $forwardPath => $name) { + $message->setBcc(array($forwardPath => $name)); + $sent += $this->_doMailTransaction( + $message, $reversePath, array($forwardPath), $failedRecipients + ); + } + + return $sent; + } + + /** Try to determine the hostname of the server this is run on */ + private function _lookupHostname() + { + if (!empty($_SERVER['SERVER_NAME']) + && $this->_isFqdn($_SERVER['SERVER_NAME'])) { + $this->_domain = $_SERVER['SERVER_NAME']; + } elseif (!empty($_SERVER['SERVER_ADDR'])) { + $this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']); + } + } + + /** Determine is the $hostname is a fully-qualified name */ + private function _isFqdn($hostname) + { + // We could do a really thorough check, but there's really no point + if (false !== $dotPos = strpos($hostname, '.')) { + return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1); + } else { + return false; + } + } + + /** + * Destructor. + */ + public function __destruct() + { + $this->stop(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php new file mode 100644 index 00000000..4774e032 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php @@ -0,0 +1,81 @@ +executeCommand("AUTH CRAM-MD5\r\n", array(334)); + $challenge = base64_decode(substr($challenge, 4)); + $message = base64_encode( + $username.' '.$this->_getResponse($password, $challenge) + ); + $agent->executeCommand(sprintf("%s\r\n", $message), array(235)); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", array(250)); + + return false; + } + } + + /** + * Generate a CRAM-MD5 response from a server challenge. + * + * @param string $secret + * @param string $challenge + * + * @return string + */ + private function _getResponse($secret, $challenge) + { + if (strlen($secret) > 64) { + $secret = pack('H32', md5($secret)); + } + + if (strlen($secret) < 64) { + $secret = str_pad($secret, 64, chr(0)); + } + + $k_ipad = substr($secret, 0, 64) ^ str_repeat(chr(0x36), 64); + $k_opad = substr($secret, 0, 64) ^ str_repeat(chr(0x5C), 64); + + $inner = pack('H32', md5($k_ipad.$challenge)); + $digest = md5($k_opad.$inner); + + return $digest; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php new file mode 100644 index 00000000..ebb35520 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php @@ -0,0 +1,51 @@ +executeCommand("AUTH LOGIN\r\n", array(334)); + $agent->executeCommand(sprintf("%s\r\n", base64_encode($username)), array(334)); + $agent->executeCommand(sprintf("%s\r\n", base64_encode($password)), array(235)); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", array(250)); + + return false; + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php new file mode 100644 index 00000000..2c02bd2c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php @@ -0,0 +1,700 @@ + + */ +class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator +{ + const NTLMSIG = "NTLMSSP\x00"; + const DESCONST = "KGS!@#$%"; + + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'NTLM'; + } + + /** + * Try to authenticate the user with $username and $password. + * + * @param Swift_Transport_SmtpAgent $agent + * @param string $username + * @param string $password + * + * @return bool + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) + { + if (!function_exists('mcrypt_module_open')) { + throw new LogicException('The mcrypt functions need to be enabled to use the NTLM authenticator.'); + } + + if (!function_exists('openssl_random_pseudo_bytes')) { + throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.'); + } + + if (!function_exists('bcmul')) { + throw new LogicException('The BCMatch functions must be enabled to use the NTLM authenticator.'); + } + + try { + // execute AUTH command and filter out the code at the beginning + // AUTH NTLM xxxx + $response = base64_decode(substr(trim($this->sendMessage1($agent)), 4)); + + // extra parameters for our unit cases + $timestamp = func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), "1000")); + $client = func_num_args() > 4 ? func_get_arg(4) : $this->getRandomBytes(8); + + // Message 3 response + $this->sendMessage3($response, $username, $password, $timestamp, $client, $agent); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", array(250)); + + return false; + } + } + + protected function si2bin($si, $bits = 32) + { + $bin = null; + if ($si >= -pow(2, $bits - 1) && ($si <= pow(2, $bits - 1))) { + // positive or zero + if ($si >= 0) { + $bin = base_convert($si, 10, 2); + // pad to $bits bit + $bin_length = strlen($bin); + if ($bin_length < $bits) { + $bin = str_repeat("0", $bits - $bin_length).$bin; + } + } else { + // negative + $si = -$si - pow(2, $bits); + $bin = base_convert($si, 10, 2); + $bin_length = strlen($bin); + if ($bin_length > $bits) { + $bin = str_repeat("1", $bits - $bin_length).$bin; + } + } + } + + return $bin; + } + + /** + * Send our auth message and returns the response + * + * @param Swift_Transport_SmtpAgent $agent + * @return string SMTP Response + */ + protected function sendMessage1(Swift_Transport_SmtpAgent $agent) + { + $message = $this->createMessage1(); + + return $agent->executeCommand(sprintf("AUTH %s %s\r\n", $this->getAuthKeyword(), base64_encode($message)), array(334)); + } + + /** + * Fetch all details of our response (message 2) + * + * @param string $response + * @return array our response parsed + */ + protected function parseMessage2($response) + { + $responseHex = bin2hex($response); + $length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2; + $offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2; + $challenge = $this->hex2bin(substr($responseHex, 48, 16)); + $context = $this->hex2bin(substr($responseHex, 64, 16)); + $targetInfoH = $this->hex2bin(substr($responseHex, 80, 16)); + $targetName = $this->hex2bin(substr($responseHex, $offset, $length)); + $offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2; + $targetInfoBlock = substr($responseHex, $offset); + list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock); + + return array( + $challenge, + $context, + $targetInfoH, + $targetName, + $domainName, + $serverName, + $DNSDomainName, + $DNSServerName, + $this->hex2bin($targetInfoBlock), + $terminatorByte, + ); + } + + /** + * Read the blob information in from message2 + * + * @param $block + * @return array + */ + protected function readSubBlock($block) + { + // remove terminatorByte cause it's always the same + $block = substr($block, 0, -8); + + $length = strlen($block); + $offset = 0; + $data = array(); + while ($offset < $length) { + $blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256; + $offset += 8; + $data[] = $this->hex2bin(substr($block, $offset, $blockLength * 2)); + $offset += $blockLength * 2; + } + + if (count($data) == 3) { + $data[] = $data[2]; + $data[2] = ''; + } + + $data[] = $this->createByte('00'); + + return $data; + } + + /** + * Send our final message with all our data + * + * @param string $response Message 1 response (message 2) + * @param string $username + * @param string $password + * @param string $timestamp + * @param string $client + * @param Swift_Transport_SmtpAgent $agent + * @param bool $v2 Use version2 of the protocol + * @return string + */ + protected function sendMessage3($response, $username, $password, $timestamp, $client, Swift_Transport_SmtpAgent $agent, $v2 = true) + { + list($domain, $username) = $this->getDomainAndUsername($username); + //$challenge, $context, $targetInfoH, $targetName, $domainName, $workstation, $DNSDomainName, $DNSServerName, $blob, $ter + list($challenge, , , , , $workstation, , , $blob) = $this->parseMessage2($response); + + if (!$v2) { + // LMv1 + $lmResponse = $this->createLMPassword($password, $challenge); + // NTLMv1 + $ntlmResponse = $this->createNTLMPassword($password, $challenge); + } else { + // LMv2 + $lmResponse = $this->createLMv2Password($password, $username, $domain, $challenge, $client); + // NTLMv2 + $ntlmResponse = $this->createNTLMv2Hash($password, $username, $domain, $challenge, $blob, $timestamp, $client); + } + + $message = $this->createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse); + + return $agent->executeCommand(sprintf("%s\r\n", base64_encode($message)), array(235)); + } + + /** + * Create our message 1 + * + * @return string + */ + protected function createMessage1() + { + return self::NTLMSIG + .$this->createByte('01') // Message 1 +.$this->createByte('0702'); // Flags + } + + /** + * Create our message 3 + * + * @param string $domain + * @param string $username + * @param string $workstation + * @param string $lmResponse + * @param string $ntlmResponse + * @return string + */ + protected function createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse) + { + // Create security buffers + $domainSec = $this->createSecurityBuffer($domain, 64); + $domainInfo = $this->readSecurityBuffer(bin2hex($domainSec)); + $userSec = $this->createSecurityBuffer($username, ($domainInfo[0] + $domainInfo[1]) / 2); + $userInfo = $this->readSecurityBuffer(bin2hex($userSec)); + $workSec = $this->createSecurityBuffer($workstation, ($userInfo[0] + $userInfo[1]) / 2); + $workInfo = $this->readSecurityBuffer(bin2hex($workSec)); + $lmSec = $this->createSecurityBuffer($lmResponse, ($workInfo[0] + $workInfo[1]) / 2, true); + $lmInfo = $this->readSecurityBuffer(bin2hex($lmSec)); + $ntlmSec = $this->createSecurityBuffer($ntlmResponse, ($lmInfo[0] + $lmInfo[1]) / 2, true); + + return self::NTLMSIG + .$this->createByte('03') // TYPE 3 message +.$lmSec // LM response header +.$ntlmSec // NTLM response header +.$domainSec // Domain header +.$userSec // User header +.$workSec // Workstation header +.$this->createByte("000000009a", 8) // session key header (empty) +.$this->createByte('01020000') // FLAGS +.$this->convertTo16bit($domain) // domain name +.$this->convertTo16bit($username) // username +.$this->convertTo16bit($workstation) // workstation +.$lmResponse + .$ntlmResponse; + } + + /** + * @param string $timestamp Epoch timestamp in microseconds + * @param string $client Random bytes + * @param string $targetInfo + * @return string + */ + protected function createBlob($timestamp, $client, $targetInfo) + { + return $this->createByte('0101') + .$this->createByte('00') + .$timestamp + .$client + .$this->createByte('00') + .$targetInfo + .$this->createByte('00'); + } + + /** + * Get domain and username from our username + * + * @example DOMAIN\username + * + * @param string $name + * @return array + */ + protected function getDomainAndUsername($name) + { + if (strpos($name, '\\') !== false) { + return explode('\\', $name); + } + + list($user, $domain) = explode('@', $name); + + return array($domain, $user); + } + + /** + * Create LMv1 response + * + * @param string $password + * @param string $challenge + * @return string + */ + protected function createLMPassword($password, $challenge) + { + // FIRST PART + $password = $this->createByte(strtoupper($password), 14, false); + list($key1, $key2) = str_split($password, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + + $constantDecrypt = $this->createByte($this->desEncrypt(self::DESCONST, $desKey1).$this->desEncrypt(self::DESCONST, $desKey2), 21, false); + + // SECOND PART + list($key1, $key2, $key3) = str_split($constantDecrypt, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + $desKey3 = $this->createDesKey($key3); + + return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); + } + + /** + * Create NTLMv1 response + * + * @param string $password + * @param string $challenge + * @return string + */ + protected function createNTLMPassword($password, $challenge) + { + // FIRST PART + $ntlmHash = $this->createByte($this->md4Encrypt($password), 21, false); + list($key1, $key2, $key3) = str_split($ntlmHash, 7); + + $desKey1 = $this->createDesKey($key1); + $desKey2 = $this->createDesKey($key2); + $desKey3 = $this->createDesKey($key3); + + return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); + } + + /** + * Convert a normal timestamp to a tenth of a microtime epoch time + * + * @param string $time + * @return string + */ + protected function getCorrectTimestamp($time) + { + // Get our timestamp (tricky!) + bcscale(0); + + $time = number_format($time, 0, '.', ''); // save microtime to string + $time = bcadd($time, "11644473600000"); // add epoch time + $time = bcmul($time, 10000); // tenths of a microsecond. + + $binary = $this->si2bin($time, 64); // create 64 bit binary string + $timestamp = ""; + for ($i = 0; $i < 8; $i++) { + $timestamp .= chr(bindec(substr($binary, -(($i + 1) * 8), 8))); + } + + return $timestamp; + } + + /** + * Create LMv2 response + * + * @param string $password + * @param string $username + * @param string $domain + * @param string $challenge NTLM Challenge + * @param string $client Random string + * @return string + */ + protected function createLMv2Password($password, $username, $domain, $challenge, $client) + { + $lmPass = '00'; // by default 00 + // if $password > 15 than we can't use this method + if (strlen($password) <= 15) { + $ntlmHash = $this->md4Encrypt($password); + $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); + + $lmPass = bin2hex($this->md5Encrypt($ntml2Hash, $challenge.$client).$client); + } + + return $this->createByte($lmPass, 24); + } + + /** + * Create NTLMv2 response + * + * @param string $password + * @param string $username + * @param string $domain + * @param string $challenge Hex values + * @param string $targetInfo Hex values + * @param string $timestamp + * @param string $client Random bytes + * @return string + * @see http://davenport.sourceforge.net/ntlm.html#theNtlmResponse + */ + protected function createNTLMv2Hash($password, $username, $domain, $challenge, $targetInfo, $timestamp, $client) + { + $ntlmHash = $this->md4Encrypt($password); + $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); + + // create blob + $blob = $this->createBlob($timestamp, $client, $targetInfo); + + $ntlmv2Response = $this->md5Encrypt($ntml2Hash, $challenge.$blob); + + return $ntlmv2Response.$blob; + } + + protected function createDesKey($key) + { + $material = array(bin2hex($key[0])); + $len = strlen($key); + for ($i = 1; $i < $len; $i++) { + list($high, $low) = str_split(bin2hex($key[$i])); + $v = $this->castToByte(ord($key[$i - 1]) << (7 + 1 - $i) | $this->uRShift(hexdec(dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xf)), $i)); + $material[] = str_pad(substr(dechex($v), -2), 2, '0', STR_PAD_LEFT); // cast to byte + } + $material[] = str_pad(substr(dechex($this->castToByte(ord($key[6]) << 1)), -2), 2, '0'); + + // odd parity + foreach ($material as $k => $v) { + $b = $this->castToByte(hexdec($v)); + $needsParity = (($this->uRShift($b, 7) ^ $this->uRShift($b, 6) ^ $this->uRShift($b, 5) + ^ $this->uRShift($b, 4) ^ $this->uRShift($b, 3) ^ $this->uRShift($b, 2) + ^ $this->uRShift($b, 1)) & 0x01) == 0; + + list($high, $low) = str_split($v); + if ($needsParity) { + $material[$k] = dechex(hexdec($high) | 0x0).dechex(hexdec($low) | 0x1); + } else { + $material[$k] = dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xe); + } + } + + return $this->hex2bin(implode('', $material)); + } + + /** HELPER FUNCTIONS */ + /** + * Create our security buffer depending on length and offset + * + * @param string $value Value we want to put in + * @param int $offset start of value + * @param bool $is16 Do we 16bit string or not? + * @return string + */ + protected function createSecurityBuffer($value, $offset, $is16 = false) + { + $length = strlen(bin2hex($value)); + $length = $is16 ? $length / 2 : $length; + $length = $this->createByte(str_pad(dechex($length), 2, '0', STR_PAD_LEFT), 2); + + return $length.$length.$this->createByte(dechex($offset), 4); + } + + /** + * Read our security buffer to fetch length and offset of our value + * + * @param string $value Securitybuffer in hex + * @return array array with length and offset + */ + protected function readSecurityBuffer($value) + { + $length = floor(hexdec(substr($value, 0, 4)) / 256) * 2; + $offset = floor(hexdec(substr($value, 8, 4)) / 256) * 2; + + return array($length, $offset); + } + + /** + * Cast to byte java equivalent to (byte) + * + * @param int $v + * @return int + */ + protected function castToByte($v) + { + return (($v + 128) % 256) - 128; + } + + /** + * Java unsigned right bitwise + * $a >>> $b + * + * @param int $a + * @param int $b + * @return int + */ + protected function uRShift($a, $b) + { + if ($b == 0) { + return $a; + } + + return ($a >> $b) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($b - 1)); + } + + /** + * Right padding with 0 to certain length + * + * @param string $input + * @param int $bytes Length of bytes + * @param bool $isHex Did we provided hex value + * @return string + */ + protected function createByte($input, $bytes = 4, $isHex = true) + { + if ($isHex) { + $byte = $this->hex2bin(str_pad($input, $bytes * 2, '00')); + } else { + $byte = str_pad($input, $bytes, "\x00"); + } + + return $byte; + } + + /** + * Create random bytes + * + * @param $length + * @return string + */ + protected function getRandomBytes($length) + { + $bytes = openssl_random_pseudo_bytes($length, $strong); + + if (false !== $bytes && true === $strong) { + return $bytes; + } + + throw new RuntimeException('OpenSSL did not produce a secure random number.'); + } + + /** ENCRYPTION ALGORITHMS */ + /** + * DES Encryption + * + * @param string $value + * @param string $key + * @return string + */ + protected function desEncrypt($value, $key) + { + $cipher = mcrypt_module_open(MCRYPT_DES, '', 'ecb', ''); + mcrypt_generic_init($cipher, $key, mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_DEV_RANDOM)); + + return mcrypt_generic($cipher, $value); + } + + /** + * MD5 Encryption + * + * @param string $key Encryption key + * @param string $msg Message to encrypt + * @return string + */ + protected function md5Encrypt($key, $msg) + { + $blocksize = 64; + if (strlen($key) > $blocksize) { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $blocksize, "\0"); + $ipadk = $key ^ str_repeat("\x36", $blocksize); + $opadk = $key ^ str_repeat("\x5c", $blocksize); + + return pack('H*', md5($opadk.pack('H*', md5($ipadk.$msg)))); + } + + /** + * MD4 Encryption + * + * @param string $input + * @return string + * @see http://php.net/manual/en/ref.hash.php + */ + protected function md4Encrypt($input) + { + $input = $this->convertTo16bit($input); + + return function_exists('hash') ? $this->hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); + } + + /** + * Convert UTF-8 to UTF-16 + * + * @param string $input + * @return string + */ + protected function convertTo16bit($input) + { + return iconv('UTF-8', 'UTF-16LE', $input); + } + + /** + * Hex2bin replacement for < PHP 5.4 + * @param string $hex + * @return string Binary + */ + protected function hex2bin($hex) + { + if (function_exists('hex2bin')) { + return hex2bin($hex); + } else { + return pack('H*', $hex); + } + } + + /** + * @param string $message + */ + protected function debug($message) + { + $message = bin2hex($message); + $messageId = substr($message, 16, 8); + echo substr($message, 0, 16)." NTLMSSP Signature
\n"; + echo $messageId." Type Indicator
\n"; + + if ($messageId == "02000000") { + $map = array( + 'Challenge', + 'Context', + 'Target Information Security Buffer', + 'Target Name Data', + 'NetBIOS Domain Name', + 'NetBIOS Server Name', + 'DNS Domain Name', + 'DNS Server Name', + 'BLOB', + 'Target Information Terminator', + ); + + $data = $this->parseMessage2($this->hex2bin($message)); + + foreach ($map as $key => $value) { + echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."
\n"; + } + } elseif ($messageId == "03000000") { + $i = 0; + $data[$i++] = substr($message, 24, 16); + list($lmLength, $lmOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 40, 16); + list($ntmlLength, $ntmlOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 56, 16); + list($targetLength, $targetOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 72, 16); + list($userLength, $userOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 88, 16); + list($workLength, $workOffset) = $this->readSecurityBuffer($data[$i - 1]); + + $data[$i++] = substr($message, 104, 16); + $data[$i++] = substr($message, 120, 8); + $data[$i++] = substr($message, $targetOffset, $targetLength); + $data[$i++] = substr($message, $userOffset, $userLength); + $data[$i++] = substr($message, $workOffset, $workLength); + $data[$i++] = substr($message, $lmOffset, $lmLength); + $data[$i] = substr($message, $ntmlOffset, $ntmlLength); + + $map = array( + 'LM Response Security Buffer', + 'NTLM Response Security Buffer', + 'Target Name Security Buffer', + 'User Name Security Buffer', + 'Workstation Name Security Buffer', + 'Session Key Security Buffer', + 'Flags', + 'Target Name Data', + 'User Name Data', + 'Workstation Name Data', + 'LM Response Data', + 'NTLM Response Data', + ); + + foreach ($map as $key => $value) { + echo $data[$key].' - '.$this->hex2bin($data[$key]).' ||| '.$value."
\n"; + } + } + + echo "

"; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php new file mode 100644 index 00000000..98f6d181 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php @@ -0,0 +1,50 @@ +executeCommand(sprintf("AUTH PLAIN %s\r\n", $message), array(235)); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", array(250)); + + return false; + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php new file mode 100644 index 00000000..80c00b98 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php @@ -0,0 +1,69 @@ + + * $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls') + * ->setAuthMode('XOAUTH2') + * ->setUsername('YOUR_EMAIL_ADDRESS') + * ->setPassword('YOUR_ACCESS_TOKEN'); + * + * + * @author xu.li + * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol + */ +class Swift_Transport_Esmtp_Auth_XOAuth2Authenticator implements Swift_Transport_Esmtp_Authenticator +{ + /** + * Get the name of the AUTH mechanism this Authenticator handles. + * + * @return string + */ + public function getAuthKeyword() + { + return 'XOAUTH2'; + } + + /** + * Try to authenticate the user with $email and $token. + * + * @param Swift_Transport_SmtpAgent $agent + * @param string $email + * @param string $token + * + * @return bool + */ + public function authenticate(Swift_Transport_SmtpAgent $agent, $email, $token) + { + try { + $param = $this->constructXOAuth2Params($email, $token); + $agent->executeCommand("AUTH XOAUTH2 ".$param."\r\n", array(235)); + + return true; + } catch (Swift_TransportException $e) { + $agent->executeCommand("RSET\r\n", array(250)); + + return false; + } + } + + /** + * Construct the auth parameter + * + * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol#the_sasl_xoauth2_mechanism + */ + protected function constructXOAuth2Params($email, $token) + { + return base64_encode("user=$email\1auth=Bearer $token\1\1"); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php new file mode 100644 index 00000000..6b83194c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php @@ -0,0 +1,263 @@ +setAuthenticators($authenticators); + } + + /** + * Set the Authenticators which can process a login request. + * + * @param Swift_Transport_Esmtp_Authenticator[] $authenticators + */ + public function setAuthenticators(array $authenticators) + { + $this->_authenticators = $authenticators; + } + + /** + * Get the Authenticators which can process a login request. + * + * @return Swift_Transport_Esmtp_Authenticator[] + */ + public function getAuthenticators() + { + return $this->_authenticators; + } + + /** + * Set the username to authenticate with. + * + * @param string $username + */ + public function setUsername($username) + { + $this->_username = $username; + } + + /** + * Get the username to authenticate with. + * + * @return string + */ + public function getUsername() + { + return $this->_username; + } + + /** + * Set the password to authenticate with. + * + * @param string $password + */ + public function setPassword($password) + { + $this->_password = $password; + } + + /** + * Get the password to authenticate with. + * + * @return string + */ + public function getPassword() + { + return $this->_password; + } + + /** + * Set the auth mode to use to authenticate. + * + * @param string $mode + */ + public function setAuthMode($mode) + { + $this->_auth_mode = $mode; + } + + /** + * Get the auth mode to use to authenticate. + * + * @return string + */ + public function getAuthMode() + { + return $this->_auth_mode; + } + + /** + * Get the name of the ESMTP extension this handles. + * + * @return bool + */ + public function getHandledKeyword() + { + return 'AUTH'; + } + + /** + * Set the parameters which the EHLO greeting indicated. + * + * @param string[] $parameters + */ + public function setKeywordParams(array $parameters) + { + $this->_esmtpParams = $parameters; + } + + /** + * Runs immediately after a EHLO has been issued. + * + * @param Swift_Transport_SmtpAgent $agent to read/write + */ + public function afterEhlo(Swift_Transport_SmtpAgent $agent) + { + if ($this->_username) { + $count = 0; + foreach ($this->_getAuthenticatorsForAgent() as $authenticator) { + if (in_array(strtolower($authenticator->getAuthKeyword()), + array_map('strtolower', $this->_esmtpParams))) { + $count++; + if ($authenticator->authenticate($agent, $this->_username, $this->_password)) { + return; + } + } + } + throw new Swift_TransportException( + 'Failed to authenticate on SMTP server with username "'. + $this->_username.'" using '.$count.' possible authenticators' + ); + } + } + + /** + * Not used. + */ + public function getMailParams() + { + return array(); + } + + /** + * Not used. + */ + public function getRcptParams() + { + return array(); + } + + /** + * Not used. + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = array(), &$failedRecipients = null, &$stop = false) + { + } + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword) + { + return 0; + } + + /** + * Returns an array of method names which are exposed to the Esmtp class. + * + * @return string[] + */ + public function exposeMixinMethods() + { + return array('setUsername', 'getUsername', 'setPassword', 'getPassword', 'setAuthMode', 'getAuthMode'); + } + + /** + * Not used. + */ + public function resetState() + { + } + + /** + * Returns the authenticator list for the given agent. + * + * @param Swift_Transport_SmtpAgent $agent + * + * @return array + */ + protected function _getAuthenticatorsForAgent() + { + if (!$mode = strtolower($this->_auth_mode)) { + return $this->_authenticators; + } + + foreach ($this->_authenticators as $authenticator) { + if (strtolower($authenticator->getAuthKeyword()) == $mode) { + return array($authenticator); + } + } + + throw new Swift_TransportException('Auth mode '.$mode.' is invalid'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php new file mode 100644 index 00000000..9078003a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/Authenticator.php @@ -0,0 +1,35 @@ +. + * + * @return string[] + */ + public function getMailParams(); + + /** + * Get params which are appended to RCPT TO:<>. + * + * @return string[] + */ + public function getRcptParams(); + + /** + * Runs when a command is due to be sent. + * + * @param Swift_Transport_SmtpAgent $agent to read/write + * @param string $command to send + * @param int[] $codes expected in response + * @param string[] $failedRecipients to collect failures + * @param bool $stop to be set true by-reference if the command is now sent + */ + public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = array(), &$failedRecipients = null, &$stop = false); + + /** + * Returns +1, -1 or 0 according to the rules for usort(). + * + * This method is called to ensure extensions can be execute in an appropriate order. + * + * @param string $esmtpKeyword to compare with + * + * @return int + */ + public function getPriorityOver($esmtpKeyword); + + /** + * Returns an array of method names which are exposed to the Esmtp class. + * + * @return string[] + */ + public function exposeMixinMethods(); + + /** + * Tells this handler to clear any buffers and reset its state. + */ + public function resetState(); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php new file mode 100644 index 00000000..e860a8ef --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php @@ -0,0 +1,386 @@ + 'tcp', + 'host' => 'localhost', + 'port' => 25, + 'timeout' => 30, + 'blocking' => 1, + 'tls' => false, + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + ); + + /** + * Creates a new EsmtpTransport using the given I/O buffer. + * + * @param Swift_Transport_IoBuffer $buf + * @param Swift_Transport_EsmtpHandler[] $extensionHandlers + * @param Swift_Events_EventDispatcher $dispatcher + */ + public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher) + { + parent::__construct($buf, $dispatcher); + $this->setExtensionHandlers($extensionHandlers); + } + + /** + * Set the host to connect to. + * + * @param string $host + * + * @return Swift_Transport_EsmtpTransport + */ + public function setHost($host) + { + $this->_params['host'] = $host; + + return $this; + } + + /** + * Get the host to connect to. + * + * @return string + */ + public function getHost() + { + return $this->_params['host']; + } + + /** + * Set the port to connect to. + * + * @param int $port + * + * @return Swift_Transport_EsmtpTransport + */ + public function setPort($port) + { + $this->_params['port'] = (int) $port; + + return $this; + } + + /** + * Get the port to connect to. + * + * @return int + */ + public function getPort() + { + return $this->_params['port']; + } + + /** + * Set the connection timeout. + * + * @param int $timeout seconds + * + * @return Swift_Transport_EsmtpTransport + */ + public function setTimeout($timeout) + { + $this->_params['timeout'] = (int) $timeout; + $this->_buffer->setParam('timeout', (int) $timeout); + + return $this; + } + + /** + * Get the connection timeout. + * + * @return int + */ + public function getTimeout() + { + return $this->_params['timeout']; + } + + /** + * Set the encryption type (tls or ssl) + * + * @param string $encryption + * + * @return Swift_Transport_EsmtpTransport + */ + public function setEncryption($encryption) + { + if ('tls' == $encryption) { + $this->_params['protocol'] = 'tcp'; + $this->_params['tls'] = true; + } else { + $this->_params['protocol'] = $encryption; + $this->_params['tls'] = false; + } + + return $this; + } + + /** + * Get the encryption type. + * + * @return string + */ + public function getEncryption() + { + return $this->_params['tls'] ? 'tls' : $this->_params['protocol']; + } + + /** + * Sets the source IP. + * + * @param string $source + * + * @return Swift_Transport_EsmtpTransport + */ + public function setSourceIp($source) + { + $this->_params['sourceIp'] = $source; + + return $this; + } + + /** + * Returns the IP used to connect to the destination. + * + * @return string + */ + public function getSourceIp() + { + return $this->_params['sourceIp']; + } + + /** + * Set ESMTP extension handlers. + * + * @param Swift_Transport_EsmtpHandler[] $handlers + * + * @return Swift_Transport_EsmtpTransport + */ + public function setExtensionHandlers(array $handlers) + { + $assoc = array(); + foreach ($handlers as $handler) { + $assoc[$handler->getHandledKeyword()] = $handler; + } + uasort($assoc, array($this, '_sortHandlers')); + $this->_handlers = $assoc; + $this->_setHandlerParams(); + + return $this; + } + + /** + * Get ESMTP extension handlers. + * + * @return Swift_Transport_EsmtpHandler[] + */ + public function getExtensionHandlers() + { + return array_values($this->_handlers); + } + + /** + * Run a command against the buffer, expecting the given response codes. + * + * If no response codes are given, the response will not be validated. + * If codes are given, an exception will be thrown on an invalid response. + * + * @param string $command + * @param int[] $codes + * @param string[] $failures An array of failures by-reference + * + * @return string + */ + public function executeCommand($command, $codes = array(), &$failures = null) + { + $failures = (array) $failures; + $stopSignal = false; + $response = null; + foreach ($this->_getActiveHandlers() as $handler) { + $response = $handler->onCommand( + $this, $command, $codes, $failures, $stopSignal + ); + if ($stopSignal) { + return $response; + } + } + + return parent::executeCommand($command, $codes, $failures); + } + + // -- Mixin invocation code + + /** Mixin handling method for ESMTP handlers */ + public function __call($method, $args) + { + foreach ($this->_handlers as $handler) { + if (in_array(strtolower($method), + array_map('strtolower', (array) $handler->exposeMixinMethods()) + )) { + $return = call_user_func_array(array($handler, $method), $args); + // Allow fluid method calls + if (is_null($return) && substr($method, 0, 3) == 'set') { + return $this; + } else { + return $return; + } + } + } + trigger_error('Call to undefined method '.$method, E_USER_ERROR); + } + + /** Get the params to initialize the buffer */ + protected function _getBufferParams() + { + return $this->_params; + } + + /** Overridden to perform EHLO instead */ + protected function _doHeloCommand() + { + try { + $response = $this->executeCommand( + sprintf("EHLO %s\r\n", $this->_domain), array(250) + ); + } catch (Swift_TransportException $e) { + return parent::_doHeloCommand(); + } + + if ($this->_params['tls']) { + try { + $this->executeCommand("STARTTLS\r\n", array(220)); + + if (!$this->_buffer->startTLS()) { + throw new Swift_TransportException('Unable to connect with TLS encryption'); + } + + try { + $response = $this->executeCommand( + sprintf("EHLO %s\r\n", $this->_domain), array(250) + ); + } catch (Swift_TransportException $e) { + return parent::_doHeloCommand(); + } + } catch (Swift_TransportException $e) { + $this->_throwException($e); + } + } + + $this->_capabilities = $this->_getCapabilities($response); + $this->_setHandlerParams(); + foreach ($this->_getActiveHandlers() as $handler) { + $handler->afterEhlo($this); + } + } + + /** Overridden to add Extension support */ + protected function _doMailFromCommand($address) + { + $handlers = $this->_getActiveHandlers(); + $params = array(); + foreach ($handlers as $handler) { + $params = array_merge($params, (array) $handler->getMailParams()); + } + $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; + $this->executeCommand( + sprintf("MAIL FROM: <%s>%s\r\n", $address, $paramStr), array(250) + ); + } + + /** Overridden to add Extension support */ + protected function _doRcptToCommand($address) + { + $handlers = $this->_getActiveHandlers(); + $params = array(); + foreach ($handlers as $handler) { + $params = array_merge($params, (array) $handler->getRcptParams()); + } + $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; + $this->executeCommand( + sprintf("RCPT TO: <%s>%s\r\n", $address, $paramStr), array(250, 251, 252) + ); + } + + /** Determine ESMTP capabilities by function group */ + private function _getCapabilities($ehloResponse) + { + $capabilities = array(); + $ehloResponse = trim($ehloResponse); + $lines = explode("\r\n", $ehloResponse); + array_shift($lines); + foreach ($lines as $line) { + if (preg_match('/^[0-9]{3}[ -]([A-Z0-9-]+)((?:[ =].*)?)$/Di', $line, $matches)) { + $keyword = strtoupper($matches[1]); + $paramStr = strtoupper(ltrim($matches[2], ' =')); + $params = !empty($paramStr) ? explode(' ', $paramStr) : array(); + $capabilities[$keyword] = $params; + } + } + + return $capabilities; + } + + /** Set parameters which are used by each extension handler */ + private function _setHandlerParams() + { + foreach ($this->_handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->_capabilities)) { + $handler->setKeywordParams($this->_capabilities[$keyword]); + } + } + } + + /** Get ESMTP handlers which are currently ok to use */ + private function _getActiveHandlers() + { + $handlers = array(); + foreach ($this->_handlers as $keyword => $handler) { + if (array_key_exists($keyword, $this->_capabilities)) { + $handlers[] = $handler; + } + } + + return $handlers; + } + + /** Custom sort for extension handler ordering */ + private function _sortHandlers($a, $b) + { + return $a->getPriorityOver($b->getHandledKeyword()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php new file mode 100644 index 00000000..eafde009 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/FailoverTransport.php @@ -0,0 +1,85 @@ +_transports); + $sent = 0; + + for ($i = 0; $i < $maxTransports + && $transport = $this->_getNextTransport(); ++$i) { + try { + if (!$transport->isStarted()) { + $transport->start(); + } + + return $transport->send($message, $failedRecipients); + } catch (Swift_TransportException $e) { + $this->_killCurrentTransport(); + } + } + + if (count($this->_transports) == 0) { + throw new Swift_TransportException( + 'All Transports in FailoverTransport failed, or no Transports available' + ); + } + + return $sent; + } + + protected function _getNextTransport() + { + if (!isset($this->_currentTransport)) { + $this->_currentTransport = parent::_getNextTransport(); + } + + return $this->_currentTransport; + } + + protected function _killCurrentTransport() + { + $this->_currentTransport = null; + parent::_killCurrentTransport(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php new file mode 100644 index 00000000..71b3f1e5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/IoBuffer.php @@ -0,0 +1,67 @@ +_transports = $transports; + $this->_deadTransports = array(); + } + + /** + * Get $transports to delegate to. + * + * @return Swift_Transport[] + */ + public function getTransports() + { + return array_merge($this->_transports, $this->_deadTransports); + } + + /** + * Test if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return count($this->_transports) > 0; + } + + /** + * Start this Transport mechanism. + */ + public function start() + { + $this->_transports = array_merge($this->_transports, $this->_deadTransports); + } + + /** + * Stop this Transport mechanism. + */ + public function stop() + { + foreach ($this->_transports as $transport) { + $transport->stop(); + } + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + $maxTransports = count($this->_transports); + $sent = 0; + + for ($i = 0; $i < $maxTransports + && $transport = $this->_getNextTransport(); ++$i) { + try { + if (!$transport->isStarted()) { + $transport->start(); + } + if ($sent = $transport->send($message, $failedRecipients)) { + break; + } + } catch (Swift_TransportException $e) { + $this->_killCurrentTransport(); + } + } + + if (count($this->_transports) == 0) { + throw new Swift_TransportException( + 'All Transports in LoadBalancedTransport failed, or no Transports available' + ); + } + + return $sent; + } + + /** + * Register a plugin. + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + foreach ($this->_transports as $transport) { + $transport->registerPlugin($plugin); + } + } + + /** + * Rotates the transport list around and returns the first instance. + * + * @return Swift_Transport + */ + protected function _getNextTransport() + { + if ($next = array_shift($this->_transports)) { + $this->_transports[] = $next; + } + + return $next; + } + + /** + * Tag the currently used (top of stack) transport as dead/useless. + */ + protected function _killCurrentTransport() + { + if ($transport = array_pop($this->_transports)) { + try { + $transport->stop(); + } catch (Exception $e) { + } + $this->_deadTransports[] = $transport; + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php new file mode 100644 index 00000000..77489ced --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/MailInvoker.php @@ -0,0 +1,32 @@ +_invoker = $invoker; + $this->_eventDispatcher = $eventDispatcher; + } + + /** + * Not used. + */ + public function isStarted() + { + return false; + } + + /** + * Not used. + */ + public function start() + { + } + + /** + * Not used. + */ + public function stop() + { + } + + /** + * Set the additional parameters used on the mail() function. + * + * This string is formatted for sprintf() where %s is the sender address. + * + * @param string $params + * + * @return Swift_Transport_MailTransport + */ + public function setExtraParams($params) + { + $this->_extraParams = $params; + + return $this; + } + + /** + * Get the additional parameters used on the mail() function. + * + * This string is formatted for sprintf() where %s is the sender address. + * + * @return string + */ + public function getExtraParams() + { + return $this->_extraParams; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * The return value is the number of recipients who were accepted for delivery. + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + $failedRecipients = (array) $failedRecipients; + + if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + $count = ( + count((array) $message->getTo()) + + count((array) $message->getCc()) + + count((array) $message->getBcc()) + ); + + $toHeader = $message->getHeaders()->get('To'); + $subjectHeader = $message->getHeaders()->get('Subject'); + + if (!$toHeader) { + throw new Swift_TransportException( + 'Cannot send message without a recipient' + ); + } + $to = $toHeader->getFieldBody(); + $subject = $subjectHeader ? $subjectHeader->getFieldBody() : ''; + + $reversePath = $this->_getReversePath($message); + + // Remove headers that would otherwise be duplicated + $message->getHeaders()->remove('To'); + $message->getHeaders()->remove('Subject'); + + $messageStr = $message->toString(); + + $message->getHeaders()->set($toHeader); + $message->getHeaders()->set($subjectHeader); + + // Separate headers from body + if (false !== $endHeaders = strpos($messageStr, "\r\n\r\n")) { + $headers = substr($messageStr, 0, $endHeaders)."\r\n"; //Keep last EOL + $body = substr($messageStr, $endHeaders + 4); + } else { + $headers = $messageStr."\r\n"; + $body = ''; + } + + unset($messageStr); + + if ("\r\n" != PHP_EOL) { + // Non-windows (not using SMTP) + $headers = str_replace("\r\n", PHP_EOL, $headers); + $body = str_replace("\r\n", PHP_EOL, $body); + } else { + // Windows, using SMTP + $headers = str_replace("\r\n.", "\r\n..", $headers); + $body = str_replace("\r\n.", "\r\n..", $body); + } + + if ($this->_invoker->mail($to, $subject, $body, $headers, + sprintf($this->_extraParams, $reversePath))) { + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + $evt->setFailedRecipients($failedRecipients); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + } else { + $failedRecipients = array_merge( + $failedRecipients, + array_keys((array) $message->getTo()), + array_keys((array) $message->getCc()), + array_keys((array) $message->getBcc()) + ); + + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); + $evt->setFailedRecipients($failedRecipients); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $message->generateId(); + + $count = 0; + } + + return $count; + } + + /** + * Register a plugin. + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->_eventDispatcher->bindEventListener($plugin); + } + + /** Determine the best-use reverse path for this message */ + private function _getReversePath(Swift_Mime_Message $message) + { + $return = $message->getReturnPath(); + $sender = $message->getSender(); + $from = $message->getFrom(); + $path = null; + if (!empty($return)) { + $path = $return; + } elseif (!empty($sender)) { + $keys = array_keys($sender); + $path = array_shift($keys); + } elseif (!empty($from)) { + $keys = array_keys($from); + $path = array_shift($keys); + } + + return $path; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php new file mode 100644 index 00000000..f87cfbf3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/NullTransport.php @@ -0,0 +1,93 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Pretends messages have been sent, but just ignores them. + * + * @author Fabien Potencier + */ +class Swift_Transport_NullTransport implements Swift_Transport +{ + /** The event dispatcher from the plugin API */ + private $_eventDispatcher; + + /** + * Constructor. + */ + public function __construct(Swift_Events_EventDispatcher $eventDispatcher) + { + $this->_eventDispatcher = $eventDispatcher; + } + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * Sends the given message. + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent emails + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $count = ( + count((array) $message->getTo()) + + count((array) $message->getCc()) + + count((array) $message->getBcc()) + ); + + return $count; + } + + /** + * Register a plugin. + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->_eventDispatcher->bindEventListener($plugin); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php new file mode 100644 index 00000000..c508cb13 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php @@ -0,0 +1,159 @@ + 30, + 'blocking' => 1, + 'command' => '/usr/sbin/sendmail -bs', + 'type' => Swift_Transport_IoBuffer::TYPE_PROCESS, + ); + + /** + * Create a new SendmailTransport with $buf for I/O. + * + * @param Swift_Transport_IoBuffer $buf + * @param Swift_Events_EventDispatcher $dispatcher + */ + public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) + { + parent::__construct($buf, $dispatcher); + } + + /** + * Start the standalone SMTP session if running in -bs mode. + */ + public function start() + { + if (false !== strpos($this->getCommand(), ' -bs')) { + parent::start(); + } + } + + /** + * Set the command to invoke. + * + * If using -t mode you are strongly advised to include -oi or -i in the flags. + * For example: /usr/sbin/sendmail -oi -t + * Swift will append a -f flag if one is not present. + * + * The recommended mode is "-bs" since it is interactive and failure notifications + * are hence possible. + * + * @param string $command + * + * @return Swift_Transport_SendmailTransport + */ + public function setCommand($command) + { + $this->_params['command'] = $command; + + return $this; + } + + /** + * Get the sendmail command which will be invoked. + * + * @return string + */ + public function getCommand() + { + return $this->_params['command']; + } + + /** + * Send the given Message. + * + * Recipient/sender data will be retrieved from the Message API. + * + * The return value is the number of recipients who were accepted for delivery. + * NOTE: If using 'sendmail -t' you will not be aware of any failures until + * they bounce (i.e. send() will always return 100% success). + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + $failedRecipients = (array) $failedRecipients; + $command = $this->getCommand(); + $buffer = $this->getBuffer(); + + if (false !== strpos($command, ' -t')) { + if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + if (false === strpos($command, ' -f')) { + $command .= ' -f'.escapeshellarg($this->_getReversePath($message)); + } + + $buffer->initialize(array_merge($this->_params, array('command' => $command))); + + if (false === strpos($command, ' -i') && false === strpos($command, ' -oi')) { + $buffer->setWriteTranslations(array("\r\n" => "\n", "\n." => "\n..")); + } else { + $buffer->setWriteTranslations(array("\r\n" => "\n")); + } + + $count = count((array) $message->getTo()) + + count((array) $message->getCc()) + + count((array) $message->getBcc()) + ; + $message->toByteStream($buffer); + $buffer->flushBuffers(); + $buffer->setWriteTranslations(array()); + $buffer->terminate(); + + if ($evt) { + $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); + $evt->setFailedRecipients($failedRecipients); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + $message->generateId(); + } elseif (false !== strpos($command, ' -bs')) { + $count = parent::send($message, $failedRecipients); + } else { + $this->_throwException(new Swift_TransportException( + 'Unsupported sendmail command flags ['.$command.']. '. + 'Must be one of "-bs" or "-t" but can include additional flags.' + )); + } + + return $count; + } + + /** Get the params to initialize the buffer */ + protected function _getBufferParams() + { + return $this->_params; + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php new file mode 100644 index 00000000..21e629a6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SimpleMailInvoker.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/** + * Stores Messages in a queue. + * + * @author Fabien Potencier + */ +class Swift_Transport_SpoolTransport implements Swift_Transport +{ + /** The spool instance */ + private $_spool; + + /** The event dispatcher from the plugin API */ + private $_eventDispatcher; + + /** + * Constructor. + */ + public function __construct(Swift_Events_EventDispatcher $eventDispatcher, Swift_Spool $spool = null) + { + $this->_eventDispatcher = $eventDispatcher; + $this->_spool = $spool; + } + + /** + * Sets the spool object. + * + * @param Swift_Spool $spool + * + * @return Swift_Transport_SpoolTransport + */ + public function setSpool(Swift_Spool $spool) + { + $this->_spool = $spool; + + return $this; + } + + /** + * Get the spool object. + * + * @return Swift_Spool + */ + public function getSpool() + { + return $this->_spool; + } + + /** + * Tests if this Transport mechanism has started. + * + * @return bool + */ + public function isStarted() + { + return true; + } + + /** + * Starts this Transport mechanism. + */ + public function start() + { + } + + /** + * Stops this Transport mechanism. + */ + public function stop() + { + } + + /** + * Sends the given message. + * + * @param Swift_Mime_Message $message + * @param string[] $failedRecipients An array of failures by-reference + * + * @return int The number of sent e-mail's + */ + public function send(Swift_Mime_Message $message, &$failedRecipients = null) + { + if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { + $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); + if ($evt->bubbleCancelled()) { + return 0; + } + } + + $success = $this->_spool->queueMessage($message); + + if ($evt) { + $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SUCCESS : Swift_Events_SendEvent::RESULT_FAILED); + $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + return 1; + } + + /** + * Register a plugin. + * + * @param Swift_Events_EventListener $plugin + */ + public function registerPlugin(Swift_Events_EventListener $plugin) + { + $this->_eventDispatcher->bindEventListener($plugin); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php new file mode 100644 index 00000000..53e2ffa8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php @@ -0,0 +1,321 @@ +_replacementFactory = $replacementFactory; + } + + /** + * Perform any initialization needed, using the given $params. + * + * Parameters will vary depending upon the type of IoBuffer used. + * + * @param array $params + */ + public function initialize(array $params) + { + $this->_params = $params; + switch ($params['type']) { + case self::TYPE_PROCESS: + $this->_establishProcessConnection(); + break; + case self::TYPE_SOCKET: + default: + $this->_establishSocketConnection(); + break; + } + } + + /** + * Set an individual param on the buffer (e.g. switching to SSL). + * + * @param string $param + * @param mixed $value + */ + public function setParam($param, $value) + { + if (isset($this->_stream)) { + switch ($param) { + case 'timeout': + if ($this->_stream) { + stream_set_timeout($this->_stream, $value); + } + break; + + case 'blocking': + if ($this->_stream) { + stream_set_blocking($this->_stream, 1); + } + + } + } + $this->_params[$param] = $value; + } + + public function startTLS() + { + return stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); + } + + /** + * Perform any shutdown logic needed. + */ + public function terminate() + { + if (isset($this->_stream)) { + switch ($this->_params['type']) { + case self::TYPE_PROCESS: + fclose($this->_in); + fclose($this->_out); + proc_close($this->_stream); + break; + case self::TYPE_SOCKET: + default: + fclose($this->_stream); + break; + } + } + $this->_stream = null; + $this->_out = null; + $this->_in = null; + } + + /** + * Set an array of string replacements which should be made on data written + * to the buffer. + * + * This could replace LF with CRLF for example. + * + * @param string[] $replacements + */ + public function setWriteTranslations(array $replacements) + { + foreach ($this->_translations as $search => $replace) { + if (!isset($replacements[$search])) { + $this->removeFilter($search); + unset($this->_translations[$search]); + } + } + + foreach ($replacements as $search => $replace) { + if (!isset($this->_translations[$search])) { + $this->addFilter( + $this->_replacementFactory->createFilter($search, $replace), $search + ); + $this->_translations[$search] = true; + } + } + } + + /** + * Get a line of output (including any CRLF). + * + * The $sequence number comes from any writes and may or may not be used + * depending upon the implementation. + * + * @param int $sequence of last write to scan from + * + * @return string + * + * @throws Swift_IoException + */ + public function readLine($sequence) + { + if (isset($this->_out) && !feof($this->_out)) { + $line = fgets($this->_out); + if (strlen($line) == 0) { + $metas = stream_get_meta_data($this->_out); + if ($metas['timed_out']) { + throw new Swift_IoException( + 'Connection to '. + $this->_getReadConnectionDescription(). + ' Timed Out' + ); + } + } + + return $line; + } + } + + /** + * Reads $length bytes from the stream into a string and moves the pointer + * through the stream by $length. + * + * If less bytes exist than are requested the remaining bytes are given instead. + * If no bytes are remaining at all, boolean false is returned. + * + * @param int $length + * + * @return string|bool + * + * @throws Swift_IoException + */ + public function read($length) + { + if (isset($this->_out) && !feof($this->_out)) { + $ret = fread($this->_out, $length); + if (strlen($ret) == 0) { + $metas = stream_get_meta_data($this->_out); + if ($metas['timed_out']) { + throw new Swift_IoException( + 'Connection to '. + $this->_getReadConnectionDescription(). + ' Timed Out' + ); + } + } + + return $ret; + } + } + + /** Not implemented */ + public function setReadPointer($byteOffset) + { + } + + /** Flush the stream contents */ + protected function _flush() + { + if (isset($this->_in)) { + fflush($this->_in); + } + } + + /** Write this bytes to the stream */ + protected function _commit($bytes) + { + if (isset($this->_in)) { + $bytesToWrite = strlen($bytes); + $totalBytesWritten = 0; + + while ($totalBytesWritten < $bytesToWrite) { + $bytesWritten = fwrite($this->_in, substr($bytes, $totalBytesWritten)); + if (false === $bytesWritten || 0 === $bytesWritten) { + break; + } + + $totalBytesWritten += $bytesWritten; + } + + if ($totalBytesWritten > 0) { + return ++$this->_sequence; + } + } + } + + /** + * Establishes a connection to a remote server. + */ + private function _establishSocketConnection() + { + $host = $this->_params['host']; + if (!empty($this->_params['protocol'])) { + $host = $this->_params['protocol'].'://'.$host; + } + $timeout = 15; + if (!empty($this->_params['timeout'])) { + $timeout = $this->_params['timeout']; + } + $options = array(); + if (!empty($this->_params['sourceIp'])) { + $options['socket']['bindto'] = $this->_params['sourceIp'].':0'; + } + $this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options)); + if (false === $this->_stream) { + throw new Swift_TransportException( + 'Connection could not be established with host '.$this->_params['host']. + ' ['.$errstr.' #'.$errno.']' + ); + } + if (!empty($this->_params['blocking'])) { + stream_set_blocking($this->_stream, 1); + } else { + stream_set_blocking($this->_stream, 0); + } + stream_set_timeout($this->_stream, $timeout); + $this->_in = & $this->_stream; + $this->_out = & $this->_stream; + } + + /** + * Opens a process for input/output. + */ + private function _establishProcessConnection() + { + $command = $this->_params['command']; + $descriptorSpec = array( + 0 => array('pipe', 'r'), + 1 => array('pipe', 'w'), + 2 => array('pipe', 'w'), + ); + $this->_stream = proc_open($command, $descriptorSpec, $pipes); + stream_set_blocking($pipes[2], 0); + if ($err = stream_get_contents($pipes[2])) { + throw new Swift_TransportException( + 'Process could not be started ['.$err.']' + ); + } + $this->_in = & $pipes[0]; + $this->_out = & $pipes[1]; + } + + private function _getReadConnectionDescription() + { + switch ($this->_params['type']) { + case self::TYPE_PROCESS: + return 'Process '.$this->_params['command']; + break; + + case self::TYPE_SOCKET: + default: + $host = $this->_params['host']; + if (!empty($this->_params['protocol'])) { + $host = $this->_params['protocol'].'://'.$host; + } + $host .= ':'.$this->_params['port']; + + return $host; + break; + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php new file mode 100644 index 00000000..bdcd23bb --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/classes/Swift/TransportException.php @@ -0,0 +1,27 @@ + + */ +class Swift_Validate +{ + /** + * Grammar Object + * + * @var Swift_Mime_Grammar + */ + private static $grammar = null; + + /** + * Checks if an e-mail address matches the current grammars. + * + * @param string $email + * + * @return bool + */ + public static function email($email) + { + if (self::$grammar === null) { + self::$grammar = Swift_DependencyContainer::getInstance() + ->lookup('mime.grammar'); + } + + return (bool) preg_match( + '/^'.self::$grammar->getDefinition('addr-spec').'$/D', + $email + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php new file mode 100644 index 00000000..6023448e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/cache_deps.php @@ -0,0 +1,23 @@ +register('cache') + ->asAliasOf('cache.array') + + ->register('tempdir') + ->asValue('/tmp') + + ->register('cache.null') + ->asSharedInstanceOf('Swift_KeyCache_NullKeyCache') + + ->register('cache.array') + ->asSharedInstanceOf('Swift_KeyCache_ArrayKeyCache') + ->withDependencies(array('cache.inputstream')) + + ->register('cache.disk') + ->asSharedInstanceOf('Swift_KeyCache_DiskKeyCache') + ->withDependencies(array('cache.inputstream', 'tempdir')) + + ->register('cache.inputstream') + ->asNewInstanceOf('Swift_KeyCache_SimpleKeyCacheInputStream') +; diff --git a/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php new file mode 100644 index 00000000..64d69d21 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/message_deps.php @@ -0,0 +1,9 @@ +register('message.message') + ->asNewInstanceOf('Swift_Message') + + ->register('message.mimepart') + ->asNewInstanceOf('Swift_MimePart') +; diff --git a/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php new file mode 100644 index 00000000..04f394b3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/mime_deps.php @@ -0,0 +1,123 @@ +register('properties.charset') + ->asValue('utf-8') + + ->register('mime.grammar') + ->asSharedInstanceOf('Swift_Mime_Grammar') + + ->register('mime.message') + ->asNewInstanceOf('Swift_Mime_SimpleMessage') + ->withDependencies(array( + 'mime.headerset', + 'mime.qpcontentencoder', + 'cache', + 'mime.grammar', + 'properties.charset', + )) + + ->register('mime.part') + ->asNewInstanceOf('Swift_Mime_MimePart') + ->withDependencies(array( + 'mime.headerset', + 'mime.qpcontentencoder', + 'cache', + 'mime.grammar', + 'properties.charset', + )) + + ->register('mime.attachment') + ->asNewInstanceOf('Swift_Mime_Attachment') + ->withDependencies(array( + 'mime.headerset', + 'mime.base64contentencoder', + 'cache', + 'mime.grammar', + )) + ->addConstructorValue($swift_mime_types) + + ->register('mime.embeddedfile') + ->asNewInstanceOf('Swift_Mime_EmbeddedFile') + ->withDependencies(array( + 'mime.headerset', + 'mime.base64contentencoder', + 'cache', + 'mime.grammar', + )) + ->addConstructorValue($swift_mime_types) + + ->register('mime.headerfactory') + ->asNewInstanceOf('Swift_Mime_SimpleHeaderFactory') + ->withDependencies(array( + 'mime.qpheaderencoder', + 'mime.rfc2231encoder', + 'mime.grammar', + 'properties.charset', + )) + + ->register('mime.headerset') + ->asNewInstanceOf('Swift_Mime_SimpleHeaderSet') + ->withDependencies(array('mime.headerfactory', 'properties.charset')) + + ->register('mime.qpheaderencoder') + ->asNewInstanceOf('Swift_Mime_HeaderEncoder_QpHeaderEncoder') + ->withDependencies(array('mime.charstream')) + + ->register('mime.base64headerencoder') + ->asNewInstanceOf('Swift_Mime_HeaderEncoder_Base64HeaderEncoder') + ->withDependencies(array('mime.charstream')) + + ->register('mime.charstream') + ->asNewInstanceOf('Swift_CharacterStream_NgCharacterStream') + ->withDependencies(array('mime.characterreaderfactory', 'properties.charset')) + + ->register('mime.bytecanonicalizer') + ->asSharedInstanceOf('Swift_StreamFilters_ByteArrayReplacementFilter') + ->addConstructorValue(array(array(0x0D, 0x0A), array(0x0D), array(0x0A))) + ->addConstructorValue(array(array(0x0A), array(0x0A), array(0x0D, 0x0A))) + + ->register('mime.characterreaderfactory') + ->asSharedInstanceOf('Swift_CharacterReaderFactory_SimpleCharacterReaderFactory') + + ->register('mime.safeqpcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') + ->withDependencies(array('mime.charstream', 'mime.bytecanonicalizer')) + + ->register('mime.rawcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_RawContentEncoder') + + ->register('mime.nativeqpcontentencoder') + ->withDependencies(array('properties.charset')) + ->asNewInstanceOf('Swift_Mime_ContentEncoder_NativeQpContentEncoder') + + ->register('mime.qpcontentencoderproxy') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoderProxy') + ->withDependencies(array('mime.safeqpcontentencoder', 'mime.nativeqpcontentencoder', 'properties.charset')) + + ->register('mime.7bitcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') + ->addConstructorValue('7bit') + ->addConstructorValue(true) + + ->register('mime.8bitcontentencoder') + ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') + ->addConstructorValue('8bit') + ->addConstructorValue(true) + + ->register('mime.base64contentencoder') + ->asSharedInstanceOf('Swift_Mime_ContentEncoder_Base64ContentEncoder') + + ->register('mime.rfc2231encoder') + ->asNewInstanceOf('Swift_Encoder_Rfc2231Encoder') + ->withDependencies(array('mime.charstream')) + + // As of PHP 5.4.7, the quoted_printable_encode() function behaves correctly. + // see https://github.com/php/php-src/commit/18bb426587d62f93c54c40bf8535eb8416603629 + ->register('mime.qpcontentencoder') + ->asAliasOf(version_compare(phpversion(), '5.4.7', '>=') ? 'mime.qpcontentencoderproxy' : 'mime.safeqpcontentencoder') +; + +unset($swift_mime_types); diff --git a/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php new file mode 100644 index 00000000..77e432cf --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php @@ -0,0 +1,76 @@ +register('transport.smtp') + ->asNewInstanceOf('Swift_Transport_EsmtpTransport') + ->withDependencies(array( + 'transport.buffer', + array('transport.authhandler'), + 'transport.eventdispatcher', + )) + + ->register('transport.sendmail') + ->asNewInstanceOf('Swift_Transport_SendmailTransport') + ->withDependencies(array( + 'transport.buffer', + 'transport.eventdispatcher', + )) + + ->register('transport.mail') + ->asNewInstanceOf('Swift_Transport_MailTransport') + ->withDependencies(array('transport.mailinvoker', 'transport.eventdispatcher')) + + ->register('transport.loadbalanced') + ->asNewInstanceOf('Swift_Transport_LoadBalancedTransport') + + ->register('transport.failover') + ->asNewInstanceOf('Swift_Transport_FailoverTransport') + + ->register('transport.spool') + ->asNewInstanceOf('Swift_Transport_SpoolTransport') + ->withDependencies(array('transport.eventdispatcher')) + + ->register('transport.null') + ->asNewInstanceOf('Swift_Transport_NullTransport') + ->withDependencies(array('transport.eventdispatcher')) + + ->register('transport.mailinvoker') + ->asSharedInstanceOf('Swift_Transport_SimpleMailInvoker') + + ->register('transport.buffer') + ->asNewInstanceOf('Swift_Transport_StreamBuffer') + ->withDependencies(array('transport.replacementfactory')) + + ->register('transport.authhandler') + ->asNewInstanceOf('Swift_Transport_Esmtp_AuthHandler') + ->withDependencies(array( + array( + 'transport.crammd5auth', + 'transport.loginauth', + 'transport.plainauth', + 'transport.ntlmauth', + 'transport.xoauth2auth', + ), + )) + + ->register('transport.crammd5auth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_CramMd5Authenticator') + + ->register('transport.loginauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_LoginAuthenticator') + + ->register('transport.plainauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_PlainAuthenticator') + + ->register('transport.xoauth2auth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_XOAuth2Authenticator') + + ->register('transport.ntlmauth') + ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_NTLMAuthenticator') + + ->register('transport.eventdispatcher') + ->asNewInstanceOf('Swift_Events_SimpleEventDispatcher') + + ->register('transport.replacementfactory') + ->asSharedInstanceOf('Swift_StreamFilters_StringReplacementFilterFactory') +; diff --git a/vendor/swiftmailer/swiftmailer/lib/mime_types.php b/vendor/swiftmailer/swiftmailer/lib/mime_types.php new file mode 100644 index 00000000..2d7b98dc --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/mime_types.php @@ -0,0 +1,1007 @@ + 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gpp', + '7z' => 'application/x-7z-compressed', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/x-aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/pkix-attr-cert', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'apk' => 'application/vnd.android.package-archive', + 'appcache' => 'text/cache-manifest', + 'apr' => 'application/vnd.lotus-approach', + 'aps' => 'application/postscript', + 'arc' => 'application/x-freearc', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/basic', + 'avi' => 'video/x-msvideo', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azw' => 'application/vnd.amazon.ebook', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'btif' => 'image/prs.btif', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/java-vm', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'csh' => 'application/x-csh', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/x-msdownload', + 'dmg' => 'application/x-apple-diskimage', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.document.macroenabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dra' => 'audio/vnd.dra', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'application/x-msmetafile', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/x-msdownload', + 'exi' => 'application/exi', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/x-f4v', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'geo' => 'application/vnd.dynageo', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/x-gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hdf' => 'application/x-hdf', + 'hh' => 'text/x-c', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'java' => 'text/x-java-source', + 'jisp' => 'application/vnd.jisp', + 'jlt' => 'application/vnd.hp-jlyt', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jpm' => 'video/jpm', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'jsonml' => 'application/jsonml+json', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'lha' => 'application/x-lzh-compressed', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/x-lzh-compressed', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm1v' => 'video/mpeg', + 'm21' => 'application/mp21', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'audio/x-mpegurl', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/mp4', + 'm4u' => 'video/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'mar' => 'application/octet-stream', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp21' => 'application/mp21', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msl' => 'application/vnd.mobius.msl', + 'msty' => 'application/vnd.muvee.style', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'ntf' => 'application/vnd.nitf', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obj' => 'application/x-tgif', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'org' => 'application/vnd.lotus-organizer', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'application/x-font-otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p10' => 'application/pkcs10', + 'p12' => 'application/x-pkcs12', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/vnd.palm', + 'pdf' => 'application/pdf', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp-encrypted', + 'php' => 'application/x-php', + 'php3' => 'application/x-php', + 'php4' => 'application/x-php', + 'php5' => 'application/x-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'application/x-mobipocket-ebook', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'image/vnd.adobe.photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-pn-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'application/vnd.rn-realmedia', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsd' => 'application/rsd+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'rtx' => 'text/richtext', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shf' => 'application/shf+xml', + 'sid' => 'image/x-mrsid-image', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil+xml', + 'smil' => 'application/smil+xml', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'application/vnd.ms-pki.stl', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tga' => 'image/x-tga', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tmo' => 'application/vnd.tmobile-livetv', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trm' => 'application/x-msterminal', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'application/x-font-ttf', + 'ttf' => 'application/x-font-ttf', + 'ttl' => 'text/turtle', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u32' => 'application/x-authorware-bin', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgt' => 'application/widget', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'application/x-msmetafile', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'application/font-woff', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x32' => 'application/x-authorware-bin', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+binary', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d+vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/vnd.adobe.xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/x-xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + '123' => 'application/vnd.lotus-1-2-3', +); diff --git a/vendor/swiftmailer/swiftmailer/lib/preferences.php b/vendor/swiftmailer/swiftmailer/lib/preferences.php new file mode 100644 index 00000000..e5195014 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/preferences.php @@ -0,0 +1,25 @@ +setCharset('utf-8'); + +// Without these lines the default caching mechanism is "array" but this uses a lot of memory. +// If possible, use a disk cache to enable attaching large attachments etc. +// You can override the default temporary directory by setting the TMPDIR environment variable. +if (@is_writable($tmpDir = sys_get_temp_dir())) { + $preferences->setTempDir($tmpDir)->setCacheType('disk'); +} + +// this should only be done when Swiftmailer won't use the native QP content encoder +// see mime_deps.php +if (version_compare(phpversion(), '5.4.7', '<')) { + $preferences->setQPDotEscape(false); +} diff --git a/vendor/swiftmailer/swiftmailer/lib/swift_init.php b/vendor/swiftmailer/swiftmailer/lib/swift_init.php new file mode 100644 index 00000000..5c4bae4f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/lib/swift_init.php @@ -0,0 +1,28 @@ + 'application/x-php', + 'php3' => 'application/x-php', + 'php4' => 'application/x-php', + 'php5' => 'application/x-php', + 'zip' => 'application/zip', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'css' => 'text/css', + 'js' => 'text/javascript', + 'txt' => 'text/plain', + 'xml' => 'text/xml', + 'aif' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'avi' => 'video/avi', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bz2', + 'csv' => 'text/csv', + 'dmg' => 'application/x-apple-diskimage', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eml' => 'message/rfc822', + 'aps' => 'application/postscript', + 'exe' => 'application/x-ms-dos-executable', + 'flv' => 'video/x-flv', + 'gz' => 'application/x-gzip', + 'hqx' => 'application/stuffit', + 'htm' => 'text/html', + 'html' => 'text/html', + 'jar' => 'application/x-java-archive', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'm3u' => 'audio/x-mpegurl', + 'm4a' => 'audio/mp4', + 'mdb' => 'application/x-msaccess', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'odg' => 'vnd.oasis.opendocument.graphics', + 'odp' => 'vnd.oasis.opendocument.presentation', + 'odt' => 'vnd.oasis.opendocument.text', + 'ods' => 'vnd.oasis.opendocument.spreadsheet', + 'ogg' => 'audio/ogg', + 'pdf' => 'application/pdf', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'rar' => 'application/x-rar-compressed', + 'rtf' => 'application/rtf', + 'tar' => 'application/x-tar', + 'sit' => 'application/x-stuffit', + 'svg' => 'image/svg+xml', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'ttf' => 'application/x-font-truetype', + 'vcf' => 'text/x-vcard', + 'wav' => 'audio/wav', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'audio/x-ms-wmv', + 'xls' => 'application/excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + ); + + // wrap array for generating file + foreach ($valid_mime_types_preset as $extension => $mime_type) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + + // collect extensions + $valid_extensions = array(); + + // all extensions from second match + foreach ($matches[2] as $i => $extensions) { + // explode multiple extensions from string + $extensions = explode(" ", strtolower($extensions)); + + // force array for foreach + if (!is_array($extensions)) { + $extensions = array($extensions); + } + + foreach ($extensions as $extension) { + // get mime type + $mime_type = $matches[1][$i]; + + // check if string length lower than 10 + if (strlen($extension) < 10) { + // add extension + $valid_extensions[] = $extension; + + if (!isset($valid_mime_types[$mime_type])) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + } + } + } + } + + $xml = simplexml_load_string($mime_xml); + + foreach ($xml as $node) { + // check if there is no pattern + if (!isset($node->glob["pattern"])) { + continue; + } + + // get all matching extensions from match + foreach ((array) $node->glob["pattern"] as $extension) { + // skip none glob extensions + if (strpos($extension, '.') === FALSE) { + continue; + } + + // remove get only last part + $extension = explode('.', strtolower($extension)); + $extension = end($extension); + + // maximum length in database column + if (strlen($extension) <= 9) { + $valid_extensions[] = $extension; + } + } + + if (isset($node->glob["pattern"][0])) { + // mime type + $mime_type = strtolower((string) $node["type"]); + + // get first extension + $extension = strtolower(trim($node->glob["ddpattern"][0], '*.')); + + // skip none glob extensions and check if string length between 1 and 10 + if (strpos($extension, '.') !== FALSE || strlen($extension) < 1 || strlen($extension) > 9) { + continue; + } + + // check if string length lower than 10 + if (!isset($valid_mime_types[$mime_type])) { + // generate array for mimetype to extension resolver (only first match) + $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; + } + } + } + + // full list of valid extensions only + $valid_mime_types = array_unique($valid_mime_types); + ksort($valid_mime_types); + + // combine mime types and extensions array + $output = "$preamble\$swift_mime_types = array(\n ".implode($valid_mime_types, ",\n ")."\n);"; + + // write mime_types.php config file + @file_put_contents('./mime_types.php', $output); +} + +generateUpToDateMimeArray(); diff --git a/vendor/swiftmailer/swiftmailer/notes/APPS b/vendor/swiftmailer/swiftmailer/notes/APPS new file mode 100644 index 00000000..b06b4cc0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/APPS @@ -0,0 +1,15 @@ +Applications I need to test with +--------------------------------- + +Standalone (can read .eml files): +--------------------------------- +Microsoft Entourage (can assume same as outlook) +Mozilla Thunderbird +Apple Mail + +Web-based: +---------- +Hotmail +Gmail +Yahoo! +Mail2Web diff --git a/vendor/swiftmailer/swiftmailer/notes/CHARSETS b/vendor/swiftmailer/swiftmailer/notes/CHARSETS new file mode 100644 index 00000000..6a97a89c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/CHARSETS @@ -0,0 +1,46 @@ +Following is a list of character sets along with their widths: +-------------------------------------------------------------- + +1 Octet 8bit: +------------- +Windows 125* (CP125*) +CP* +ANSI +ISO-8859-* (IEC-8859-*) +Macintosh (Mac OS Roman) +KOI8-U (potentially KOI*8-*) +KOI8-R +MIK +Cork (T1) +ISCII +VISCII + + +1 Octet 7bit: +------------- +US-ASCII +K0I7 + +2 octets 16 bit: +---------------- +UCS-2 +UTF-16* (UTF-16BE etc) + +4-octets 32 bit: +---------------- +UCS-4 +UTF-32 + +Variable-width: +---------------------------- +Big5 - http://en.wikipedia.org/wiki/Big5 (1-2 bytes: 00-7f=1, 81-fe=2) +HKSCS - http://en.wikipedia.org/wiki/HKSCS (a big5 variant, but some variants use 10646) +ISO-10646 (IEC-10646) - http://en.wikipedia.org/wiki/ISO_10646 (unicode) +UTF-8 (1-5 bytes) +ISO-2022 (IEC-2022) - http://en.wikipedia.org/wiki/ISO_2022 +Shift-JIS - http://en.wikipedia.org/wiki/Shift-JIS + +A good resource: +---------------- +http://en.wikipedia.org/wiki/Character_encoding#Simple_character_sets + diff --git a/vendor/swiftmailer/swiftmailer/notes/message.xml b/vendor/swiftmailer/swiftmailer/notes/message.xml new file mode 100644 index 00000000..1183ecaa --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/message.xml @@ -0,0 +1,22 @@ + + + Some test message + chris@w3style.co.uk + mark@swiftmailer.org + chris.corbyn@sitepoint.com + text/plain + + Here's a recipe for beef stifado + + + text/html + + This is the other part + + + + application/pdf + stifado.pdf + /path/to/stifado.pdf + + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0821.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0821.txt new file mode 100644 index 00000000..d877b72c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0821.txt @@ -0,0 +1,4050 @@ + + + + RFC 821 + + + + + + SIMPLE MAIL TRANSFER PROTOCOL + + + + Jonathan B. Postel + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + August 1982 + + + + Information Sciences Institute + University of Southern California + 4676 Admiralty Way + Marina del Rey, California 90291 + + (213) 822-1511 + + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + TABLE OF CONTENTS + + 1. INTRODUCTION .................................................. 1 + + 2. THE SMTP MODEL ................................................ 2 + + 3. THE SMTP PROCEDURE ............................................ 4 + + 3.1. Mail ..................................................... 4 + 3.2. Forwarding ............................................... 7 + 3.3. Verifying and Expanding .................................. 8 + 3.4. Sending and Mailing ..................................... 11 + 3.5. Opening and Closing ..................................... 13 + 3.6. Relaying ................................................ 14 + 3.7. Domains ................................................. 17 + 3.8. Changing Roles .......................................... 18 + + 4. THE SMTP SPECIFICATIONS ...................................... 19 + + 4.1. SMTP Commands ........................................... 19 + 4.1.1. Command Semantics ..................................... 19 + 4.1.2. Command Syntax ........................................ 27 + 4.2. SMTP Replies ............................................ 34 + 4.2.1. Reply Codes by Function Group ......................... 35 + 4.2.2. Reply Codes in Numeric Order .......................... 36 + 4.3. Sequencing of Commands and Replies ...................... 37 + 4.4. State Diagrams .......................................... 39 + 4.5. Details ................................................. 41 + 4.5.1. Minimum Implementation ................................ 41 + 4.5.2. Transparency .......................................... 41 + 4.5.3. Sizes ................................................. 42 + + APPENDIX A: TCP ................................................. 44 + APPENDIX B: NCP ................................................. 45 + APPENDIX C: NITS ................................................ 46 + APPENDIX D: X.25 ................................................ 47 + APPENDIX E: Theory of Reply Codes ............................... 48 + APPENDIX F: Scenarios ........................................... 51 + + GLOSSARY ......................................................... 64 + + REFERENCES ....................................................... 67 + + + + +Network Working Group J. Postel +Request for Comments: DRAFT ISI +Replaces: RFC 788, 780, 772 August 1982 + + SIMPLE MAIL TRANSFER PROTOCOL + + +1. INTRODUCTION + + The objective of Simple Mail Transfer Protocol (SMTP) is to transfer + mail reliably and efficiently. + + SMTP is independent of the particular transmission subsystem and + requires only a reliable ordered data stream channel. Appendices A, + B, C, and D describe the use of SMTP with various transport services. + A Glossary provides the definitions of terms as used in this + document. + + An important feature of SMTP is its capability to relay mail across + transport service environments. A transport service provides an + interprocess communication environment (IPCE). An IPCE may cover one + network, several networks, or a subset of a network. It is important + to realize that transport systems (or IPCEs) are not one-to-one with + networks. A process can communicate directly with another process + through any mutually known IPCE. Mail is an application or use of + interprocess communication. Mail can be communicated between + processes in different IPCEs by relaying through a process connected + to two (or more) IPCEs. More specifically, mail can be relayed + between hosts on different transport systems by a host on both + transport systems. + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 1] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +2. THE SMTP MODEL + + The SMTP design is based on the following model of communication: as + the result of a user mail request, the sender-SMTP establishes a + two-way transmission channel to a receiver-SMTP. The receiver-SMTP + may be either the ultimate destination or an intermediate. SMTP + commands are generated by the sender-SMTP and sent to the + receiver-SMTP. SMTP replies are sent from the receiver-SMTP to the + sender-SMTP in response to the commands. + + Once the transmission channel is established, the SMTP-sender sends a + MAIL command indicating the sender of the mail. If the SMTP-receiver + can accept mail it responds with an OK reply. The SMTP-sender then + sends a RCPT command identifying a recipient of the mail. If the + SMTP-receiver can accept mail for that recipient it responds with an + OK reply; if not, it responds with a reply rejecting that recipient + (but not the whole mail transaction). The SMTP-sender and + SMTP-receiver may negotiate several recipients. When the recipients + have been negotiated the SMTP-sender sends the mail data, terminating + with a special sequence. If the SMTP-receiver successfully processes + the mail data it responds with an OK reply. The dialog is purposely + lock-step, one-at-a-time. + + ------------------------------------------------------------- + + + +----------+ +----------+ + +------+ | | | | + | User |<-->| | SMTP | | + +------+ | Sender- |Commands/Replies| Receiver-| + +------+ | SMTP |<-------------->| SMTP | +------+ + | File |<-->| | and Mail | |<-->| File | + |System| | | | | |System| + +------+ +----------+ +----------+ +------+ + + + Sender-SMTP Receiver-SMTP + + Model for SMTP Use + + Figure 1 + + ------------------------------------------------------------- + + The SMTP provides mechanisms for the transmission of mail; directly + from the sending user's host to the receiving user's host when the + + + +[Page 2] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + two host are connected to the same transport service, or via one or + more relay SMTP-servers when the source and destination hosts are not + connected to the same transport service. + + To be able to provide the relay capability the SMTP-server must be + supplied with the name of the ultimate destination host as well as + the destination mailbox name. + + The argument to the MAIL command is a reverse-path, which specifies + who the mail is from. The argument to the RCPT command is a + forward-path, which specifies who the mail is to. The forward-path + is a source route, while the reverse-path is a return route (which + may be used to return a message to the sender when an error occurs + with a relayed message). + + When the same message is sent to multiple recipients the SMTP + encourages the transmission of only one copy of the data for all the + recipients at the same destination host. + + The mail commands and replies have a rigid syntax. Replies also have + a numeric code. In the following, examples appear which use actual + commands and replies. The complete lists of commands and replies + appears in Section 4 on specifications. + + Commands and replies are not case sensitive. That is, a command or + reply word may be upper case, lower case, or any mixture of upper and + lower case. Note that this is not true of mailbox user names. For + some hosts the user name is case sensitive, and SMTP implementations + must take case to preserve the case of user names as they appear in + mailbox arguments. Host names are not case sensitive. + + Commands and replies are composed of characters from the ASCII + character set [1]. When the transport service provides an 8-bit byte + (octet) transmission channel, each 7-bit character is transmitted + right justified in an octet with the high order bit cleared to zero. + + When specifying the general form of a command or reply, an argument + (or special symbol) will be denoted by a meta-linguistic variable (or + constant), for example, "" or "". Here the + angle brackets indicate these are meta-linguistic variables. + However, some arguments use the angle brackets literally. For + example, an actual reverse-path is enclosed in angle brackets, i.e., + "" is an instance of (the + angle brackets are actually transmitted in the command or reply). + + + + + +Postel [Page 3] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +3. THE SMTP PROCEDURES + + This section presents the procedures used in SMTP in several parts. + First comes the basic mail procedure defined as a mail transaction. + Following this are descriptions of forwarding mail, verifying mailbox + names and expanding mailing lists, sending to terminals instead of or + in combination with mailboxes, and the opening and closing exchanges. + At the end of this section are comments on relaying, a note on mail + domains, and a discussion of changing roles. Throughout this section + are examples of partial command and reply sequences, several complete + scenarios are presented in Appendix F. + + 3.1. MAIL + + There are three steps to SMTP mail transactions. The transaction + is started with a MAIL command which gives the sender + identification. A series of one or more RCPT commands follows + giving the receiver information. Then a DATA command gives the + mail data. And finally, the end of mail data indicator confirms + the transaction. + + The first step in the procedure is the MAIL command. The + contains the source mailbox. + + MAIL FROM: + + This command tells the SMTP-receiver that a new mail + transaction is starting and to reset all its state tables and + buffers, including any recipients or mail data. It gives the + reverse-path which can be used to report errors. If accepted, + the receiver-SMTP returns a 250 OK reply. + + The can contain more than just a mailbox. The + is a reverse source routing list of hosts and + source mailbox. The first host in the should be + the host sending this command. + + The second step in the procedure is the RCPT command. + + RCPT TO: + + This command gives a forward-path identifying one recipient. + If accepted, the receiver-SMTP returns a 250 OK reply, and + stores the forward-path. If the recipient is unknown the + receiver-SMTP returns a 550 Failure reply. This second step of + the procedure can be repeated any number of times. + + + +[Page 4] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + The can contain more than just a mailbox. The + is a source routing list of hosts and the + destination mailbox. The first host in the + should be the host receiving this command. + + The third step in the procedure is the DATA command. + + DATA + + If accepted, the receiver-SMTP returns a 354 Intermediate reply + and considers all succeeding lines to be the message text. + When the end of text is received and stored the SMTP-receiver + sends a 250 OK reply. + + Since the mail data is sent on the transmission channel the end + of the mail data must be indicated so that the command and + reply dialog can be resumed. SMTP indicates the end of the + mail data by sending a line containing only a period. A + transparency procedure is used to prevent this from interfering + with the user's text (see Section 4.5.2). + + Please note that the mail data includes the memo header + items such as Date, Subject, To, Cc, From [2]. + + The end of mail data indicator also confirms the mail + transaction and tells the receiver-SMTP to now process the + stored recipients and mail data. If accepted, the + receiver-SMTP returns a 250 OK reply. The DATA command should + fail only if the mail transaction was incomplete (for example, + no recipients), or if resources are not available. + + The above procedure is an example of a mail transaction. These + commands must be used only in the order discussed above. + Example 1 (below) illustrates the use of these commands in a mail + transaction. + + + + + + + + + + + + + + +Postel [Page 5] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + ------------------------------------------------------------- + + Example of the SMTP Procedure + + This SMTP example shows mail sent by Smith at host Alpha.ARPA, + to Jones, Green, and Brown at host Beta.ARPA. Here we assume + that host Alpha contacts host Beta directly. + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: RCPT TO: + R: 550 No such user here + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + The mail has now been accepted for Jones and Brown. Green did + not have a mailbox at host Beta. + + Example 1 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + +[Page 6] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 3.2. FORWARDING + + There are some cases where the destination information in the + is incorrect, but the receiver-SMTP knows the + correct destination. In such cases, one of the following replies + should be used to allow the sender to contact the correct + destination. + + 251 User not local; will forward to + + This reply indicates that the receiver-SMTP knows the user's + mailbox is on another host and indicates the correct + forward-path to use in the future. Note that either the + host or user or both may be different. The receiver takes + responsibility for delivering the message. + + 551 User not local; please try + + This reply indicates that the receiver-SMTP knows the user's + mailbox is on another host and indicates the correct + forward-path to use. Note that either the host or user or + both may be different. The receiver refuses to accept mail + for this user, and the sender must either redirect the mail + according to the information provided or return an error + response to the originating user. + + Example 2 illustrates the use of these responses. + + ------------------------------------------------------------- + + Example of Forwarding + + Either + + S: RCPT TO: + R: 251 User not local; will forward to + + Or + + S: RCPT TO: + R: 551 User not local; please try + + Example 2 + + ------------------------------------------------------------- + + + + +Postel [Page 7] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + 3.3. VERIFYING AND EXPANDING + + SMTP provides as additional features, commands to verify a user + name or expand a mailing list. This is done with the VRFY and + EXPN commands, which have character string arguments. For the + VRFY command, the string is a user name, and the response may + include the full name of the user and must include the mailbox of + the user. For the EXPN command, the string identifies a mailing + list, and the multiline response may include the full name of the + users and must give the mailboxes on the mailing list. + + "User name" is a fuzzy term and used purposely. If a host + implements the VRFY or EXPN commands then at least local mailboxes + must be recognized as "user names". If a host chooses to + recognize other strings as "user names" that is allowed. + + In some hosts the distinction between a mailing list and an alias + for a single mailbox is a bit fuzzy, since a common data structure + may hold both types of entries, and it is possible to have mailing + lists of one mailbox. If a request is made to verify a mailing + list a positive response can be given if on receipt of a message + so addressed it will be delivered to everyone on the list, + otherwise an error should be reported (e.g., "550 That is a + mailing list, not a user"). If a request is made to expand a user + name a positive response can be formed by returning a list + containing one name, or an error can be reported (e.g., "550 That + is a user name, not a mailing list"). + + In the case of a multiline reply (normal for EXPN) exactly one + mailbox is to be specified on each line of the reply. In the case + of an ambiguous request, for example, "VRFY Smith", where there + are two Smith's the response must be "553 User ambiguous". + + The case of verifying a user name is straightforward as shown in + example 3. + + + + + + + + + + + + + + +[Page 8] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + ------------------------------------------------------------- + + Example of Verifying a User Name + + Either + + S: VRFY Smith + R: 250 Fred Smith + + Or + + S: VRFY Smith + R: 251 User not local; will forward to + + Or + + S: VRFY Jones + R: 550 String does not match anything. + + Or + + S: VRFY Jones + R: 551 User not local; please try + + Or + + S: VRFY Gourzenkyinplatz + R: 553 User ambiguous. + + Example 3 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + +Postel [Page 9] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + The case of expanding a mailbox list requires a multiline reply as + shown in example 4. + + ------------------------------------------------------------- + + Example of Expanding a Mailing List + + Either + + S: EXPN Example-People + R: 250-Jon Postel + R: 250-Fred Fonebone + R: 250-Sam Q. Smith + R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> + R: 250- + R: 250 + + Or + + S: EXPN Executive-Washroom-List + R: 550 Access Denied to You. + + Example 4 + + ------------------------------------------------------------- + + The character string arguments of the VRFY and EXPN commands + cannot be further restricted due to the variety of implementations + of the user name and mailbox list concepts. On some systems it + may be appropriate for the argument of the EXPN command to be a + file name for a file containing a mailing list, but again there is + a variety of file naming conventions in the Internet. + + The VRFY and EXPN commands are not included in the minimum + implementation (Section 4.5.1), and are not required to work + across relays when they are implemented. + + + + + + + + + + + + + +[Page 10] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 3.4. SENDING AND MAILING + + The main purpose of SMTP is to deliver messages to user's + mailboxes. A very similar service provided by some hosts is to + deliver messages to user's terminals (provided the user is active + on the host). The delivery to the user's mailbox is called + "mailing", the delivery to the user's terminal is called + "sending". Because in many hosts the implementation of sending is + nearly identical to the implementation of mailing these two + functions are combined in SMTP. However the sending commands are + not included in the required minimum implementation + (Section 4.5.1). Users should have the ability to control the + writing of messages on their terminals. Most hosts permit the + users to accept or refuse such messages. + + The following three command are defined to support the sending + options. These are used in the mail transaction instead of the + MAIL command and inform the receiver-SMTP of the special semantics + of this transaction: + + SEND FROM: + + The SEND command requires that the mail data be delivered to + the user's terminal. If the user is not active (or not + accepting terminal messages) on the host a 450 reply may + returned to a RCPT command. The mail transaction is + successful if the message is delivered the terminal. + + SOML FROM: + + The Send Or MaiL command requires that the mail data be + delivered to the user's terminal if the user is active (and + accepting terminal messages) on the host. If the user is + not active (or not accepting terminal messages) then the + mail data is entered into the user's mailbox. The mail + transaction is successful if the message is delivered either + to the terminal or the mailbox. + + SAML FROM: + + The Send And MaiL command requires that the mail data be + delivered to the user's terminal if the user is active (and + accepting terminal messages) on the host. In any case the + mail data is entered into the user's mailbox. The mail + transaction is successful if the message is delivered the + mailbox. + + + +Postel [Page 11] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + The same reply codes that are used for the MAIL commands are used + for these commands. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 12] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 3.5. OPENING AND CLOSING + + At the time the transmission channel is opened there is an + exchange to ensure that the hosts are communicating with the hosts + they think they are. + + The following two commands are used in transmission channel + opening and closing: + + HELO + + QUIT + + In the HELO command the host sending the command identifies + itself; the command may be interpreted as saying "Hello, I am + ". + + ------------------------------------------------------------- + + Example of Connection Opening + + R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready + S: HELO USC-ISIF.ARPA + R: 250 BBN-UNIX.ARPA + + Example 5 + + ------------------------------------------------------------- + + ------------------------------------------------------------- + + Example of Connection Closing + + S: QUIT + R: 221 BBN-UNIX.ARPA Service closing transmission channel + + Example 6 + + ------------------------------------------------------------- + + + + + + + + + + +Postel [Page 13] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + 3.6. RELAYING + + The forward-path may be a source route of the form + "@ONE,@TWO:JOE@THREE", where ONE, TWO, and THREE are hosts. This + form is used to emphasize the distinction between an address and a + route. The mailbox is an absolute address, and the route is + information about how to get there. The two concepts should not + be confused. + + Conceptually the elements of the forward-path are moved to the + reverse-path as the message is relayed from one server-SMTP to + another. The reverse-path is a reverse source route, (i.e., a + source route from the current location of the message to the + originator of the message). When a server-SMTP deletes its + identifier from the forward-path and inserts it into the + reverse-path, it must use the name it is known by in the + environment it is sending into, not the environment the mail came + from, in case the server-SMTP is known by different names in + different environments. + + If when the message arrives at an SMTP the first element of the + forward-path is not the identifier of that SMTP the element is not + deleted from the forward-path and is used to determine the next + SMTP to send the message to. In any case, the SMTP adds its own + identifier to the reverse-path. + + Using source routing the receiver-SMTP receives mail to be relayed + to another server-SMTP The receiver-SMTP may accept or reject the + task of relaying the mail in the same way it accepts or rejects + mail for a local user. The receiver-SMTP transforms the command + arguments by moving its own identifier from the forward-path to + the beginning of the reverse-path. The receiver-SMTP then becomes + a sender-SMTP, establishes a transmission channel to the next SMTP + in the forward-path, and sends it the mail. + + The first host in the reverse-path should be the host sending the + SMTP commands, and the first host in the forward-path should be + the host receiving the SMTP commands. + + Notice that the forward-path and reverse-path appear in the SMTP + commands and replies, but not necessarily in the message. That + is, there is no need for these paths and especially this syntax to + appear in the "To:" , "From:", "CC:", etc. fields of the message + header. + + If a server-SMTP has accepted the task of relaying the mail and + + + +[Page 14] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + later finds that the forward-path is incorrect or that the mail + cannot be delivered for whatever reason, then it must construct an + "undeliverable mail" notification message and send it to the + originator of the undeliverable mail (as indicated by the + reverse-path). + + This notification message must be from the server-SMTP at this + host. Of course, server-SMTPs should not send notification + messages about problems with notification messages. One way to + prevent loops in error reporting is to specify a null reverse-path + in the MAIL command of a notification message. When such a + message is relayed it is permissible to leave the reverse-path + null. A MAIL command with a null reverse-path appears as follows: + + MAIL FROM:<> + + An undeliverable mail notification message is shown in example 7. + This notification is in response to a message originated by JOE at + HOSTW and sent via HOSTX to HOSTY with instructions to relay it on + to HOSTZ. What we see in the example is the transaction between + HOSTY and HOSTX, which is the first step in the return of the + notification message. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 15] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + ------------------------------------------------------------- + + Example Undeliverable Mail Notification Message + + S: MAIL FROM:<> + R: 250 ok + S: RCPT TO:<@HOSTX.ARPA:JOE@HOSTW.ARPA> + R: 250 ok + S: DATA + R: 354 send the mail data, end with . + S: Date: 23 Oct 81 11:22:33 + S: From: SMTP@HOSTY.ARPA + S: To: JOE@HOSTW.ARPA + S: Subject: Mail System Problem + S: + S: Sorry JOE, your message to SAM@HOSTZ.ARPA lost. + S: HOSTZ.ARPA said this: + S: "550 No Such User" + S: . + R: 250 ok + + Example 7 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 16] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 3.7. DOMAINS + + Domains are a recently introduced concept in the ARPA Internet + mail system. The use of domains changes the address space from a + flat global space of simple character string host names to a + hierarchically structured rooted tree of global addresses. The + host name is replaced by a domain and host designator which is a + sequence of domain element strings separated by periods with the + understanding that the domain elements are ordered from the most + specific to the most general. + + For example, "USC-ISIF.ARPA", "Fred.Cambridge.UK", and + "PC7.LCS.MIT.ARPA" might be host-and-domain identifiers. + + Whenever domain names are used in SMTP only the official names are + used, the use of nicknames or aliases is not allowed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 17] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + 3.8. CHANGING ROLES + + The TURN command may be used to reverse the roles of the two + programs communicating over the transmission channel. + + If program-A is currently the sender-SMTP and it sends the TURN + command and receives an ok reply (250) then program-A becomes the + receiver-SMTP. + + If program-B is currently the receiver-SMTP and it receives the + TURN command and sends an ok reply (250) then program-B becomes + the sender-SMTP. + + To refuse to change roles the receiver sends the 502 reply. + + Please note that this command is optional. It would not normally + be used in situations where the transmission channel is TCP. + However, when the cost of establishing the transmission channel is + high, this command may be quite useful. For example, this command + may be useful in supporting be mail exchange using the public + switched telephone system as a transmission channel, especially if + some hosts poll other hosts for mail exchanges. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 18] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + +4. THE SMTP SPECIFICATIONS + + 4.1. SMTP COMMANDS + + 4.1.1. COMMAND SEMANTICS + + The SMTP commands define the mail transfer or the mail system + function requested by the user. SMTP commands are character + strings terminated by . The command codes themselves are + alphabetic characters terminated by if parameters follow + and otherwise. The syntax of mailboxes must conform to + receiver site conventions. The SMTP commands are discussed + below. The SMTP replies are discussed in the Section 4.2. + + A mail transaction involves several data objects which are + communicated as arguments to different commands. The + reverse-path is the argument of the MAIL command, the + forward-path is the argument of the RCPT command, and the mail + data is the argument of the DATA command. These arguments or + data objects must be transmitted and held pending the + confirmation communicated by the end of mail data indication + which finalizes the transaction. The model for this is that + distinct buffers are provided to hold the types of data + objects, that is, there is a reverse-path buffer, a + forward-path buffer, and a mail data buffer. Specific commands + cause information to be appended to a specific buffer, or cause + one or more buffers to be cleared. + + HELLO (HELO) + + This command is used to identify the sender-SMTP to the + receiver-SMTP. The argument field contains the host name of + the sender-SMTP. + + The receiver-SMTP identifies itself to the sender-SMTP in + the connection greeting reply, and in the response to this + command. + + This command and an OK reply to it confirm that both the + sender-SMTP and the receiver-SMTP are in the initial state, + that is, there is no transaction in progress and all state + tables and buffers are cleared. + + + + + + + +Postel [Page 19] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + MAIL (MAIL) + + This command is used to initiate a mail transaction in which + the mail data is delivered to one or more mailboxes. The + argument field contains a reverse-path. + + The reverse-path consists of an optional list of hosts and + the sender mailbox. When the list of hosts is present, it + is a "reverse" source route and indicates that the mail was + relayed through each host on the list (the first host in the + list was the most recent relay). This list is used as a + source route to return non-delivery notices to the sender. + As each relay host adds itself to the beginning of the list, + it must use its name as known in the IPCE to which it is + relaying the mail rather than the IPCE from which the mail + came (if they are different). In some types of error + reporting messages (for example, undeliverable mail + notifications) the reverse-path may be null (see Example 7). + + This command clears the reverse-path buffer, the + forward-path buffer, and the mail data buffer; and inserts + the reverse-path information from this command into the + reverse-path buffer. + + RECIPIENT (RCPT) + + This command is used to identify an individual recipient of + the mail data; multiple recipients are specified by multiple + use of this command. + + The forward-path consists of an optional list of hosts and a + required destination mailbox. When the list of hosts is + present, it is a source route and indicates that the mail + must be relayed to the next host on the list. If the + receiver-SMTP does not implement the relay function it may + user the same reply it would for an unknown local user + (550). + + When mail is relayed, the relay host must remove itself from + the beginning forward-path and put itself at the beginning + of the reverse-path. When mail reaches its ultimate + destination (the forward-path contains only a destination + mailbox), the receiver-SMTP inserts it into the destination + mailbox in accordance with its host mail conventions. + + + + + +[Page 20] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + For example, mail received at relay host A with arguments + + FROM: + TO:<@HOSTA.ARPA,@HOSTB.ARPA:USERC@HOSTD.ARPA> + + will be relayed on to host B with arguments + + FROM:<@HOSTA.ARPA:USERX@HOSTY.ARPA> + TO:<@HOSTB.ARPA:USERC@HOSTD.ARPA>. + + This command causes its forward-path argument to be appended + to the forward-path buffer. + + DATA (DATA) + + The receiver treats the lines following the command as mail + data from the sender. This command causes the mail data + from this command to be appended to the mail data buffer. + The mail data may contain any of the 128 ASCII character + codes. + + The mail data is terminated by a line containing only a + period, that is the character sequence "." (see + Section 4.5.2 on Transparency). This is the end of mail + data indication. + + The end of mail data indication requires that the receiver + must now process the stored mail transaction information. + This processing consumes the information in the reverse-path + buffer, the forward-path buffer, and the mail data buffer, + and on the completion of this command these buffers are + cleared. If the processing is successful the receiver must + send an OK reply. If the processing fails completely the + receiver must send a failure reply. + + When the receiver-SMTP accepts a message either for relaying + or for final delivery it inserts at the beginning of the + mail data a time stamp line. The time stamp line indicates + the identity of the host that sent the message, and the + identity of the host that received the message (and is + inserting this time stamp), and the date and time the + message was received. Relayed messages will have multiple + time stamp lines. + + When the receiver-SMTP makes the "final delivery" of a + message it inserts at the beginning of the mail data a + + + +Postel [Page 21] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + return path line. The return path line preserves the + information in the from the MAIL command. + Here, final delivery means the message leaves the SMTP + world. Normally, this would mean it has been delivered to + the destination user, but in some cases it may be further + processed and transmitted by another mail system. + + It is possible for the mailbox in the return path be + different from the actual sender's mailbox, for example, + if error responses are to be delivered a special error + handling mailbox rather than the message senders. + + The preceding two paragraphs imply that the final mail data + will begin with a return path line, followed by one or more + time stamp lines. These lines will be followed by the mail + data header and body [2]. See Example 8. + + Special mention is needed of the response and further action + required when the processing following the end of mail data + indication is partially successful. This could arise if + after accepting several recipients and the mail data, the + receiver-SMTP finds that the mail data can be successfully + delivered to some of the recipients, but it cannot be to + others (for example, due to mailbox space allocation + problems). In such a situation, the response to the DATA + command must be an OK reply. But, the receiver-SMTP must + compose and send an "undeliverable mail" notification + message to the originator of the message. Either a single + notification which lists all of the recipients that failed + to get the message, or separate notification messages must + be sent for each failed recipient (see Example 7). All + undeliverable mail notification messages are sent using the + MAIL command (even if they result from processing a SEND, + SOML, or SAML command). + + + + + + + + + + + + + + + +[Page 22] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + ------------------------------------------------------------- + + Example of Return Path and Received Time Stamps + + Return-Path: <@GHI.ARPA,@DEF.ARPA,@ABC.ARPA:JOE@ABC.ARPA> + Received: from GHI.ARPA by JKL.ARPA ; 27 Oct 81 15:27:39 PST + Received: from DEF.ARPA by GHI.ARPA ; 27 Oct 81 15:15:13 PST + Received: from ABC.ARPA by DEF.ARPA ; 27 Oct 81 15:01:59 PST + Date: 27 Oct 81 15:01:01 PST + From: JOE@ABC.ARPA + Subject: Improved Mailing System Installed + To: SAM@JKL.ARPA + + This is to inform you that ... + + Example 8 + + ------------------------------------------------------------- + + SEND (SEND) + + This command is used to initiate a mail transaction in which + the mail data is delivered to one or more terminals. The + argument field contains a reverse-path. This command is + successful if the message is delivered to a terminal. + + The reverse-path consists of an optional list of hosts and + the sender mailbox. When the list of hosts is present, it + is a "reverse" source route and indicates that the mail was + relayed through each host on the list (the first host in the + list was the most recent relay). This list is used as a + source route to return non-delivery notices to the sender. + As each relay host adds itself to the beginning of the list, + it must use its name as known in the IPCE to which it is + relaying the mail rather than the IPCE from which the mail + came (if they are different). + + This command clears the reverse-path buffer, the + forward-path buffer, and the mail data buffer; and inserts + the reverse-path information from this command into the + reverse-path buffer. + + SEND OR MAIL (SOML) + + This command is used to initiate a mail transaction in which + the mail data is delivered to one or more terminals or + + + +Postel [Page 23] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + mailboxes. For each recipient the mail data is delivered to + the recipient's terminal if the recipient is active on the + host (and accepting terminal messages), otherwise to the + recipient's mailbox. The argument field contains a + reverse-path. This command is successful if the message is + delivered to a terminal or the mailbox. + + The reverse-path consists of an optional list of hosts and + the sender mailbox. When the list of hosts is present, it + is a "reverse" source route and indicates that the mail was + relayed through each host on the list (the first host in the + list was the most recent relay). This list is used as a + source route to return non-delivery notices to the sender. + As each relay host adds itself to the beginning of the list, + it must use its name as known in the IPCE to which it is + relaying the mail rather than the IPCE from which the mail + came (if they are different). + + This command clears the reverse-path buffer, the + forward-path buffer, and the mail data buffer; and inserts + the reverse-path information from this command into the + reverse-path buffer. + + SEND AND MAIL (SAML) + + This command is used to initiate a mail transaction in which + the mail data is delivered to one or more terminals and + mailboxes. For each recipient the mail data is delivered to + the recipient's terminal if the recipient is active on the + host (and accepting terminal messages), and for all + recipients to the recipient's mailbox. The argument field + contains a reverse-path. This command is successful if the + message is delivered to the mailbox. + + The reverse-path consists of an optional list of hosts and + the sender mailbox. When the list of hosts is present, it + is a "reverse" source route and indicates that the mail was + relayed through each host on the list (the first host in the + list was the most recent relay). This list is used as a + source route to return non-delivery notices to the sender. + As each relay host adds itself to the beginning of the list, + it must use its name as known in the IPCE to which it is + relaying the mail rather than the IPCE from which the mail + came (if they are different). + + This command clears the reverse-path buffer, the + + + +[Page 24] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + forward-path buffer, and the mail data buffer; and inserts + the reverse-path information from this command into the + reverse-path buffer. + + RESET (RSET) + + This command specifies that the current mail transaction is + to be aborted. Any stored sender, recipients, and mail data + must be discarded, and all buffers and state tables cleared. + The receiver must send an OK reply. + + VERIFY (VRFY) + + This command asks the receiver to confirm that the argument + identifies a user. If it is a user name, the full name of + the user (if known) and the fully specified mailbox are + returned. + + This command has no effect on any of the reverse-path + buffer, the forward-path buffer, or the mail data buffer. + + EXPAND (EXPN) + + This command asks the receiver to confirm that the argument + identifies a mailing list, and if so, to return the + membership of that list. The full name of the users (if + known) and the fully specified mailboxes are returned in a + multiline reply. + + This command has no effect on any of the reverse-path + buffer, the forward-path buffer, or the mail data buffer. + + HELP (HELP) + + This command causes the receiver to send helpful information + to the sender of the HELP command. The command may take an + argument (e.g., any command name) and return more specific + information as a response. + + This command has no effect on any of the reverse-path + buffer, the forward-path buffer, or the mail data buffer. + + + + + + + + +Postel [Page 25] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + NOOP (NOOP) + + This command does not affect any parameters or previously + entered commands. It specifies no action other than that + the receiver send an OK reply. + + This command has no effect on any of the reverse-path + buffer, the forward-path buffer, or the mail data buffer. + + QUIT (QUIT) + + This command specifies that the receiver must send an OK + reply, and then close the transmission channel. + + The receiver should not close the transmission channel until + it receives and replies to a QUIT command (even if there was + an error). The sender should not close the transmission + channel until it send a QUIT command and receives the reply + (even if there was an error response to a previous command). + If the connection is closed prematurely the receiver should + act as if a RSET command had been received (canceling any + pending transaction, but not undoing any previously + completed transaction), the sender should act as if the + command or transaction in progress had received a temporary + error (4xx). + + TURN (TURN) + + This command specifies that the receiver must either (1) + send an OK reply and then take on the role of the + sender-SMTP, or (2) send a refusal reply and retain the role + of the receiver-SMTP. + + If program-A is currently the sender-SMTP and it sends the + TURN command and receives an OK reply (250) then program-A + becomes the receiver-SMTP. Program-A is then in the initial + state as if the transmission channel just opened, and it + then sends the 220 service ready greeting. + + If program-B is currently the receiver-SMTP and it receives + the TURN command and sends an OK reply (250) then program-B + becomes the sender-SMTP. Program-B is then in the initial + state as if the transmission channel just opened, and it + then expects to receive the 220 service ready greeting. + + To refuse to change roles the receiver sends the 502 reply. + + + +[Page 26] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + There are restrictions on the order in which these command may + be used. + + The first command in a session must be the HELO command. + The HELO command may be used later in a session as well. If + the HELO command argument is not acceptable a 501 failure + reply must be returned and the receiver-SMTP must stay in + the same state. + + The NOOP, HELP, EXPN, and VRFY commands can be used at any + time during a session. + + The MAIL, SEND, SOML, or SAML commands begin a mail + transaction. Once started a mail transaction consists of + one of the transaction beginning commands, one or more RCPT + commands, and a DATA command, in that order. A mail + transaction may be aborted by the RSET command. There may + be zero or more transactions in a session. + + If the transaction beginning command argument is not + acceptable a 501 failure reply must be returned and the + receiver-SMTP must stay in the same state. If the commands + in a transaction are out of order a 503 failure reply must + be returned and the receiver-SMTP must stay in the same + state. + + The last command in a session must be the QUIT command. The + QUIT command can not be used at any other time in a session. + + 4.1.2. COMMAND SYNTAX + + The commands consist of a command code followed by an argument + field. Command codes are four alphabetic characters. Upper + and lower case alphabetic characters are to be treated + identically. Thus, any of the following may represent the mail + command: + + MAIL Mail mail MaIl mAIl + + This also applies to any symbols representing parameter values, + such as "TO" or "to" for the forward-path. Command codes and + the argument fields are separated by one or more spaces. + However, within the reverse-path and forward-path arguments + case is important. In particular, in some hosts the user + "smith" is different from the user "Smith". + + + + +Postel [Page 27] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + The argument field consists of a variable length character + string ending with the character sequence . The receiver + is to take no action until this sequence is received. + + Square brackets denote an optional argument field. If the + option is not taken, the appropriate default is implied. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 28] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + The following are the SMTP commands: + + HELO + + MAIL FROM: + + RCPT TO: + + DATA + + RSET + + SEND FROM: + + SOML FROM: + + SAML FROM: + + VRFY + + EXPN + + HELP [ ] + + NOOP + + QUIT + + TURN + + + + + + + + + + + + + + + + + + + + +Postel [Page 29] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + The syntax of the above argument fields (using BNF notation + where applicable) is given below. The "..." notation indicates + that a field may be repeated one or more times. + + ::= + + ::= + + ::= "<" [ ":" ] ">" + + ::= | "," + + ::= "@" + + ::= | "." + + ::= | "#" | "[" "]" + + ::= "@" + + ::= | + + ::= + + ::= | + + ::= | + + ::= | | "-" + + ::= | "." + + ::= | + + ::= """ """ + + ::= "\" | "\" | | + + ::= | "\" + + ::= "." "." "." + + ::= | + + ::= + + + + +[Page 30] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + ::= the carriage return character (ASCII code 13) + + ::= the line feed character (ASCII code 10) + + ::= the space character (ASCII code 32) + + ::= one, two, or three digits representing a decimal + integer value in the range 0 through 255 + + ::= any one of the 52 alphabetic characters A through Z + in upper case and a through z in lower case + + ::= any one of the 128 ASCII characters, but not any + or + + ::= any one of the ten digits 0 through 9 + + ::= any one of the 128 ASCII characters except , + , quote ("), or backslash (\) + + ::= any one of the 128 ASCII characters (no exceptions) + + ::= "<" | ">" | "(" | ")" | "[" | "]" | "\" | "." + | "," | ";" | ":" | "@" """ | the control + characters (ASCII codes 0 through 31 inclusive and + 127) + + Note that the backslash, "\", is a quote character, which is + used to indicate that the next character is to be used + literally (instead of its normal interpretation). For example, + "Joe\,Smith" could be used to indicate a single nine character + user field with comma being the fourth character of the field. + + Hosts are generally known by names which are translated to + addresses in each host. Note that the name elements of domains + are the official names -- no use of nicknames or aliases is + allowed. + + Sometimes a host is not known to the translation function and + communication is blocked. To bypass this barrier two numeric + forms are also allowed for host "names". One form is a decimal + integer prefixed by a pound sign, "#", which indicates the + number is the address of the host. Another form is four small + decimal integers separated by dots and enclosed by brackets, + e.g., "[123.255.37.2]", which indicates a 32-bit ARPA Internet + Address in four 8-bit fields. + + + +Postel [Page 31] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + The time stamp line and the return path line are formally + defined as follows: + + ::= "Return-Path:" + + ::= "Received:" + + ::= ";" + + + ::= "FROM" + + ::= "BY" + + ::= [] [] [] [] + + ::= "VIA" + + ::= "WITH" + + ::= "ID" + + ::= "FOR" + + ::= The standard names for links are registered with + the Network Information Center. + + ::= The standard names for protocols are + registered with the Network Information Center. + + ::=
::= the one or two decimal integer day of the month in + the range 1 to 31. + + ::= "JAN" | "FEB" | "MAR" | "APR" | "MAY" | "JUN" | + "JUL" | "AUG" | "SEP" | "OCT" | "NOV" | "DEC" + + ::= the two decimal integer year of the century in the + range 00 to 99. + + + + + +[Page 32] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + ::= the two decimal integer hour of the day in the + range 00 to 24. + + ::= the two decimal integer minute of the hour in the + range 00 to 59. + + ::= the two decimal integer second of the minute in the + range 00 to 59. + + ::= "UT" for Universal Time (the default) or other + time zone designator (as in [2]). + + + + ------------------------------------------------------------- + + Return Path Example + + Return-Path: <@CHARLIE.ARPA,@BAKER.ARPA:JOE@ABLE.ARPA> + + Example 9 + + ------------------------------------------------------------- + + ------------------------------------------------------------- + + Time Stamp Line Example + + Received: FROM ABC.ARPA BY XYZ.ARPA ; 22 OCT 81 09:23:59 PDT + + Received: from ABC.ARPA by XYZ.ARPA via TELENET with X25 + id M12345 for Smith@PDQ.ARPA ; 22 OCT 81 09:23:59 PDT + + Example 10 + + ------------------------------------------------------------- + + + + + + + + + + + + + +Postel [Page 33] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + 4.2. SMTP REPLIES + + Replies to SMTP commands are devised to ensure the synchronization + of requests and actions in the process of mail transfer, and to + guarantee that the sender-SMTP always knows the state of the + receiver-SMTP. Every command must generate exactly one reply. + + The details of the command-reply sequence are made explicit in + Section 5.3 on Sequencing and Section 5.4 State Diagrams. + + An SMTP reply consists of a three digit number (transmitted as + three alphanumeric characters) followed by some text. The number + is intended for use by automata to determine what state to enter + next; the text is meant for the human user. It is intended that + the three digits contain enough encoded information that the + sender-SMTP need not examine the text and may either discard it or + pass it on to the user, as appropriate. In particular, the text + may be receiver-dependent and context dependent, so there are + likely to be varying texts for each reply code. A discussion of + the theory of reply codes is given in Appendix E. Formally, a + reply is defined to be the sequence: a three-digit code, , + one line of text, and , or a multiline reply (as defined in + Appendix E). Only the EXPN and HELP commands are expected to + result in multiline replies in normal circumstances, however + multiline replies are allowed for any command. + + + + + + + + + + + + + + + + + + + + + + + + +[Page 34] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 4.2.1. REPLY CODES BY FUNCTION GROUPS + + 500 Syntax error, command unrecognized + [This may include errors such as command line too long] + 501 Syntax error in parameters or arguments + 502 Command not implemented + 503 Bad sequence of commands + 504 Command parameter not implemented + + 211 System status, or system help reply + 214 Help message + [Information on how to use the receiver or the meaning of a + particular non-standard command; this reply is useful only + to the human user] + + 220 Service ready + 221 Service closing transmission channel + 421 Service not available, + closing transmission channel + [This may be a reply to any command if the service knows it + must shut down] + + 250 Requested mail action okay, completed + 251 User not local; will forward to + 450 Requested mail action not taken: mailbox unavailable + [E.g., mailbox busy] + 550 Requested action not taken: mailbox unavailable + [E.g., mailbox not found, no access] + 451 Requested action aborted: error in processing + 551 User not local; please try + 452 Requested action not taken: insufficient system storage + 552 Requested mail action aborted: exceeded storage allocation + 553 Requested action not taken: mailbox name not allowed + [E.g., mailbox syntax incorrect] + 354 Start mail input; end with . + 554 Transaction failed + + + + + + + + + + + + + +Postel [Page 35] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + 4.2.2. NUMERIC ORDER LIST OF REPLY CODES + + 211 System status, or system help reply + 214 Help message + [Information on how to use the receiver or the meaning of a + particular non-standard command; this reply is useful only + to the human user] + 220 Service ready + 221 Service closing transmission channel + 250 Requested mail action okay, completed + 251 User not local; will forward to + + 354 Start mail input; end with . + + 421 Service not available, + closing transmission channel + [This may be a reply to any command if the service knows it + must shut down] + 450 Requested mail action not taken: mailbox unavailable + [E.g., mailbox busy] + 451 Requested action aborted: local error in processing + 452 Requested action not taken: insufficient system storage + + 500 Syntax error, command unrecognized + [This may include errors such as command line too long] + 501 Syntax error in parameters or arguments + 502 Command not implemented + 503 Bad sequence of commands + 504 Command parameter not implemented + 550 Requested action not taken: mailbox unavailable + [E.g., mailbox not found, no access] + 551 User not local; please try + 552 Requested mail action aborted: exceeded storage allocation + 553 Requested action not taken: mailbox name not allowed + [E.g., mailbox syntax incorrect] + 554 Transaction failed + + + + + + + + + + + + + +[Page 36] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 4.3. SEQUENCING OF COMMANDS AND REPLIES + + The communication between the sender and receiver is intended to + be an alternating dialogue, controlled by the sender. As such, + the sender issues a command and the receiver responds with a + reply. The sender must wait for this response before sending + further commands. + + One important reply is the connection greeting. Normally, a + receiver will send a 220 "Service ready" reply when the connection + is completed. The sender should wait for this greeting message + before sending any commands. + + Note: all the greeting type replies have the official name of + the server host as the first word following the reply code. + + For example, + + 220 USC-ISIF.ARPA Service ready + + The table below lists alternative success and failure replies for + each command. These must be strictly adhered to; a receiver may + substitute text in the replies, but the meaning and action implied + by the code numbers and by the specific command reply sequence + cannot be altered. + + COMMAND-REPLY SEQUENCES + + Each command is listed with its possible replies. The prefixes + used before the possible replies are "P" for preliminary (not + used in SMTP), "I" for intermediate, "S" for success, "F" for + failure, and "E" for error. The 421 reply (service not + available, closing transmission channel) may be given to any + command if the SMTP-receiver knows it must shut down. This + listing forms the basis for the State Diagrams in Section 4.4. + + CONNECTION ESTABLISHMENT + S: 220 + F: 421 + HELO + S: 250 + E: 500, 501, 504, 421 + MAIL + S: 250 + F: 552, 451, 452 + E: 500, 501, 421 + + + +Postel [Page 37] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + RCPT + S: 250, 251 + F: 550, 551, 552, 553, 450, 451, 452 + E: 500, 501, 503, 421 + DATA + I: 354 -> data -> S: 250 + F: 552, 554, 451, 452 + F: 451, 554 + E: 500, 501, 503, 421 + RSET + S: 250 + E: 500, 501, 504, 421 + SEND + S: 250 + F: 552, 451, 452 + E: 500, 501, 502, 421 + SOML + S: 250 + F: 552, 451, 452 + E: 500, 501, 502, 421 + SAML + S: 250 + F: 552, 451, 452 + E: 500, 501, 502, 421 + VRFY + S: 250, 251 + F: 550, 551, 553 + E: 500, 501, 502, 504, 421 + EXPN + S: 250 + F: 550 + E: 500, 501, 502, 504, 421 + HELP + S: 211, 214 + E: 500, 501, 502, 504, 421 + NOOP + S: 250 + E: 500, 421 + QUIT + S: 221 + E: 500 + TURN + S: 250 + F: 502 + E: 500, 503 + + + + +[Page 38] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 4.4. STATE DIAGRAMS + + Following are state diagrams for a simple-minded SMTP + implementation. Only the first digit of the reply codes is used. + There is one state diagram for each group of SMTP commands. The + command groupings were determined by constructing a model for each + command and then collecting together the commands with + structurally identical models. + + For each command there are three possible outcomes: "success" + (S), "failure" (F), and "error" (E). In the state diagrams below + we use the symbol B for "begin", and the symbol W for "wait for + reply". + + First, the diagram that represents most of the SMTP commands: + + + 1,3 +---+ + ----------->| E | + | +---+ + | + +---+ cmd +---+ 2 +---+ + | B |---------->| W |---------->| S | + +---+ +---+ +---+ + | + | 4,5 +---+ + ----------->| F | + +---+ + + + This diagram models the commands: + + HELO, MAIL, RCPT, RSET, SEND, SOML, SAML, VRFY, EXPN, HELP, + NOOP, QUIT, TURN. + + + + + + + + + + + + + + + +Postel [Page 39] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + A more complex diagram models the DATA command: + + + +---+ DATA +---+ 1,2 +---+ + | B |---------->| W |-------------------->| E | + +---+ +---+ ------------>+---+ + 3| |4,5 | + | | | + -------------- ----- | + | | | +---+ + | ---------- -------->| S | + | | | | +---+ + | | ------------ + | | | | + V 1,3| |2 | + +---+ data +---+ --------------->+---+ + | |---------->| W | | F | + +---+ +---+-------------------->+---+ + 4,5 + + + Note that the "data" here is a series of lines sent from the + sender to the receiver with no response expected until the last + line is sent. + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 40] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + 4.5. DETAILS + + 4.5.1. MINIMUM IMPLEMENTATION + + In order to make SMTP workable, the following minimum + implementation is required for all receivers: + + COMMANDS -- HELO + MAIL + RCPT + DATA + RSET + NOOP + QUIT + + 4.5.2. TRANSPARENCY + + Without some provision for data transparency the character + sequence "." ends the mail text and cannot be sent + by the user. In general, users are not aware of such + "forbidden" sequences. To allow all user composed text to be + transmitted transparently the following procedures are used. + + 1. Before sending a line of mail text the sender-SMTP checks + the first character of the line. If it is a period, one + additional period is inserted at the beginning of the line. + + 2. When a line of mail text is received by the receiver-SMTP + it checks the line. If the line is composed of a single + period it is the end of mail. If the first character is a + period and there are other characters on the line, the first + character is deleted. + + The mail data may contain any of the 128 ASCII characters. All + characters are to be delivered to the recipient's mailbox + including format effectors and other control characters. If + the transmission channel provides an 8-bit byte (octets) data + stream, the 7-bit ASCII codes are transmitted right justified + in the octets with the high order bits cleared to zero. + + In some systems it may be necessary to transform the data as + it is received and stored. This may be necessary for hosts + that use a different character set than ASCII as their local + character set, or that store data in records rather than + + + + + +Postel [Page 41] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + strings. If such transforms are necessary, they must be + reversible -- especially if such transforms are applied to + mail being relayed. + + 4.5.3. SIZES + + There are several objects that have required minimum maximum + sizes. That is, every implementation must be able to receive + objects of at least these sizes, but must not send objects + larger than these sizes. + + + **************************************************** + * * + * TO THE MAXIMUM EXTENT POSSIBLE, IMPLEMENTATION * + * TECHNIQUES WHICH IMPOSE NO LIMITS ON THE LENGTH * + * OF THESE OBJECTS SHOULD BE USED. * + * * + **************************************************** + + user + + The maximum total length of a user name is 64 characters. + + domain + + The maximum total length of a domain name or number is 64 + characters. + + path + + The maximum total length of a reverse-path or + forward-path is 256 characters (including the punctuation + and element separators). + + command line + + The maximum total length of a command line including the + command word and the is 512 characters. + + reply line + + The maximum total length of a reply line including the + reply code and the is 512 characters. + + + + + +[Page 42] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + text line + + The maximum total length of a text line including the + is 1000 characters (but not counting the leading + dot duplicated for transparency). + + recipients buffer + + The maximum total number of recipients that must be + buffered is 100 recipients. + + + **************************************************** + * * + * TO THE MAXIMUM EXTENT POSSIBLE, IMPLEMENTATION * + * TECHNIQUES WHICH IMPOSE NO LIMITS ON THE LENGTH * + * OF THESE OBJECTS SHOULD BE USED. * + * * + **************************************************** + + Errors due to exceeding these limits may be reported by using + the reply codes, for example: + + 500 Line too long. + + 501 Path too long + + 552 Too many recipients. + + 552 Too much mail data. + + + + + + + + + + + + + + + + + + + +Postel [Page 43] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +APPENDIX A + + TCP Transport service + + The Transmission Control Protocol [3] is used in the ARPA + Internet, and in any network following the US DoD standards for + internetwork protocols. + + Connection Establishment + + The SMTP transmission channel is a TCP connection established + between the sender process port U and the receiver process port + L. This single full duplex connection is used as the + transmission channel. This protocol is assigned the service + port 25 (31 octal), that is L=25. + + Data Transfer + + The TCP connection supports the transmission of 8-bit bytes. + The SMTP data is 7-bit ASCII characters. Each character is + transmitted as an 8-bit byte with the high-order bit cleared to + zero. + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 44] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + +APPENDIX B + + NCP Transport service + + The ARPANET Host-to-Host Protocol [4] (implemented by the Network + Control Program) may be used in the ARPANET. + + Connection Establishment + + The SMTP transmission channel is established via NCP between + the sender process socket U and receiver process socket L. The + Initial Connection Protocol [5] is followed resulting in a pair + of simplex connections. This pair of connections is used as + the transmission channel. This protocol is assigned the + contact socket 25 (31 octal), that is L=25. + + Data Transfer + + The NCP data connections are established in 8-bit byte mode. + The SMTP data is 7-bit ASCII characters. Each character is + transmitted as an 8-bit byte with the high-order bit cleared to + zero. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 45] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +APPENDIX C + + NITS + + The Network Independent Transport Service [6] may be used. + + Connection Establishment + + The SMTP transmission channel is established via NITS between + the sender process and receiver process. The sender process + executes the CONNECT primitive, and the waiting receiver + process executes the ACCEPT primitive. + + Data Transfer + + The NITS connection supports the transmission of 8-bit bytes. + The SMTP data is 7-bit ASCII characters. Each character is + transmitted as an 8-bit byte with the high-order bit cleared to + zero. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 46] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + +APPENDIX D + + X.25 Transport service + + It may be possible to use the X.25 service [7] as provided by the + Public Data Networks directly, however, it is suggested that a + reliable end-to-end protocol such as TCP be used on top of X.25 + connections. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 47] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +APPENDIX E + + Theory of Reply Codes + + The three digits of the reply each have a special significance. + The first digit denotes whether the response is good, bad or + incomplete. An unsophisticated sender-SMTP will be able to + determine its next action (proceed as planned, redo, retrench, + etc.) by simply examining this first digit. A sender-SMTP that + wants to know approximately what kind of error occurred (e.g., + mail system error, command syntax error) may examine the second + digit, reserving the third digit for the finest gradation of + information. + + There are five values for the first digit of the reply code: + + 1yz Positive Preliminary reply + + The command has been accepted, but the requested action + is being held in abeyance, pending confirmation of the + information in this reply. The sender-SMTP should send + another command specifying whether to continue or abort + the action. + + [Note: SMTP does not have any commands that allow this + type of reply, and so does not have the continue or + abort commands.] + + 2yz Positive Completion reply + + The requested action has been successfully completed. A + new request may be initiated. + + 3yz Positive Intermediate reply + + The command has been accepted, but the requested action + is being held in abeyance, pending receipt of further + information. The sender-SMTP should send another command + specifying this information. This reply is used in + command sequence groups. + + 4yz Transient Negative Completion reply + + The command was not accepted and the requested action did + not occur. However, the error condition is temporary and + the action may be requested again. The sender should + + + +[Page 48] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + return to the beginning of the command sequence (if any). + It is difficult to assign a meaning to "transient" when + two different sites (receiver- and sender- SMTPs) must + agree on the interpretation. Each reply in this category + might have a different time value, but the sender-SMTP is + encouraged to try again. A rule of thumb to determine if + a reply fits into the 4yz or the 5yz category (see below) + is that replies are 4yz if they can be repeated without + any change in command form or in properties of the sender + or receiver. (E.g., the command is repeated identically + and the receiver does not put up a new implementation.) + + 5yz Permanent Negative Completion reply + + The command was not accepted and the requested action did + not occur. The sender-SMTP is discouraged from repeating + the exact request (in the same sequence). Even some + "permanent" error conditions can be corrected, so the + human user may want to direct the sender-SMTP to + reinitiate the command sequence by direct action at some + point in the future (e.g., after the spelling has been + changed, or the user has altered the account status). + + The second digit encodes responses in specific categories: + + x0z Syntax -- These replies refer to syntax errors, + syntactically correct commands that don't fit any + functional category, and unimplemented or superfluous + commands. + + x1z Information -- These are replies to requests for + information, such as status or help. + + x2z Connections -- These are replies referring to the + transmission channel. + + x3z Unspecified as yet. + + x4z Unspecified as yet. + + x5z Mail system -- These replies indicate the status of + the receiver mail system vis-a-vis the requested + transfer or other mail system action. + + The third digit gives a finer gradation of meaning in each + category specified by the second digit. The list of replies + + + +Postel [Page 49] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + illustrates this. Each reply text is recommended rather than + mandatory, and may even change according to the command with + which it is associated. On the other hand, the reply codes + must strictly follow the specifications in this section. + Receiver implementations should not invent new codes for + slightly different situations from the ones described here, but + rather adapt codes already defined. + + For example, a command such as NOOP whose successful execution + does not offer the sender-SMTP any new information will return + a 250 reply. The response is 502 when the command requests an + unimplemented non-site-specific action. A refinement of that + is the 504 reply for a command that is implemented, but that + requests an unimplemented parameter. + + The reply text may be longer than a single line; in these cases + the complete text must be marked so the sender-SMTP knows when it + can stop reading the reply. This requires a special format to + indicate a multiple line reply. + + The format for multiline replies requires that every line, + except the last, begin with the reply code, followed + immediately by a hyphen, "-" (also known as minus), followed by + text. The last line will begin with the reply code, followed + immediately by , optionally some text, and . + + For example: + 123-First line + 123-Second line + 123-234 text beginning with numbers + 123 The last line + + In many cases the sender-SMTP then simply needs to search for + the reply code followed by at the beginning of a line, and + ignore all preceding lines. In a few cases, there is important + data for the sender in the reply "text". The sender will know + these cases from the current context. + + + + + + + + + + + + +[Page 50] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + +APPENDIX F + + Scenarios + + This section presents complete scenarios of several types of SMTP + sessions. + + A Typical SMTP Transaction Scenario + + This SMTP example shows mail sent by Smith at host USC-ISIF, to + Jones, Green, and Brown at host BBN-UNIX. Here we assume that + host USC-ISIF contacts host BBN-UNIX directly. The mail is + accepted for Jones and Brown. Green does not have a mailbox at + host BBN-UNIX. + + ------------------------------------------------------------- + + R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready + S: HELO USC-ISIF.ARPA + R: 250 BBN-UNIX.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: RCPT TO: + R: 550 No such user here + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 BBN-UNIX.ARPA Service closing transmission channel + + Scenario 1 + + ------------------------------------------------------------- + + + +Postel [Page 51] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + Aborted SMTP Transaction Scenario + + ------------------------------------------------------------- + + R: 220 MIT-Multics.ARPA Simple Mail Transfer Service Ready + S: HELO ISI-VAXA.ARPA + R: 250 MIT-Multics.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: RCPT TO: + R: 550 No such user here + + S: RSET + R: 250 OK + + S: QUIT + R: 221 MIT-Multics.ARPA Service closing transmission channel + + Scenario 2 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + + +[Page 52] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Relayed Mail Scenario + + ------------------------------------------------------------- + + Step 1 -- Source Host to Relay Host + + R: 220 USC-ISIE.ARPA Simple Mail Transfer Service Ready + S: HELO MIT-AI.ARPA + R: 250 USC-ISIE.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO:<@USC-ISIE.ARPA:Jones@BBN-VAX.ARPA> + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Date: 2 Nov 81 22:33:44 + S: From: John Q. Public + S: Subject: The Next Meeting of the Board + S: To: Jones@BBN-Vax.ARPA + S: + S: Bill: + S: The next meeting of the board of directors will be + S: on Tuesday. + S: John. + S: . + R: 250 OK + + S: QUIT + R: 221 USC-ISIE.ARPA Service closing transmission channel + + + + + + + + + + + + + + + + + +Postel [Page 53] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + Step 2 -- Relay Host to Destination Host + + R: 220 BBN-VAX.ARPA Simple Mail Transfer Service Ready + S: HELO USC-ISIE.ARPA + R: 250 BBN-VAX.ARPA + + S: MAIL FROM:<@USC-ISIE.ARPA:JQP@MIT-AI.ARPA> + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Received: from MIT-AI.ARPA by USC-ISIE.ARPA ; + 2 Nov 81 22:40:10 UT + S: Date: 2 Nov 81 22:33:44 + S: From: John Q. Public + S: Subject: The Next Meeting of the Board + S: To: Jones@BBN-Vax.ARPA + S: + S: Bill: + S: The next meeting of the board of directors will be + S: on Tuesday. + S: John. + S: . + R: 250 OK + + S: QUIT + R: 221 USC-ISIE.ARPA Service closing transmission channel + + Scenario 3 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + +[Page 54] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Verifying and Sending Scenario + + ------------------------------------------------------------- + + R: 220 SU-SCORE.ARPA Simple Mail Transfer Service Ready + S: HELO MIT-MC.ARPA + R: 250 SU-SCORE.ARPA + + S: VRFY Crispin + R: 250 Mark Crispin + + S: SEND FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 SU-SCORE.ARPA Service closing transmission channel + + Scenario 4 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + +Postel [Page 55] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + Sending and Mailing Scenarios + + First the user's name is verified, then an attempt is made to + send to the user's terminal. When that fails, the messages is + mailed to the user's mailbox. + + ------------------------------------------------------------- + + R: 220 SU-SCORE.ARPA Simple Mail Transfer Service Ready + S: HELO MIT-MC.ARPA + R: 250 SU-SCORE.ARPA + + S: VRFY Crispin + R: 250 Mark Crispin + + S: SEND FROM: + R: 250 OK + + S: RCPT TO: + R: 450 User not active now + + S: RSET + R: 250 OK + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 SU-SCORE.ARPA Service closing transmission channel + + Scenario 5 + + ------------------------------------------------------------- + + + + + + +[Page 56] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Doing the preceding scenario more efficiently. + + ------------------------------------------------------------- + + R: 220 SU-SCORE.ARPA Simple Mail Transfer Service Ready + S: HELO MIT-MC.ARPA + R: 250 SU-SCORE.ARPA + + S: VRFY Crispin + R: 250 Mark Crispin + + S: SOML FROM: + R: 250 OK + + S: RCPT TO: + R: 250 User not active now, so will do mail. + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 SU-SCORE.ARPA Service closing transmission channel + + Scenario 6 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + +Postel [Page 57] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + Mailing List Scenario + + First each of two mailing lists are expanded in separate sessions + with different hosts. Then the message is sent to everyone that + appeared on either list (but no duplicates) via a relay host. + + ------------------------------------------------------------- + + Step 1 -- Expanding the First List + + R: 220 MIT-AI.ARPA Simple Mail Transfer Service Ready + S: HELO SU-SCORE.ARPA + R: 250 MIT-AI.ARPA + + S: EXPN Example-People + R: 250- + R: 250-Fred Fonebone + R: 250-Xenon Y. Zither + R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> + R: 250- + R: 250 + + S: QUIT + R: 221 MIT-AI.ARPA Service closing transmission channel + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 58] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Step 2 -- Expanding the Second List + + R: 220 MIT-MC.ARPA Simple Mail Transfer Service Ready + S: HELO SU-SCORE.ARPA + R: 250 MIT-MC.ARPA + + S: EXPN Interested-Parties + R: 250-Al Calico + R: 250- + R: 250-Quincy Smith <@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> + R: 250- + R: 250 + + S: QUIT + R: 221 MIT-MC.ARPA Service closing transmission channel + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 59] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + Step 3 -- Mailing to All via a Relay Host + + R: 220 USC-ISIE.ARPA Simple Mail Transfer Service Ready + S: HELO SU-SCORE.ARPA + R: 250 USC-ISIE.ARPA + + S: MAIL FROM: + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:ABC@MIT-MC.ARPA> + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:Fonebone@USC-ISIQA.ARPA> + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:XYZ@MIT-AI.ARPA> + R: 250 OK + S: RCPT + TO:<@USC-ISIE.ARPA,@USC-ISIF.ARPA:Q-Smith@ISI-VAXA.ARPA> + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:joe@FOO-UNIX.ARPA> + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:xyz@BAR-UNIX.ARPA> + R: 250 OK + S: RCPT TO:<@USC-ISIE.ARPA:fred@BBN-UNIX.ARPA> + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 USC-ISIE.ARPA Service closing transmission channel + + Scenario 7 + + ------------------------------------------------------------- + + + + + + + + + + + + +[Page 60] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Forwarding Scenarios + + ------------------------------------------------------------- + + R: 220 USC-ISIF.ARPA Simple Mail Transfer Service Ready + S: HELO LBL-UNIX.ARPA + R: 250 USC-ISIF.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 251 User not local; will forward to + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 USC-ISIF.ARPA Service closing transmission channel + + Scenario 8 + + ------------------------------------------------------------- + + + + + + + + + + + + + + + + + + + + + + +Postel [Page 61] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + ------------------------------------------------------------- + + Step 1 -- Trying the Mailbox at the First Host + + R: 220 USC-ISIF.ARPA Simple Mail Transfer Service Ready + S: HELO LBL-UNIX.ARPA + R: 250 USC-ISIF.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 251 User not local; will forward to + + S: RSET + R: 250 OK + + S: QUIT + R: 221 USC-ISIF.ARPA Service closing transmission channel + + Step 2 -- Delivering the Mail at the Second Host + + R: 220 USC-ISI.ARPA Simple Mail Transfer Service Ready + S: HELO LBL-UNIX.ARPA + R: 250 USC-ISI.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 USC-ISI.ARPA Service closing transmission channel + + Scenario 9 + + ------------------------------------------------------------- + + + + +[Page 62] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + Too Many Recipients Scenario + + ------------------------------------------------------------- + + R: 220 BERKELEY.ARPA Simple Mail Transfer Service Ready + S: HELO USC-ISIF.ARPA + R: 250 BERKELEY.ARPA + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: RCPT TO: + R: 552 Recipient storage full, try again in another transaction + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: MAIL FROM: + R: 250 OK + + S: RCPT TO: + R: 250 OK + + S: DATA + R: 354 Start mail input; end with . + S: Blah blah blah... + S: ...etc. etc. etc. + S: . + R: 250 OK + + S: QUIT + R: 221 BERKELEY.ARPA Service closing transmission channel + + Scenario 10 + + ------------------------------------------------------------- + + Note that a real implementation must handle many recipients as + specified in Section 4.5.3. + + + +Postel [Page 63] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + +GLOSSARY + + ASCII + + American Standard Code for Information Interchange [1]. + + command + + A request for a mail service action sent by the sender-SMTP to the + receiver-SMTP. + + domain + + The hierarchially structured global character string address of a + host computer in the mail system. + + end of mail data indication + + A special sequence of characters that indicates the end of the + mail data. In particular, the five characters carriage return, + line feed, period, carriage return, line feed, in that order. + + host + + A computer in the internetwork environment on which mailboxes or + SMTP processes reside. + + line + + A a sequence of ASCII characters ending with a . + + mail data + + A sequence of ASCII characters of arbitrary length, which conforms + to the standard set in the Standard for the Format of ARPA + Internet Text Messages (RFC 822 [2]). + + mailbox + + A character string (address) which identifies a user to whom mail + is to be sent. Mailbox normally consists of the host and user + specifications. The standard mailbox naming convention is defined + to be "user@domain". Additionally, the "container" in which mail + is stored. + + + + + +[Page 64] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + + receiver-SMTP process + + A process which transfers mail in cooperation with a sender-SMTP + process. It waits for a connection to be established via the + transport service. It receives SMTP commands from the + sender-SMTP, sends replies, and performs the specified operations. + + reply + + A reply is an acknowledgment (positive or negative) sent from + receiver to sender via the transmission channel in response to a + command. The general form of a reply is a completion code + (including error codes) followed by a text string. The codes are + for use by programs and the text is usually intended for human + users. + + sender-SMTP process + + A process which transfers mail in cooperation with a receiver-SMTP + process. A local language may be used in the user interface + command/reply dialogue. The sender-SMTP initiates the transport + service connection. It initiates SMTP commands, receives replies, + and governs the transfer of mail. + + session + + The set of exchanges that occur while the transmission channel is + open. + + transaction + + The set of exchanges required for one message to be transmitted + for one or more recipients. + + transmission channel + + A full-duplex communication path between a sender-SMTP and a + receiver-SMTP for the exchange of commands, replies, and mail + text. + + transport service + + Any reliable stream-oriented data communication services. For + example, NCP, TCP, NITS. + + + + + +Postel [Page 65] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + user + + A human being (or a process on behalf of a human being) wishing to + obtain mail transfer service. In addition, a recipient of + computer mail. + + word + + A sequence of printing characters. + + + + The characters carriage return and line feed (in that order). + + + + The space character. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 66] Postel + + + +RFC 821 August 1982 + Simple Mail Transfer Protocol + + + +REFERENCES + + [1] ASCII + + ASCII, "USA Code for Information Interchange", United States of + America Standards Institute, X3.4, 1968. Also in: Feinler, E. + and J. Postel, eds., "ARPANET Protocol Handbook", NIC 7104, for + the Defense Communications Agency by SRI International, Menlo + Park, California, Revised January 1978. + + [2] RFC 822 + + Crocker, D., "Standard for the Format of ARPA Internet Text + Messages," RFC 822, Department of Electrical Engineering, + University of Delaware, August 1982. + + [3] TCP + + Postel, J., ed., "Transmission Control Protocol - DARPA Internet + Program Protocol Specification", RFC 793, USC/Information Sciences + Institute, NTIS AD Number A111091, September 1981. Also in: + Feinler, E. and J. Postel, eds., "Internet Protocol Transition + Workbook", SRI International, Menlo Park, California, March 1982. + + [4] NCP + + McKenzie,A., "Host/Host Protocol for the ARPA Network", NIC 8246, + January 1972. Also in: Feinler, E. and J. Postel, eds., "ARPANET + Protocol Handbook", NIC 7104, for the Defense Communications + Agency by SRI International, Menlo Park, California, Revised + January 1978. + + [5] Initial Connection Protocol + + Postel, J., "Official Initial Connection Protocol", NIC 7101, + 11 June 1971. Also in: Feinler, E. and J. Postel, eds., "ARPANET + Protocol Handbook", NIC 7104, for the Defense Communications + Agency by SRI International, Menlo Park, California, Revised + January 1978. + + [6] NITS + + PSS/SG3, "A Network Independent Transport Service", Study Group 3, + The Post Office PSS Users Group, February 1980. Available from + the DCPU, National Physical Laboratory, Teddington, UK. + + + + +Postel [Page 67] + + + +August 1982 RFC 821 +Simple Mail Transfer Protocol + + + + [7] X.25 + + CCITT, "Recommendation X.25 - Interface Between Data Terminal + Equipment (DTE) and Data Circuit-terminating Equipment (DCE) for + Terminals Operating in the Packet Mode on Public Data Networks," + CCITT Orange Book, Vol. VIII.2, International Telephone and + Telegraph Consultative Committee, Geneva, 1976. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Page 68] Postel + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0822.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0822.txt new file mode 100644 index 00000000..35b09a3c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc0822.txt @@ -0,0 +1,2901 @@ + + + + + + + RFC # 822 + + Obsoletes: RFC #733 (NIC #41952) + + + + + + + + + + + + + STANDARD FOR THE FORMAT OF + + ARPA INTERNET TEXT MESSAGES + + + + + + + August 13, 1982 + + + + + + + Revised by + + David H. Crocker + + + Dept. of Electrical Engineering + University of Delaware, Newark, DE 19711 + Network: DCrocker @ UDel-Relay + + + + + + + + + + + + + + + + Standard for ARPA Internet Text Messages + + + TABLE OF CONTENTS + + + PREFACE .................................................... ii + + 1. INTRODUCTION ........................................... 1 + + 1.1. Scope ............................................ 1 + 1.2. Communication Framework .......................... 2 + + 2. NOTATIONAL CONVENTIONS ................................. 3 + + 3. LEXICAL ANALYSIS OF MESSAGES ........................... 5 + + 3.1. General Description .............................. 5 + 3.2. Header Field Definitions ......................... 9 + 3.3. Lexical Tokens ................................... 10 + 3.4. Clarifications ................................... 11 + + 4. MESSAGE SPECIFICATION .................................. 17 + + 4.1. Syntax ........................................... 17 + 4.2. Forwarding ....................................... 19 + 4.3. Trace Fields ..................................... 20 + 4.4. Originator Fields ................................ 21 + 4.5. Receiver Fields .................................. 23 + 4.6. Reference Fields ................................. 23 + 4.7. Other Fields ..................................... 24 + + 5. DATE AND TIME SPECIFICATION ............................ 26 + + 5.1. Syntax ........................................... 26 + 5.2. Semantics ........................................ 26 + + 6. ADDRESS SPECIFICATION .................................. 27 + + 6.1. Syntax ........................................... 27 + 6.2. Semantics ........................................ 27 + 6.3. Reserved Address ................................. 33 + + 7. BIBLIOGRAPHY ........................................... 34 + + + APPENDIX + + A. EXAMPLES ............................................... 36 + B. SIMPLE FIELD PARSING ................................... 40 + C. DIFFERENCES FROM RFC #733 .............................. 41 + D. ALPHABETICAL LISTING OF SYNTAX RULES ................... 44 + + + August 13, 1982 - i - RFC #822 + + + + + Standard for ARPA Internet Text Messages + + + PREFACE + + + By 1977, the Arpanet employed several informal standards for + the text messages (mail) sent among its host computers. It was + felt necessary to codify these practices and provide for those + features that seemed imminent. The result of that effort was + Request for Comments (RFC) #733, "Standard for the Format of ARPA + Network Text Message", by Crocker, Vittal, Pogran, and Henderson. + The specification attempted to avoid major changes in existing + software, while permitting several new features. + + This document revises the specifications in RFC #733, in + order to serve the needs of the larger and more complex ARPA + Internet. Some of RFC #733's features failed to gain adequate + acceptance. In order to simplify the standard and the software + that follows it, these features have been removed. A different + addressing scheme is used, to handle the case of inter-network + mail; and the concept of re-transmission has been introduced. + + This specification is intended for use in the ARPA Internet. + However, an attempt has been made to free it of any dependence on + that environment, so that it can be applied to other network text + message systems. + + The specification of RFC #733 took place over the course of + one year, using the ARPANET mail environment, itself, to provide + an on-going forum for discussing the capabilities to be included. + More than twenty individuals, from across the country, partici- + pated in the original discussion. The development of this + revised specification has, similarly, utilized network mail-based + group discussion. Both specification efforts greatly benefited + from the comments and ideas of the participants. + + The syntax of the standard, in RFC #733, was originally + specified in the Backus-Naur Form (BNF) meta-language. Ken L. + Harrenstien, of SRI International, was responsible for re-coding + the BNF into an augmented BNF that makes the representation + smaller and easier to understand. + + + + + + + + + + + + + August 13, 1982 - ii - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 1. INTRODUCTION + + 1.1. SCOPE + + This standard specifies a syntax for text messages that are + sent among computer users, within the framework of "electronic + mail". The standard supersedes the one specified in ARPANET + Request for Comments #733, "Standard for the Format of ARPA Net- + work Text Messages". + + In this context, messages are viewed as having an envelope + and contents. The envelope contains whatever information is + needed to accomplish transmission and delivery. The contents + compose the object to be delivered to the recipient. This stan- + dard applies only to the format and some of the semantics of mes- + sage contents. It contains no specification of the information + in the envelope. + + However, some message systems may use information from the + contents to create the envelope. It is intended that this stan- + dard facilitate the acquisition of such information by programs. + + Some message systems may store messages in formats that + differ from the one specified in this standard. This specifica- + tion is intended strictly as a definition of what message content + format is to be passed BETWEEN hosts. + + Note: This standard is NOT intended to dictate the internal for- + mats used by sites, the specific message system features + that they are expected to support, or any of the charac- + teristics of user interface programs that create or read + messages. + + A distinction should be made between what the specification + REQUIRES and what it ALLOWS. Messages can be made complex and + rich with formally-structured components of information or can be + kept small and simple, with a minimum of such information. Also, + the standard simplifies the interpretation of differing visual + formats in messages; only the visual aspect of a message is + affected and not the interpretation of information within it. + Implementors may choose to retain such visual distinctions. + + The formal definition is divided into four levels. The bot- + tom level describes the meta-notation used in this document. The + second level describes basic lexical analyzers that feed tokens + to higher-level parsers. Next is an overall specification for + messages; it permits distinguishing individual fields. Finally, + there is definition of the contents of several structured fields. + + + + August 13, 1982 - 1 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 1.2. COMMUNICATION FRAMEWORK + + Messages consist of lines of text. No special provisions + are made for encoding drawings, facsimile, speech, or structured + text. No significant consideration has been given to questions + of data compression or to transmission and storage efficiency, + and the standard tends to be free with the number of bits con- + sumed. For example, field names are specified as free text, + rather than special terse codes. + + A general "memo" framework is used. That is, a message con- + sists of some information in a rigid format, followed by the main + part of the message, with a format that is not specified in this + document. The syntax of several fields of the rigidly-formated + ("headers") section is defined in this specification; some of + these fields must be included in all messages. + + The syntax that distinguishes between header fields is + specified separately from the internal syntax for particular + fields. This separation is intended to allow simple parsers to + operate on the general structure of messages, without concern for + the detailed structure of individual header fields. Appendix B + is provided to facilitate construction of these parsers. + + In addition to the fields specified in this document, it is + expected that other fields will gain common use. As necessary, + the specifications for these "extension-fields" will be published + through the same mechanism used to publish this document. Users + may also wish to extend the set of fields that they use + privately. Such "user-defined fields" are permitted. + + The framework severely constrains document tone and appear- + ance and is primarily useful for most intra-organization communi- + cations and well-structured inter-organization communication. + It also can be used for some types of inter-process communica- + tion, such as simple file transfer and remote job entry. A more + robust framework might allow for multi-font, multi-color, multi- + dimension encoding of information. A less robust one, as is + present in most single-machine message systems, would more + severely constrain the ability to add fields and the decision to + include specific fields. In contrast with paper-based communica- + tion, it is interesting to note that the RECEIVER of a message + can exercise an extraordinary amount of control over the + message's appearance. The amount of actual control available to + message receivers is contingent upon the capabilities of their + individual message systems. + + + + + + August 13, 1982 - 2 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 2. NOTATIONAL CONVENTIONS + + This specification uses an augmented Backus-Naur Form (BNF) + notation. The differences from standard BNF involve naming rules + and indicating repetition and "local" alternatives. + + 2.1. RULE NAMING + + Angle brackets ("<", ">") are not used, in general. The + name of a rule is simply the name itself, rather than "". + Quotation-marks enclose literal text (which may be upper and/or + lower case). Certain basic rules are in uppercase, such as + SPACE, TAB, CRLF, DIGIT, ALPHA, etc. Angle brackets are used in + rule definitions, and in the rest of this document, whenever + their presence will facilitate discerning the use of rule names. + + 2.2. RULE1 / RULE2: ALTERNATIVES + + Elements separated by slash ("/") are alternatives. There- + fore "foo / bar" will accept foo or bar. + + 2.3. (RULE1 RULE2): LOCAL ALTERNATIVES + + Elements enclosed in parentheses are treated as a single + element. Thus, "(elem (foo / bar) elem)" allows the token + sequences "elem foo elem" and "elem bar elem". + + 2.4. *RULE: REPETITION + + The character "*" preceding an element indicates repetition. + The full form is: + + *element + + indicating at least and at most occurrences of element. + Default values are 0 and infinity so that "*(element)" allows any + number, including zero; "1*element" requires at least one; and + "1*2element" allows one or two. + + 2.5. [RULE]: OPTIONAL + + Square brackets enclose optional elements; "[foo bar]" is + equivalent to "*1(foo bar)". + + 2.6. NRULE: SPECIFIC REPETITION + + "(element)" is equivalent to "*(element)"; that is, + exactly occurrences of (element). Thus 2DIGIT is a 2-digit + number, and 3ALPHA is a string of three alphabetic characters. + + + August 13, 1982 - 3 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 2.7. #RULE: LISTS + + A construct "#" is defined, similar to "*", as follows: + + #element + + indicating at least and at most elements, each separated + by one or more commas (","). This makes the usual form of lists + very easy; a rule such as '(element *("," element))' can be shown + as "1#element". Wherever this construct is used, null elements + are allowed, but do not contribute to the count of elements + present. That is, "(element),,(element)" is permitted, but + counts as only two elements. Therefore, where at least one ele- + ment is required, at least one non-null element must be present. + Default values are 0 and infinity so that "#(element)" allows any + number, including zero; "1#element" requires at least one; and + "1#2element" allows one or two. + + 2.8. ; COMMENTS + + A semi-colon, set off some distance to the right of rule + text, starts a comment that continues to the end of line. This + is a simple way of including useful notes in parallel with the + specifications. + + + + + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 4 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 3. LEXICAL ANALYSIS OF MESSAGES + + 3.1. GENERAL DESCRIPTION + + A message consists of header fields and, optionally, a body. + The body is simply a sequence of lines containing ASCII charac- + ters. It is separated from the headers by a null line (i.e., a + line with nothing preceding the CRLF). + + 3.1.1. LONG HEADER FIELDS + + Each header field can be viewed as a single, logical line of + ASCII characters, comprising a field-name and a field-body. + For convenience, the field-body portion of this conceptual + entity can be split into a multiple-line representation; this + is called "folding". The general rule is that wherever there + may be linear-white-space (NOT simply LWSP-chars), a CRLF + immediately followed by AT LEAST one LWSP-char may instead be + inserted. Thus, the single line + + To: "Joe & J. Harvey" , JJV @ BBN + + can be represented as: + + To: "Joe & J. Harvey" , + JJV@BBN + + and + + To: "Joe & J. Harvey" + , JJV + @BBN + + and + + To: "Joe & + J. Harvey" , JJV @ BBN + + The process of moving from this folded multiple-line + representation of a header field to its single line represen- + tation is called "unfolding". Unfolding is accomplished by + regarding CRLF immediately followed by a LWSP-char as + equivalent to the LWSP-char. + + Note: While the standard permits folding wherever linear- + white-space is permitted, it is recommended that struc- + tured fields, such as those containing addresses, limit + folding to higher-level syntactic breaks. For address + fields, it is recommended that such folding occur + + + August 13, 1982 - 5 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + between addresses, after the separating comma. + + 3.1.2. STRUCTURE OF HEADER FIELDS + + Once a field has been unfolded, it may be viewed as being com- + posed of a field-name followed by a colon (":"), followed by a + field-body, and terminated by a carriage-return/line-feed. + The field-name must be composed of printable ASCII characters + (i.e., characters that have values between 33. and 126., + decimal, except colon). The field-body may be composed of any + ASCII characters, except CR or LF. (While CR and/or LF may be + present in the actual text, they are removed by the action of + unfolding the field.) + + Certain field-bodies of headers may be interpreted according + to an internal syntax that some systems may wish to parse. + These fields are called "structured fields". Examples + include fields containing dates and addresses. Other fields, + such as "Subject" and "Comments", are regarded simply as + strings of text. + + Note: Any field which has a field-body that is defined as + other than simply is to be treated as a struc- + tured field. + + Field-names, unstructured field bodies and structured + field bodies each are scanned by their own, independent + "lexical" analyzers. + + 3.1.3. UNSTRUCTURED FIELD BODIES + + For some fields, such as "Subject" and "Comments", no struc- + turing is assumed, and they are treated simply as s, as + in the message body. Rules of folding apply to these fields, + so that such field bodies which occupy several lines must + therefore have the second and successive lines indented by at + least one LWSP-char. + + 3.1.4. STRUCTURED FIELD BODIES + + To aid in the creation and reading of structured fields, the + free insertion of linear-white-space (which permits folding + by inclusion of CRLFs) is allowed between lexical tokens. + Rather than obscuring the syntax specifications for these + structured fields with explicit syntax for this linear-white- + space, the existence of another "lexical" analyzer is assumed. + This analyzer does not apply for unstructured field bodies + that are simply strings of text, as described above. The + analyzer provides an interpretation of the unfolded text + + + August 13, 1982 - 6 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + composing the body of the field as a sequence of lexical sym- + bols. + + These symbols are: + + - individual special characters + - quoted-strings + - domain-literals + - comments + - atoms + + The first four of these symbols are self-delimiting. Atoms + are not; they are delimited by the self-delimiting symbols and + by linear-white-space. For the purposes of regenerating + sequences of atoms and quoted-strings, exactly one SPACE is + assumed to exist, and should be used, between them. (Also, in + the "Clarifications" section on "White Space", below, note the + rules about treatment of multiple contiguous LWSP-chars.) + + So, for example, the folded body of an address field + + ":sysmail"@ Some-Group. Some-Org, + Muhammed.(I am the greatest) Ali @(the)Vegas.WBA + + + + + + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 7 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + is analyzed into the following lexical symbols and types: + + :sysmail quoted string + @ special + Some-Group atom + . special + Some-Org atom + , special + Muhammed atom + . special + (I am the greatest) comment + Ali atom + @ atom + (the) comment + Vegas atom + . special + WBA atom + + The canonical representations for the data in these addresses + are the following strings: + + ":sysmail"@Some-Group.Some-Org + + and + + Muhammed.Ali@Vegas.WBA + + Note: For purposes of display, and when passing such struc- + tured information to other systems, such as mail proto- + col services, there must be NO linear-white-space + between s that are separated by period (".") or + at-sign ("@") and exactly one SPACE between all other + s. Also, headers should be in a folded form. + + + + + + + + + + + + + + + + + + + August 13, 1982 - 8 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 3.2. HEADER FIELD DEFINITIONS + + These rules show a field meta-syntax, without regard for the + particular type or internal syntax. Their purpose is to permit + detection of fields; also, they present to higher-level parsers + an image of each field as fitting on one line. + + field = field-name ":" [ field-body ] CRLF + + field-name = 1* + + field-body = field-body-contents + [CRLF LWSP-char field-body] + + field-body-contents = + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 9 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 3.3. LEXICAL TOKENS + + The following rules are used to define an underlying lexical + analyzer, which feeds tokens to higher level parsers. See the + ANSI references, in the Bibliography. + + ; ( Octal, Decimal.) + CHAR = ; ( 0-177, 0.-127.) + ALPHA = + ; (101-132, 65.- 90.) + ; (141-172, 97.-122.) + DIGIT = ; ( 60- 71, 48.- 57.) + CTL = ; ( 177, 127.) + CR = ; ( 15, 13.) + LF = ; ( 12, 10.) + SPACE = ; ( 40, 32.) + HTAB = ; ( 11, 9.) + <"> = ; ( 42, 34.) + CRLF = CR LF + + LWSP-char = SPACE / HTAB ; semantics = SPACE + + linear-white-space = 1*([CRLF] LWSP-char) ; semantics = SPACE + ; CRLF => folding + + specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted- + / "," / ";" / ":" / "\" / <"> ; string, to use + / "." / "[" / "]" ; within a word. + + delimiters = specials / linear-white-space / comment + + text = atoms, specials, + CR & bare LF, but NOT ; comments and + including CRLF> ; quoted-strings are + ; NOT recognized. + + atom = 1* + + quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or + ; quoted chars. + + qtext = , ; => may be folded + "\" & CR, and including + linear-white-space> + + domain-literal = "[" *(dtext / quoted-pair) "]" + + + + + August 13, 1982 - 10 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + dtext = may be folded + "]", "\" & CR, & including + linear-white-space> + + comment = "(" *(ctext / quoted-pair / comment) ")" + + ctext = may be folded + ")", "\" & CR, & including + linear-white-space> + + quoted-pair = "\" CHAR ; may quote any char + + phrase = 1*word ; Sequence of words + + word = atom / quoted-string + + + 3.4. CLARIFICATIONS + + 3.4.1. QUOTING + + Some characters are reserved for special interpretation, such + as delimiting lexical tokens. To permit use of these charac- + ters as uninterpreted data, a quoting mechanism is provided. + To quote a character, precede it with a backslash ("\"). + + This mechanism is not fully general. Characters may be quoted + only within a subset of the lexical constructs. In particu- + lar, quoting is limited to use within: + + - quoted-string + - domain-literal + - comment + + Within these constructs, quoting is REQUIRED for CR and "\" + and for the character(s) that delimit the token (e.g., "(" and + ")" for a comment). However, quoting is PERMITTED for any + character. + + Note: In particular, quoting is NOT permitted within atoms. + For example when the local-part of an addr-spec must + contain a special character, a quoted string must be + used. Therefore, a specification such as: + + Full\ Name@Domain + + is not legal and must be specified as: + + "Full Name"@Domain + + + August 13, 1982 - 11 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 3.4.2. WHITE SPACE + + Note: In structured field bodies, multiple linear space ASCII + characters (namely HTABs and SPACEs) are treated as + single spaces and may freely surround any symbol. In + all header fields, the only place in which at least one + LWSP-char is REQUIRED is at the beginning of continua- + tion lines in a folded field. + + When passing text to processes that do not interpret text + according to this standard (e.g., mail protocol servers), then + NO linear-white-space characters should occur between a period + (".") or at-sign ("@") and a . Exactly ONE SPACE should + be used in place of arbitrary linear-white-space and comment + sequences. + + Note: Within systems conforming to this standard, wherever a + member of the list of delimiters is allowed, LWSP-chars + may also occur before and/or after it. + + Writers of mail-sending (i.e., header-generating) programs + should realize that there is no network-wide definition of the + effect of ASCII HT (horizontal-tab) characters on the appear- + ance of text at another network host; therefore, the use of + tabs in message headers, though permitted, is discouraged. + + 3.4.3. COMMENTS + + A comment is a set of ASCII characters, which is enclosed in + matching parentheses and which is not within a quoted-string + The comment construct permits message originators to add text + which will be useful for human readers, but which will be + ignored by the formal semantics. Comments should be retained + while the message is subject to interpretation according to + this standard. However, comments must NOT be included in + other cases, such as during protocol exchanges with mail + servers. + + Comments nest, so that if an unquoted left parenthesis occurs + in a comment string, there must also be a matching right + parenthesis. When a comment acts as the delimiter between a + sequence of two lexical symbols, such as two atoms, it is lex- + ically equivalent with a single SPACE, for the purposes of + regenerating the sequence, such as when passing the sequence + onto a mail protocol server. Comments are detected as such + only within field-bodies of structured fields. + + If a comment is to be "folded" onto multiple lines, then the + syntax for folding must be adhered to. (See the "Lexical + + + August 13, 1982 - 12 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + Analysis of Messages" section on "Folding Long Header Fields" + above, and the section on "Case Independence" below.) Note + that the official semantics therefore do not "see" any + unquoted CRLFs that are in comments, although particular pars- + ing programs may wish to note their presence. For these pro- + grams, it would be reasonable to interpret a "CRLF LWSP-char" + as being a CRLF that is part of the comment; i.e., the CRLF is + kept and the LWSP-char is discarded. Quoted CRLFs (i.e., a + backslash followed by a CR followed by a LF) still must be + followed by at least one LWSP-char. + + 3.4.4. DELIMITING AND QUOTING CHARACTERS + + The quote character (backslash) and characters that delimit + syntactic units are not, generally, to be taken as data that + are part of the delimited or quoted unit(s). In particular, + the quotation-marks that define a quoted-string, the + parentheses that define a comment and the backslash that + quotes a following character are NOT part of the quoted- + string, comment or quoted character. A quotation-mark that is + to be part of a quoted-string, a parenthesis that is to be + part of a comment and a backslash that is to be part of either + must each be preceded by the quote-character backslash ("\"). + Note that the syntax allows any character to be quoted within + a quoted-string or comment; however only certain characters + MUST be quoted to be included as data. These characters are + the ones that are not part of the alternate text group (i.e., + ctext or qtext). + + The one exception to this rule is that a single SPACE is + assumed to exist between contiguous words in a phrase, and + this interpretation is independent of the actual number of + LWSP-chars that the creator places between the words. To + include more than one SPACE, the creator must make the LWSP- + chars be part of a quoted-string. + + Quotation marks that delimit a quoted string and backslashes + that quote the following character should NOT accompany the + quoted-string when the string is passed to processes that do + not interpret data according to this specification (e.g., mail + protocol servers). + + 3.4.5. QUOTED-STRINGS + + Where permitted (i.e., in words in structured fields) quoted- + strings are treated as a single symbol. That is, a quoted- + string is equivalent to an atom, syntactically. If a quoted- + string is to be "folded" onto multiple lines, then the syntax + for folding must be adhered to. (See the "Lexical Analysis of + + + August 13, 1982 - 13 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + Messages" section on "Folding Long Header Fields" above, and + the section on "Case Independence" below.) Therefore, the + official semantics do not "see" any bare CRLFs that are in + quoted-strings; however particular parsing programs may wish + to note their presence. For such programs, it would be rea- + sonable to interpret a "CRLF LWSP-char" as being a CRLF which + is part of the quoted-string; i.e., the CRLF is kept and the + LWSP-char is discarded. Quoted CRLFs (i.e., a backslash fol- + lowed by a CR followed by a LF) are also subject to rules of + folding, but the presence of the quoting character (backslash) + explicitly indicates that the CRLF is data to the quoted + string. Stripping off the first following LWSP-char is also + appropriate when parsing quoted CRLFs. + + 3.4.6. BRACKETING CHARACTERS + + There is one type of bracket which must occur in matched pairs + and may have pairs nested within each other: + + o Parentheses ("(" and ")") are used to indicate com- + ments. + + There are three types of brackets which must occur in matched + pairs, and which may NOT be nested: + + o Colon/semi-colon (":" and ";") are used in address + specifications to indicate that the included list of + addresses are to be treated as a group. + + o Angle brackets ("<" and ">") are generally used to + indicate the presence of a one machine-usable refer- + ence (e.g., delimiting mailboxes), possibly including + source-routing to the machine. + + o Square brackets ("[" and "]") are used to indicate the + presence of a domain-literal, which the appropriate + name-domain is to use directly, bypassing normal + name-resolution mechanisms. + + 3.4.7. CASE INDEPENDENCE + + Except as noted, alphabetic strings may be represented in any + combination of upper and lower case. The only syntactic units + + + + + + + + + August 13, 1982 - 14 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + which requires preservation of case information are: + + - text + - qtext + - dtext + - ctext + - quoted-pair + - local-part, except "Postmaster" + + When matching any other syntactic unit, case is to be ignored. + For example, the field-names "From", "FROM", "from", and even + "FroM" are semantically equal and should all be treated ident- + ically. + + When generating these units, any mix of upper and lower case + alphabetic characters may be used. The case shown in this + specification is suggested for message-creating processes. + + Note: The reserved local-part address unit, "Postmaster", is + an exception. When the value "Postmaster" is being + interpreted, it must be accepted in any mixture of + case, including "POSTMASTER", and "postmaster". + + 3.4.8. FOLDING LONG HEADER FIELDS + + Each header field may be represented on exactly one line con- + sisting of the name of the field and its body, and terminated + by a CRLF; this is what the parser sees. For readability, the + field-body portion of long header fields may be "folded" onto + multiple lines of the actual field. "Long" is commonly inter- + preted to mean greater than 65 or 72 characters. The former + length serves as a limit, when the message is to be viewed on + most simple terminals which use simple display software; how- + ever, the limit is not imposed by this standard. + + Note: Some display software often can selectively fold lines, + to suit the display terminal. In such cases, sender- + provided folding can interfere with the display + software. + + 3.4.9. BACKSPACE CHARACTERS + + ASCII BS characters (Backspace, decimal 8) may be included in + texts and quoted-strings to effect overstriking. However, any + use of backspaces which effects an overstrike to the left of + the beginning of the text or quoted-string is prohibited. + + + + + + August 13, 1982 - 15 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 3.4.10. NETWORK-SPECIFIC TRANSFORMATIONS + + During transmission through heterogeneous networks, it may be + necessary to force data to conform to a network's local con- + ventions. For example, it may be required that a CR be fol- + lowed either by LF, making a CRLF, or by , if the CR is + to stand alone). Such transformations are reversed, when the + message exits that network. + + When crossing network boundaries, the message should be + treated as passing through two modules. It will enter the + first module containing whatever network-specific transforma- + tions that were necessary to permit migration through the + "current" network. It then passes through the modules: + + o Transformation Reversal + + The "current" network's idiosyncracies are removed and + the message is returned to the canonical form speci- + fied in this standard. + + o Transformation + + The "next" network's local idiosyncracies are imposed + on the message. + + ------------------ + From ==> | Remove Net-A | + Net-A | idiosyncracies | + ------------------ + || + \/ + Conformance + with standard + || + \/ + ------------------ + | Impose Net-B | ==> To + | idiosyncracies | Net-B + ------------------ + + + + + + + + + + + + August 13, 1982 - 16 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 4. MESSAGE SPECIFICATION + + 4.1. SYNTAX + + Note: Due to an artifact of the notational conventions, the syn- + tax indicates that, when present, some fields, must be in + a particular order. Header fields are NOT required to + occur in any particular order, except that the message + body must occur AFTER the headers. It is recommended + that, if present, headers be sent in the order "Return- + Path", "Received", "Date", "From", "Subject", "Sender", + "To", "cc", etc. + + This specification permits multiple occurrences of most + fields. Except as noted, their interpretation is not + specified here, and their use is discouraged. + + The following syntax for the bodies of various fields should + be thought of as describing each field body as a single long + string (or line). The "Lexical Analysis of Message" section on + "Long Header Fields", above, indicates how such long strings can + be represented on more than one line in the actual transmitted + message. + + message = fields *( CRLF *text ) ; Everything after + ; first null line + ; is message body + + fields = dates ; Creation time, + source ; author id & one + 1*destination ; address required + *optional-field ; others optional + + source = [ trace ] ; net traversals + originator ; original mail + [ resent ] ; forwarded + + trace = return ; path to sender + 1*received ; receipt tags + + return = "Return-path" ":" route-addr ; return address + + received = "Received" ":" ; one per relay + ["from" domain] ; sending host + ["by" domain] ; receiving host + ["via" atom] ; physical path + *("with" atom) ; link/mail protocol + ["id" msg-id] ; receiver msg id + ["for" addr-spec] ; initial form + + + August 13, 1982 - 17 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + ";" date-time ; time received + + originator = authentic ; authenticated addr + [ "Reply-To" ":" 1#address] ) + + authentic = "From" ":" mailbox ; Single author + / ( "Sender" ":" mailbox ; Actual submittor + "From" ":" 1#mailbox) ; Multiple authors + ; or not sender + + resent = resent-authentic + [ "Resent-Reply-To" ":" 1#address] ) + + resent-authentic = + = "Resent-From" ":" mailbox + / ( "Resent-Sender" ":" mailbox + "Resent-From" ":" 1#mailbox ) + + dates = orig-date ; Original + [ resent-date ] ; Forwarded + + orig-date = "Date" ":" date-time + + resent-date = "Resent-Date" ":" date-time + + destination = "To" ":" 1#address ; Primary + / "Resent-To" ":" 1#address + / "cc" ":" 1#address ; Secondary + / "Resent-cc" ":" 1#address + / "bcc" ":" #address ; Blind carbon + / "Resent-bcc" ":" #address + + optional-field = + / "Message-ID" ":" msg-id + / "Resent-Message-ID" ":" msg-id + / "In-Reply-To" ":" *(phrase / msg-id) + / "References" ":" *(phrase / msg-id) + / "Keywords" ":" #phrase + / "Subject" ":" *text + / "Comments" ":" *text + / "Encrypted" ":" 1#2word + / extension-field ; To be defined + / user-defined-field ; May be pre-empted + + msg-id = "<" addr-spec ">" ; Unique message id + + + + + + + August 13, 1982 - 18 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + extension-field = + + + user-defined-field = + + + 4.2. FORWARDING + + Some systems permit mail recipients to forward a message, + retaining the original headers, by adding some new fields. This + standard supports such a service, through the "Resent-" prefix to + field names. + + Whenever the string "Resent-" begins a field name, the field + has the same semantics as a field whose name does not have the + prefix. However, the message is assumed to have been forwarded + by an original recipient who attached the "Resent-" field. This + new field is treated as being more recent than the equivalent, + original field. For example, the "Resent-From", indicates the + person that forwarded the message, whereas the "From" field indi- + cates the original author. + + Use of such precedence information depends upon partici- + pants' communication needs. For example, this standard does not + dictate when a "Resent-From:" address should receive replies, in + lieu of sending them to the "From:" address. + + Note: In general, the "Resent-" fields should be treated as con- + taining a set of information that is independent of the + set of original fields. Information for one set should + not automatically be taken from the other. The interpre- + tation of multiple "Resent-" fields, of the same type, is + undefined. + + In the remainder of this specification, occurrence of legal + "Resent-" fields are treated identically with the occurrence of + + + + + + + + + August 13, 1982 - 19 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + fields whose names do not contain this prefix. + + 4.3. TRACE FIELDS + + Trace information is used to provide an audit trail of mes- + sage handling. In addition, it indicates a route back to the + sender of the message. + + The list of known "via" and "with" values are registered + with the Network Information Center, SRI International, Menlo + Park, California. + + 4.3.1. RETURN-PATH + + This field is added by the final transport system that + delivers the message to its recipient. The field is intended + to contain definitive information about the address and route + back to the message's originator. + + Note: The "Reply-To" field is added by the originator and + serves to direct replies, whereas the "Return-Path" + field is used to identify a path back to the origina- + tor. + + While the syntax indicates that a route specification is + optional, every attempt should be made to provide that infor- + mation in this field. + + 4.3.2. RECEIVED + + A copy of this field is added by each transport service that + relays the message. The information in the field can be quite + useful for tracing transport problems. + + The names of the sending and receiving hosts and time-of- + receipt may be specified. The "via" parameter may be used, to + indicate what physical mechanism the message was sent over, + such as Arpanet or Phonenet, and the "with" parameter may be + used to indicate the mail-, or connection-, level protocol + that was used, such as the SMTP mail protocol, or X.25 tran- + sport protocol. + + Note: Several "with" parameters may be included, to fully + specify the set of protocols that were used. + + Some transport services queue mail; the internal message iden- + tifier that is assigned to the message may be noted, using the + "id" parameter. When the sending host uses a destination + address specification that the receiving host reinterprets, by + + + August 13, 1982 - 20 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + expansion or transformation, the receiving host may wish to + record the original specification, using the "for" parameter. + For example, when a copy of mail is sent to the member of a + distribution list, this parameter may be used to record the + original address that was used to specify the list. + + 4.4. ORIGINATOR FIELDS + + The standard allows only a subset of the combinations possi- + ble with the From, Sender, Reply-To, Resent-From, Resent-Sender, + and Resent-Reply-To fields. The limitation is intentional. + + 4.4.1. FROM / RESENT-FROM + + This field contains the identity of the person(s) who wished + this message to be sent. The message-creation process should + default this field to be a single, authenticated machine + address, indicating the AGENT (person, system or process) + entering the message. If this is not done, the "Sender" field + MUST be present. If the "From" field IS defaulted this way, + the "Sender" field is optional and is redundant with the + "From" field. In all cases, addresses in the "From" field + must be machine-usable (addr-specs) and may not contain named + lists (groups). + + 4.4.2. SENDER / RESENT-SENDER + + This field contains the authenticated identity of the AGENT + (person, system or process) that sends the message. It is + intended for use when the sender is not the author of the mes- + sage, or to indicate who among a group of authors actually + sent the message. If the contents of the "Sender" field would + be completely redundant with the "From" field, then the + "Sender" field need not be present and its use is discouraged + (though still legal). In particular, the "Sender" field MUST + be present if it is NOT the same as the "From" Field. + + The Sender mailbox specification includes a word sequence + which must correspond to a specific agent (i.e., a human user + or a computer program) rather than a standard address. This + indicates the expectation that the field will identify the + single AGENT (person, system, or process) responsible for + sending the mail and not simply include the name of a mailbox + from which the mail was sent. For example in the case of a + shared login name, the name, by itself, would not be adequate. + The local-part address unit, which refers to this agent, is + expected to be a computer system term, and not (for example) a + generalized person reference which can be used outside the + network text message context. + + + August 13, 1982 - 21 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + Since the critical function served by the "Sender" field is + identification of the agent responsible for sending mail and + since computer programs cannot be held accountable for their + behavior, it is strongly recommended that when a computer pro- + gram generates a message, the HUMAN who is responsible for + that program be referenced as part of the "Sender" field mail- + box specification. + + 4.4.3. REPLY-TO / RESENT-REPLY-TO + + This field provides a general mechanism for indicating any + mailbox(es) to which responses are to be sent. Three typical + uses for this feature can be distinguished. In the first + case, the author(s) may not have regular machine-based mail- + boxes and therefore wish(es) to indicate an alternate machine + address. In the second case, an author may wish additional + persons to be made aware of, or responsible for, replies. A + somewhat different use may be of some help to "text message + teleconferencing" groups equipped with automatic distribution + services: include the address of that service in the "Reply- + To" field of all messages submitted to the teleconference; + then participants can "reply" to conference submissions to + guarantee the correct distribution of any submission of their + own. + + Note: The "Return-Path" field is added by the mail transport + service, at the time of final deliver. It is intended + to identify a path back to the orginator of the mes- + sage. The "Reply-To" field is added by the message + originator and is intended to direct replies. + + 4.4.4. AUTOMATIC USE OF FROM / SENDER / REPLY-TO + + For systems which automatically generate address lists for + replies to messages, the following recommendations are made: + + o The "Sender" field mailbox should be sent notices of + any problems in transport or delivery of the original + messages. If there is no "Sender" field, then the + "From" field mailbox should be used. + + o The "Sender" field mailbox should NEVER be used + automatically, in a recipient's reply message. + + o If the "Reply-To" field exists, then the reply should + go to the addresses indicated in that field and not to + the address(es) indicated in the "From" field. + + + + + August 13, 1982 - 22 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + o If there is a "From" field, but no "Reply-To" field, + the reply should be sent to the address(es) indicated + in the "From" field. + + Sometimes, a recipient may actually wish to communicate with + the person that initiated the message transfer. In such + cases, it is reasonable to use the "Sender" address. + + This recommendation is intended only for automated use of + originator-fields and is not intended to suggest that replies + may not also be sent to other recipients of messages. It is + up to the respective mail-handling programs to decide what + additional facilities will be provided. + + Examples are provided in Appendix A. + + 4.5. RECEIVER FIELDS + + 4.5.1. TO / RESENT-TO + + This field contains the identity of the primary recipients of + the message. + + 4.5.2. CC / RESENT-CC + + This field contains the identity of the secondary (informa- + tional) recipients of the message. + + 4.5.3. BCC / RESENT-BCC + + This field contains the identity of additional recipients of + the message. The contents of this field are not included in + copies of the message sent to the primary and secondary reci- + pients. Some systems may choose to include the text of the + "Bcc" field only in the author(s)'s copy, while others may + also include it in the text sent to all those indicated in the + "Bcc" list. + + 4.6. REFERENCE FIELDS + + 4.6.1. MESSAGE-ID / RESENT-MESSAGE-ID + + This field contains a unique identifier (the local-part + address unit) which refers to THIS version of THIS message. + The uniqueness of the message identifier is guaranteed by the + host which generates it. This identifier is intended to be + machine readable and not necessarily meaningful to humans. A + message identifier pertains to exactly one instantiation of a + particular message; subsequent revisions to the message should + + + August 13, 1982 - 23 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + each receive new message identifiers. + + 4.6.2. IN-REPLY-TO + + The contents of this field identify previous correspon- + dence which this message answers. Note that if message iden- + tifiers are used in this field, they must use the msg-id + specification format. + + 4.6.3. REFERENCES + + The contents of this field identify other correspondence + which this message references. Note that if message identif- + iers are used, they must use the msg-id specification format. + + 4.6.4. KEYWORDS + + This field contains keywords or phrases, separated by + commas. + + 4.7. OTHER FIELDS + + 4.7.1. SUBJECT + + This is intended to provide a summary, or indicate the + nature, of the message. + + 4.7.2. COMMENTS + + Permits adding text comments onto the message without + disturbing the contents of the message's body. + + 4.7.3. ENCRYPTED + + Sometimes, data encryption is used to increase the + privacy of message contents. If the body of a message has + been encrypted, to keep its contents private, the "Encrypted" + field can be used to note the fact and to indicate the nature + of the encryption. The first parameter indicates the + software used to encrypt the body, and the second, optional + is intended to aid the recipient in selecting the + proper decryption key. This code word may be viewed as an + index to a table of keys held by the recipient. + + Note: Unfortunately, headers must contain envelope, as well + as contents, information. Consequently, it is neces- + sary that they remain unencrypted, so that mail tran- + sport services may access them. Since names, + addresses, and "Subject" field contents may contain + + + August 13, 1982 - 24 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + sensitive information, this requirement limits total + message privacy. + + Names of encryption software are registered with the Net- + work Information Center, SRI International, Menlo Park, Cali- + fornia. + + 4.7.4. EXTENSION-FIELD + + A limited number of common fields have been defined in + this document. As network mail requirements dictate, addi- + tional fields may be standardized. To provide user-defined + fields with a measure of safety, in name selection, such + extension-fields will never have names that begin with the + string "X-". + + Names of Extension-fields are registered with the Network + Information Center, SRI International, Menlo Park, California. + + 4.7.5. USER-DEFINED-FIELD + + Individual users of network mail are free to define and + use additional header fields. Such fields must have names + which are not already used in the current specification or in + any definitions of extension-fields, and the overall syntax of + these user-defined-fields must conform to this specification's + rules for delimiting and folding fields. Due to the + extension-field publishing process, the name of a user- + defined-field may be pre-empted + + Note: The prefatory string "X-" will never be used in the + names of Extension-fields. This provides user-defined + fields with a protected set of names. + + + + + + + + + + + + + + + + + + + August 13, 1982 - 25 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 5. DATE AND TIME SPECIFICATION + + 5.1. SYNTAX + + date-time = [ day "," ] date time ; dd mm yy + ; hh:mm:ss zzz + + day = "Mon" / "Tue" / "Wed" / "Thu" + / "Fri" / "Sat" / "Sun" + + date = 1*2DIGIT month 2DIGIT ; day month year + ; e.g. 20 Jun 82 + + month = "Jan" / "Feb" / "Mar" / "Apr" + / "May" / "Jun" / "Jul" / "Aug" + / "Sep" / "Oct" / "Nov" / "Dec" + + time = hour zone ; ANSI and Military + + hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] + ; 00:00:00 - 23:59:59 + + zone = "UT" / "GMT" ; Universal Time + ; North American : UT + / "EST" / "EDT" ; Eastern: - 5/ - 4 + / "CST" / "CDT" ; Central: - 6/ - 5 + / "MST" / "MDT" ; Mountain: - 7/ - 6 + / "PST" / "PDT" ; Pacific: - 8/ - 7 + / 1ALPHA ; Military: Z = UT; + ; A:-1; (J not used) + ; M:-12; N:+1; Y:+12 + / ( ("+" / "-") 4DIGIT ) ; Local differential + ; hours+min. (HHMM) + + 5.2. SEMANTICS + + If included, day-of-week must be the day implied by the date + specification. + + Time zone may be indicated in several ways. "UT" is Univer- + sal Time (formerly called "Greenwich Mean Time"); "GMT" is per- + mitted as a reference to Universal Time. The military standard + uses a single character for each zone. "Z" is Universal Time. + "A" indicates one hour earlier, and "M" indicates 12 hours ear- + lier; "N" is one hour later, and "Y" is 12 hours later. The + letter "J" is not used. The other remaining two forms are taken + from ANSI standard X3.51-1975. One allows explicit indication of + the amount of offset from UT; the other uses common 3-character + strings for indicating time zones in North America. + + + August 13, 1982 - 26 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 6. ADDRESS SPECIFICATION + + 6.1. SYNTAX + + address = mailbox ; one addressee + / group ; named list + + group = phrase ":" [#mailbox] ";" + + mailbox = addr-spec ; simple address + / phrase route-addr ; name & addr-spec + + route-addr = "<" [route] addr-spec ">" + + route = 1#("@" domain) ":" ; path-relative + + addr-spec = local-part "@" domain ; global address + + local-part = word *("." word) ; uninterpreted + ; case-preserved + + domain = sub-domain *("." sub-domain) + + sub-domain = domain-ref / domain-literal + + domain-ref = atom ; symbolic reference + + 6.2. SEMANTICS + + A mailbox receives mail. It is a conceptual entity which + does not necessarily pertain to file storage. For example, some + sites may choose to print mail on their line printer and deliver + the output to the addressee's desk. + + A mailbox specification comprises a person, system or pro- + cess name reference, a domain-dependent string, and a name-domain + reference. The name reference is optional and is usually used to + indicate the human name of a recipient. The name-domain refer- + ence specifies a sequence of sub-domains. The domain-dependent + string is uninterpreted, except by the final sub-domain; the rest + of the mail service merely transmits it as a literal string. + + 6.2.1. DOMAINS + + A name-domain is a set of registered (mail) names. A name- + domain specification resolves to a subordinate name-domain + specification or to a terminal domain-dependent string. + Hence, domain specification is extensible, permitting any + number of registration levels. + + + August 13, 1982 - 27 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + Name-domains model a global, logical, hierarchical addressing + scheme. The model is logical, in that an address specifica- + tion is related to name registration and is not necessarily + tied to transmission path. The model's hierarchy is a + directed graph, called an in-tree, such that there is a single + path from the root of the tree to any node in the hierarchy. + If more than one path actually exists, they are considered to + be different addresses. + + The root node is common to all addresses; consequently, it is + not referenced. Its children constitute "top-level" name- + domains. Usually, a service has access to its own full domain + specification and to the names of all top-level name-domains. + + The "top" of the domain addressing hierarchy -- a child of the + root -- is indicated by the right-most field, in a domain + specification. Its child is specified to the left, its child + to the left, and so on. + + Some groups provide formal registration services; these con- + stitute name-domains that are independent logically of + specific machines. In addition, networks and machines impli- + citly compose name-domains, since their membership usually is + registered in name tables. + + In the case of formal registration, an organization implements + a (distributed) data base which provides an address-to-route + mapping service for addresses of the form: + + person@registry.organization + + Note that "organization" is a logical entity, separate from + any particular communication network. + + A mechanism for accessing "organization" is universally avail- + able. That mechanism, in turn, seeks an instantiation of the + registry; its location is not indicated in the address specif- + ication. It is assumed that the system which operates under + the name "organization" knows how to find a subordinate regis- + try. The registry will then use the "person" string to deter- + mine where to send the mail specification. + + The latter, network-oriented case permits simple, direct, + attachment-related address specification, such as: + + user@host.network + + Once the network is accessed, it is expected that a message + will go directly to the host and that the host will resolve + + + August 13, 1982 - 28 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + the user name, placing the message in the user's mailbox. + + 6.2.2. ABBREVIATED DOMAIN SPECIFICATION + + Since any number of levels is possible within the domain + hierarchy, specification of a fully qualified address can + become inconvenient. This standard permits abbreviated domain + specification, in a special case: + + For the address of the sender, call the left-most + sub-domain Level N. In a header address, if all of + the sub-domains above (i.e., to the right of) Level N + are the same as those of the sender, then they do not + have to appear in the specification. Otherwise, the + address must be fully qualified. + + This feature is subject to approval by local sub- + domains. Individual sub-domains may require their + member systems, which originate mail, to provide full + domain specification only. When permitted, abbrevia- + tions may be present only while the message stays + within the sub-domain of the sender. + + Use of this mechanism requires the sender's sub-domain + to reserve the names of all top-level domains, so that + full specifications can be distinguished from abbrevi- + ated specifications. + + For example, if a sender's address is: + + sender@registry-A.registry-1.organization-X + + and one recipient's address is: + + recipient@registry-B.registry-1.organization-X + + and another's is: + + recipient@registry-C.registry-2.organization-X + + then ".registry-1.organization-X" need not be specified in the + the message, but "registry-C.registry-2" DOES have to be + specified. That is, the first two addresses may be abbrevi- + ated, but the third address must be fully specified. + + When a message crosses a domain boundary, all addresses must + be specified in the full format, ending with the top-level + name-domain in the right-most field. It is the responsibility + of mail forwarding services to ensure that addresses conform + + + August 13, 1982 - 29 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + with this requirement. In the case of abbreviated addresses, + the relaying service must make the necessary expansions. It + should be noted that it often is difficult for such a service + to locate all occurrences of address abbreviations. For exam- + ple, it will not be possible to find such abbreviations within + the body of the message. The "Return-Path" field can aid + recipients in recovering from these errors. + + Note: When passing any portion of an addr-spec onto a process + which does not interpret data according to this stan- + dard (e.g., mail protocol servers). There must be NO + LWSP-chars preceding or following the at-sign or any + delimiting period ("."), such as shown in the above + examples, and only ONE SPACE between contiguous + s. + + 6.2.3. DOMAIN TERMS + + A domain-ref must be THE official name of a registry, network, + or host. It is a symbolic reference, within a name sub- + domain. At times, it is necessary to bypass standard mechan- + isms for resolving such references, using more primitive + information, such as a network host address rather than its + associated host name. + + To permit such references, this standard provides the domain- + literal construct. Its contents must conform with the needs + of the sub-domain in which it is interpreted. + + Domain-literals which refer to domains within the ARPA Inter- + net specify 32-bit Internet addresses, in four 8-bit fields + noted in decimal, as described in Request for Comments #820, + "Assigned Numbers." For example: + + [10.0.3.19] + + Note: THE USE OF DOMAIN-LITERALS IS STRONGLY DISCOURAGED. It + is permitted only as a means of bypassing temporary + system limitations, such as name tables which are not + complete. + + The names of "top-level" domains, and the names of domains + under in the ARPA Internet, are registered with the Network + Information Center, SRI International, Menlo Park, California. + + 6.2.4. DOMAIN-DEPENDENT LOCAL STRING + + The local-part of an addr-spec in a mailbox specification + (i.e., the host's name for the mailbox) is understood to be + + + August 13, 1982 - 30 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + whatever the receiving mail protocol server allows. For exam- + ple, some systems do not understand mailbox references of the + form "P. D. Q. Bach", but others do. + + This specification treats periods (".") as lexical separators. + Hence, their presence in local-parts which are not quoted- + strings, is detected. However, such occurrences carry NO + semantics. That is, if a local-part has periods within it, an + address parser will divide the local-part into several tokens, + but the sequence of tokens will be treated as one uninter- + preted unit. The sequence will be re-assembled, when the + address is passed outside of the system such as to a mail pro- + tocol service. + + For example, the address: + + First.Last@Registry.Org + + is legal and does not require the local-part to be surrounded + with quotation-marks. (However, "First Last" DOES require + quoting.) The local-part of the address, when passed outside + of the mail system, within the Registry.Org domain, is + "First.Last", again without quotation marks. + + 6.2.5. BALANCING LOCAL-PART AND DOMAIN + + In some cases, the boundary between local-part and domain can + be flexible. The local-part may be a simple string, which is + used for the final determination of the recipient's mailbox. + All other levels of reference are, therefore, part of the + domain. + + For some systems, in the case of abbreviated reference to the + local and subordinate sub-domains, it may be possible to + specify only one reference within the domain part and place + the other, subordinate name-domain references within the + local-part. This would appear as: + + mailbox.sub1.sub2@this-domain + + Such a specification would be acceptable to address parsers + which conform to RFC #733, but do not support this newer + Internet standard. While contrary to the intent of this stan- + dard, the form is legal. + + Also, some sub-domains have a specification syntax which does + not conform to this standard. For example: + + sub-net.mailbox@sub-domain.domain + + + August 13, 1982 - 31 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + uses a different parsing sequence for local-part than for + domain. + + Note: As a rule, the domain specification should contain + fields which are encoded according to the syntax of + this standard and which contain generally-standardized + information. The local-part specification should con- + tain only that portion of the address which deviates + from the form or intention of the domain field. + + 6.2.6. MULTIPLE MAILBOXES + + An individual may have several mailboxes and wish to receive + mail at whatever mailbox is convenient for the sender to + access. This standard does not provide a means of specifying + "any member of" a list of mailboxes. + + A set of individuals may wish to receive mail as a single unit + (i.e., a distribution list). The construct permits + specification of such a list. Recipient mailboxes are speci- + fied within the bracketed part (":" - ";"). A copy of the + transmitted message is to be sent to each mailbox listed. + This standard does not permit recursive specification of + groups within groups. + + While a list must be named, it is not required that the con- + tents of the list be included. In this case, the
+ serves only as an indication of group distribution and would + appear in the form: + + name:; + + Some mail services may provide a group-list distribution + facility, accepting a single mailbox reference, expanding it + to the full distribution list, and relaying the mail to the + list's members. This standard provides no additional syntax + for indicating such a service. Using the address + alternative, while listing one mailbox in it, can mean either + that the mailbox reference will be expanded to a list or that + there is a group with one member. + + 6.2.7. EXPLICIT PATH SPECIFICATION + + At times, a message originator may wish to indicate the + transmission path that a message should follow. This is + called source routing. The normal addressing scheme, used in + an addr-spec, is carefully separated from such information; + the portion of a route-addr is provided for such occa- + sions. It specifies the sequence of hosts and/or transmission + + + August 13, 1982 - 32 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + services that are to be traversed. Both domain-refs and + domain-literals may be used. + + Note: The use of source routing is discouraged. Unless the + sender has special need of path restriction, the choice + of transmission route should be left to the mail tran- + sport service. + + 6.3. RESERVED ADDRESS + + It often is necessary to send mail to a site, without know- + ing any of its valid addresses. For example, there may be mail + system dysfunctions, or a user may wish to find out a person's + correct address, at that site. + + This standard specifies a single, reserved mailbox address + (local-part) which is to be valid at each site. Mail sent to + that address is to be routed to a person responsible for the + site's mail system or to a person with responsibility for general + site operation. The name of the reserved local-part address is: + + Postmaster + + so that "Postmaster@domain" is required to be valid. + + Note: This reserved local-part must be matched without sensi- + tivity to alphabetic case, so that "POSTMASTER", "postmas- + ter", and even "poStmASteR" is to be accepted. + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 33 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + 7. BIBLIOGRAPHY + + + ANSI. "USA Standard Code for Information Interchange," X3.4. + American National Standards Institute: New York (1968). Also + in: Feinler, E. and J. Postel, eds., "ARPANET Protocol Hand- + book", NIC 7104. + + ANSI. "Representations of Universal Time, Local Time Differen- + tials, and United States Time Zone References for Information + Interchange," X3.51-1975. American National Standards Insti- + tute: New York (1975). + + Bemer, R.W., "Time and the Computer." In: Interface Age (Feb. + 1979). + + Bennett, C.J. "JNT Mail Protocol". Joint Network Team, Ruther- + ford and Appleton Laboratory: Didcot, England. + + Bhushan, A.K., Pogran, K.T., Tomlinson, R.S., and White, J.E. + "Standardizing Network Mail Headers," ARPANET Request for + Comments No. 561, Network Information Center No. 18516; SRI + International: Menlo Park (September 1973). + + Birrell, A.D., Levin, R., Needham, R.M., and Schroeder, M.D. + "Grapevine: An Exercise in Distributed Computing," Communica- + tions of the ACM 25, 4 (April 1982), 260-274. + + Crocker, D.H., Vittal, J.J., Pogran, K.T., Henderson, D.A. + "Standard for the Format of ARPA Network Text Message," + ARPANET Request for Comments No. 733, Network Information + Center No. 41952. SRI International: Menlo Park (November + 1977). + + Feinler, E.J. and Postel, J.B. ARPANET Protocol Handbook, Net- + work Information Center No. 7104 (NTIS AD A003890). SRI + International: Menlo Park (April 1976). + + Harary, F. "Graph Theory". Addison-Wesley: Reading, Mass. + (1969). + + Levin, R. and Schroeder, M. "Transport of Electronic Messages + through a Network," TeleInformatics 79, pp. 29-33. North + Holland (1979). Also as Xerox Palo Alto Research Center + Technical Report CSL-79-4. + + Myer, T.H. and Henderson, D.A. "Message Transmission Protocol," + ARPANET Request for Comments, No. 680, Network Information + Center No. 32116. SRI International: Menlo Park (1975). + + + August 13, 1982 - 34 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + NBS. "Specification of Message Format for Computer Based Message + Systems, Recommended Federal Information Processing Standard." + National Bureau of Standards: Gaithersburg, Maryland + (October 1981). + + NIC. Internet Protocol Transition Workbook. Network Information + Center, SRI-International, Menlo Park, California (March + 1982). + + Oppen, D.C. and Dalal, Y.K. "The Clearinghouse: A Decentralized + Agent for Locating Named Objects in a Distributed Environ- + ment," OPD-T8103. Xerox Office Products Division: Palo Alto, + CA. (October 1981). + + Postel, J.B. "Assigned Numbers," ARPANET Request for Comments, + No. 820. SRI International: Menlo Park (August 1982). + + Postel, J.B. "Simple Mail Transfer Protocol," ARPANET Request + for Comments, No. 821. SRI International: Menlo Park (August + 1982). + + Shoch, J.F. "Internetwork naming, addressing and routing," in + Proc. 17th IEEE Computer Society International Conference, pp. + 72-79, Sept. 1978, IEEE Cat. No. 78 CH 1388-8C. + + Su, Z. and Postel, J. "The Domain Naming Convention for Internet + User Applications," ARPANET Request for Comments, No. 819. + SRI International: Menlo Park (August 1982). + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 35 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + APPENDIX + + + A. EXAMPLES + + A.1. ADDRESSES + + A.1.1. Alfred Neuman + + A.1.2. Neuman@BBN-TENEXA + + These two "Alfred Neuman" examples have identical seman- + tics, as far as the operation of the local host's mail sending + (distribution) program (also sometimes called its "mailer") + and the remote host's mail protocol server are concerned. In + the first example, the "Alfred Neuman" is ignored by the + mailer, as "Neuman@BBN-TENEXA" completely specifies the reci- + pient. The second example contains no superfluous informa- + tion, and, again, "Neuman@BBN-TENEXA" is the intended reci- + pient. + + Note: When the message crosses name-domain boundaries, then + these specifications must be changed, so as to indicate + the remainder of the hierarchy, starting with the top + level. + + A.1.3. "George, Ted" + + This form might be used to indicate that a single mailbox + is shared by several users. The quoted string is ignored by + the originating host's mailer, because "Shared@Group.Arpanet" + completely specifies the destination mailbox. + + A.1.4. Wilt . (the Stilt) Chamberlain@NBA.US + + The "(the Stilt)" is a comment, which is NOT included in + the destination mailbox address handed to the originating + system's mailer. The local-part of the address is the string + "Wilt.Chamberlain", with NO space between the first and second + words. + + A.1.5. Address Lists + + Gourmets: Pompous Person , + Childs@WGBH.Boston, Galloping Gourmet@ + ANT.Down-Under (Australian National Television), + Cheapie@Discount-Liquors;, + Cruisers: Port@Portugal, Jones@SEA;, + Another@Somewhere.SomeOrg + + + August 13, 1982 - 36 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + This group list example points out the use of comments and the + mixing of addresses and groups. + + A.2. ORIGINATOR ITEMS + + A.2.1. Author-sent + + George Jones logs into his host as "Jones". He sends + mail himself. + + From: Jones@Group.Org + + or + + From: George Jones + + A.2.2. Secretary-sent + + George Jones logs in as Jones on his host. His secre- + tary, who logs in as Secy sends mail for him. Replies to the + mail should go to George. + + From: George Jones + Sender: Secy@Other-Group + + A.2.3. Secretary-sent, for user of shared directory + + George Jones' secretary sends mail for George. Replies + should go to George. + + From: George Jones + Sender: Secy@Other-Group + + Note that there need not be a space between "Jones" and the + "<", but adding a space enhances readability (as is the case + in other examples. + + A.2.4. Committee activity, with one author + + George is a member of a committee. He wishes to have any + replies to his message go to all committee members. + + From: George Jones + Sender: Jones@Host + Reply-To: The Committee: Jones@Host.Net, + Smith@Other.Org, + Doe@Somewhere-Else; + + Note that if George had not included himself in the + + + August 13, 1982 - 37 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + enumeration of The Committee, he would not have gotten an + implicit reply; the presence of the "Reply-to" field SUPER- + SEDES the sending of a reply to the person named in the "From" + field. + + A.2.5. Secretary acting as full agent of author + + George Jones asks his secretary (Secy@Host) to send a + message for him in his capacity as Group. He wants his secre- + tary to handle all replies. + + From: George Jones + Sender: Secy@Host + Reply-To: Secy@Host + + A.2.6. Agent for user without online mailbox + + A friend of George's, Sarah, is visiting. George's + secretary sends some mail to a friend of Sarah in computer- + land. Replies should go to George, whose mailbox is Jones at + Registry. + + From: Sarah Friendly + Sender: Secy-Name + Reply-To: Jones@Registry. + + A.2.7. Agent for member of a committee + + George's secretary sends out a message which was authored + jointly by all the members of a committee. Note that the name + of the committee cannot be specified, since names are + not permitted in the From field. + + From: Jones@Host, + Smith@Other-Host, + Doe@Somewhere-Else + Sender: Secy@SHost + + + + + + + + + + + + + + + August 13, 1982 - 38 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + A.3. COMPLETE HEADERS + + A.3.1. Minimum required + + Date: 26 Aug 76 1429 EDT Date: 26 Aug 76 1429 EDT + From: Jones@Registry.Org or From: Jones@Registry.Org + Bcc: To: Smith@Registry.Org + + Note that the "Bcc" field may be empty, while the "To" field + is required to have at least one address. + + A.3.2. Using some of the additional fields + + Date: 26 Aug 76 1430 EDT + From: George Jones + Sender: Secy@SHOST + To: "Al Neuman"@Mad-Host, + Sam.Irving@Other-Host + Message-ID: + + A.3.3. About as complex as you're going to get + + Date : 27 Aug 76 0932 PDT + From : Ken Davis + Subject : Re: The Syntax in the RFC + Sender : KSecy@Other-Host + Reply-To : Sam.Irving@Reg.Organization + To : George Jones , + Al.Neuman@MAD.Publisher + cc : Important folk: + Tom Softwood , + "Sam Irving"@Other-Host;, + Standard Distribution: + /main/davis/people/standard@Other-Host, + "standard.dist.3"@Tops-20-Host>; + Comment : Sam is away on business. He asked me to handle + his mail for him. He'll be able to provide a + more accurate explanation when he returns + next week. + In-Reply-To: , George's message + X-Special-action: This is a sample of user-defined field- + names. There could also be a field-name + "Special-action", but its name might later be + preempted + Message-ID: <4231.629.XYzi-What@Other-Host> + + + + + + + August 13, 1982 - 39 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + B. SIMPLE FIELD PARSING + + Some mail-reading software systems may wish to perform only + minimal processing, ignoring the internal syntax of structured + field-bodies and treating them the same as unstructured-field- + bodies. Such software will need only to distinguish: + + o Header fields from the message body, + + o Beginnings of fields from lines which continue fields, + + o Field-names from field-contents. + + The abbreviated set of syntactic rules which follows will + suffice for this purpose. It describes a limited view of mes- + sages and is a subset of the syntactic rules provided in the main + part of this specification. One small exception is that the con- + tents of field-bodies consist only of text: + + B.1. SYNTAX + + + message = *field *(CRLF *text) + + field = field-name ":" [field-body] CRLF + + field-name = 1* + + field-body = *text [CRLF LWSP-char field-body] + + + B.2. SEMANTICS + + Headers occur before the message body and are terminated by + a null line (i.e., two contiguous CRLFs). + + A line which continues a header field begins with a SPACE or + HTAB character, while a line beginning a field starts with a + printable character which is not a colon. + + A field-name consists of one or more printable characters + (excluding colon, space, and control-characters). A field-name + MUST be contained on one line. Upper and lower case are not dis- + tinguished when comparing field-names. + + + + + + + + August 13, 1982 - 40 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + C. DIFFERENCES FROM RFC #733 + + The following summarizes the differences between this stan- + dard and the one specified in Arpanet Request for Comments #733, + "Standard for the Format of ARPA Network Text Messages". The + differences are listed in the order of their occurrence in the + current specification. + + C.1. FIELD DEFINITIONS + + C.1.1. FIELD NAMES + + These now must be a sequence of printable characters. They + may not contain any LWSP-chars. + + C.2. LEXICAL TOKENS + + C.2.1. SPECIALS + + The characters period ("."), left-square bracket ("["), and + right-square bracket ("]") have been added. For presentation + purposes, and when passing a specification to a system that + does not conform to this standard, periods are to be contigu- + ous with their surrounding lexical tokens. No linear-white- + space is permitted between them. The presence of one LWSP- + char between other tokens is still directed. + + C.2.2. ATOM + + Atoms may not contain SPACE. + + C.2.3. SPECIAL TEXT + + ctext and qtext have had backslash ("\") added to the list of + prohibited characters. + + C.2.4. DOMAINS + + The lexical tokens and have been + added. + + C.3. MESSAGE SPECIFICATION + + C.3.1. TRACE + + The "Return-path:" and "Received:" fields have been specified. + + + + + + August 13, 1982 - 41 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + C.3.2. FROM + + The "From" field must contain machine-usable addresses (addr- + spec). Multiple addresses may be specified, but named-lists + (groups) may not. + + C.3.3. RESENT + + The meta-construct of prefacing field names with the string + "Resent-" has been added, to indicate that a message has been + forwarded by an intermediate recipient. + + C.3.4. DESTINATION + + A message must contain at least one destination address field. + "To" and "CC" are required to contain at least one address. + + C.3.5. IN-REPLY-TO + + The field-body is no longer a comma-separated list, although a + sequence is still permitted. + + C.3.6. REFERENCE + + The field-body is no longer a comma-separated list, although a + sequence is still permitted. + + C.3.7. ENCRYPTED + + A field has been specified that permits senders to indicate + that the body of a message has been encrypted. + + C.3.8. EXTENSION-FIELD + + Extension fields are prohibited from beginning with the char- + acters "X-". + + C.4. DATE AND TIME SPECIFICATION + + C.4.1. SIMPLIFICATION + + Fewer optional forms are permitted and the list of three- + letter time zones has been shortened. + + C.5. ADDRESS SPECIFICATION + + + + + + + August 13, 1982 - 42 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + C.5.1. ADDRESS + + The use of quoted-string, and the ":"-atom-":" construct, have + been removed. An address now is either a single mailbox + reference or is a named list of addresses. The latter indi- + cates a group distribution. + + C.5.2. GROUPS + + Group lists are now required to to have a name. Group lists + may not be nested. + + C.5.3. MAILBOX + + A mailbox specification may indicate a person's name, as + before. Such a named list no longer may specify multiple + mailboxes and may not be nested. + + C.5.4. ROUTE ADDRESSING + + Addresses now are taken to be absolute, global specifications, + independent of transmission paths. The construct has + been provided, to permit explicit specification of transmis- + sion path. RFC #733's use of multiple at-signs ("@") was + intended as a general syntax for indicating routing and/or + hierarchical addressing. The current standard separates these + specifications and only one at-sign is permitted. + + C.5.5. AT-SIGN + + The string " at " no longer is used as an address delimiter. + Only at-sign ("@") serves the function. + + C.5.6. DOMAINS + + Hierarchical, logical name-domains have been added. + + C.6. RESERVED ADDRESS + + The local-part "Postmaster" has been reserved, so that users can + be guaranteed at least one valid address at a site. + + + + + + + + + + + August 13, 1982 - 43 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + D. ALPHABETICAL LISTING OF SYNTAX RULES + + address = mailbox ; one addressee + / group ; named list + addr-spec = local-part "@" domain ; global address + ALPHA = + ; (101-132, 65.- 90.) + ; (141-172, 97.-122.) + atom = 1* + authentic = "From" ":" mailbox ; Single author + / ( "Sender" ":" mailbox ; Actual submittor + "From" ":" 1#mailbox) ; Multiple authors + ; or not sender + CHAR = ; ( 0-177, 0.-127.) + comment = "(" *(ctext / quoted-pair / comment) ")" + CR = ; ( 15, 13.) + CRLF = CR LF + ctext = may be folded + ")", "\" & CR, & including + linear-white-space> + CTL = ; ( 177, 127.) + date = 1*2DIGIT month 2DIGIT ; day month year + ; e.g. 20 Jun 82 + dates = orig-date ; Original + [ resent-date ] ; Forwarded + date-time = [ day "," ] date time ; dd mm yy + ; hh:mm:ss zzz + day = "Mon" / "Tue" / "Wed" / "Thu" + / "Fri" / "Sat" / "Sun" + delimiters = specials / linear-white-space / comment + destination = "To" ":" 1#address ; Primary + / "Resent-To" ":" 1#address + / "cc" ":" 1#address ; Secondary + / "Resent-cc" ":" 1#address + / "bcc" ":" #address ; Blind carbon + / "Resent-bcc" ":" #address + DIGIT = ; ( 60- 71, 48.- 57.) + domain = sub-domain *("." sub-domain) + domain-literal = "[" *(dtext / quoted-pair) "]" + domain-ref = atom ; symbolic reference + dtext = may be folded + "]", "\" & CR, & including + linear-white-space> + extension-field = + + + + August 13, 1982 - 44 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + field = field-name ":" [ field-body ] CRLF + fields = dates ; Creation time, + source ; author id & one + 1*destination ; address required + *optional-field ; others optional + field-body = field-body-contents + [CRLF LWSP-char field-body] + field-body-contents = + + field-name = 1* + group = phrase ":" [#mailbox] ";" + hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] + ; 00:00:00 - 23:59:59 + HTAB = ; ( 11, 9.) + LF = ; ( 12, 10.) + linear-white-space = 1*([CRLF] LWSP-char) ; semantics = SPACE + ; CRLF => folding + local-part = word *("." word) ; uninterpreted + ; case-preserved + LWSP-char = SPACE / HTAB ; semantics = SPACE + mailbox = addr-spec ; simple address + / phrase route-addr ; name & addr-spec + message = fields *( CRLF *text ) ; Everything after + ; first null line + ; is message body + month = "Jan" / "Feb" / "Mar" / "Apr" + / "May" / "Jun" / "Jul" / "Aug" + / "Sep" / "Oct" / "Nov" / "Dec" + msg-id = "<" addr-spec ">" ; Unique message id + optional-field = + / "Message-ID" ":" msg-id + / "Resent-Message-ID" ":" msg-id + / "In-Reply-To" ":" *(phrase / msg-id) + / "References" ":" *(phrase / msg-id) + / "Keywords" ":" #phrase + / "Subject" ":" *text + / "Comments" ":" *text + / "Encrypted" ":" 1#2word + / extension-field ; To be defined + / user-defined-field ; May be pre-empted + orig-date = "Date" ":" date-time + originator = authentic ; authenticated addr + [ "Reply-To" ":" 1#address] ) + phrase = 1*word ; Sequence of words + + + + + August 13, 1982 - 45 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + qtext = , ; => may be folded + "\" & CR, and including + linear-white-space> + quoted-pair = "\" CHAR ; may quote any char + quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or + ; quoted chars. + received = "Received" ":" ; one per relay + ["from" domain] ; sending host + ["by" domain] ; receiving host + ["via" atom] ; physical path + *("with" atom) ; link/mail protocol + ["id" msg-id] ; receiver msg id + ["for" addr-spec] ; initial form + ";" date-time ; time received + + resent = resent-authentic + [ "Resent-Reply-To" ":" 1#address] ) + resent-authentic = + = "Resent-From" ":" mailbox + / ( "Resent-Sender" ":" mailbox + "Resent-From" ":" 1#mailbox ) + resent-date = "Resent-Date" ":" date-time + return = "Return-path" ":" route-addr ; return address + route = 1#("@" domain) ":" ; path-relative + route-addr = "<" [route] addr-spec ">" + source = [ trace ] ; net traversals + originator ; original mail + [ resent ] ; forwarded + SPACE = ; ( 40, 32.) + specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted- + / "," / ";" / ":" / "\" / <"> ; string, to use + / "." / "[" / "]" ; within a word. + sub-domain = domain-ref / domain-literal + text = atoms, specials, + CR & bare LF, but NOT ; comments and + including CRLF> ; quoted-strings are + ; NOT recognized. + time = hour zone ; ANSI and Military + trace = return ; path to sender + 1*received ; receipt tags + user-defined-field = + + word = atom / quoted-string + + + + + August 13, 1982 - 46 - RFC #822 + + + + Standard for ARPA Internet Text Messages + + + zone = "UT" / "GMT" ; Universal Time + ; North American : UT + / "EST" / "EDT" ; Eastern: - 5/ - 4 + / "CST" / "CDT" ; Central: - 6/ - 5 + / "MST" / "MDT" ; Mountain: - 7/ - 6 + / "PST" / "PDT" ; Pacific: - 8/ - 7 + / 1ALPHA ; Military: Z = UT; + <"> = ; ( 42, 34.) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + August 13, 1982 - 47 - RFC #822 + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1341.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1341.txt new file mode 100644 index 00000000..1be6f7d6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1341.txt @@ -0,0 +1,5265 @@ + + + + + + + Network Working Group N. Borenstein, Bellcore + Request for Comments: 1341 N. Freed, Innosoft + June 1992 + + + + MIME (Multipurpose Internet Mail Extensions): + + + Mechanisms for Specifying and Describing + the Format of Internet Message Bodies + + + Status of this Memo + + This RFC specifies an IAB standards track protocol for the + Internet community, and requests discussion and suggestions + for improvements. Please refer to the current edition of + the "IAB Official Protocol Standards" for the + standardization state and status of this protocol. + Distribution of this memo is unlimited. + + Abstract + + RFC 822 defines a message representation protocol which + specifies considerable detail about message headers, but + which leaves the message content, or message body, as flat + ASCII text. This document redefines the format of message + bodies to allow multi-part textual and non-textual message + bodies to be represented and exchanged without loss of + information. This is based on earlier work documented in + RFC 934 and RFC 1049, but extends and revises that work. + Because RFC 822 said so little about message bodies, this + document is largely orthogonal to (rather than a revision + of) RFC 822. + + In particular, this document is designed to provide + facilities to include multiple objects in a single message, + to represent body text in character sets other than US- + ASCII, to represent formatted multi-font text messages, to + represent non-textual material such as images and audio + fragments, and generally to facilitate later extensions + defining new types of Internet mail for use by cooperating + mail agents. + + This document does NOT extend Internet mail header fields to + permit anything other than US-ASCII text data. It is + recognized that such extensions are necessary, and they are + the subject of a companion document [RFC -1342]. + + A table of contents appears at the end of this document. + + + + + + + Borenstein & Freed [Page i] + + + + + + + + 1 Introduction + + Since its publication in 1982, RFC 822 [RFC-822] has defined + the standard format of textual mail messages on the + Internet. Its success has been such that the RFC 822 format + has been adopted, wholly or partially, well beyond the + confines of the Internet and the Internet SMTP transport + defined by RFC 821 [RFC-821]. As the format has seen wider + use, a number of limitations have proven increasingly + restrictive for the user community. + + RFC 822 was intended to specify a format for text messages. + As such, non-text messages, such as multimedia messages that + might include audio or images, are simply not mentioned. + Even in the case of text, however, RFC 822 is inadequate for + the needs of mail users whose languages require the use of + character sets richer than US ASCII [US-ASCII]. Since RFC + 822 does not specify mechanisms for mail containing audio, + video, Asian language text, or even text in most European + languages, additional specifications are needed + + One of the notable limitations of RFC 821/822 based mail + systems is the fact that they limit the contents of + electronic mail messages to relatively short lines of + seven-bit ASCII. This forces users to convert any non- + textual data that they may wish to send into seven-bit bytes + representable as printable ASCII characters before invoking + a local mail UA (User Agent, a program with which human + users send and receive mail). Examples of such encodings + currently used in the Internet include pure hexadecimal, + uuencode, the 3-in-4 base 64 scheme specified in RFC 1113, + the Andrew Toolkit Representation [ATK], and many others. + + The limitations of RFC 822 mail become even more apparent as + gateways are designed to allow for the exchange of mail + messages between RFC 822 hosts and X.400 hosts. X.400 [X400] + specifies mechanisms for the inclusion of non-textual body + parts within electronic mail messages. The current + standards for the mapping of X.400 messages to RFC 822 + messages specify that either X.400 non-textual body parts + should be converted to (not encoded in) an ASCII format, or + that they should be discarded, notifying the RFC 822 user + that discarding has occurred. This is clearly undesirable, + as information that a user may wish to receive is lost. + Even though a user's UA may not have the capability of + dealing with the non-textual body part, the user might have + some mechanism external to the UA that can extract useful + information from the body part. Moreover, it does not allow + for the fact that the message may eventually be gatewayed + back into an X.400 message handling system (i.e., the X.400 + message is "tunneled" through Internet mail), where the + non-textual information would definitely become useful + again. + + + + + Borenstein & Freed [Page 1] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + This document describes several mechanisms that combine to + solve most of these problems without introducing any serious + incompatibilities with the existing world of RFC 822 mail. + In particular, it describes: + + 1. A MIME-Version header field, which uses a version number + to declare a message to be conformant with this + specification and allows mail processing agents to + distinguish between such messages and those generated + by older or non-conformant software, which is presumed + to lack such a field. + + 2. A Content-Type header field, generalized from RFC 1049 + [RFC-1049], which can be used to specify the type and + subtype of data in the body of a message and to fully + specify the native representation (encoding) of such + data. + + 2.a. A "text" Content-Type value, which can be used to + represent textual information in a number of + character sets and formatted text description + languages in a standardized manner. + + 2.b. A "multipart" Content-Type value, which can be + used to combine several body parts, possibly of + differing types of data, into a single message. + + 2.c. An "application" Content-Type value, which can be + used to transmit application data or binary data, + and hence, among other uses, to implement an + electronic mail file transfer service. + + 2.d. A "message" Content-Type value, for encapsulating + a mail message. + + 2.e An "image" Content-Type value, for transmitting + still image (picture) data. + + 2.f. An "audio" Content-Type value, for transmitting + audio or voice data. + + 2.g. A "video" Content-Type value, for transmitting + video or moving image data, possibly with audio as + part of the composite video data format. + + 3. A Content-Transfer-Encoding header field, which can be + used to specify an auxiliary encoding that was applied + to the data in order to allow it to pass through mail + transport mechanisms which may have data or character + set limitations. + + 4. Two optional header fields that can be used to further + describe the data in a message body, the Content-ID and + Content-Description header fields. + + + + Borenstein & Freed [Page 2] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + MIME has been carefully designed as an extensible mechanism, + and it is expected that the set of content-type/subtype + pairs and their associated parameters will grow + significantly with time. Several other MIME fields, notably + including character set names, are likely to have new values + defined over time. In order to ensure that the set of such + values is developed in an orderly, well-specified, and + public manner, MIME defines a registration process which + uses the Internet Assigned Numbers Authority (IANA) as a + central registry for such values. Appendix F provides + details about how IANA registration is accomplished. + + Finally, to specify and promote interoperability, Appendix A + of this document provides a basic applicability statement + for a subset of the above mechanisms that defines a minimal + level of "conformance" with this document. + + HISTORICAL NOTE: Several of the mechanisms described in + this document may seem somewhat strange or even baroque at + first reading. It is important to note that compatibility + with existing standards AND robustness across existing + practice were two of the highest priorities of the working + group that developed this document. In particular, + compatibility was always favored over elegance. + + 2 Notations, Conventions, and Generic BNF Grammar + + This document is being published in two versions, one as + plain ASCII text and one as PostScript. The latter is + recommended, though the textual contents are identical. An + Andrew-format copy of this document is also available from + the first author (Borenstein). + + Although the mechanisms specified in this document are all + described in prose, most are also described formally in the + modified BNF notation of RFC 822. Implementors will need to + be familiar with this notation in order to understand this + specification, and are referred to RFC 822 for a complete + explanation of the modified BNF notation. + + Some of the modified BNF in this document makes reference to + syntactic entities that are defined in RFC 822 and not in + this document. A complete formal grammar, then, is obtained + by combining the collected grammar appendix of this document + with that of RFC 822. + + The term CRLF, in this document, refers to the sequence of + the two ASCII characters CR (13) and LF (10) which, taken + together, in this order, denote a line break in RFC 822 + mail. + + The term "character set", wherever it is used in this + document, refers to a coded character set, in the sense of + ISO character set standardization work, and must not be + + + + Borenstein & Freed [Page 3] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + misinterpreted as meaning "a set of characters." + + The term "message", when not further qualified, means either + the (complete or "top-level") message being transferred on a + network, or a message encapsulated in a body of type + "message". + + The term "body part", in this document, means one of the + parts of the body of a multipart entity. A body part has a + header and a body, so it makes sense to speak about the body + of a body part. + + The term "entity", in this document, means either a message + or a body part. All kinds of entities share the property + that they have a header and a body. + + The term "body", when not further qualified, means the body + of an entity, that is the body of either a message or of a + body part. + + Note : the previous four definitions are clearly circular. + This is unavoidable, since the overal structure of a MIME + message is indeed recursive. + + In this document, all numeric and octet values are given in + decimal notation. + + It must be noted that Content-Type values, subtypes, and + parameter names as defined in this document are case- + insensitive. However, parameter values are case-sensitive + unless otherwise specified for the specific parameter. + + FORMATTING NOTE: This document has been carefully formatted + for ease of reading. The PostScript version of this + document, in particular, places notes like this one, which + may be skipped by the reader, in a smaller, italicized, + font, and indents it as well. In the text version, only the + indentation is preserved, so if you are reading the text + version of this you might consider using the PostScript + version instead. However, all such notes will be indented + and preceded by "NOTE:" or some similar introduction, even + in the text version. + + The primary purpose of these non-essential notes is to + convey information about the rationale of this document, or + to place this document in the proper historical or + evolutionary context. Such information may be skipped by + those who are focused entirely on building a compliant + implementation, but may be of use to those who wish to + understand why this document is written as it is. + + For ease of recognition, all BNF definitions have been + placed in a fixed-width font in the PostScript version of + this document. + + + + Borenstein & Freed [Page 4] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 3 The MIME-Version Header Field + + Since RFC 822 was published in 1982, there has really been + only one format standard for Internet messages, and there + has been little perceived need to declare the format + standard in use. This document is an independent document + that complements RFC 822. Although the extensions in this + document have been defined in such a way as to be compatible + with RFC 822, there are still circumstances in which it + might be desirable for a mail-processing agent to know + whether a message was composed with the new standard in + mind. + + Therefore, this document defines a new header field, "MIME- + Version", which is to be used to declare the version of the + Internet message body format standard in use. + + Messages composed in accordance with this document MUST + include such a header field, with the following verbatim + text: + + MIME-Version: 1.0 + + The presence of this header field is an assertion that the + message has been composed in compliance with this document. + + Since it is possible that a future document might extend the + message format standard again, a formal BNF is given for the + content of the MIME-Version field: + + MIME-Version := text + + Thus, future format specifiers, which might replace or + extend "1.0", are (minimally) constrained by the definition + of "text", which appears in RFC 822. + + Note that the MIME-Version header field is required at the + top level of a message. It is not required for each body + part of a multipart entity. It is required for the embedded + headers of a body of type "message" if and only if the + embedded message is itself claimed to be MIME-compliant. + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 5] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 4 The Content-Type Header Field + + The purpose of the Content-Type field is to describe the + data contained in the body fully enough that the receiving + user agent can pick an appropriate agent or mechanism to + present the data to the user, or otherwise deal with the + data in an appropriate manner. + + HISTORICAL NOTE: The Content-Type header field was first + defined in RFC 1049. RFC 1049 Content-types used a simpler + and less powerful syntax, but one that is largely compatible + with the mechanism given here. + + The Content-Type header field is used to specify the nature + of the data in the body of an entity, by giving type and + subtype identifiers, and by providing auxiliary information + that may be required for certain types. After the type and + subtype names, the remainder of the header field is simply a + set of parameters, specified in an attribute/value notation. + The set of meaningful parameters differs for the different + types. The ordering of parameters is not significant. + Among the defined parameters is a "charset" parameter by + which the character set used in the body may be declared. + Comments are allowed in accordance with RFC 822 rules for + structured header fields. + + In general, the top-level Content-Type is used to declare + the general type of data, while the subtype specifies a + specific format for that type of data. Thus, a Content-Type + of "image/xyz" is enough to tell a user agent that the data + is an image, even if the user agent has no knowledge of the + specific image format "xyz". Such information can be used, + for example, to decide whether or not to show a user the raw + data from an unrecognized subtype -- such an action might be + reasonable for unrecognized subtypes of text, but not for + unrecognized subtypes of image or audio. For this reason, + registered subtypes of audio, image, text, and video, should + not contain embedded information that is really of a + different type. Such compound types should be represented + using the "multipart" or "application" types. + + Parameters are modifiers of the content-subtype, and do not + fundamentally affect the requirements of the host system. + Although most parameters make sense only with certain + content-types, others are "global" in the sense that they + might apply to any subtype. For example, the "boundary" + parameter makes sense only for the "multipart" content-type, + but the "charset" parameter might make sense with several + content-types. + + An initial set of seven Content-Types is defined by this + document. This set of top-level names is intended to be + substantially complete. It is expected that additions to + the larger set of supported types can generally be + + + + Borenstein & Freed [Page 6] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + accomplished by the creation of new subtypes of these + initial types. In the future, more top-level types may be + defined only by an extension to this standard. If another + primary type is to be used for any reason, it must be given + a name starting with "X-" to indicate its non-standard + status and to avoid a potential conflict with a future + official name. + + In the Extended BNF notation of RFC 822, a Content-Type + header field value is defined as follows: + + Content-Type := type "/" subtype *[";" parameter] + + type := "application" / "audio" + / "image" / "message" + / "multipart" / "text" + / "video" / x-token + + x-token := + + subtype := token + + parameter := attribute "=" value + + attribute := token + + value := token / quoted-string + + token := 1* + + tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in + / "," / ";" / ":" / "\" / <"> ; quoted-string, + / "/" / "[" / "]" / "?" / "." ; to use within + / "=" ; parameter values + + Note that the definition of "tspecials" is the same as the + RFC 822 definition of "specials" with the addition of the + three characters "/", "?", and "=". + + Note also that a subtype specification is MANDATORY. There + are no default subtypes. + + The type, subtype, and parameter names are not case + sensitive. For example, TEXT, Text, and TeXt are all + equivalent. Parameter values are normally case sensitive, + but certain parameters are interpreted to be case- + insensitive, depending on the intended use. (For example, + multipart boundaries are case-sensitive, but the "access- + type" for message/External-body is not case-sensitive.) + + Beyond this syntax, the only constraint on the definition of + subtype names is the desire that their uses must not + conflict. That is, it would be undesirable to have two + + + + Borenstein & Freed [Page 7] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + different communities using "Content-Type: + application/foobar" to mean two different things. The + process of defining new content-subtypes, then, is not + intended to be a mechanism for imposing restrictions, but + simply a mechanism for publicizing the usages. There are, + therefore, two acceptable mechanisms for defining new + Content-Type subtypes: + + 1. Private values (starting with "X-") may be + defined bilaterally between two cooperating + agents without outside registration or + standardization. + + 2. New standard values must be documented, + registered with, and approved by IANA, as + described in Appendix F. Where intended for + public use, the formats they refer to must + also be defined by a published specification, + and possibly offered for standardization. + + The seven standard initial predefined Content-Types are + detailed in the bulk of this document. They are: + + text -- textual information. The primary subtype, + "plain", indicates plain (unformatted) text. No + special software is required to get the full + meaning of the text, aside from support for the + indicated character set. Subtypes are to be used + for enriched text in forms where application + software may enhance the appearance of the text, + but such software must not be required in order to + get the general idea of the content. Possible + subtypes thus include any readable word processor + format. A very simple and portable subtype, + richtext, is defined in this document. + multipart -- data consisting of multiple parts of + independent data types. Four initial subtypes + are defined, including the primary "mixed" + subtype, "alternative" for representing the same + data in multiple formats, "parallel" for parts + intended to be viewed simultaneously, and "digest" + for multipart entities in which each part is of + type "message". + message -- an encapsulated message. A body of + Content-Type "message" is itself a fully formatted + RFC 822 conformant message which may contain its + own different Content-Type header field. The + primary subtype is "rfc822". The "partial" + subtype is defined for partial messages, to permit + the fragmented transmission of bodies that are + thought to be too large to be passed through mail + transport facilities. Another subtype, + "External-body", is defined for specifying large + bodies by reference to an external data source. + + + + Borenstein & Freed [Page 8] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + image -- image data. Image requires a display device + (such as a graphical display, a printer, or a FAX + machine) to view the information. Initial + subtypes are defined for two widely-used image + formats, jpeg and gif. + audio -- audio data, with initial subtype "basic". + Audio requires an audio output device (such as a + speaker or a telephone) to "display" the contents. + video -- video data. Video requires the capability to + display moving images, typically including + specialized hardware and software. The initial + subtype is "mpeg". + application -- some other kind of data, typically + either uninterpreted binary data or information to + be processed by a mail-based application. The + primary subtype, "octet-stream", is to be used in + the case of uninterpreted binary data, in which + case the simplest recommended action is to offer + to write the information into a file for the user. + Two additional subtypes, "ODA" and "PostScript", + are defined for transporting ODA and PostScript + documents in bodies. Other expected uses for + "application" include spreadsheets, data for + mail-based scheduling systems, and languages for + "active" (computational) email. (Note that active + email entails several securityconsiderations, + which are discussed later in this memo, + particularly in the context of + application/PostScript.) + + Default RFC 822 messages are typed by this protocol as plain + text in the US-ASCII character set, which can be explicitly + specified as "Content-type: text/plain; charset=us-ascii". + If no Content-Type is specified, either by error or by an + older user agent, this default is assumed. In the presence + of a MIME-Version header field, a receiving User Agent can + also assume that plain US-ASCII text was the sender's + intent. In the absence of a MIME-Version specification, + plain US-ASCII text must still be assumed, but the sender's + intent might have been otherwise. + + RATIONALE: In the absence of any Content-Type header field + or MIME-Version header field, it is impossible to be certain + that a message is actually text in the US-ASCII character + set, since it might well be a message that, using the + conventions that predate this document, includes text in + another character set or non-textual data in a manner that + cannot be automatically recognized (e.g., a uuencoded + compressed UNIX tar file). Although there is no fully + acceptable alternative to treating such untyped messages as + "text/plain; charset=us-ascii", implementors should remain + aware that if a message lacks both the MIME-Version and the + Content-Type header fields, it may in practice contain + almost anything. + + + + Borenstein & Freed [Page 9] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + It should be noted that the list of Content-Type values + given here may be augmented in time, via the mechanisms + described above, and that the set of subtypes is expected to + grow substantially. + + When a mail reader encounters mail with an unknown Content- + type value, it should generally treat it as equivalent to + "application/octet-stream", as described later in this + document. + + 5 The Content-Transfer-Encoding Header Field + + Many Content-Types which could usefully be transported via + email are represented, in their "natural" format, as 8-bit + character or binary data. Such data cannot be transmitted + over some transport protocols. For example, RFC 821 + restricts mail messages to 7-bit US-ASCII data with 1000 + character lines. + + It is necessary, therefore, to define a standard mechanism + for re-encoding such data into a 7-bit short-line format. + This document specifies that such encodings will be + indicated by a new "Content-Transfer-Encoding" header field. + The Content-Transfer-Encoding field is used to indicate the + type of transformation that has been used in order to + represent the body in an acceptable manner for transport. + + Unlike Content-Types, a proliferation of Content-Transfer- + Encoding values is undesirable and unnecessary. However, + establishing only a single Content-Transfer-Encoding + mechanism does not seem possible. There is a tradeoff + between the desire for a compact and efficient encoding of + largely-binary data and the desire for a readable encoding + of data that is mostly, but not entirely, 7-bit data. For + this reason, at least two encoding mechanisms are necessary: + a "readable" encoding and a "dense" encoding. + + The Content-Transfer-Encoding field is designed to specify + an invertible mapping between the "native" representation of + a type of data and a representation that can be readily + exchanged using 7 bit mail transport protocols, such as + those defined by RFC 821 (SMTP). This field has not been + defined by any previous standard. The field's value is a + single token specifying the type of encoding, as enumerated + below. Formally: + + Content-Transfer-Encoding := "BASE64" / "QUOTED-PRINTABLE" / + "8BIT" / "7BIT" / + "BINARY" / x-token + + These values are not case sensitive. That is, Base64 and + BASE64 and bAsE64 are all equivalent. An encoding type of + 7BIT requires that the body is already in a seven-bit mail- + ready representation. This is the default value -- that is, + + + + Borenstein & Freed [Page 10] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + "Content-Transfer-Encoding: 7BIT" is assumed if the + Content-Transfer-Encoding header field is not present. + + The values "8bit", "7bit", and "binary" all imply that NO + encoding has been performed. However, they are potentially + useful as indications of the kind of data contained in the + object, and therefore of the kind of encoding that might + need to be performed for transmission in a given transport + system. "7bit" means that the data is all represented as + short lines of US-ASCII data. "8bit" means that the lines + are short, but there may be non-ASCII characters (octets + with the high-order bit set). "Binary" means that not only + may non-ASCII characters be present, but also that the lines + are not necessarily short enough for SMTP transport. + + The difference between "8bit" (or any other conceivable + bit-width token) and the "binary" token is that "binary" + does not require adherence to any limits on line length or + to the SMTP CRLF semantics, while the bit-width tokens do + require such adherence. If the body contains data in any + bit-width other than 7-bit, the appropriate bit-width + Content-Transfer-Encoding token must be used (e.g., "8bit" + for unencoded 8 bit wide data). If the body contains binary + data, the "binary" Content-Transfer-Encoding token must be + used. + + NOTE: The distinction between the Content-Transfer-Encoding + values of "binary," "8bit," etc. may seem unimportant, in + that all of them really mean "none" -- that is, there has + been no encoding of the data for transport. However, clear + labeling will be of enormous value to gateways between + future mail transport systems with differing capabilities in + transporting data that do not meet the restrictions of RFC + 821 transport. + + As of the publication of this document, there are no + standardized Internet transports for which it is legitimate + to include unencoded 8-bit or binary data in mail bodies. + Thus there are no circumstances in which the "8bit" or + "binary" Content-Transfer-Encoding is actually legal on the + Internet. However, in the event that 8-bit or binary mail + transport becomes a reality in Internet mail, or when this + document is used in conjunction with any other 8-bit or + binary-capable transport mechanism, 8-bit or binary bodies + should be labeled as such using this mechanism. + + NOTE: The five values defined for the Content-Transfer- + Encoding field imply nothing about the Content-Type other + than the algorithm by which it was encoded or the transport + system requirements if unencoded. + + Implementors may, if necessary, define new Content- + Transfer-Encoding values, but must use an x-token, which is + a name prefixed by "X-" to indicate its non-standard status, + + + + Borenstein & Freed [Page 11] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + e.g., "Content-Transfer-Encoding: x-my-new-encoding". + However, unlike Content-Types and subtypes, the creation of + new Content-Transfer-Encoding values is explicitly and + strongly discouraged, as it seems likely to hinder + interoperability with little potential benefit. Their use + is allowed only as the result of an agreement between + cooperating user agents. + + If a Content-Transfer-Encoding header field appears as part + of a message header, it applies to the entire body of that + message. If a Content-Transfer-Encoding header field + appears as part of a body part's headers, it applies only to + the body of that body part. If an entity is of type + "multipart" or "message", the Content-Transfer-Encoding is + not permitted to have any value other than a bit width + (e.g., "7bit", "8bit", etc.) or "binary". + + It should be noted that email is character-oriented, so that + the mechanisms described here are mechanisms for encoding + arbitrary byte streams, not bit streams. If a bit stream is + to be encoded via one of these mechanisms, it must first be + converted to an 8-bit byte stream using the network standard + bit order ("big-endian"), in which the earlier bits in a + stream become the higher-order bits in a byte. A bit stream + not ending at an 8-bit boundary must be padded with zeroes. + This document provides a mechanism for noting the addition + of such padding in the case of the application Content-Type, + which has a "padding" parameter. + + The encoding mechanisms defined here explicitly encode all + data in ASCII. Thus, for example, suppose an entity has + header fields such as: + + Content-Type: text/plain; charset=ISO-8859-1 + Content-transfer-encoding: base64 + + This should be interpreted to mean that the body is a base64 + ASCII encoding of data that was originally in ISO-8859-1, + and will be in that character set again after decoding. + + The following sections will define the two standard encoding + mechanisms. The definition of new content-transfer- + encodings is explicitly discouraged and should only occur + when absolutely necessary. All content-transfer-encoding + namespace except that beginning with "X-" is explicitly + reserved to the IANA for future use. Private agreements + about content-transfer-encodings are also explicitly + discouraged. + + Certain Content-Transfer-Encoding values may only be used on + certain Content-Types. In particular, it is expressly + forbidden to use any encodings other than "7bit", "8bit", or + "binary" with any Content-Type that recursively includes + other Content-Type fields, notably the "multipart" and + + + + Borenstein & Freed [Page 12] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + "message" Content-Types. All encodings that are desired for + bodies of type multipart or message must be done at the + innermost level, by encoding the actual body that needs to + be encoded. + + NOTE ON ENCODING RESTRICTIONS: Though the prohibition + against using content-transfer-encodings on data of type + multipart or message may seem overly restrictive, it is + necessary to prevent nested encodings, in which data are + passed through an encoding algorithm multiple times, and + must be decoded multiple times in order to be properly + viewed. Nested encodings add considerable complexity to + user agents: aside from the obvious efficiency problems + with such multiple encodings, they can obscure the basic + structure of a message. In particular, they can imply that + several decoding operations are necessary simply to find out + what types of objects a message contains. Banning nested + encodings may complicate the job of certain mail gateways, + but this seems less of a problem than the effect of nested + encodings on user agents. + + NOTE ON THE RELATIONSHIP BETWEEN CONTENT-TYPE AND CONTENT- + TRANSFER-ENCODING: It may seem that the Content-Transfer- + Encoding could be inferred from the characteristics of the + Content-Type that is to be encoded, or, at the very least, + that certain Content-Transfer-Encodings could be mandated + for use with specific Content-Types. There are several + reasons why this is not the case. First, given the varying + types of transports used for mail, some encodings may be + appropriate for some Content-Type/transport combinations and + not for others. (For example, in an 8-bit transport, no + encoding would be required for text in certain character + sets, while such encodings are clearly required for 7-bit + SMTP.) Second, certain Content-Types may require different + types of transfer encoding under different circumstances. + For example, many PostScript bodies might consist entirely + of short lines of 7-bit data and hence require little or no + encoding. Other PostScript bodies (especially those using + Level 2 PostScript's binary encoding mechanism) may only be + reasonably represented using a binary transport encoding. + Finally, since Content-Type is intended to be an open-ended + specification mechanism, strict specification of an + association between Content-Types and encodings effectively + couples the specification of an application protocol with a + specific lower-level transport. This is not desirable since + the developers of a Content-Type should not have to be aware + of all the transports in use and what their limitations are. + + NOTE ON TRANSLATING ENCODINGS: The quoted-printable and + base64 encodings are designed so that conversion between + them is possible. The only issue that arises in such a + conversion is the handling of line breaks. When converting + from quoted-printable to base64 a line break must be + converted into a CRLF sequence. Similarly, a CRLF sequence + + + + Borenstein & Freed [Page 13] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + in base64 data should be converted to a quoted-printable + line break, but ONLY when converting text data. + + NOTE ON CANONICAL ENCODING MODEL: There was some + confusion, in earlier drafts of this memo, regarding the + model for when email data was to be converted to canonical + form and encoded, and in particular how this process would + affect the treatment of CRLFs, given that the representation + of newlines varies greatly from system to system. For this + reason, a canonical model for encoding is presented as + Appendix H. + + 5.1 Quoted-Printable Content-Transfer-Encoding + + The Quoted-Printable encoding is intended to represent data + that largely consists of octets that correspond to printable + characters in the ASCII character set. It encodes the data + in such a way that the resulting octets are unlikely to be + modified by mail transport. If the data being encoded are + mostly ASCII text, the encoded form of the data remains + largely recognizable by humans. A body which is entirely + ASCII may also be encoded in Quoted-Printable to ensure the + integrity of the data should the message pass through a + character-translating, and/or line-wrapping gateway. + + In this encoding, octets are to be represented as determined + by the following rules: + + Rule #1: (General 8-bit representation) Any octet, + except those indicating a line break according to the + newline convention of the canonical form of the data + being encoded, may be represented by an "=" followed by + a two digit hexadecimal representation of the octet's + value. The digits of the hexadecimal alphabet, for this + purpose, are "0123456789ABCDEF". Uppercase letters must + be + used when sending hexadecimal data, though a robust + implementation may choose to recognize lowercase + letters on receipt. Thus, for example, the value 12 + (ASCII form feed) can be represented by "=0C", and the + value 61 (ASCII EQUAL SIGN) can be represented by + "=3D". Except when the following rules allow an + alternative encoding, this rule is mandatory. + + Rule #2: (Literal representation) Octets with decimal + values of 33 through 60 inclusive, and 62 through 126, + inclusive, MAY be represented as the ASCII characters + which correspond to those octets (EXCLAMATION POINT + through LESS THAN, and GREATER THAN through TILDE, + respectively). + + Rule #3: (White Space): Octets with values of 9 and 32 + MAY be represented as ASCII TAB (HT) and SPACE + characters, respectively, but MUST NOT be so + + + + Borenstein & Freed [Page 14] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + represented at the end of an encoded line. Any TAB (HT) + or SPACE characters on an encoded line MUST thus be + followed on that line by a printable character. In + particular, an "=" at the end of an encoded line, + indicating a soft line break (see rule #5) may follow + one or more TAB (HT) or SPACE characters. It follows + that an octet with value 9 or 32 appearing at the end + of an encoded line must be represented according to + Rule #1. This rule is necessary because some MTAs + (Message Transport Agents, programs which transport + messages from one user to another, or perform a part of + such transfers) are known to pad lines of text with + SPACEs, and others are known to remove "white space" + characters from the end of a line. Therefore, when + decoding a Quoted-Printable body, any trailing white + space on a line must be deleted, as it will necessarily + have been added by intermediate transport agents. + + Rule #4 (Line Breaks): A line break in a text body + part, independent of what its representation is + following the canonical representation of the data + being encoded, must be represented by a (RFC 822) line + break, which is a CRLF sequence, in the Quoted- + Printable encoding. If isolated CRs and LFs, or LF CR + and CR LF sequences are allowed to appear in binary + data according to the canonical form, they must be + represented using the "=0D", "=0A", "=0A=0D" and + "=0D=0A" notations respectively. + + Note that many implementation may elect to encode the + local representation of various content types directly. + In particular, this may apply to plain text material on + systems that use newline conventions other than CRLF + delimiters. Such an implementation is permissible, but + the generation of line breaks must be generalized to + account for the case where alternate representations of + newline sequences are used. + + Rule #5 (Soft Line Breaks): The Quoted-Printable + encoding REQUIRES that encoded lines be no more than 76 + characters long. If longer lines are to be encoded with + the Quoted-Printable encoding, 'soft' line breaks must + be used. An equal sign as the last character on a + encoded line indicates such a non-significant ('soft') + line break in the encoded text. Thus if the "raw" form + of the line is a single unencoded line that says: + + Now's the time for all folk to come to the aid of + their country. + + This can be represented, in the Quoted-Printable + encoding, as + + + + + + Borenstein & Freed [Page 15] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Now's the time = + for all folk to come= + to the aid of their country. + + This provides a mechanism with which long lines are + encoded in such a way as to be restored by the user + agent. The 76 character limit does not count the + trailing CRLF, but counts all other characters, + including any equal signs. + + Since the hyphen character ("-") is represented as itself in + the Quoted-Printable encoding, care must be taken, when + encapsulating a quoted-printable encoded body in a multipart + entity, to ensure that the encapsulation boundary does not + appear anywhere in the encoded body. (A good strategy is to + choose a boundary that includes a character sequence such as + "=_" which can never appear in a quoted-printable body. See + the definition of multipart messages later in this + document.) + + NOTE: The quoted-printable encoding represents something of + a compromise between readability and reliability in + transport. Bodies encoded with the quoted-printable + encoding will work reliably over most mail gateways, but may + not work perfectly over a few gateways, notably those + involving translation into EBCDIC. (In theory, an EBCDIC + gateway could decode a quoted-printable body and re-encode + it using base64, but such gateways do not yet exist.) A + higher level of confidence is offered by the base64 + Content-Transfer-Encoding. A way to get reasonably reliable + transport through EBCDIC gateways is to also quote the ASCII + characters + + !"#$@[\]^`{|}~ + + according to rule #1. See Appendix B for more information. + + Because quoted-printable data is generally assumed to be + line-oriented, it is to be expected that the breaks between + the lines of quoted printable data may be altered in + transport, in the same manner that plain text mail has + always been altered in Internet mail when passing between + systems with differing newline conventions. If such + alterations are likely to constitute a corruption of the + data, it is probably more sensible to use the base64 + encoding rather than the quoted-printable encoding. + + + + + + + + + + + + Borenstein & Freed [Page 16] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 5.2 Base64 Content-Transfer-Encoding + + The Base64 Content-Transfer-Encoding is designed to + represent arbitrary sequences of octets in a form that is + not humanly readable. The encoding and decoding algorithms + are simple, but the encoded data are consistently only about + 33 percent larger than the unencoded data. This encoding is + based on the one used in Privacy Enhanced Mail applications, + as defined in RFC 1113. The base64 encoding is adapted + from RFC 1113, with one change: base64 eliminates the "*" + mechanism for embedded clear text. + + A 65-character subset of US-ASCII is used, enabling 6 bits + to be represented per printable character. (The extra 65th + character, "=", is used to signify a special processing + function.) + + NOTE: This subset has the important property that it is + represented identically in all versions of ISO 646, + including US ASCII, and all characters in the subset are + also represented identically in all versions of EBCDIC. + Other popular encodings, such as the encoding used by the + UUENCODE utility and the base85 encoding specified as part + of Level 2 PostScript, do not share these properties, and + thus do not fulfill the portability requirements a binary + transport encoding for mail must meet. + + The encoding process represents 24-bit groups of input bits + as output strings of 4 encoded characters. Proceeding from + left to right, a 24-bit input group is formed by + concatenating 3 8-bit input groups. These 24 bits are then + treated as 4 concatenated 6-bit groups, each of which is + translated into a single digit in the base64 alphabet. When + encoding a bit stream via the base64 encoding, the bit + stream must be presumed to be ordered with the most- + significant-bit first. That is, the first bit in the stream + will be the high-order bit in the first byte, and the eighth + bit will be the low-order bit in the first byte, and so on. + + Each 6-bit group is used as an index into an array of 64 + printable characters. The character referenced by the index + is placed in the output string. These characters, identified + in Table 1, below, are selected so as to be universally + representable, and the set excludes characters with + particular significance to SMTP (e.g., ".", "CR", "LF") and + to the encapsulation boundaries defined in this document + (e.g., "-"). + + + + + + + + + + + Borenstein & Freed [Page 17] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Table 1: The Base64 Alphabet + + Value Encoding Value Encoding Value Encoding Value + Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + The output stream (encoded bytes) must be represented in + lines of no more than 76 characters each. All line breaks + or other characters not found in Table 1 must be ignored by + decoding software. In base64 data, characters other than + those in Table 1, line breaks, and other white space + probably indicate a transmission error, about which a + warning message or even a message rejection might be + appropriate under some circumstances. + + Special processing is performed if fewer than 24 bits are + available at the end of the data being encoded. A full + encoding quantum is always completed at the end of a body. + When fewer than 24 input bits are available in an input + group, zero bits are added (on the right) to form an + integral number of 6-bit groups. Output character positions + which are not required to represent actual input data are + set to the character "=". Since all base64 input is an + integral number of octets, only the following cases can + arise: (1) the final quantum of encoding input is an + integral multiple of 24 bits; here, the final unit of + encoded output will be an integral multiple of 4 characters + with no "=" padding, (2) the final quantum of encoding input + is exactly 8 bits; here, the final unit of encoded output + will be two characters followed by two "=" padding + characters, or (3) the final quantum of encoding input is + exactly 16 bits; here, the final unit of encoded output will + be three characters followed by one "=" padding character. + + Care must be taken to use the proper octets for line breaks + if base64 encoding is applied directly to text material that + has not been converted to canonical form. In particular, + text line breaks should be converted into CRLF sequences + + + + Borenstein & Freed [Page 18] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + prior to base64 encoding. The important thing to note is + that this may be done directly by the encoder rather than in + a prior canonicalization step in some implementations. + + NOTE: There is no need to worry about quoting apparent + encapsulation boundaries within base64-encoded parts of + multipart entities because no hyphen characters are used in + the base64 encoding. + + 6 Additional Optional Content- Header Fields + + 6.1 Optional Content-ID Header Field + + In constructing a high-level user agent, it may be desirable + to allow one body to make reference to another. + Accordingly, bodies may be labeled using the "Content-ID" + header field, which is syntactically identical to the + "Message-ID" header field: + + Content-ID := msg-id + + Like the Message-ID values, Content-ID values must be + generated to be as unique as possible. + + 6.2 Optional Content-Description Header Field + + The ability to associate some descriptive information with a + given body is often desirable. For example, it may be useful + to mark an "image" body as "a picture of the Space Shuttle + Endeavor." Such text may be placed in the Content- + Description header field. + + Content-Description := *text + + The description is presumed to be given in the US-ASCII + character set, although the mechanism specified in [RFC- + 1342] may be used for non-US-ASCII Content-Description + values. + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 19] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7 The Predefined Content-Type Values + + This document defines seven initial Content-Type values and + an extension mechanism for private or experimental types. + Further standard types must be defined by new published + specifications. It is expected that most innovation in new + types of mail will take place as subtypes of the seven types + defined here. The most essential characteristics of the + seven content-types are summarized in Appendix G. + + 7.1 The Text Content-Type + + The text Content-Type is intended for sending material which + is principally textual in form. It is the default Content- + Type. A "charset" parameter may be used to indicate the + character set of the body text. The primary subtype of text + is "plain". This indicates plain (unformatted) text. The + default Content-Type for Internet mail is "text/plain; + charset=us-ascii". + + Beyond plain text, there are many formats for representing + what might be known as "extended text" -- text with embedded + formatting and presentation information. An interesting + characteristic of many such representations is that they are + to some extent readable even without the software that + interprets them. It is useful, then, to distinguish them, + at the highest level, from such unreadable data as images, + audio, or text represented in an unreadable form. In the + absence of appropriate interpretation software, it is + reasonable to show subtypes of text to the user, while it is + not reasonable to do so with most nontextual data. + + Such formatted textual data should be represented using + subtypes of text. Plausible subtypes of text are typically + given by the common name of the representation format, e.g., + "text/richtext". + + 7.1.1 The charset parameter + + A critical parameter that may be specified in the Content- + Type field for text data is the character set. This is + specified with a "charset" parameter, as in: + + Content-type: text/plain; charset=us-ascii + + Unlike some other parameter values, the values of the + charset parameter are NOT case sensitive. The default + character set, which must be assumed in the absence of a + charset parameter, is US-ASCII. + + An initial list of predefined character set names can be + found at the end of this section. Additional character sets + may be registered with IANA as described in Appendix F, + although the standardization of their use requires the usual + + + + Borenstein & Freed [Page 20] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + IAB review and approval. Note that if the specified + character set includes 8-bit data, a Content-Transfer- + Encoding header field and a corresponding encoding on the + data are required in order to transmit the body via some + mail transfer protocols, such as SMTP. + + The default character set, US-ASCII, has been the subject of + some confusion and ambiguity in the past. Not only were + there some ambiguities in the definition, there have been + wide variations in practice. In order to eliminate such + ambiguity and variations in the future, it is strongly + recommended that new user agents explicitly specify a + character set via the Content-Type header field. "US-ASCII" + does not indicate an arbitrary seven-bit character code, but + specifies that the body uses character coding that uses the + exact correspondence of codes to characters specified in + ASCII. National use variations of ISO 646 [ISO-646] are NOT + ASCII and their use in Internet mail is explicitly + discouraged. The omission of the ISO 646 character set is + deliberate in this regard. The character set name of "US- + ASCII" explicitly refers to ANSI X3.4-1986 [US-ASCII] only. + The character set name "ASCII" is reserved and must not be + used for any purpose. + + NOTE: RFC 821 explicitly specifies "ASCII", and references + an earlier version of the American Standard. Insofar as one + of the purposes of specifying a Content-Type and character + set is to permit the receiver to unambiguously determine how + the sender intended the coded message to be interpreted, + assuming anything other than "strict ASCII" as the default + would risk unintentional and incompatible changes to the + semantics of messages now being transmitted. This also + implies that messages containing characters coded according + to national variations on ISO 646, or using code-switching + procedures (e.g., those of ISO 2022), as well as 8-bit or + multiple octet character encodings MUST use an appropriate + character set specification to be consistent with this + specification. + + The complete US-ASCII character set is listed in [US-ASCII]. + Note that the control characters including DEL (0-31, 127) + have no defined meaning apart from the combination CRLF + (ASCII values 13 and 10) indicating a new line. Two of the + characters have de facto meanings in wide use: FF (12) often + means "start subsequent text on the beginning of a new + page"; and TAB or HT (9) often (though not always) means + "move the cursor to the next available column after the + current position where the column number is a multiple of 8 + (counting the first column as column 0)." Apart from this, + any use of the control characters or DEL in a body must be + part of a private agreement between the sender and + recipient. Such private agreements are discouraged and + should be replaced by the other capabilities of this + document. + + + + Borenstein & Freed [Page 21] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + NOTE: Beyond US-ASCII, an enormous proliferation of + character sets is possible. It is the opinion of the IETF + working group that a large number of character sets is NOT a + good thing. We would prefer to specify a single character + set that can be used universally for representing all of the + world's languages in electronic mail. Unfortunately, + existing practice in several communities seems to point to + the continued use of multiple character sets in the near + future. For this reason, we define names for a small number + of character sets for which a strong constituent base + exists. It is our hope that ISO 10646 or some other + effort will eventually define a single world character set + which can then be specified for use in Internet mail, but in + the advance of that definition we cannot specify the use of + ISO 10646, Unicode, or any other character set whose + definition is, as of this writing, incomplete. + + The defined charset values are: + + US-ASCII -- as defined in [US-ASCII]. + + ISO-8859-X -- where "X" is to be replaced, as + necessary, for the parts of ISO-8859 [ISO- + 8859]. Note that the ISO 646 character sets + have deliberately been omitted in favor of + their 8859 replacements, which are the + designated character sets for Internet mail. + As of the publication of this document, the + legitimate values for "X" are the digits 1 + through 9. + + Note that the character set used, if anything other than + US-ASCII, must always be explicitly specified in the + Content-Type field. + + No other character set name may be used in Internet mail + without the publication of a formal specification and its + registration with IANA as described in Appendix F, or by + private agreement, in which case the character set name must + begin with "X-". + + Implementors are discouraged from defining new character + sets for mail use unless absolutely necessary. + + The "charset" parameter has been defined primarily for the + purpose of textual data, and is described in this section + for that reason. However, it is conceivable that non- + textual data might also wish to specify a charset value for + some purpose, in which case the same syntax and values + should be used. + + In general, mail-sending software should always use the + "lowest common denominator" character set possible. For + example, if a body contains only US-ASCII characters, it + + + + Borenstein & Freed [Page 22] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + should be marked as being in the US-ASCII character set, not + ISO-8859-1, which, like all the ISO-8859 family of character + sets, is a superset of US-ASCII. More generally, if a + widely-used character set is a subset of another character + set, and a body contains only characters in the widely-used + subset, it should be labeled as being in that subset. This + will increase the chances that the recipient will be able to + view the mail correctly. + + 7.1.2 The Text/plain subtype + + The primary subtype of text is "plain". This indicates + plain (unformatted) text. The default Content-Type for + Internet mail, "text/plain; charset=us-ascii", describes + existing Internet practice, that is, it is the type of body + defined by RFC 822. + + 7.1.3 The Text/richtext subtype + + In order to promote the wider interoperability of simple + formatted text, this document defines an extremely simple + subtype of "text", the "richtext" subtype. This subtype was + designed to meet the following criteria: + + 1. The syntax must be extremely simple to parse, + so that even teletype-oriented mail systems can + easily strip away the formatting information and + leave only the readable text. + + 2. The syntax must be extensible to allow for new + formatting commands that are deemed essential. + + 3. The capabilities must be extremely limited, to + ensure that it can represent no more than is + likely to be representable by the user's primary + word processor. While this limits what can be + sent, it increases the likelihood that what is + sent can be properly displayed. + + 4. The syntax must be compatible with SGML, so + that, with an appropriate DTD (Document Type + Definition, the standard mechanism for defining a + document type using SGML), a general SGML parser + could be made to parse richtext. However, despite + this compatibility, the syntax should be far + simpler than full SGML, so that no SGML knowledge + is required in order to implement it. + + The syntax of "richtext" is very simple. It is assumed, at + the top-level, to be in the US-ASCII character set, unless + of course a different charset parameter was specified in the + Content-type field. All characters represent themselves, + with the exception of the "<" character (ASCII 60), which is + used to mark the beginning of a formatting command. + + + + Borenstein & Freed [Page 23] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Formatting instructions consist of formatting commands + surrounded by angle brackets ("<>", ASCII 60 and 62). Each + formatting command may be no more than 40 characters in + length, all in US-ASCII, restricted to the alphanumeric and + hyphen ("-") characters. Formatting commands may be preceded + by a forward slash or solidus ("/", ASCII 47), making them + negations, and such negations must always exist to balance + the initial opening commands, except as noted below. Thus, + if the formatting command "" appears at some point, + there must later be a "" to balance it. There are + only three exceptions to this "balancing" rule: First, the + command "" is used to represent a literal "<" character. + Second, the command "" is used to represent a required + line break. (Otherwise, CRLFs in the data are treated as + equivalent to a single SPACE character.) Finally, the + command "" is used to represent a page break. (NOTE: + The 40 character limit on formatting commands does not + include the "<", ">", or "/" characters that might be + attached to such commands.) + + Initially defined formatting commands, not all of which will + be implemented by all richtext implementations, include: + + Bold -- causes the subsequent text to be in a bold + font. + Italic -- causes the subsequent text to be in an italic + font. + Fixed -- causes the subsequent text to be in a fixed + width font. + Smaller -- causes the subsequent text to be in a + smaller font. + Bigger -- causes the subsequent text to be in a bigger + font. + Underline -- causes the subsequent text to be + underlined. + Center -- causes the subsequent text to be centered. + FlushLeft -- causes the subsequent text to be left + justified. + FlushRight -- causes the subsequent text to be right + justified. + Indent -- causes the subsequent text to be indented at + the left margin. + IndentRight -- causes the subsequent text to be + indented at the right margin. + Outdent -- causes the subsequent text to be outdented + at the left margin. + OutdentRight -- causes the subsequent text to be + outdented at the right margin. + SamePage -- causes the subsequent text to be grouped, + if possible, on one page. + Subscript -- causes the subsequent text to be + interpreted as a subscript. + + + + + + Borenstein & Freed [Page 24] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Superscript -- causes the subsequent text to be + interpreted as a superscript. + Heading -- causes the subsequent text to be interpreted + as a page heading. + Footing -- causes the subsequent text to be interpreted + as a page footing. + ISO-8859-X (for any value of X that is legal as a + "charset" parameter) -- causes the subsequent text + to be interpreted as text in the appropriate + character set. + US-ASCII -- causes the subsequent text to be + interpreted as text in the US-ASCII character set. + Excerpt -- causes the subsequent text to be interpreted + as a textual excerpt from another source. + Typically this will be displayed using indentation + and an alternate font, but such decisions are up + to the viewer. + Paragraph -- causes the subsequent text to be + interpreted as a single paragraph, with + appropriate paragraph breaks (typically blank + space) before and after. + Signature -- causes the subsequent text to be + interpreted as a "signature". Some systems may + wish to display signatures in a smaller font or + otherwise set them apart from the main text of the + message. + Comment -- causes the subsequent text to be interpreted + as a comment, and hence not shown to the reader. + No-op -- has no effect on the subsequent text. + lt -- is replaced by a literal "<" character. No + balancing is allowed. + nl -- causes a line break. No balancing is + allowed. + np -- causes a page break. No balancing is + allowed. + + Each positive formatting command affects all subsequent text + until the matching negative formatting command. Such pairs + of formatting commands must be properly balanced and nested. + Thus, a proper way to describe text in bold italics is: + + the-text + + or, alternately, + + the-text + + but, in particular, the following is illegal + richtext: + + the-text + + NOTE: The nesting requirement for formatting commands + imposes a slightly higher burden upon the composers of + + + + Borenstein & Freed [Page 25] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + richtext bodies, but potentially simplifies richtext + displayers by allowing them to be stack-based. The main + goal of richtext is to be simple enough to make multifont, + formatted email widely readable, so that those with the + capability of sending it will be able to do so with + confidence. Thus slightly increased complexity in the + composing software was deemed a reasonable tradeoff for + simplified reading software. Nonetheless, implementors of + richtext readers are encouraged to follow the general + Internet guidelines of being conservative in what you send + and liberal in what you accept. Those implementations that + can do so are encouraged to deal reasonably with improperly + nested richtext. + + Implementations must regard any unrecognized formatting + command as equivalent to "No-op", thus facilitating future + extensions to "richtext". Private extensions may be defined + using formatting commands that begin with "X-", by analogy + to Internet mail header field names. + + It is worth noting that no special behavior is required for + the TAB (HT) character. It is recommended, however, that, at + least when fixed-width fonts are in use, the common + semantics of the TAB (HT) character should be observed, + namely that it moves to the next column position that is a + multiple of 8. (In other words, if a TAB (HT) occurs in + column n, where the leftmost column is column 0, then that + TAB (HT) should be replaced by 8-(n mod 8) SPACE + characters.) + + Richtext also differentiates between "hard" and "soft" line + breaks. A line break (CRLF) in the richtext data stream is + interpreted as a "soft" line break, one that is included + only for purposes of mail transport, and is to be treated as + white space by richtext interpreters. To include a "hard" + line break (one that must be displayed as such), the "" + or " formatting constructs should be used. In + general, a soft line break should be treated as white space, + but when soft line breaks immediately follow a or a + tag they should be ignored rather than treated + as white space. + + Putting all this together, the following "text/richtext" + body fragment: + + Now is the time for + all good men + (and women>) to + come + + to the aid of their + + + + + + + Borenstein & Freed [Page 26] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + beloved country. Stupid + quote! -- the end + + represents the following formatted text (which will, no + doubt, look cryptic in the text-only version of this + document): + + Now is the time for all good men (and ) to + come to the aid of their + beloved + + country. -- the end + + Richtext conformance: A minimal richtext implementation is + one that simply converts "" to "<", converts CRLFs to + SPACE, converts to a newline according to local newline + convention, removes everything between a command + and the next balancing command, and removes all + other formatting commands (all text enclosed in angle + brackets). + + NOTE ON THE RELATIONSHIP OF RICHTEXT TO SGML: Richtext is + decidedly not SGML, and must not be used to transport + arbitrary SGML documents. Those who wish to use SGML + document types as a mail transport format must define a new + text or application subtype, e.g., "text/sgml-dtd-whatever" + or "application/sgml-dtd-whatever", depending on the + perceived readability of the DTD in use. Richtext is + designed to be compatible with SGML, and specifically so + that it will be possible to define a richtext DTD if one is + needed. However, this does not imply that arbitrary SGML + can be called richtext, nor that richtext implementors have + any need to understand SGML; the description in this + document is a complete definition of richtext, which is far + simpler than complete SGML. + + NOTE ON THE INTENDED USE OF RICHTEXT: It is recognized that + implementors of future mail systems will want rich text + functionality far beyond that currently defined for + richtext. The intent of richtext is to provide a common + format for expressing that functionality in a form in which + much of it, at least, will be understood by interoperating + software. Thus, in particular, software with a richer + notion of formatted text than richtext can still use + richtext as its basic representation, but can extend it with + new formatting commands and by hiding information specific + to that software system in richtext comments. As such + systems evolve, it is expected that the definition of + richtext will be further refined by future published + specifications, but richtext as defined here provides a + platform on which evolutionary refinements can be based. + + IMPLEMENTATION NOTE: In some environments, it might be + impossible to combine certain richtext formatting commands, + + + + Borenstein & Freed [Page 27] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + whereas in others they might be combined easily. For + example, the combination of and might + produce bold italics on systems that support such fonts, but + there exist systems that can make text bold or italicized, + but not both. In such cases, the most recently issued + recognized formatting command should be preferred. + + One of the major goals in the design of richtext was to make + it so simple that even text-only mailers will implement + richtext-to-plain-text translators, thus increasing the + likelihood that multifont text will become "safe" to use + very widely. To demonstrate this simplicity, an extremely + simple 35-line C program that converts richtext input into + plain text output is included in Appendix D. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 28] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.2 The Multipart Content-Type + + In the case of multiple part messages, in which one or more + different sets of data are combined in a single body, a + "multipart" Content-Type field must appear in the entity's + header. The body must then contain one or more "body parts," + each preceded by an encapsulation boundary, and the last one + followed by a closing boundary. Each part starts with an + encapsulation boundary, and then contains a body part + consisting of header area, a blank line, and a body area. + Thus a body part is similar to an RFC 822 message in syntax, + but different in meaning. + + A body part is NOT to be interpreted as actually being an + RFC 822 message. To begin with, NO header fields are + actually required in body parts. A body part that starts + with a blank line, therefore, is allowed and is a body part + for which all default values are to be assumed. In such a + case, the absence of a Content-Type header field implies + that the encapsulation is plain US-ASCII text. The only + header fields that have defined meaning for body parts are + those the names of which begin with "Content-". All other + header fields are generally to be ignored in body parts. + Although they should generally be retained in mail + processing, they may be discarded by gateways if necessary. + Such other fields are permitted to appear in body parts but + should not be depended on. "X-" fields may be created for + experimental or private purposes, with the recognition that + the information they contain may be lost at some gateways. + + The distinction between an RFC 822 message and a body part + is subtle, but important. A gateway between Internet and + X.400 mail, for example, must be able to tell the difference + between a body part that contains an image and a body part + that contains an encapsulated message, the body of which is + an image. In order to represent the latter, the body part + must have "Content-Type: message", and its body (after the + blank line) must be the encapsulated message, with its own + "Content-Type: image" header field. The use of similar + syntax facilitates the conversion of messages to body parts, + and vice versa, but the distinction between the two must be + understood by implementors. (For the special case in which + all parts actually are messages, a "digest" subtype is also + defined.) + + As stated previously, each body part is preceded by an + encapsulation boundary. The encapsulation boundary MUST NOT + appear inside any of the encapsulated parts. Thus, it is + crucial that the composing agent be able to choose and + specify the unique boundary that will separate the parts. + + All present and future subtypes of the "multipart" type must + use an identical syntax. Subtypes may differ in their + semantics, and may impose additional restrictions on syntax, + + + + Borenstein & Freed [Page 29] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + but must conform to the required syntax for the multipart + type. This requirement ensures that all conformant user + agents will at least be able to recognize and separate the + parts of any multipart entity, even of an unrecognized + subtype. + + As stated in the definition of the Content-Transfer-Encoding + field, no encoding other than "7bit", "8bit", or "binary" is + permitted for entities of type "multipart". The multipart + delimiters and header fields are always 7-bit ASCII in any + case, and data within the body parts can be encoded on a + part-by-part basis, with Content-Transfer-Encoding fields + for each appropriate body part. + + Mail gateways, relays, and other mail handling agents are + commonly known to alter the top-level header of an RFC 822 + message. In particular, they frequently add, remove, or + reorder header fields. Such alterations are explicitly + forbidden for the body part headers embedded in the bodies + of messages of type "multipart." + + 7.2.1 Multipart: The common syntax + + All subtypes of "multipart" share a common syntax, defined + in this section. A simple example of a multipart message + also appears in this section. An example of a more complex + multipart message is given in Appendix C. + + The Content-Type field for multipart entities requires one + parameter, "boundary", which is used to specify the + encapsulation boundary. The encapsulation boundary is + defined as a line consisting entirely of two hyphen + characters ("-", decimal code 45) followed by the boundary + parameter value from the Content-Type header field. + + NOTE: The hyphens are for rough compatibility with the + earlier RFC 934 method of message encapsulation, and for + ease of searching for the boundaries in some + implementations. However, it should be noted that multipart + messages are NOT completely compatible with RFC 934 + encapsulations; in particular, they do not obey RFC 934 + quoting conventions for embedded lines that begin with + hyphens. This mechanism was chosen over the RFC 934 + mechanism because the latter causes lines to grow with each + level of quoting. The combination of this growth with the + fact that SMTP implementations sometimes wrap long lines + made the RFC 934 mechanism unsuitable for use in the event + that deeply-nested multipart structuring is ever desired. + + Thus, a typical multipart Content-Type header field might + look like this: + + Content-Type: multipart/mixed; + + + + + Borenstein & Freed [Page 30] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + boundary=gc0p4Jq0M2Yt08jU534c0p + + This indicates that the entity consists of several parts, + each itself with a structure that is syntactically identical + to an RFC 822 message, except that the header area might be + completely empty, and that the parts are each preceded by + the line + + --gc0p4Jq0M2Yt08jU534c0p + + Note that the encapsulation boundary must occur at the + beginning of a line, i.e., following a CRLF, and that that + initial CRLF is considered to be part of the encapsulation + boundary rather than part of the preceding part. The + boundary must be followed immediately either by another CRLF + and the header fields for the next part, or by two CRLFs, in + which case there are no header fields for the next part (and + it is therefore assumed to be of Content-Type text/plain). + + NOTE: The CRLF preceding the encapsulation line is + considered part of the boundary so that it is possible to + have a part that does not end with a CRLF (line break). + Body parts that must be considered to end with line breaks, + therefore, should have two CRLFs preceding the encapsulation + line, the first of which is part of the preceding body part, + and the second of which is part of the encapsulation + boundary. + + The requirement that the encapsulation boundary begins with + a CRLF implies that the body of a multipart entity must + itself begin with a CRLF before the first encapsulation line + -- that is, if the "preamble" area is not used, the entity + headers must be followed by TWO CRLFs. This is indeed how + such entities should be composed. A tolerant mail reading + program, however, may interpret a body of type multipart + that begins with an encapsulation line NOT initiated by a + CRLF as also being an encapsulation boundary, but a + compliant mail sending program must not generate such + entities. + + Encapsulation boundaries must not appear within the + encapsulations, and must be no longer than 70 characters, + not counting the two leading hyphens. + + The encapsulation boundary following the last body part is a + distinguished delimiter that indicates that no further body + parts will follow. Such a delimiter is identical to the + previous delimiters, with the addition of two more hyphens + at the end of the line: + + --gc0p4Jq0M2Yt08jU534c0p-- + + There appears to be room for additional information prior to + the first encapsulation boundary and following the final + + + + Borenstein & Freed [Page 31] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + boundary. These areas should generally be left blank, and + implementations should ignore anything that appears before + the first boundary or after the last one. + + NOTE: These "preamble" and "epilogue" areas are not used + because of the lack of proper typing of these parts and the + lack of clear semantics for handling these areas at + gateways, particularly X.400 gateways. + + NOTE: Because encapsulation boundaries must not appear in + the body parts being encapsulated, a user agent must + exercise care to choose a unique boundary. The boundary in + the example above could have been the result of an algorithm + designed to produce boundaries with a very low probability + of already existing in the data to be encapsulated without + having to prescan the data. Alternate algorithms might + result in more 'readable' boundaries for a recipient with an + old user agent, but would require more attention to the + possibility that the boundary might appear in the + encapsulated part. The simplest boundary possible is + something like "---", with a closing boundary of "-----". + + As a very simple example, the following multipart message + has two parts, both of them plain text, one of them + explicitly typed and one of them implicitly typed: + + From: Nathaniel Borenstein + To: Ned Freed + Subject: Sample message + MIME-Version: 1.0 + Content-type: multipart/mixed; boundary="simple + boundary" + + This is the preamble. It is to be ignored, though it + is a handy place for mail composers to include an + explanatory note to non-MIME compliant readers. + --simple boundary + + This is implicitly typed plain ASCII text. + It does NOT end with a linebreak. + --simple boundary + Content-type: text/plain; charset=us-ascii + + This is explicitly typed plain ASCII text. + It DOES end with a linebreak. + + --simple boundary-- + This is the epilogue. It is also to be ignored. + + The use of a Content-Type of multipart in a body part within + another multipart entity is explicitly allowed. In such + cases, for obvious reasons, care must be taken to ensure + that each nested multipart entity must use a different + boundary delimiter. See Appendix C for an example of nested + + + + Borenstein & Freed [Page 32] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + multipart entities. + + The use of the multipart Content-Type with only a single + body part may be useful in certain contexts, and is + explicitly permitted. + + The only mandatory parameter for the multipart Content-Type + is the boundary parameter, which consists of 1 to 70 + characters from a set of characters known to be very robust + through email gateways, and NOT ending with white space. + (If a boundary appears to end with white space, the white + space must be presumed to have been added by a gateway, and + should be deleted.) It is formally specified by the + following BNF: + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / + "_" + / "," / "-" / "." / "/" / ":" / "=" / "?" + + Overall, the body of a multipart entity may be specified as + follows: + + multipart-body := preamble 1*encapsulation + close-delimiter epilogue + + encapsulation := delimiter CRLF body-part + + delimiter := CRLF "--" boundary ; taken from Content-Type + field. + ; when content-type is + multipart + ; There must be no space + ; between "--" and boundary. + + close-delimiter := delimiter "--" ; Again, no space before + "--" + + preamble := *text ; to be ignored upon + receipt. + + epilogue := *text ; to be ignored upon + receipt. + + body-part = <"message" as defined in RFC 822, + with all header fields optional, and with the + specified delimiter not occurring anywhere in + the message body, either on a line by itself + or as a substring anywhere. Note that the + + + + + + Borenstein & Freed [Page 33] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + semantics of a part differ from the semantics + of a message, as described in the text.> + + NOTE: Conspicuously missing from the multipart type is a + notion of structured, related body parts. In general, it + seems premature to try to standardize interpart structure + yet. It is recommended that those wishing to provide a more + structured or integrated multipart messaging facility should + define a subtype of multipart that is syntactically + identical, but that always expects the inclusion of a + distinguished part that can be used to specify the structure + and integration of the other parts, probably referring to + them by their Content-ID field. If this approach is used, + other implementations will not recognize the new subtype, + but will treat it as the primary subtype (multipart/mixed) + and will thus be able to show the user the parts that are + recognized. + + 7.2.2 The Multipart/mixed (primary) subtype + + The primary subtype for multipart, "mixed", is intended for + use when the body parts are independent and intended to be + displayed serially. Any multipart subtypes that an + implementation does not recognize should be treated as being + of subtype "mixed". + + 7.2.3 The Multipart/alternative subtype + + The multipart/alternative type is syntactically identical to + multipart/mixed, but the semantics are different. In + particular, each of the parts is an "alternative" version of + the same information. User agents should recognize that the + content of the various parts are interchangeable. The user + agent should either choose the "best" type based on the + user's environment and preferences, or offer the user the + available alternatives. In general, choosing the best type + means displaying only the LAST part that can be displayed. + This may be used, for example, to send mail in a fancy text + format in such a way that it can easily be displayed + anywhere: + + From: Nathaniel Borenstein + To: Ned Freed + Subject: Formatted text mail + MIME-Version: 1.0 + Content-Type: multipart/alternative; boundary=boundary42 + + + --boundary42 + Content-Type: text/plain; charset=us-ascii + + ...plain text version of message goes here.... + + + + + + Borenstein & Freed [Page 34] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + --boundary42 + Content-Type: text/richtext + + .... richtext version of same message goes here ... + --boundary42 + Content-Type: text/x-whatever + + .... fanciest formatted version of same message goes here + ... + --boundary42-- + + In this example, users whose mail system understood the + "text/x-whatever" format would see only the fancy version, + while other users would see only the richtext or plain text + version, depending on the capabilities of their system. + + In general, user agents that compose multipart/alternative + entities should place the body parts in increasing order of + preference, that is, with the preferred format last. For + fancy text, the sending user agent should put the plainest + format first and the richest format last. Receiving user + agents should pick and display the last format they are + capable of displaying. In the case where one of the + alternatives is itself of type "multipart" and contains + unrecognized sub-parts, the user agent may choose either to + show that alternative, an earlier alternative, or both. + + NOTE: From an implementor's perspective, it might seem more + sensible to reverse this ordering, and have the plainest + alternative last. However, placing the plainest alternative + first is the friendliest possible option when + mutlipart/alternative entities are viewed using a non-MIME- + compliant mail reader. While this approach does impose some + burden on compliant mail readers, interoperability with + older mail readers was deemed to be more important in this + case. + + It may be the case that some user agents, if they can + recognize more than one of the formats, will prefer to offer + the user the choice of which format to view. This makes + sense, for example, if mail includes both a nicely-formatted + image version and an easily-edited text version. What is + most critical, however, is that the user not automatically + be shown multiple versions of the same data. Either the + user should be shown the last recognized version or should + explicitly be given the choice. + + + + + + + + + + + + Borenstein & Freed [Page 35] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.2.4 The Multipart/digest subtype + + This document defines a "digest" subtype of the multipart + Content-Type. This type is syntactically identical to + multipart/mixed, but the semantics are different. In + particular, in a digest, the default Content-Type value for + a body part is changed from "text/plain" to + "message/rfc822". This is done to allow a more readable + digest format that is largely compatible (except for the + quoting convention) with RFC 934. + + A digest in this format might, then, look something like + this: + + From: Moderator-Address + MIME-Version: 1.0 + Subject: Internet Digest, volume 42 + Content-Type: multipart/digest; + boundary="---- next message ----" + + + ------ next message ---- + + From: someone-else + Subject: my opinion + + ...body goes here ... + + ------ next message ---- + + From: someone-else-again + Subject: my different opinion + + ... another body goes here... + + ------ next message ------ + + 7.2.5 The Multipart/parallel subtype + + This document defines a "parallel" subtype of the multipart + Content-Type. This type is syntactically identical to + multipart/mixed, but the semantics are different. In + particular, in a parallel entity, all of the parts are + intended to be presented in parallel, i.e., simultaneously, + on hardware and software that are capable of doing so. + Composing agents should be aware that many mail readers will + lack this capability and will show the parts serially in any + event. + + + + + + + + + + Borenstein & Freed [Page 36] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.3 The Message Content-Type + + It is frequently desirable, in sending mail, to encapsulate + another mail message. For this common operation, a special + Content-Type, "message", is defined. The primary subtype, + message/rfc822, has no required parameters in the Content- + Type field. Additional subtypes, "partial" and "External- + body", do have required parameters. These subtypes are + explained below. + + NOTE: It has been suggested that subtypes of message might + be defined for forwarded or rejected messages. However, + forwarded and rejected messages can be handled as multipart + messages in which the first part contains any control or + descriptive information, and a second part, of type + message/rfc822, is the forwarded or rejected message. + Composing rejection and forwarding messages in this manner + will preserve the type information on the original message + and allow it to be correctly presented to the recipient, and + hence is strongly encouraged. + + As stated in the definition of the Content-Transfer-Encoding + field, no encoding other than "7bit", "8bit", or "binary" is + permitted for messages or parts of type "message". The + message header fields are always US-ASCII in any case, and + data within the body can still be encoded, in which case the + Content-Transfer-Encoding header field in the encapsulated + message will reflect this. Non-ASCII text in the headers of + an encapsulated message can be specified using the + mechanisms described in [RFC-1342]. + + Mail gateways, relays, and other mail handling agents are + commonly known to alter the top-level header of an RFC 822 + message. In particular, they frequently add, remove, or + reorder header fields. Such alterations are explicitly + forbidden for the encapsulated headers embedded in the + bodies of messages of type "message." + + 7.3.1 The Message/rfc822 (primary) subtype + + A Content-Type of "message/rfc822" indicates that the body + contains an encapsulated message, with the syntax of an RFC + 822 message. + + 7.3.2 The Message/Partial subtype + + A subtype of message, "partial", is defined in order to + allow large objects to be delivered as several separate + pieces of mail and automatically reassembled by the + receiving user agent. (The concept is similar to IP + fragmentation/reassembly in the basic Internet Protocols.) + This mechanism can be used when intermediate transport + agents limit the size of individual messages that can be + sent. Content-Type "message/partial" thus indicates that + + + + Borenstein & Freed [Page 37] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + the body contains a fragment of a larger message. + + Three parameters must be specified in the Content-Type field + of type message/partial: The first, "id", is a unique + identifier, as close to a world-unique identifier as + possible, to be used to match the parts together. (In + general, the identifier is essentially a message-id; if + placed in double quotes, it can be any message-id, in + accordance with the BNF for "parameter" given earlier in + this specification.) The second, "number", an integer, is + the part number, which indicates where this part fits into + the sequence of fragments. The third, "total", another + integer, is the total number of parts. This third subfield + is required on the final part, and is optional on the + earlier parts. Note also that these parameters may be given + in any order. + + Thus, part 2 of a 3-part message may have either of the + following header fields: + + Content-Type: Message/Partial; + number=2; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com"; + + Content-Type: Message/Partial; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com"; + number=2 + + But part 3 MUST specify the total number of parts: + + Content-Type: Message/Partial; + number=3; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com"; + + Note that part numbering begins with 1, not 0. + + When the parts of a message broken up in this manner are put + together, the result is a complete RFC 822 format message, + which may have its own Content-Type header field, and thus + may contain any other data type. + + Message fragmentation and reassembly: The semantics of a + reassembled partial message must be those of the "inner" + message, rather than of a message containing the inner + message. This makes it possible, for example, to send a + large audio message as several partial messages, and still + have it appear to the recipient as a simple audio message + rather than as an encapsulated message containing an audio + message. That is, the encapsulation of the message is + considered to be "transparent". + + When generating and reassembling the parts of a + message/partial message, the headers of the encapsulated + message must be merged with the headers of the enclosing + + + + Borenstein & Freed [Page 38] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + entities. In this process the following rules must be + observed: + + (1) All of the headers from the initial enclosing + entity (part one), except those that start with + "Content-" and "Message-ID", must be copied, in + order, to the new message. + + (2) Only those headers in the enclosed message + which start with "Content-" and "Message-ID" must + be appended, in order, to the headers of the new + message. Any headers in the enclosed message + which do not start with "Content-" (except for + "Message-ID") will be ignored. + + (3) All of the headers from the second and any + subsequent messages will be ignored. + + For example, if an audio message is broken into two parts, + the first part might look something like this: + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + Message-ID: id1@host.com + MIME-Version: 1.0 + Content-type: message/partial; + id="ABC@host.com"; + number=1; total=2 + + X-Weird-Header-1: Bar + X-Weird-Header-2: Hello + Message-ID: anotherid@foo.com + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here... + + and the second half might look something like this: + + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + MIME-Version: 1.0 + Message-ID: id2@host.com + Content-type: message/partial; + id="ABC@host.com"; number=2; total=2 + + ... second half of encoded audio data goes here... + + Then, when the fragmented message is reassembled, the + resulting message to be displayed to the user should look + something like this: + + + + Borenstein & Freed [Page 39] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + Message-ID: anotherid@foo.com + MIME-Version: 1.0 + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here... + ... second half of encoded audio data goes here... + + It should be noted that, because some message transfer + agents may choose to automatically fragment large messages, + and because such agents may use different fragmentation + thresholds, it is possible that the pieces of a partial + message, upon reassembly, may prove themselves to comprise a + partial message. This is explicitly permitted. + + It should also be noted that the inclusion of a "References" + field in the headers of the second and subsequent pieces of + a fragmented message that references the Message-Id on the + previous piece may be of benefit to mail readers that + understand and track references. However, the generation of + such "References" fields is entirely optional. + + 7.3.3 The Message/External-Body subtype + + The external-body subtype indicates that the actual body + data are not included, but merely referenced. In this case, + the parameters describe a mechanism for accessing the + external data. + + When a message body or body part is of type + "message/external-body", it consists of a header, two + consecutive CRLFs, and the message header for the + encapsulated message. If another pair of consecutive CRLFs + appears, this of course ends the message header for the + encapsulated message. However, since the encapsulated + message's body is itself external, it does NOT appear in the + area that follows. For example, consider the following + message: + + Content-type: message/external-body; access- + type=local-file; + name=/u/nsb/Me.gif + + Content-type: image/gif + + THIS IS NOT REALLY THE BODY! + + The area at the end, which might be called the "phantom + body", is ignored for most external-body messages. However, + it may be used to contain auxilliary information for some + + + + Borenstein & Freed [Page 40] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + such messages, as indeed it is when the access-type is + "mail-server". Of the access-types defined by this + document, the phantom body is used only when the access-type + is "mail-server". In all other cases, the phantom body is + ignored. + + The only always-mandatory parameter for message/external- + body is "access-type"; all of the other parameters may be + mandatory or optional depending on the value of access-type. + + ACCESS-TYPE -- One or more case-insensitive words, + comma-separated, indicating supported access + mechanisms by which the file or data may be + obtained. Values include, but are not limited to, + "FTP", "ANON-FTP", "TFTP", "AFS", "LOCAL-FILE", + and "MAIL-SERVER". Future values, except for + experimental values beginning with "X-", must be + registered with IANA, as described in Appendix F . + + In addition, the following two parameters are optional for + ALL access-types: + + EXPIRATION -- The date (in the RFC 822 "date-time" + syntax, as extended by RFC 1123 to permit 4 digits + in the date field) after which the existence of + the external data is not guaranteed. + + SIZE -- The size (in octets) of the data. The + intent of this parameter is to help the recipient + decide whether or not to expend the necessary + resources to retrieve the external data. + + PERMISSION -- A field that indicates whether or + not it is expected that clients might also attempt + to overwrite the data. By default, or if + permission is "read", the assumption is that they + are not, and that if the data is retrieved once, + it is never needed again. If PERMISSION is "read- + write", this assumption is invalid, and any local + copy must be considered no more than a cache. + "Read" and "Read-write" are the only defined + values of permission. + + The precise semantics of the access-types defined here are + described in the sections that follow. + + 7.3.3.1 The "ftp" and "tftp" access-types + + An access-type of FTP or TFTP indicates that the message + body is accessible as a file using the FTP [RFC-959] or TFTP + [RFC-783] protocols, respectively. For these access-types, + the following additional parameters are mandatory: + + + + + + Borenstein & Freed [Page 41] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + NAME -- The name of the file that contains the + actual body data. + + SITE -- A machine from which the file may be + obtained, using the given protocol + + Before the data is retrieved, using these protocols, the + user will generally need to be asked to provide a login id + and a password for the machine named by the site parameter. + + In addition, the following optional parameters may also + appear when the access-type is FTP or ANON-FTP: + + DIRECTORY -- A directory from which the data named + by NAME should be retrieved. + + MODE -- A transfer mode for retrieving the + information, e.g. "image". + + 7.3.3.2 The "anon-ftp" access-type + + The "anon-ftp" access-type is identical to the "ftp" access + type, except that the user need not be asked to provide a + name and password for the specified site. Instead, the ftp + protocol will be used with login "anonymous" and a password + that corresponds to the user's email address. + + 7.3.3.3 The "local-file" and "afs" access-types + + An access-type of "local-file" indicates that the actual + body is accessible as a file on the local machine. An + access-type of "afs" indicates that the file is accessible + via the global AFS file system. In both cases, only a + single parameter is required: + + NAME -- The name of the file that contains the + actual body data. + + The following optional parameter may be used to describe the + locality of reference for the data, that is, the site or + sites at which the file is expected to be visible: + + SITE -- A domain specifier for a machine or set of + machines that are known to have access to the data + file. Asterisks may be used for wildcard matching + to a part of a domain name, such as + "*.bellcore.com", to indicate a set of machines on + which the data should be directly visible, while a + single asterisk may be used to indicate a file + that is expected to be universally available, + e.g., via a global file system. + + 7.3.3.4 The "mail-server" access-type + + + + + Borenstein & Freed [Page 42] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + The "mail-server" access-type indicates that the actual body + is available from a mail server. The mandatory parameter + for this access-type is: + + SERVER -- The email address of the mail server + from which the actual body data can be obtained. + + Because mail servers accept a variety of syntax, some of + which is multiline, the full command to be sent to a mail + server is not included as a parameter on the content-type + line. Instead, it may be provided as the "phantom body" + when the content-type is message/external-body and the + access-type is mail-server. + + Note that MIME does not define a mail server syntax. + Rather, it allows the inclusion of arbitrary mail server + commands in the phantom body. Implementations should + include the phantom body in the body of the message it sends + to the mail server address to retrieve the relevant data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 43] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.3.3.5 Examples and Further Explanations + + With the emerging possibility of very wide-area file + systems, it becomes very hard to know in advance the set of + machines where a file will and will not be accessible + directly from the file system. Therefore it may make sense + to provide both a file name, to be tried directly, and the + name of one or more sites from which the file is known to be + accessible. An implementation can try to retrieve remote + files using FTP or any other protocol, using anonymous file + retrieval or prompting the user for the necessary name and + password. If an external body is accessible via multiple + mechanisms, the sender may include multiple parts of type + message/external-body within an entity of type + multipart/alternative. + + However, the external-body mechanism is not intended to be + limited to file retrieval, as shown by the mail-server + access-type. Beyond this, one can imagine, for example, + using a video server for external references to video clips. + + If an entity is of type "message/external-body", then the + body of the entity will contain the header fields of the + encapsulated message. The body itself is to be found in the + external location. This means that if the body of the + "message/external-body" message contains two consecutive + CRLFs, everything after those pairs is NOT part of the + message itself. For most message/external-body messages, + this trailing area must simply be ignored. However, it is a + convenient place for additional data that cannot be included + in the content-type header field. In particular, if the + "access-type" value is "mail-server", then the trailing area + must contain commands to be sent to the mail server at the + address given by NAME@SITE, where NAME and SITE are the + values of the NAME and SITE parameters, respectively. + + The embedded message header fields which appear in the body + of the message/external-body data can be used to declare the + Content-type of the external body. Thus a complete + message/external-body message, referring to a document in + PostScript format, might look like this: + + From: Whomever + Subject: whatever + MIME-Version: 1.0 + Message-ID: id1@host.com + Content-Type: multipart/alternative; boundary=42 + + + --42 + Content-Type: message/external-body; + name="BodyFormats.ps"; + + + + + + Borenstein & Freed [Page 44] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + site="thumper.bellcore.com"; + access-type=ANON-FTP; + directory="pub"; + mode="image"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + + --42 + Content-Type: message/external-body; + name="/u/nsb/writing/rfcs/RFC-XXXX.ps"; + site="thumper.bellcore.com"; + access-type=AFS + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + + --42 + Content-Type: message/external-body; + access-type=mail-server + server="listserv@bogus.bitnet"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + + get rfc-xxxx doc + + --42-- + + Like the message/partial type, the message/external-body + type is intended to be transparent, that is, to convey the + data type in the external body rather than to convey a + message with a body of that type. Thus the headers on the + outer and inner parts must be merged using the same rules as + for message/partial. In particular, this means that the + Content-type header is overridden, but the From and Subject + headers are preserved. + + Note that since the external bodies are not transported as + mail, they need not conform to the 7-bit and line length + requirements, but might in fact be binary files. Thus a + Content-Transfer-Encoding is not generally necessary, though + it is permitted. + + Note that the body of a message of type "message/external- + body" is governed by the basic syntax for an RFC 822 + message. In particular, anything before the first + consecutive pair of CRLFs is header information, while + anything after it is body information, which is ignored for + most access-types. + + + + + + + + Borenstein & Freed [Page 45] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.4 The Application Content-Type + + The "application" Content-Type is to be used for data which + do not fit in any of the other categories, and particularly + for data to be processed by mail-based uses of application + programs. This is information which must be processed by an + application before it is viewable or usable to a user. + Expected uses for Content-Type application include mail- + based file transfer, spreadsheets, data for mail-based + scheduling systems, and languages for "active" + (computational) email. (The latter, in particular, can pose + security problems which should be understood by + implementors, and are considered in detail in the discussion + of the application/PostScript content-type.) + + For example, a meeting scheduler might define a standard + representation for information about proposed meeting dates. + An intelligent user agent would use this information to + conduct a dialog with the user, and might then send further + mail based on that dialog. More generally, there have been + several "active" messaging languages developed in which + programs in a suitably specialized language are sent through + the mail and automatically run in the recipient's + environment. + + Such applications may be defined as subtypes of the + "application" Content-Type. This document defines three + subtypes: octet-stream, ODA, and PostScript. + + In general, the subtype of application will often be the + name of the application for which the data are intended. + This does not mean, however, that any application program + name may be used freely as a subtype of application. Such + usages must be registered with IANA, as described in + Appendix F. + + 7.4.1 The Application/Octet-Stream (primary) subtype + + The primary subtype of application, "octet-stream", may be + used to indicate that a body contains binary data. The set + of possible parameters includes, but is not limited to: + + NAME -- a suggested name for the binary data if + stored as a file. + + TYPE -- the general type or category of binary + data. This is intended as information for the + human recipient rather than for any automatic + processing. + + CONVERSIONS -- the set of operations that have + been performed on the data before putting it in + the mail (and before any Content-Transfer-Encoding + that might have been applied). If multiple + + + + Borenstein & Freed [Page 46] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + conversions have occurred, they must be separated + by commas and specified in the order they were + applied -- that is, the leftmost conversion must + have occurred first, and conversions are undone + from right to left. Note that NO conversion + values are defined by this document. Any + conversion values that that do not begin with "X-" + must be preceded by a published specification and + by registration with IANA, as described in + Appendix F. + + PADDING -- the number of bits of padding that were + appended to the bitstream comprising the actual + contents to produce the enclosed byte-oriented + data. This is useful for enclosing a bitstream in + a body when the total number of bits is not a + multiple of the byte size. + + The values for these attributes are left undefined at + present, but may require specification in the future. An + example of a common (though UNIX-specific) usage might be: + + Content-Type: application/octet-stream; + name=foo.tar.Z; type=tar; + conversions="x-encrypt,x-compress" + + However, it should be noted that the use of such conversions + is explicitly discouraged due to a lack of portability and + standardization. The use of uuencode is particularly + discouraged, in favor of the Content-Transfer-Encoding + mechanism, which is both more standardized and more portable + across mail boundaries. + + The recommended action for an implementation that receives + application/octet-stream mail is to simply offer to put the + data in a file, with any Content-Transfer-Encoding undone, + or perhaps to use it as input to a user-specified process. + + To reduce the danger of transmitting rogue programs through + the mail, it is strongly recommended that implementations + NOT implement a path-search mechanism whereby an arbitrary + program named in the Content-Type parameter (e.g., an + "interpreter=" parameter) is found and executed using the + mail body as input. + + 7.4.2 The Application/PostScript subtype + + A Content-Type of "application/postscript" indicates a + PostScript program. The language is defined in + [POSTSCRIPT]. It is recommended that Postscript as sent + through email should use Postscript document structuring + conventions if at all possible, and correctly. + + + + + + Borenstein & Freed [Page 47] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + The execution of general-purpose PostScript interpreters + entails serious security risks, and implementors are + discouraged from simply sending PostScript email bodies to + "off-the-shelf" interpreters. While it is usually safe to + send PostScript to a printer, where the potential for harm + is greatly constrained, implementors should consider all of + the following before they add interactive display of + PostScript bodies to their mail readers. + + The remainder of this section outlines some, though probably + not all, of the possible problems with sending PostScript + through the mail. + + Dangerous operations in the PostScript language include, but + may not be limited to, the PostScript operators deletefile, + renamefile, filenameforall, and file. File is only + dangerous when applied to something other than standard + input or output. Implementations may also define additional + nonstandard file operators; these may also pose a threat to + security. Filenameforall, the wildcard file search + operator, may appear at first glance to be harmless. Note, + however, that this operator has the potential to reveal + information about what files the recipient has access to, + and this information may itself be sensitive. Message + senders should avoid the use of potentially dangerous file + operators, since these operators are quite likely to be + unavailable in secure PostScript implementations. Message- + receiving and -displaying software should either completely + disable all potentially dangerous file operators or take + special care not to delegate any special authority to their + operation. These operators should be viewed as being done by + an outside agency when interpreting PostScript documents. + Such disabling and/or checking should be done completely + outside of the reach of the PostScript language itself; care + should be taken to insure that no method exists for + reenabling full-function versions of these operators. + + The PostScript language provides facilities for exiting the + normal interpreter, or server, loop. Changes made in this + "outer" environment are customarily retained across + documents, and may in some cases be retained semipermanently + in nonvolatile memory. The operators associated with exiting + the interpreter loop have the potential to interfere with + subsequent document processing. As such, their unrestrained + use constitutes a threat of service denial. PostScript + operators that exit the interpreter loop include, but may + not be limited to, the exitserver and startjob operators. + Message-sending software should not generate PostScript that + depends on exiting the interpreter loop to operate. The + ability to exit will probably be unavailable in secure + PostScript implementations. Message-receiving and + -displaying software should, if possible, disable the + ability to make retained changes to the PostScript + environment. Eliminate the startjob and exitserver commands. + + + + Borenstein & Freed [Page 48] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + If these commands cannot be eliminated, at least set the + password associated with them to a hard-to-guess value. + + PostScript provides operators for setting system-wide and + device-specific parameters. These parameter settings may be + retained across jobs and may potentially pose a threat to + the correct operation of the interpreter. The PostScript + operators that set system and device parameters include, but + may not be limited to, the setsystemparams and setdevparams + operators. Message-sending software should not generate + PostScript that depends on the setting of system or device + parameters to operate correctly. The ability to set these + parameters will probably be unavailable in secure PostScript + implementations. Message-receiving and -displaying software + should, if possible, disable the ability to change system + and device parameters. If these operators cannot be + disabled, at least set the password associated with them to + a hard-to-guess value. + + Some PostScript implementations provide nonstandard + facilities for the direct loading and execution of machine + code. Such facilities are quite obviously open to + substantial abuse. Message-sending software should not + make use of such features. Besides being totally hardware- + specific, they are also likely to be unavailable in secure + implementations of PostScript. Message-receiving and + -displaying software should not allow such operators to be + used if they exist. + + PostScript is an extensible language, and many, if not most, + implementations of it provide a number of their own + extensions. This document does not deal with such extensions + explicitly since they constitute an unknown factor. + Message-sending software should not make use of nonstandard + extensions; they are likely to be missing from some + implementations. Message-receiving and -displaying software + should make sure that any nonstandard PostScript operators + are secure and don't present any kind of threat. + + It is possible to write PostScript that consumes huge + amounts of various system resources. It is also possible to + write PostScript programs that loop infinitely. Both types + of programs have the potential to cause damage if sent to + unsuspecting recipients. Message-sending software should + avoid the construction and dissemination of such programs, + which is antisocial. Message-receiving and -displaying + software should provide appropriate mechanisms to abort + processing of a document after a reasonable amount of time + has elapsed. In addition, PostScript interpreters should be + limited to the consumption of only a reasonable amount of + any given system resource. + + Finally, bugs may exist in some PostScript interpreters + which could possibly be exploited to gain unauthorized + + + + Borenstein & Freed [Page 49] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + access to a recipient's system. Apart from noting this + possibility, there is no specific action to take to prevent + this, apart from the timely correction of such bugs if any + are found. + + 7.4.3 The Application/ODA subtype + + The "ODA" subtype of application is used to indicate that a + body contains information encoded according to the Office + Document Architecture [ODA] standards, using the ODIF + representation format. For application/oda, the Content- + Type line should also specify an attribute/value pair that + indicates the document application profile (DAP), using the + key word "profile". Thus an appropriate header field might + look like this: + + Content-Type: application/oda; profile=Q112 + + Consult the ODA standard [ODA] for further information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 50] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 7.5 The Image Content-Type + + A Content-Type of "image" indicates that the bodycontains an + image. The subtype names the specific image format. These + names are case insensitive. Two initial subtypes are "jpeg" + for the JPEG format, JFIF encoding, and "gif" for GIF format + [GIF]. + + The list of image subtypes given here is neither exclusive + nor exhaustive, and is expected to grow as more types are + registered with IANA, as described in Appendix F. + + 7.6 The Audio Content-Type + + A Content-Type of "audio" indicates that the body contains + audio data. Although there is not yet a consensus on an + "ideal" audio format for use with computers, there is a + pressing need for a format capable of providing + interoperable behavior. + + The initial subtype of "basic" is specified to meet this + requirement by providing an absolutely minimal lowest common + denominator audio format. It is expected that richer + formats for higher quality and/or lower bandwidth audio will + be defined by a later document. + + The content of the "audio/basic" subtype is audio encoded + using 8-bit ISDN u-law [PCM]. When this subtype is present, + a sample rate of 8000 Hz and a single channel is assumed. + + 7.7 The Video Content-Type + + A Content-Type of "video" indicates that the body contains a + time-varying-picture image, possibly with color and + coordinated sound. The term "video" is used extremely + generically, rather than with reference to any particular + technology or format, and is not meant to preclude subtypes + such as animated drawings encoded compactly. The subtype + "mpeg" refers to video coded according to the MPEG standard + [MPEG]. + + Note that although in general this document strongly + discourages the mixing of multiple media in a single body, + it is recognized that many so-called "video" formats include + a representation for synchronized audio, and this is + explicitly permitted for subtypes of "video". + + 7.8 Experimental Content-Type Values + + A Content-Type value beginning with the characters "X-" is a + private value, to be used by consenting mail systems by + mutual agreement. Any format without a rigorous and public + definition must be named with an "X-" prefix, and publicly + specified values shall never begin with "X-". (Older + + + + Borenstein & Freed [Page 51] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + versions of the widely-used Andrew system use the "X-BE2" + name, so new systems should probably choose a different + name.) + + In general, the use of "X-" top-level types is strongly + discouraged. Implementors should invent subtypes of the + existing types whenever possible. The invention of new + types is intended to be restricted primarily to the + development of new media types for email, such as digital + odors or holography, and not for new data formats in + general. In many cases, a subtype of application will be + more appropriate than a new top-level type. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 52] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Summary + + Using the MIME-Version, Content-Type, and Content-Transfer- + Encoding header fields, it is possible to include, in a + standardized way, arbitrary types of data objects with RFC + 822 conformant mail messages. No restrictions imposed by + either RFC 821 or RFC 822 are violated, and care has been + taken to avoid problems caused by additional restrictions + imposed by the characteristics of some Internet mail + transport mechanisms (see Appendix B). The "multipart" and + "message" Content-Types allow mixing and hierarchical + structuring of objects of different types in a single + message. Further Content-Types provide a standardized + mechanism for tagging messages or body parts as audio, + image, or several other kinds of data. A distinguished + parameter syntax allows further specification of data format + details, particularly the specification of alternate + character sets. Additional optional header fields provide + mechanisms for certain extensions deemed desirable by many + implementors. Finally, a number of useful Content-Types are + defined for general use by consenting user agents, notably + text/richtext, message/partial, and message/external-body. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 53] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Acknowledgements + + This document is the result of the collective effort of a + large number of people, at several IETF meetings, on the + IETF-SMTP and IETF-822 mailing lists, and elsewhere. + Although any enumeration seems doomed to suffer from + egregious omissions, the following are among the many + contributors to this effort: + + Harald Tveit Alvestrand Timo Lehtinen + Randall Atkinson John R. MacMillan + Philippe Brandon Rick McGowan + Kevin Carosso Leo Mclaughlin + Uhhyung Choi Goli Montaser-Kohsari + Cristian Constantinof Keith Moore + Mark Crispin Tom Moore + Dave Crocker Erik Naggum + Terry Crowley Mark Needleman + Walt Daniels John Noerenberg + Frank Dawson Mats Ohrman + Hitoshi Doi Julian Onions + Kevin Donnelly Michael Patton + Keith Edwards David J. Pepper + Chris Eich Blake C. Ramsdell + Johnny Eriksson Luc Rooijakkers + Craig Everhart Marshall T. Rose + Patrik Faeltstroem Jonathan Rosenberg + Erik E. Fair Jan Rynning + Roger Fajman Harri Salminen + Alain Fontaine Michael Sanderson + James M. Galvin Masahiro Sekiguchi + Philip Gladstone Mark Sherman + Thomas Gordon Keld Simonsen + Phill Gross Bob Smart + James Hamilton Peter Speck + Steve Hardcastle-Kille Henry Spencer + David Herron Einar Stefferud + Bruce Howard Michael Stein + Bill Janssen Klaus Steinberger + Olle Jaernefors Peter Svanberg + Risto Kankkunen James Thompson + Phil Karn Steve Uhler + Alan Katz Stuart Vance + Tim Kehres Erik van der Poel + Neil Katin Guido van Rossum + Kyuho Kim Peter Vanderbilt + Anders Klemets Greg Vaudreuil + John Klensin Ed Vielmetti + Valdis Kletniek Ryan Waldron + Jim Knowles Wally Wedel + Stev Knowles Sven-Ove Westberg + Bob Kummerfeld Brian Wideen + + + + + + Borenstein & Freed [Page 54] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Pekka Kytolaakso John Wobus + Stellan Lagerstr.m Glenn Wright + Vincent Lau Rayan Zachariassen + Donald Lindsay David Zimmerman + The authors apologize for any omissions from this list, + which are certainly unintentional. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 55] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix A -- Minimal MIME-Conformance + + The mechanisms described in this document are open-ended. + It is definitely not expected that all implementations will + support all of the Content-Types described, nor that they + will all share the same extensions. In order to promote + interoperability, however, it is useful to define the + concept of "MIME-conformance" to define a certain level of + implementation that allows the useful interworking of + messages with content that differs from US ASCII text. In + this section, we specify the requirements for such + conformance. + + A mail user agent that is MIME-conformant MUST: + + 1. Always generate a "MIME-Version: 1.0" header + field. + + 2. Recognize the Content-Transfer-Encoding header + field, and decode all received data encoded with + either the quoted-printable or base64 + implementations. Encode any data sent that is + not in seven-bit mail-ready representation using + one of these transformations and include the + appropriate Content-Transfer-Encoding header + field, unless the underlying transport mechanism + supports non-seven-bit data, as SMTP does not. + + 3. Recognize and interpret the Content-Type + header field, and avoid showing users raw data + with a Content-Type field other than text. Be + able to send at least text/plain messages, with + the character set specified as a parameter if it + is not US-ASCII. + + 4. Explicitly handle the following Content-Type + values, to at least the following extents: + + Text: + -- Recognize and display "text" mail + with the character set "US-ASCII." + -- Recognize other character sets at + least to the extent of being able + to inform the user about what + character set the message uses. + -- Recognize the "ISO-8859-*" character + sets to the extent of being able to + display those characters that are + common to ISO-8859-* and US-ASCII, + namely all characters represented + by octet values 0-127. + -- For unrecognized subtypes, show or + offer to show the user the "raw" + version of the data. An ability at + + + + Borenstein & Freed [Page 56] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + least to convert "text/richtext" to + plain text, as shown in Appendix D, + is encouraged, but not required for + conformance. + Message: + --Recognize and display at least the + primary (822) encapsulation. + Multipart: + -- Recognize the primary (mixed) + subtype. Display all relevant + information on the message level + and the body part header level and + then display or offer to display + each of the body parts + individually. + -- Recognize the "alternative" subtype, + and avoid showing the user + redundant parts of + multipart/alternative mail. + -- Treat any unrecognized subtypes as if + they were "mixed". + Application: + -- Offer the ability to remove either of + the two types of Content-Transfer- + Encoding defined in this document + and put the resulting information + in a user file. + + 5. Upon encountering any unrecognized Content- + Type, an implementation must treat it as if it had + a Content-Type of "application/octet-stream" with + no parameter sub-arguments. How such data are + handled is up to an implementation, but likely + options for handling such unrecognized data + include offering the user to write it into a file + (decoded from its mail transport format) or + offering the user to name a program to which the + decoded data should be passed as input. + Unrecognized predefined types, which in a MIME- + conformant mailer might still include audio, + image, or video, should also be treated in this + way. + + A user agent that meets the above conditions is said to be + MIME-conformant. The meaning of this phrase is that it is + assumed to be "safe" to send virtually any kind of + properly-marked data to users of such mail systems, because + such systems will at least be able to treat the data as + undifferentiated binary, and will not simply splash it onto + the screen of unsuspecting users. There is another sense + in which it is always "safe" to send data in a format that + is MIME-conformant, which is that such data will not break + or be broken by any known systems that are conformant with + RFC 821 and RFC 822. User agents that are MIME-conformant + + + + Borenstein & Freed [Page 57] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + have the additional guarantee that the user will not be + shown data that were never intended to be viewed as text. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 58] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix B -- General Guidelines For Sending Email Data + + Internet email is not a perfect, homogeneous system. Mail + may become corrupted at several stages in its travel to a + final destination. Specifically, email sent throughout the + Internet may travel across many networking technologies. + Many networking and mail technologies do not support the + full functionality possible in the SMTP transport + environment. Mail traversing these systems is likely to be + modified in such a way that it can be transported. + + There exist many widely-deployed non-conformant MTAs in the + Internet. These MTAs, speaking the SMTP protocol, alter + messages on the fly to take advantage of the internal data + structure of the hosts they are implemented on, or are just + plain broken. + + The following guidelines may be useful to anyone devising a + data format (Content-Type) that will survive the widest + range of networking technologies and known broken MTAs + unscathed. Note that anything encoded in the base64 + encoding will satisfy these rules, but that some well-known + mechanisms, notably the UNIX uuencode facility, will not. + Note also that anything encoded in the Quoted-Printable + encoding will survive most gateways intact, but possibly not + some gateways to systems that use the EBCDIC character set. + + (1) Under some circumstances the encoding used for + data may change as part of normal gateway or user + agent operation. In particular, conversion from + base64 to quoted-printable and vice versa may be + necessary. This may result in the confusion of + CRLF sequences with line breaks in text body + parts. As such, the persistence of CRLF as + something other than a line break should not be + relied on. + + (2) Many systems may elect to represent and store + text data using local newline conventions. Local + newline conventions may not match the RFC822 CRLF + convention -- systems are known that use plain CR, + plain LF, CRLF, or counted records. The result is + that isolated CR and LF characters are not well + tolerated in general; they may be lost or + converted to delimiters on some systems, and hence + should not be relied on. + + (3) TAB (HT) characters may be misinterpreted or + may be automatically converted to variable numbers + of spaces. This is unavoidable in some + environments, notably those not based on the ASCII + character set. Such conversion is STRONGLY + DISCOURAGED, but it may occur, and mail formats + should not rely on the persistence of TAB (HT) + + + + Borenstein & Freed [Page 59] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + characters. + + (4) Lines longer than 76 characters may be wrapped + or truncated in some environments. Line wrapping + and line truncation are STRONGLY DISCOURAGED, but + unavoidable in some cases. Applications which + require long lines should somehow differentiate + between soft and hard line breaks. (A simple way + to do this is to use the quoted-printable + encoding.) + + (5) Trailing "white space" characters (SPACE, TAB + (HT)) on a line may be discarded by some transport + agents, while other transport agents may pad lines + with these characters so that all lines in a mail + file are of equal length. The persistence of + trailing white space, therefore, should not be + relied on. + + (6) Many mail domains use variations on the ASCII + character set, or use character sets such as + EBCDIC which contain most but not all of the US- + ASCII characters. The correct translation of + characters not in the "invariant" set cannot be + depended on across character converting gateways. + For example, this situation is a problem when + sending uuencoded information across BITNET, an + EBCDIC system. Similar problems can occur without + crossing a gateway, since many Internet hosts use + character sets other than ASCII internally. The + definition of Printable Strings in X.400 adds + further restrictions in certain special cases. In + particular, the only characters that are known to + be consistent across all gateways are the 73 + characters that correspond to the upper and lower + case letters A-Z and a-z, the 10 digits 0-9, and + the following eleven special characters: + + "'" (ASCII code 39) + "(" (ASCII code 40) + ")" (ASCII code 41) + "+" (ASCII code 43) + "," (ASCII code 44) + "-" (ASCII code 45) + "." (ASCII code 46) + "/" (ASCII code 47) + ":" (ASCII code 58) + "=" (ASCII code 61) + "?" (ASCII code 63) + + A maximally portable mail representation, such as + the base64 encoding, will confine itself to + relatively short lines of text in which the only + meaningful characters are taken from this set of + + + + Borenstein & Freed [Page 60] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + 73 characters. + + Please note that the above list is NOT a list of recommended + practices for MTAs. RFC 821 MTAs are prohibited from + altering the character of white space or wrapping long + lines. These BAD and illegal practices are known to occur + on established networks, and implementions should be robust + in dealing with the bad effects they can cause. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 61] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix C -- A Complex Multipart Example + + What follows is the outline of a complex multipart message. + This message has five parts to be displayed serially: two + introductory plain text parts, an embedded multipart + message, a richtext part, and a closing encapsulated text + message in a non-ASCII character set. The embedded + multipart message has two parts to be displayed in parallel, + a picture and an audio fragment. + + MIME-Version: 1.0 + From: Nathaniel Borenstein + Subject: A multipart example + Content-Type: multipart/mixed; + boundary=unique-boundary-1 + + This is the preamble area of a multipart message. + Mail readers that understand multipart format + should ignore this preamble. + If you are reading this text, you might want to + consider changing to a mail reader that understands + how to properly display multipart messages. + --unique-boundary-1 + + ...Some text appears here... + [Note that the preceding blank line means + no header fields were given and this is text, + with charset US ASCII. It could have been + done with explicit typing as in the next part.] + + --unique-boundary-1 + Content-type: text/plain; charset=US-ASCII + + This could have been part of the previous part, + but illustrates explicit versus implicit + typing of body parts. + + --unique-boundary-1 + Content-Type: multipart/parallel; + boundary=unique-boundary-2 + + + --unique-boundary-2 + Content-Type: audio/basic + Content-Transfer-Encoding: base64 + + ... base64-encoded 8000 Hz single-channel + u-law-format audio data goes here.... + + --unique-boundary-2 + Content-Type: image/gif + Content-Transfer-Encoding: Base64 + + + + + + Borenstein & Freed [Page 62] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + ... base64-encoded image data goes here.... + + --unique-boundary-2-- + + --unique-boundary-1 + Content-type: text/richtext + + This is richtext. + Isn't it + cool? + + --unique-boundary-1 + Content-Type: message/rfc822 + + From: (name in US-ASCII) + Subject: (subject in US-ASCII) + Content-Type: Text/plain; charset=ISO-8859-1 + Content-Transfer-Encoding: Quoted-printable + + ... Additional text in ISO-8859-1 goes here ... + + --unique-boundary-1-- + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 63] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix D -- A Simple Richtext-to-Text Translator in C + + One of the major goals in the design of the richtext subtype + of the text Content-Type is to make formatted text so simple + that even text-only mailers will implement richtext-to- + plain-text translators, thus increasing the likelihood that + multifont text will become "safe" to use very widely. To + demonstrate this simplicity, what follows is an extremely + simple 44-line C program that converts richtext input into + plain text output: + + #include + #include + main() { + int c, i; + char token[50]; + + while((c = getc(stdin)) != EOF) { + if (c == '<') { + for (i=0; (i<49 && (c = getc(stdin)) != '>' + && c != EOF); ++i) { + token[i] = isupper(c) ? tolower(c) : c; + } + if (c == EOF) break; + if (c != '>') while ((c = getc(stdin)) != + '>' + && c != EOF) {;} + if (c == EOF) break; + token[i] = '\0'; + if (!strcmp(token, "lt")) { + putc('<', stdout); + } else if (!strcmp(token, "nl")) { + putc('\n', stdout); + } else if (!strcmp(token, "/paragraph")) { + fputs("\n\n", stdout); + } else if (!strcmp(token, "comment")) { + int commct=1; + while (commct > 0) { + while ((c = getc(stdin)) != '<' + && c != EOF) ; + if (c == EOF) break; + for (i=0; (c = getc(stdin)) != '>' + && c != EOF; ++i) { + token[i] = isupper(c) ? + tolower(c) : c; + } + if (c== EOF) break; + token[i] = NULL; + if (!strcmp(token, "/comment")) -- + commct; + if (!strcmp(token, "comment")) + ++commct; + + + + + + Borenstein & Freed [Page 64] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + } + } /* Ignore all other tokens */ + } else if (c != '\n') putc(c, stdout); + } + putc('\n', stdout); /* for good measure */ + } + It should be noted that one can do considerably better than + this in displaying richtext data on a dumb terminal. In + particular, one can replace font information such as "bold" + with textual emphasis (like *this* or _T_H_I_S_). One can + also properly handle the richtext formatting commands + regarding indentation, justification, and others. However, + the above program is all that is necessary in order to + present richtext on a dumb terminal. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 65] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix E -- Collected Grammar + + This appendix contains the complete BNF grammar for all the + syntax specified by this document. + + By itself, however, this grammar is incomplete. It refers + to several entities that are defined by RFC 822. Rather + than reproduce those definitions here, and risk + unintentional differences between the two, this document + simply refers the reader to RFC 822 for the remaining + definitions. Wherever a term is undefined, it refers to the + RFC 822 definition. + + attribute := token + + body-part = <"message" as defined in RFC 822, + with all header fields optional, and with the + specified delimiter not occurring anywhere in + the message body, either on a line by itself + or as a substring anywhere.> + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / + "_" + / "," / "-" / "." / "/" / ":" / "=" / "?" + + close-delimiter := delimiter "--" + + Content-Description := *text + + Content-ID := msg-id + + Content-Transfer-Encoding := "BASE64" / "QUOTED- + PRINTABLE" / + "8BIT" / "7BIT" / + "BINARY" / x-token + + Content-Type := type "/" subtype *[";" parameter] + + delimiter := CRLF "--" boundary ; taken from Content-Type + field. + ; when content-type is + multipart + ; There should be no space + ; between "--" and boundary. + + encapsulation := delimiter CRLF body-part + + epilogue := *text ; to be ignored upon + receipt. + + + + + Borenstein & Freed [Page 66] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + MIME-Version := 1*text + + multipart-body := preamble 1*encapsulation close-delimiter + epilogue + + parameter := attribute "=" value + + preamble := *text ; to be ignored upon + receipt. + + subtype := token + + token := 1* + + tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in + / "," / ";" / ":" / "\" / <"> ; quoted-string, + / "/" / "[" / "]" / "?" / "." ; to use within + / "=" ; parameter values + + + type := "application" / "audio" ; case- + insensitive + / "image" / "message" + / "multipart" / "text" + / "video" / x-token + + value := token / quoted-string + + x-token := + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 67] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix F -- IANA Registration Procedures + + MIME has been carefully designed to have extensible + mechanisms, and it is expected that the set of content- + type/subtype pairs and their associated parameters will grow + significantly with time. Several other MIME fields, notably + character set names, access-type parameters for the + message/external-body type, conversions parameters for the + application type, and possibly even Content-Transfer- + Encoding values, are likely to have new values defined over + time. In order to ensure that the set of such values is + developed in an orderly, well-specified, and public manner, + MIME defines a registration process which uses the Internet + Assigned Numbers Authority (IANA) as a central registry for + such values. + + In general, parameters in the content-type header field are + used to convey supplemental information for various content + types, and their use is defined when the content-type and + subtype are defined. New parameters should not be defined + as a way to introduce new functionality. + + In order to simplify and standardize the registration + process, this appendix gives templates for the registration + of new values with IANA. Each of these is given in the form + of an email message template, to be filled in by the + registering party. + + F.1 Registration of New Content-type/subtype Values + + Note that MIME is generally expected to be extended by + subtypes. If a new fundamental top-level type is needed, + its specification should be published as an RFC or + submitted in a form suitable to become an RFC, and be + subject to the Internet standards process. + + To: IANA@isi.edu + Subject: Registration of new MIME content-type/subtype + + MIME type name: + + (If the above is not an existing top-level MIME type, + please explain why an existing type cannot be used.) + + MIME subtype name: + + Required parameters: + + Optional parameters: + + Encoding considerations: + + Security considerations: + + + + + Borenstein & Freed [Page 68] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be if a new top-level type is being defined, and + must be a publicly available specification in any + case.) + + Person & email address to contact for further + information: + F.2 Registration of New Character Set Values + + To: IANA@isi.edu + Subject: Registration of new MIME character set value + + MIME character set name: + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be or an international standard.) + + Person & email address to contact for further + information: + + F.3 Registration of New Access-type Values for + Message/external-body + + To: IANA@isi.edu + Subject: Registration of new MIME Access-type for + Message/external-body content-type + + MIME access-type name: + + Required parameters: + + Optional parameters: + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be.) + + Person & email address to contact for further + information: + + + F.4 Registration of New Conversions Values for Application + + To: IANA@isi.edu + Subject: Registration of new MIME Conversions value + for Application content-type + + MIME Conversions name: + + + + + Borenstein & Freed [Page 69] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be.) + + Person & email address to contact for further + information: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 70] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix G -- Summary of the Seven Content-types + + Content-type: text + + Subtypes defined by this document: plain, richtext + + Important Parameters: charset + + Encoding notes: quoted-printable generally preferred if an + encoding is needed and the character set is mostly an + ASCII superset. + + Security considerations: Rich text formats such as TeX and + Troff often contain mechanisms for executing arbitrary + commands or file system operations, and should not be + used automatically unless these security problems have + been addressed. Even plain text may contain control + characters that can be used to exploit the capabilities + of "intelligent" terminals and cause security + violations. User interfaces designed to run on such + terminals should be aware of and try to prevent such + problems. + ________________________________________________________________ + + Content-type: multipart + + Subtypes defined by this document: mixed, alternative, + digest, parallel. + + Important Parameters: boundary + + Encoding notes: No content-transfer-encoding is permitted. + + ________________________________________________________________ + + Content-type: message + + Subtypes defined by this document: rfc822, partial, + external-body + + Important Parameters: id, number, total + + Encoding notes: No content-transfer-encoding is permitted. + + ________________________________________________________________ + + Content-type: application + + Subtypes defined by this document: octet-stream, + postscript, oda + + Important Parameters: profile + + + + + + Borenstein & Freed [Page 71] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Encoding notes: base64 generally preferred for octet-stream + or other unreadable subtypes. + + Security considerations: This type is intended for the + transmission of data to be interpreted by locally-installed + programs. If used, for example, to transmit executable + binary programs or programs in general-purpose interpreted + languages, such as LISP programs or shell scripts, severe + security problems could result. In general, authors of + mail-reading agents are cautioned against giving their + systems the power to execute mail-based application data + without carefully considering the security implications. + While it is certainly possible to define safe application + formats and even safe interpreters for unsafe formats, each + interpreter should be evaluated separately for possible + security problems. + ________________________________________________________________ + + Content-type: image + + Subtypes defined by this document: jpeg, gif + + Important Parameters: none + + Encoding notes: base64 generally preferred + + ________________________________________________________________ + + Content-type: audio + + Subtypes defined by this document: basic + + Important Parameters: none + + Encoding notes: base64 generally preferred + + ________________________________________________________________ + + Content-type: video + + Subtypes defined by this document: mpeg + + Important Parameters: none + + Encoding notes: base64 generally preferred + + + + + + + + + + + + + Borenstein & Freed [Page 72] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Appendix H -- Canonical Encoding Model + + + + There was some confusion, in earlier drafts of this memo, + regarding the model for when email data was to be converted + to canonical form and encoded, and in particular how this + process would affect the treatment of CRLFs, given that the + representation of newlines varies greatly from system to + system. For this reason, a canonical model for encoding is + presented below. + + The process of composing a MIME message part can be modelled + as being done in a number of steps. Note that these steps + are roughly similar to those steps used in RFC1113: + + Step 1. Creation of local form. + + The body part to be transmitted is created in the system's + native format. The native character set is used, and where + appropriate local end of line conventions are used as well. + The may be a UNIX-style text file, or a Sun raster image, or + a VMS indexed file, or audio data in a system-dependent + format stored only in memory, or anything else that + corresponds to the local model for the representation of + some form of information. + + Step 2. Conversion to canonical form. + + The entire body part, including "out-of-band" information + such as record lengths and possibly file attribute + information, is converted to a universal canonical form. + The specific content type of the body part as well as its + associated attributes dictate the nature of the canonical + form that is used. Conversion to the proper canonical form + may involve character set conversion, transformation of + audio data, compression, or various other operations + specific to the various content types. + + For example, in the case of text/plain data, the text must + be converted to a supported character set and lines must be + delimited with CRLF delimiters in accordance with RFC822. + Note that the restriction on line lengths implied by RFC822 + is eliminated if the next step employs either quoted- + printable or base64 encoding. + + Step 3. Apply transfer encoding. + + A Content-Transfer-Encoding appropriate for this body part + is applied. Note that there is no fixed relationship + between the content type and the transfer encoding. In + particular, it may be appropriate to base the choice of + base64 or quoted-printable on character frequency counts + which are specific to a given instance of body part. + + + + Borenstein & Freed [Page 73] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Step 4. Insertion into message. + + The encoded object is inserted into a MIME message with + appropriate body part headers and boundary markers. + + It is vital to note that these steps are only a model; they + are specifically NOT a blueprint for how an actual system + would be built. In particular, the model fails to account + for two common designs: + + 1. In many cases the conversion to a canonical + form prior to encoding will be subsumed into the + encoder itself, which understands local formats + directly. For example, the local newline + convention for text bodyparts might be carried + through to the encoder itself along with knowledge + of what that format is. + + 2. The output of the encoders may have to pass + through one or more additional steps prior to + being transmitted as a message. As such, the + output of the encoder may not be compliant with + the formats specified by RFC822. In particular, + once again it may be appropriate for the + converter's output to be expressed using local + newline conventions rather than using the standard + RFC822 CRLF delimiters. + + Other implementation variations are conceivable as well. + The only important aspect of this discussion is that the + resulting messages are consistent with those produced by the + model described here. + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 74] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + References + + [US-ASCII] Coded Character Set--7-Bit American Standard Code + for Information Interchange, ANSI X3.4-1986. + + [ATK] Borenstein, Nathaniel S., Multimedia Applications + Development with the Andrew Toolkit, Prentice-Hall, 1990. + + [GIF] Graphics Interchange Format (Version 89a), Compuserve, + Inc., Columbus, Ohio, 1990. + + [ISO-2022] International Standard--Information Processing-- + ISO 7-bit and 8-bit coded character sets--Code extension + techniques, ISO 2022:1986. + + [ISO-8859] Information Processing -- 8-bit Single-Byte Coded + Graphic Character Sets -- Part 1: Latin Alphabet No. 1, ISO + 8859-1:1987. Part 2: Latin alphabet No. 2, ISO 8859-2, + 1987. Part 3: Latin alphabet No. 3, ISO 8859-3, 1988. Part + 4: Latin alphabet No. 4, ISO 8859-4, 1988. Part 5: + Latin/Cyrillic alphabet, ISO 8859-5, 1988. Part 6: + Latin/Arabic alphabet, ISO 8859-6, 1987. Part 7: + Latin/Greek alphabet, ISO 8859-7, 1987. Part 8: + Latin/Hebrew alphabet, ISO 8859-8, 1988. Part 9: Latin + alphabet No. 5, ISO 8859-9, 1990. + + [ISO-646] International Standard--Information Processing-- + ISO 7-bit coded character set for information interchange, + ISO 646:1983. + + [MPEG] Video Coding Draft Standard ISO 11172 CD, ISO + IEC/TJC1/SC2/WG11 (Motion Picture Experts Group), May, 1991. + + [ODA] ISO 8613; Information Processing: Text and Office + System; Office Document Architecture (ODA) and Interchange + Format (ODIF), Part 1-8, 1989. + + [PCM] CCITT, Fascicle III.4 - Recommendation G.711, Geneva, + 1972, "Pulse Code Modulation (PCM) of Voice Frequencies". + + [POSTSCRIPT] Adobe Systems, Inc., PostScript Language + Reference Manual, Addison-Wesley, 1985. + + [X400] Schicker, Pietro, "Message Handling Systems, X.400", + Message Handling Systems and Distributed Applications, E. + Stefferud, O-j. Jacobsen, and P. Schicker, eds., North- + Holland, 1989, pp. 3-41. + + [RFC-783] Sollins, K.R. TFTP Protocol (revision 2). June, + 1981, MIT, RFC-783. + + [RFC-821] Postel, J.B. Simple Mail Transfer Protocol. + August, 1982, USC/Information Sciences Institute, RFC-821. + + + + + Borenstein & Freed [Page 75] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + [RFC-822] Crocker, D. Standard for the format of ARPA + Internet text messages. August, 1982, UDEL, RFC-822. + + [RFC-934] Rose, M.T.; Stefferud, E.A. Proposed standard + for message encapsulation. January, 1985, Delaware + and NMA, RFC-934. + + [RFC-959] Postel, J.B.; Reynolds, J.K. File Transfer + Protocol. October, 1985, USC/Information Sciences + Institute, RFC-959. + + [RFC-1049] Sirbu, M.A. Content-Type header field for + Internet messages. March, 1988, CMU, RFC-1049. + + [RFC-1113] Linn, J. Privacy enhancement for Internet + electronic mail: Part I - message encipherment and + authentication procedures. August, 1989, IAB Privacy Task + Force, RFC-1113. + + [RFC-1154] Robinson, D.; Ullmann, R. Encoding header field + for Internet messages. April, 1990, Prime Computer, + Inc., RFC-1154. + + [RFC-1342] Moore, Keith, Representation of Non-Ascii Text in + Internet Message Headers. June, 1992, University of + Tennessee, RFC-1342. + + Security Considerations + + Security issues are discussed in Section 7.4.2 and in + Appendix G. Implementors should pay special attention to + the security implications of any mail content-types that can + cause the remote execution of any actions in the recipient's + environment. In such cases, the discussion of the + applicaton/postscript content-type in Section 7.4.2 may + serve as a model for considering other content-types with + remote execution capabilities. + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 76] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + Authors' Addresses + + For more information, the authors of this document may be + contacted via Internet mail: + + Nathaniel S. Borenstein + MRE 2D-296, Bellcore + 445 South St. + Morristown, NJ 07962-1910 + + Phone: +1 201 829 4270 + Fax: +1 201 829 7019 + Email: nsb@bellcore.com + + + Ned Freed + Innosoft International, Inc. + 250 West First Street + Suite 240 + Claremont, CA 91711 + + Phone: +1 714 624 7907 + Fax: +1 714 621 5319 + Email: ned@innosoft.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page 77] + + + + + RFC 1341MIME: Multipurpose Internet Mail ExtensionsJune 1992 + + + + + + THIS PAGE INTENTIONALLY LEFT BLANK. + + Please discard this page and place the following table of + contents after the title page. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page i] + + + + + + + + + Table of Contents + + + 1 Introduction....................................... 1 + 2 Notations, Conventions, and Generic BNF Grammar.... 3 + 3 The MIME-Version Header Field...................... 5 + 4 The Content-Type Header Field...................... 6 + 5 The Content-Transfer-Encoding Header Field......... 10 + 5.1 Quoted-Printable Content-Transfer-Encoding......... 14 + 5.2 Base64 Content-Transfer-Encoding................... 17 + 6 Additional Optional Content- Header Fields......... 19 + 6.1 Optional Content-ID Header Field................... 19 + 6.2 Optional Content-Description Header Field.......... 19 + 7 The Predefined Content-Type Values................. 20 + 7.1 The Text Content-Type.............................. 20 + 7.1.1 The charset parameter.............................. 20 + 7.1.2 The Text/plain subtype............................. 23 + 7.1.3 The Text/richtext subtype.......................... 23 + 7.2 The Multipart Content-Type......................... 29 + 7.2.1 Multipart: The common syntax...................... 30 + 7.2.2 The Multipart/mixed (primary) subtype.............. 34 + 7.2.3 The Multipart/alternative subtype.................. 34 + 7.2.4 The Multipart/digest subtype....................... 36 + 7.2.5 The Multipart/parallel subtype..................... 36 + 7.3 The Message Content-Type........................... 37 + 7.3.1 The Message/rfc822 (primary) subtype............... 37 + 7.3.2 The Message/Partial subtype........................ 37 + 7.3.3 The Message/External-Body subtype.................. 40 + 7.4 The Application Content-Type....................... 46 + 7.4.1 The Application/Octet-Stream (primary) subtype..... 46 + 7.4.2 The Application/PostScript subtype................. 47 + 7.4.3 The Application/ODA subtype........................ 50 + 7.5 The Image Content-Type............................. 51 + 7.6 The Audio Content-Type............................. 51 + 7.7 The Video Content-Type............................. 51 + 7.8 Experimental Content-Type Values................... 51 + Summary............................................ 53 + Acknowledgements................................... 54 + Appendix A -- Minimal MIME-Conformance............. 56 + Appendix B -- General Guidelines For Sending Email Data59 + Appendix C -- A Complex Multipart Example.......... 62 + Appendix D -- A Simple Richtext-to-Text Translator in C64 + Appendix E -- Collected Grammar.................... 66 + Appendix F -- IANA Registration Procedures......... 68 + F.1 Registration of New Content-type/subtype Values..68 + F.2 Registration of New Character Set Values...... 69 + F.3 Registration of New Access-type Values for Message/external-body69 + F.4 Registration of New Conversions Values for Application69 + Appendix G -- Summary of the Seven Content-types... 71 + Appendix H -- Canonical Encoding Model............. 73 + References......................................... 75 + Security Considerations............................ 76 + Authors' Addresses................................. 77 + + + + Borenstein & Freed [Page ii] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Borenstein & Freed [Page iii] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1521.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1521.txt new file mode 100644 index 00000000..074ba415 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1521.txt @@ -0,0 +1,4539 @@ + + + + + + +Network Working Group N. Borenstein +Request for Comments: 1521 Bellcore +Obsoletes: 1341 N. Freed +Category: Standards Track Innosoft + September 1993 + + + MIME (Multipurpose Internet Mail Extensions) Part One: + Mechanisms for Specifying and Describing + the Format of Internet Message Bodies + +Status of this Memo + + This RFC specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" for the standardization state and status + of this protocol. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822 defines a message representation protocol which + specifies considerable detail about message headers, but which leaves + the message content, or message body, as flat ASCII text. This + document redefines the format of message bodies to allow multi-part + textual and non-textual message bodies to be represented and + exchanged without loss of information. This is based on earlier work + documented in RFC 934 and STD 11, RFC 1049, but extends and revises + that work. Because RFC 822 said so little about message bodies, this + document is largely orthogonal to (rather than a revision of) RFC + 822. + + In particular, this document is designed to provide facilities to + include multiple objects in a single message, to represent body text + in character sets other than US-ASCII, to represent formatted multi- + font text messages, to represent non-textual material such as images + and audio fragments, and generally to facilitate later extensions + defining new types of Internet mail for use by cooperating mail + agents. + + This document does NOT extend Internet mail header fields to permit + anything other than US-ASCII text data. Such extensions are the + subject of a companion document [RFC-1522]. + + This document is a revision of RFC 1341. Significant differences + from RFC 1341 are summarized in Appendix H. + + + + + +Borenstein & Freed [Page 1] + +RFC 1521 MIME September 1993 + + +Table of Contents + + 1. Introduction....................................... 3 + 2. Notations, Conventions, and Generic BNF Grammar.... 6 + 3. The MIME-Version Header Field...................... 7 + 4. The Content-Type Header Field...................... 9 + 5. The Content-Transfer-Encoding Header Field......... 13 + 5.1. Quoted-Printable Content-Transfer-Encoding......... 18 + 5.2. Base64 Content-Transfer-Encoding................... 21 + 6. Additional Content-Header Fields................... 23 + 6.1. Optional Content-ID Header Field................... 23 + 6.2. Optional Content-Description Header Field.......... 24 + 7. The Predefined Content-Type Values................. 24 + 7.1. The Text Content-Type.............................. 24 + 7.1.1. The charset parameter.............................. 25 + 7.1.2. The Text/plain subtype............................. 28 + 7.2. The Multipart Content-Type......................... 28 + 7.2.1. Multipart: The common syntax...................... 29 + 7.2.2. The Multipart/mixed (primary) subtype.............. 34 + 7.2.3. The Multipart/alternative subtype.................. 34 + 7.2.4. The Multipart/digest subtype....................... 36 + 7.2.5. The Multipart/parallel subtype..................... 37 + 7.2.6. Other Multipart subtypes........................... 37 + 7.3. The Message Content-Type........................... 38 + 7.3.1. The Message/rfc822 (primary) subtype............... 38 + 7.3.2. The Message/Partial subtype........................ 39 + 7.3.3. The Message/External-Body subtype.................. 42 + 7.3.3.1. The "ftp" and "tftp" access-types............... 44 + 7.3.3.2. The "anon-ftp" access-type...................... 45 + 7.3.3.3. The "local-file" and "afs" access-types......... 45 + 7.3.3.4. The "mail-server" access-type................... 45 + 7.3.3.5. Examples and Further Explanations............... 46 + 7.4. The Application Content-Type....................... 49 + 7.4.1. The Application/Octet-Stream (primary) subtype..... 50 + 7.4.2. The Application/PostScript subtype................. 50 + 7.4.3. Other Application subtypes......................... 53 + 7.5. The Image Content-Type............................. 53 + 7.6. The Audio Content-Type............................. 54 + 7.7. The Video Content-Type............................. 54 + 7.8. Experimental Content-Type Values................... 54 + 8. Summary............................................ 56 + 9. Security Considerations............................ 56 + 10. Authors' Addresses................................. 57 + 11. Acknowledgements................................... 58 + Appendix A -- Minimal MIME-Conformance.................... 60 + Appendix B -- General Guidelines For Sending Email Data... 63 + Appendix C -- A Complex Multipart Example................. 66 + Appendix D -- Collected Grammar........................... 68 + + + +Borenstein & Freed [Page 2] + +RFC 1521 MIME September 1993 + + + Appendix E -- IANA Registration Procedures................ 72 + E.1 Registration of New Content-type/subtype Values...... 72 + E.2 Registration of New Access-type Values + for Message/external-body............................ 73 + Appendix F -- Summary of the Seven Content-types.......... 74 + Appendix G -- Canonical Encoding Model.................... 76 + Appendix H -- Changes from RFC 1341....................... 78 + References................................................ 80 + +1. Introduction + + Since its publication in 1982, STD 11, RFC 822 [RFC-822] has defined + the standard format of textual mail messages on the Internet. Its + success has been such that the RFC 822 format has been adopted, + wholly or partially, well beyond the confines of the Internet and the + Internet SMTP transport defined by STD 10, RFC 821 [RFC-821]. As the + format has seen wider use, a number of limitations have proven + increasingly restrictive for the user community. + + RFC 822 was intended to specify a format for text messages. As such, + non-text messages, such as multimedia messages that might include + audio or images, are simply not mentioned. Even in the case of text, + however, RFC 822 is inadequate for the needs of mail users whose + languages require the use of character sets richer than US ASCII + [US-ASCII]. Since RFC 822 does not specify mechanisms for mail + containing audio, video, Asian language text, or even text in most + European languages, additional specifications are needed. + + One of the notable limitations of RFC 821/822 based mail systems is + the fact that they limit the contents of electronic mail messages to + relatively short lines of seven-bit ASCII. This forces users to + convert any non-textual data that they may wish to send into seven- + bit bytes representable as printable ASCII characters before invoking + a local mail UA (User Agent, a program with which human users send + and receive mail). Examples of such encodings currently used in the + Internet include pure hexadecimal, uuencode, the 3-in-4 base 64 + scheme specified in RFC 1421, the Andrew Toolkit Representation + [ATK], and many others. + + The limitations of RFC 822 mail become even more apparent as gateways + are designed to allow for the exchange of mail messages between RFC + 822 hosts and X.400 hosts. X.400 [X400] specifies mechanisms for the + inclusion of non-textual body parts within electronic mail messages. + The current standards for the mapping of X.400 messages to RFC 822 + messages specify either that X.400 non-textual body parts must be + converted to (not encoded in) an ASCII format, or that they must be + discarded, notifying the RFC 822 user that discarding has occurred. + This is clearly undesirable, as information that a user may wish to + + + +Borenstein & Freed [Page 3] + +RFC 1521 MIME September 1993 + + + receive is lost. Even though a user's UA may not have the capability + of dealing with the non-textual body part, the user might have some + mechanism external to the UA that can extract useful information from + the body part. Moreover, it does not allow for the fact that the + message may eventually be gatewayed back into an X.400 message + handling system (i.e., the X.400 message is "tunneled" through + Internet mail), where the non-textual information would definitely + become useful again. + + This document describes several mechanisms that combine to solve most + of these problems without introducing any serious incompatibilities + with the existing world of RFC 822 mail. In particular, it + describes: + + 1. A MIME-Version header field, which uses a version number to + declare a message to be conformant with this specification and + allows mail processing agents to distinguish between such + messages and those generated by older or non-conformant software, + which is presumed to lack such a field. + + 2. A Content-Type header field, generalized from RFC 1049 [RFC-1049], + which can be used to specify the type and subtype of data in the + body of a message and to fully specify the native representation + (encoding) of such data. + + 2.a. A "text" Content-Type value, which can be used to represent + textual information in a number of character sets and + formatted text description languages in a standardized + manner. + + 2.b. A "multipart" Content-Type value, which can be used to + combine several body parts, possibly of differing types of + data, into a single message. + + 2.c. An "application" Content-Type value, which can be used to + transmit application data or binary data, and hence, among + other uses, to implement an electronic mail file transfer + service. + + 2.d. A "message" Content-Type value, for encapsulating another + mail message. + + 2.e An "image" Content-Type value, for transmitting still image + (picture) data. + + 2.f. An "audio" Content-Type value, for transmitting audio or + voice data. + + + + +Borenstein & Freed [Page 4] + +RFC 1521 MIME September 1993 + + + 2.g. A "video" Content-Type value, for transmitting video or + moving image data, possibly with audio as part of the + composite video data format. + + 3. A Content-Transfer-Encoding header field, which can be used to + specify an auxiliary encoding that was applied to the data in + order to allow it to pass through mail transport mechanisms which + may have data or character set limitations. + + 4. Two additional header fields that can be used to further describe + the data in a message body, the Content-ID and Content- + Description header fields. + + MIME has been carefully designed as an extensible mechanism, and it + is expected that the set of content-type/subtype pairs and their + associated parameters will grow significantly with time. Several + other MIME fields, notably including character set names, are likely + to have new values defined over time. In order to ensure that the + set of such values is developed in an orderly, well-specified, and + public manner, MIME defines a registration process which uses the + Internet Assigned Numbers Authority (IANA) as a central registry for + such values. Appendix E provides details about how IANA registration + is accomplished. + + Finally, to specify and promote interoperability, Appendix A of this + document provides a basic applicability statement for a subset of the + above mechanisms that defines a minimal level of "conformance" with + this document. + + HISTORICAL NOTE: Several of the mechanisms described in this + document may seem somewhat strange or even baroque at first + reading. It is important to note that compatibility with existing + standards AND robustness across existing practice were two of the + highest priorities of the working group that developed this + document. In particular, compatibility was always favored over + elegance. + + MIME was first defined and published as RFCs 1341 and 1342 [RFC-1341] + [RFC-1342]. This document is a relatively minor updating of RFC + 1341, and is intended to supersede it. The differences between this + document and RFC 1341 are summarized in Appendix H. Please refer to + the current edition of the "IAB Official Protocol Standards" for the + standardization state and status of this protocol. Several other RFC + documents will be of interest to the MIME implementor, in particular + [RFC 1343], [RFC-1344], and [RFC-1345]. + + + + + + +Borenstein & Freed [Page 5] + +RFC 1521 MIME September 1993 + + +2. Notations, Conventions, and Generic BNF Grammar + + This document is being published in two versions, one as plain ASCII + text and one as PostScript (PostScript is a trademark of Adobe + Systems Incorporated.). While the text version is the official + specification, some will find the PostScript version easier to read. + The textual contents are identical. An Andrew-format copy of this + document is also available from the first author (Borenstein). + + Although the mechanisms specified in this document are all described + in prose, most are also described formally in the modified BNF + notation of RFC 822. Implementors will need to be familiar with this + notation in order to understand this specification, and are referred + to RFC 822 for a complete explanation of the modified BNF notation. + + Some of the modified BNF in this document makes reference to + syntactic entities that are defined in RFC 822 and not in this + document. A complete formal grammar, then, is obtained by combining + the collected grammar appendix of this document with that of RFC 822 + plus the modifications to RFC 822 defined in RFC 1123, which + specifically changes the syntax for `return', `date' and `mailbox'. + + The term CRLF, in this document, refers to the sequence of the two + ASCII characters CR (13) and LF (10) which, taken together, in this + order, denote a line break in RFC 822 mail. + + The term "character set" is used in this document to refer to a + method used with one or more tables to convert encoded text to a + series of octets. This definition is intended to allow various kinds + of text encodings, from simple single-table mappings such as ASCII to + complex table switching methods such as those that use ISO 2022's + techniques. However, a MIME character set name must fully specify + the mapping to be performed. + + The term "message", when not further qualified, means either the + (complete or "top-level") message being transferred on a network, or + a message encapsulated in a body of type "message". + + The term "body part", in this document, means one of the parts of the + body of a multipart entity. A body part has a header and a body, so + it makes sense to speak about the body of a body part. + + The term "entity", in this document, means either a message or a body + part. All kinds of entities share the property that they have a + header and a body. + + The term "body", when not further qualified, means the body of an + entity, that is the body of either a message or of a body part. + + + +Borenstein & Freed [Page 6] + +RFC 1521 MIME September 1993 + + + NOTE: The previous four definitions are clearly circular. This is + unavoidable, since the overall structure of a MIME message is + indeed recursive. + + In this document, all numeric and octet values are given in decimal + notation. + + It must be noted that Content-Type values, subtypes, and parameter + names as defined in this document are case-insensitive. However, + parameter values are case-sensitive unless otherwise specified for + the specific parameter. + + FORMATTING NOTE: This document has been carefully formatted for + ease of reading. The PostScript version of this document, in + particular, places notes like this one, which may be skipped by + the reader, in a smaller, italicized, font, and indents it as + well. In the text version, only the indentation is preserved, so + if you are reading the text version of this you might consider + using the PostScript version instead. However, all such notes will + be indented and preceded by "NOTE:" or some similar introduction, + even in the text version. + + The primary purpose of these non-essential notes is to convey + information about the rationale of this document, or to place this + document in the proper historical or evolutionary context. Such + information may be skipped by those who are focused entirely on + building a conformant implementation, but may be of use to those + who wish to understand why this document is written as it is. + + For ease of recognition, all BNF definitions have been placed in a + fixed-width font in the PostScript version of this document. + +3. The MIME-Version Header Field + + Since RFC 822 was published in 1982, there has really been only one + format standard for Internet messages, and there has been little + perceived need to declare the format standard in use. This document + is an independent document that complements RFC 822. Although the + extensions in this document have been defined in such a way as to be + compatible with RFC 822, there are still circumstances in which it + might be desirable for a mail-processing agent to know whether a + message was composed with the new standard in mind. + + Therefore, this document defines a new header field, "MIME-Version", + which is to be used to declare the version of the Internet message + body format standard in use. + + Messages composed in accordance with this document MUST include such + + + +Borenstein & Freed [Page 7] + +RFC 1521 MIME September 1993 + + + a header field, with the following verbatim text: + + MIME-Version: 1.0 + + The presence of this header field is an assertion that the message + has been composed in compliance with this document. + + Since it is possible that a future document might extend the message + format standard again, a formal BNF is given for the content of the + MIME-Version field: + + version := "MIME-Version" ":" 1*DIGIT "." 1*DIGIT + + Thus, future format specifiers, which might replace or extend "1.0", + are constrained to be two integer fields, separated by a period. If + a message is received with a MIME-version value other than "1.0", it + cannot be assumed to conform with this specification. + + Note that the MIME-Version header field is required at the top level + of a message. It is not required for each body part of a multipart + entity. It is required for the embedded headers of a body of type + "message" if and only if the embedded message is itself claimed to be + MIME-conformant. + + It is not possible to fully specify how a mail reader that conforms + with MIME as defined in this document should treat a message that + might arrive in the future with some value of MIME-Version other than + "1.0". However, conformant software is encouraged to check the + version number and at least warn the user if an unrecognized MIME- + version is encountered. + + It is also worth noting that version control for specific content- + types is not accomplished using the MIME-Version mechanism. In + particular, some formats (such as application/postscript) have + version numbering conventions that are internal to the document + format. Where such conventions exist, MIME does nothing to supersede + them. Where no such conventions exist, a MIME type might use a + "version" parameter in the content-type field if necessary. + + NOTE TO IMPLEMENTORS: All header fields defined in this document, + including MIME-Version, Content-type, etc., are subject to the + general syntactic rules for header fields specified in RFC 822. In + particular, all can include comments, which means that the following + two MIME-Version fields are equivalent: + + MIME-Version: 1.0 + MIME-Version: 1.0 (Generated by GBD-killer 3.7) + + + + +Borenstein & Freed [Page 8] + +RFC 1521 MIME September 1993 + + +4. The Content-Type Header Field + + The purpose of the Content-Type field is to describe the data + contained in the body fully enough that the receiving user agent can + pick an appropriate agent or mechanism to present the data to the + user, or otherwise deal with the data in an appropriate manner. + + HISTORICAL NOTE: The Content-Type header field was first defined in + RFC 1049. RFC 1049 Content-types used a simpler and less powerful + syntax, but one that is largely compatible with the mechanism given + here. + + The Content-Type header field is used to specify the nature of the + data in the body of an entity, by giving type and subtype + identifiers, and by providing auxiliary information that may be + required for certain types. After the type and subtype names, the + remainder of the header field is simply a set of parameters, + specified in an attribute/value notation. The set of meaningful + parameters differs for the different types. In particular, there are + NO globally-meaningful parameters that apply to all content-types. + Global mechanisms are best addressed, in the MIME model, by the + definition of additional Content-* header fields. The ordering of + parameters is not significant. Among the defined parameters is a + "charset" parameter by which the character set used in the body may + be declared. Comments are allowed in accordance with RFC 822 rules + for structured header fields. + + In general, the top-level Content-Type is used to declare the general + type of data, while the subtype specifies a specific format for that + type of data. Thus, a Content-Type of "image/xyz" is enough to tell + a user agent that the data is an image, even if the user agent has no + knowledge of the specific image format "xyz". Such information can + be used, for example, to decide whether or not to show a user the raw + data from an unrecognized subtype -- such an action might be + reasonable for unrecognized subtypes of text, but not for + unrecognized subtypes of image or audio. For this reason, registered + subtypes of audio, image, text, and video, should not contain + embedded information that is really of a different type. Such + compound types should be represented using the "multipart" or + "application" types. + + Parameters are modifiers of the content-subtype, and do not + fundamentally affect the requirements of the host system. Although + most parameters make sense only with certain content-types, others + are "global" in the sense that they might apply to any subtype. For + example, the "boundary" parameter makes sense only for the + "multipart" content-type, but the "charset" parameter might make + sense with several content-types. + + + +Borenstein & Freed [Page 9] + +RFC 1521 MIME September 1993 + + + An initial set of seven Content-Types is defined by this document. + This set of top-level names is intended to be substantially complete. + It is expected that additions to the larger set of supported types + can generally be accomplished by the creation of new subtypes of + these initial types. In the future, more top-level types may be + defined only by an extension to this standard. If another primary + type is to be used for any reason, it must be given a name starting + with "X-" to indicate its non-standard status and to avoid a + potential conflict with a future official name. + + In the Augmented BNF notation of RFC 822, a Content-Type header field + value is defined as follows: + + content := "Content-Type" ":" type "/" subtype *(";" + parameter) + ; case-insensitive matching of type and subtype + + type := "application" / "audio" + / "image" / "message" + / "multipart" / "text" + / "video" / extension-token + ; All values case-insensitive + + extension-token := x-token / iana-token + + iana-token := + + x-token := + + subtype := token ; case-insensitive + + parameter := attribute "=" value + + attribute := token ; case-insensitive + + value := token / quoted-string + + token := 1* + + tspecials := "(" / ")" / "<" / ">" / "@" + / "," / ";" / ":" / "\" / <"> + / "/" / "[" / "]" / "?" / "=" + ; Must be in quoted-string, + ; to use within parameter values + + + +Borenstein & Freed [Page 10] + +RFC 1521 MIME September 1993 + + + Note that the definition of "tspecials" is the same as the RFC 822 + definition of "specials" with the addition of the three characters + "/", "?", and "=", and the removal of ".". + + Note also that a subtype specification is MANDATORY. There are no + default subtypes. + + The type, subtype, and parameter names are not case sensitive. For + example, TEXT, Text, and TeXt are all equivalent. Parameter values + are normally case sensitive, but certain parameters are interpreted + to be case-insensitive, depending on the intended use. (For example, + multipart boundaries are case-sensitive, but the "access-type" for + message/External-body is not case-sensitive.) + + Beyond this syntax, the only constraint on the definition of subtype + names is the desire that their uses must not conflict. That is, it + would be undesirable to have two different communities using + "Content-Type: application/foobar" to mean two different things. The + process of defining new content-subtypes, then, is not intended to be + a mechanism for imposing restrictions, but simply a mechanism for + publicizing the usages. There are, therefore, two acceptable + mechanisms for defining new Content-Type subtypes: + + 1. Private values (starting with "X-") may be + defined bilaterally between two cooperating + agents without outside registration or + standardization. + + 2. New standard values must be documented, + registered with, and approved by IANA, as + described in Appendix E. Where intended for + public use, the formats they refer to must + also be defined by a published specification, + and possibly offered for standardization. + + The seven standard initial predefined Content-Types are detailed in + the bulk of this document. They are: + + text -- textual information. The primary subtype, + "plain", indicates plain (unformatted) text. No + special software is required to get the full + meaning of the text, aside from support for the + indicated character set. Subtypes are to be used + for enriched text in forms where application + software may enhance the appearance of the text, + but such software must not be required in order to + get the general idea of the content. Possible + subtypes thus include any readable word processor + + + +Borenstein & Freed [Page 11] + +RFC 1521 MIME September 1993 + + + format. A very simple and portable subtype, + richtext, was defined in RFC 1341, with a future + revision expected. + + multipart -- data consisting of multiple parts of + independent data types. Four initial subtypes + are defined, including the primary "mixed" + subtype, "alternative" for representing the same + data in multiple formats, "parallel" for parts + intended to be viewed simultaneously, and "digest" + for multipart entities in which each part is of + type "message". + + message -- an encapsulated message. A body of + Content-Type "message" is itself all or part of a + fully formatted RFC 822 conformant message which + may contain its own different Content-Type header + field. The primary subtype is "rfc822". The + "partial" subtype is defined for partial messages, + to permit the fragmented transmission of bodies + that are thought to be too large to be passed + through mail transport facilities. Another + subtype, "External-body", is defined for + specifying large bodies by reference to an + external data source. + + image -- image data. Image requires a display device + (such as a graphical display, a printer, or a FAX + machine) to view the information. Initial + subtypes are defined for two widely-used image + formats, jpeg and gif. + + audio -- audio data, with initial subtype "basic". + Audio requires an audio output device (such as a + speaker or a telephone) to "display" the contents. + + video -- video data. Video requires the capability to + display moving images, typically including + specialized hardware and software. The initial + subtype is "mpeg". + + application -- some other kind of data, typically + either uninterpreted binary data or information to + be processed by a mail-based application. The + primary subtype, "octet-stream", is to be used in + the case of uninterpreted binary data, in which + case the simplest recommended action is to offer + to write the information into a file for the user. + + + +Borenstein & Freed [Page 12] + +RFC 1521 MIME September 1993 + + + An additional subtype, "PostScript", is defined + for transporting PostScript documents in bodies. + Other expected uses for "application" include + spreadsheets, data for mail-based scheduling + systems, and languages for "active" + (computational) email. (Note that active email + and other application data may entail several + security considerations, which are discussed later + in this memo, particularly in the context of + application/PostScript.) + + Default RFC 822 messages are typed by this protocol as plain text in + the US-ASCII character set, which can be explicitly specified as + "Content-type: text/plain; charset=us-ascii". If no Content-Type is + specified, this default is assumed. In the presence of a MIME- + Version header field, a receiving User Agent can also assume that + plain US-ASCII text was the sender's intent. In the absence of a + MIME-Version specification, plain US-ASCII text must still be + assumed, but the sender's intent might have been otherwise. + + RATIONALE: In the absence of any Content-Type header field or + MIME-Version header field, it is impossible to be certain that a + message is actually text in the US-ASCII character set, since it + might well be a message that, using the conventions that predate + this document, includes text in another character set or non- + textual data in a manner that cannot be automatically recognized + (e.g., a uuencoded compressed UNIX tar file). Although there is + no fully acceptable alternative to treating such untyped messages + as "text/plain; charset=us-ascii", implementors should remain + aware that if a message lacks both the MIME-Version and the + Content-Type header fields, it may in practice contain almost + anything. + + It should be noted that the list of Content-Type values given here + may be augmented in time, via the mechanisms described above, and + that the set of subtypes is expected to grow substantially. + + When a mail reader encounters mail with an unknown Content-type + value, it should generally treat it as equivalent to + "application/octet-stream", as described later in this document. + +5. The Content-Transfer-Encoding Header Field + + Many Content-Types which could usefully be transported via email are + represented, in their "natural" format, as 8-bit character or binary + data. Such data cannot be transmitted over some transport protocols. + For example, RFC 821 restricts mail messages to 7-bit US-ASCII data + with lines no longer than 1000 characters. + + + +Borenstein & Freed [Page 13] + +RFC 1521 MIME September 1993 + + + It is necessary, therefore, to define a standard mechanism for re- + encoding such data into a 7-bit short-line format. This document + specifies that such encodings will be indicated by a new "Content- + Transfer-Encoding" header field. The Content-Transfer-Encoding field + is used to indicate the type of transformation that has been used in + order to represent the body in an acceptable manner for transport. + + Unlike Content-Types, a proliferation of Content-Transfer-Encoding + values is undesirable and unnecessary. However, establishing only a + single Content-Transfer-Encoding mechanism does not seem possible. + There is a tradeoff between the desire for a compact and efficient + encoding of largely-binary data and the desire for a readable + encoding of data that is mostly, but not entirely, 7-bit data. For + this reason, at least two encoding mechanisms are necessary: a + "readable" encoding and a "dense" encoding. + + The Content-Transfer-Encoding field is designed to specify an + invertible mapping between the "native" representation of a type of + data and a representation that can be readily exchanged using 7 bit + mail transport protocols, such as those defined by RFC 821 (SMTP). + This field has not been defined by any previous standard. The field's + value is a single token specifying the type of encoding, as + enumerated below. Formally: + + encoding := "Content-Transfer-Encoding" ":" mechanism + + mechanism := "7bit" ; case-insensitive + / "quoted-printable" + / "base64" + / "8bit" + / "binary" + / x-token + + These values are not case sensitive. That is, Base64 and BASE64 and + bAsE64 are all equivalent. An encoding type of 7BIT requires that + the body is already in a seven-bit mail-ready representation. This + is the default value -- that is, "Content-Transfer-Encoding: 7BIT" is + assumed if the Content-Transfer-Encoding header field is not present. + + The values "8bit", "7bit", and "binary" all mean that NO encoding has + been performed. However, they are potentially useful as indications + of the kind of data contained in the object, and therefore of the + kind of encoding that might need to be performed for transmission in + a given transport system. In particular: + + "7bit" means that the data is all represented as short + lines of US-ASCII data. + + + + +Borenstein & Freed [Page 14] + +RFC 1521 MIME September 1993 + + + "8bit" means that the lines are short, but there may be + non-ASCII characters (octets with the high-order + bit set). + + "Binary" means that not only may non-ASCII characters + be present, but also that the lines are not + necessarily short enough for SMTP transport. + + The difference between "8bit" (or any other conceivable bit-width + token) and the "binary" token is that "binary" does not require + adherence to any limits on line length or to the SMTP CRLF semantics, + while the bit-width tokens do require such adherence. If the body + contains data in any bit-width other than 7-bit, the appropriate + bit-width Content-Transfer-Encoding token must be used (e.g., "8bit" + for unencoded 8 bit wide data). If the body contains binary data, + the "binary" Content-Transfer-Encoding token must be used. + + NOTE: The distinction between the Content-Transfer-Encoding values + of "binary", "8bit", etc. may seem unimportant, in that all of + them really mean "none" -- that is, there has been no encoding of + the data for transport. However, clear labeling will be of + enormous value to gateways between future mail transport systems + with differing capabilities in transporting data that do not meet + the restrictions of RFC 821 transport. + + Mail transport for unencoded 8-bit data is defined in RFC-1426 + [RFC-1426]. As of the publication of this document, there are no + standardized Internet mail transports for which it is legitimate + to include unencoded binary data in mail bodies. Thus there are + no circumstances in which the "binary" Content-Transfer-Encoding + is actually legal on the Internet. However, in the event that + binary mail transport becomes a reality in Internet mail, or when + this document is used in conjunction with any other binary-capable + transport mechanism, binary bodies should be labeled as such using + this mechanism. + + NOTE: The five values defined for the Content-Transfer-Encoding + field imply nothing about the Content-Type other than the + algorithm by which it was encoded or the transport system + requirements if unencoded. + + Implementors may, if necessary, define new Content-Transfer-Encoding + values, but must use an x-token, which is a name prefixed by "X-" to + indicate its non-standard status, e.g., "Content-Transfer-Encoding: + x-my-new-encoding". However, unlike Content-Types and subtypes, the + creation of new Content-Transfer-Encoding values is explicitly and + strongly discouraged, as it seems likely to hinder interoperability + with little potential benefit. Their use is allowed only as the + + + +Borenstein & Freed [Page 15] + +RFC 1521 MIME September 1993 + + + result of an agreement between cooperating user agents. + + If a Content-Transfer-Encoding header field appears as part of a + message header, it applies to the entire body of that message. If a + Content-Transfer-Encoding header field appears as part of a body + part's headers, it applies only to the body of that body part. If an + entity is of type "multipart" or "message", the Content-Transfer- + Encoding is not permitted to have any value other than a bit width + (e.g., "7bit", "8bit", etc.) or "binary". + + It should be noted that email is character-oriented, so that the + mechanisms described here are mechanisms for encoding arbitrary octet + streams, not bit streams. If a bit stream is to be encoded via one + of these mechanisms, it must first be converted to an 8-bit byte + stream using the network standard bit order ("big-endian"), in which + the earlier bits in a stream become the higher-order bits in a byte. + A bit stream not ending at an 8-bit boundary must be padded with + zeroes. This document provides a mechanism for noting the addition + of such padding in the case of the application Content-Type, which + has a "padding" parameter. + + The encoding mechanisms defined here explicitly encode all data in + ASCII. Thus, for example, suppose an entity has header fields such + as: + + Content-Type: text/plain; charset=ISO-8859-1 + Content-transfer-encoding: base64 + + This must be interpreted to mean that the body is a base64 ASCII + encoding of data that was originally in ISO-8859-1, and will be in + that character set again after decoding. + + The following sections will define the two standard encoding + mechanisms. The definition of new content-transfer-encodings is + explicitly discouraged and should only occur when absolutely + necessary. All content-transfer-encoding namespace except that + beginning with "X-" is explicitly reserved to the IANA for future + use. Private agreements about content-transfer-encodings are also + explicitly discouraged. + + Certain Content-Transfer-Encoding values may only be used on certain + Content-Types. In particular, it is expressly forbidden to use any + encodings other than "7bit", "8bit", or "binary" with any Content- + Type that recursively includes other Content-Type fields, notably the + "multipart" and "message" Content-Types. All encodings that are + desired for bodies of type multipart or message must be done at the + innermost level, by encoding the actual body that needs to be + encoded. + + + +Borenstein & Freed [Page 16] + +RFC 1521 MIME September 1993 + + + NOTE ON ENCODING RESTRICTIONS: Though the prohibition against + using content-transfer-encodings on data of type multipart or + message may seem overly restrictive, it is necessary to prevent + nested encodings, in which data are passed through an encoding + algorithm multiple times, and must be decoded multiple times in + order to be properly viewed. Nested encodings add considerable + complexity to user agents: aside from the obvious efficiency + problems with such multiple encodings, they can obscure the basic + structure of a message. In particular, they can imply that + several decoding operations are necessary simply to find out what + types of objects a message contains. Banning nested encodings may + complicate the job of certain mail gateways, but this seems less + of a problem than the effect of nested encodings on user agents. + + NOTE ON THE RELATIONSHIP BETWEEN CONTENT-TYPE AND CONTENT- + TRANSFER-ENCODING: It may seem that the Content-Transfer-Encoding + could be inferred from the characteristics of the Content-Type + that is to be encoded, or, at the very least, that certain + Content-Transfer-Encodings could be mandated for use with specific + Content-Types. There are several reasons why this is not the case. + First, given the varying types of transports used for mail, some + encodings may be appropriate for some Content-Type/transport + combinations and not for others. (For example, in an 8-bit + transport, no encoding would be required for text in certain + character sets, while such encodings are clearly required for 7- + bit SMTP.) Second, certain Content-Types may require different + types of transfer encoding under different circumstances. For + example, many PostScript bodies might consist entirely of short + lines of 7-bit data and hence require little or no encoding. + Other PostScript bodies (especially those using Level 2 + PostScript's binary encoding mechanism) may only be reasonably + represented using a binary transport encoding. Finally, since + Content-Type is intended to be an open-ended specification + mechanism, strict specification of an association between + Content-Types and encodings effectively couples the specification + of an application protocol with a specific lower-level transport. + This is not desirable since the developers of a Content-Type + should not have to be aware of all the transports in use and what + their limitations are. + + NOTE ON TRANSLATING ENCODINGS: The quoted-printable and base64 + encodings are designed so that conversion between them is + possible. The only issue that arises in such a conversion is the + handling of line breaks. When converting from quoted-printable to + base64 a line break must be converted into a CRLF sequence. + Similarly, a CRLF sequence in base64 data must be converted to a + quoted-printable line break, but ONLY when converting text data. + + + + +Borenstein & Freed [Page 17] + +RFC 1521 MIME September 1993 + + + NOTE ON CANONICAL ENCODING MODEL: There was some confusion, in + earlier drafts of this memo, regarding the model for when email + data was to be converted to canonical form and encoded, and in + particular how this process would affect the treatment of CRLFs, + given that the representation of newlines varies greatly from + system to system, and the relationship between content-transfer- + encodings and character sets. For this reason, a canonical model + for encoding is presented as Appendix G. + +5.1. Quoted-Printable Content-Transfer-Encoding + + The Quoted-Printable encoding is intended to represent data that + largely consists of octets that correspond to printable characters in + the ASCII character set. It encodes the data in such a way that the + resulting octets are unlikely to be modified by mail transport. If + the data being encoded are mostly ASCII text, the encoded form of the + data remains largely recognizable by humans. A body which is + entirely ASCII may also be encoded in Quoted-Printable to ensure the + integrity of the data should the message pass through a character- + translating, and/or line-wrapping gateway. + + In this encoding, octets are to be represented as determined by the + following rules: + + Rule #1: (General 8-bit representation) Any octet, except those + indicating a line break according to the newline convention of the + canonical (standard) form of the data being encoded, may be + represented by an "=" followed by a two digit hexadecimal + representation of the octet's value. The digits of the + hexadecimal alphabet, for this purpose, are "0123456789ABCDEF". + Uppercase letters must be used when sending hexadecimal data, + though a robust implementation may choose to recognize lowercase + letters on receipt. Thus, for example, the value 12 (ASCII form + feed) can be represented by "=0C", and the value 61 (ASCII EQUAL + SIGN) can be represented by "=3D". Except when the following + rules allow an alternative encoding, this rule is mandatory. + + Rule #2: (Literal representation) Octets with decimal values of 33 + through 60 inclusive, and 62 through 126, inclusive, MAY be + represented as the ASCII characters which correspond to those + octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN + through TILDE, respectively). + + Rule #3: (White Space): Octets with values of 9 and 32 MAY be + represented as ASCII TAB (HT) and SPACE characters, respectively, + but MUST NOT be so represented at the end of an encoded line. Any + TAB (HT) or SPACE characters on an encoded line MUST thus be + followed on that line by a printable character. In particular, an + + + +Borenstein & Freed [Page 18] + +RFC 1521 MIME September 1993 + + + "=" at the end of an encoded line, indicating a soft line break + (see rule #5) may follow one or more TAB (HT) or SPACE characters. + It follows that an octet with value 9 or 32 appearing at the end + of an encoded line must be represented according to Rule #1. This + rule is necessary because some MTAs (Message Transport Agents, + programs which transport messages from one user to another, or + perform a part of such transfers) are known to pad lines of text + with SPACEs, and others are known to remove "white space" + characters from the end of a line. Therefore, when decoding a + Quoted-Printable body, any trailing white space on a line must be + deleted, as it will necessarily have been added by intermediate + transport agents. + + Rule #4 (Line Breaks): A line break in a text body, independent of + what its representation is following the canonical representation + of the data being encoded, must be represented by a (RFC 822) line + break, which is a CRLF sequence, in the Quoted-Printable encoding. + Since the canonical representation of types other than text do not + generally include the representation of line breaks, no hard line + breaks (i.e. line breaks that are intended to be meaningful and + to be displayed to the user) should occur in the quoted-printable + encoding of such types. Of course, occurrences of "=0D", "=0A", + "0A=0D" and "=0D=0A" will eventually be encountered. In general, + however, base64 is preferred over quoted-printable for binary + data. + + Note that many implementations may elect to encode the local + representation of various content types directly, as described in + Appendix G. In particular, this may apply to plain text material + on systems that use newline conventions other than CRLF + delimiters. Such an implementation is permissible, but the + generation of line breaks must be generalized to account for the + case where alternate representations of newline sequences are + used. + + Rule #5 (Soft Line Breaks): The Quoted-Printable encoding REQUIRES + that encoded lines be no more than 76 characters long. If longer + lines are to be encoded with the Quoted-Printable encoding, 'soft' + line breaks must be used. An equal sign as the last character on a + encoded line indicates such a non-significant ('soft') line break + in the encoded text. Thus if the "raw" form of the line is a + single unencoded line that says: + + Now's the time for all folk to come to the aid of + their country. + + This can be represented, in the Quoted-Printable encoding, as + + + + +Borenstein & Freed [Page 19] + +RFC 1521 MIME September 1993 + + + Now's the time = + for all folk to come= + to the aid of their country. + + This provides a mechanism with which long lines are encoded in + such a way as to be restored by the user agent. The 76 character + limit does not count the trailing CRLF, but counts all other + characters, including any equal signs. + + Since the hyphen character ("-") is represented as itself in the + Quoted-Printable encoding, care must be taken, when encapsulating a + quoted-printable encoded body in a multipart entity, to ensure that + the encapsulation boundary does not appear anywhere in the encoded + body. (A good strategy is to choose a boundary that includes a + character sequence such as "=_" which can never appear in a quoted- + printable body. See the definition of multipart messages later in + this document.) + + NOTE: The quoted-printable encoding represents something of a + compromise between readability and reliability in transport. + Bodies encoded with the quoted-printable encoding will work + reliably over most mail gateways, but may not work perfectly over + a few gateways, notably those involving translation into EBCDIC. + (In theory, an EBCDIC gateway could decode a quoted-printable body + and re-encode it using base64, but such gateways do not yet + exist.) A higher level of confidence is offered by the base64 + Content-Transfer-Encoding. A way to get reasonably reliable + transport through EBCDIC gateways is to also quote the ASCII + characters + + !"#$@[\]^`{|}~ + + according to rule #1. See Appendix B for more information. + + Because quoted-printable data is generally assumed to be line- + oriented, it is to be expected that the representation of the breaks + between the lines of quoted printable data may be altered in + transport, in the same manner that plain text mail has always been + altered in Internet mail when passing between systems with differing + newline conventions. If such alterations are likely to constitute a + corruption of the data, it is probably more sensible to use the + base64 encoding rather than the quoted-printable encoding. + + WARNING TO IMPLEMENTORS: If binary data are encoded in quoted- + printable, care must be taken to encode CR and LF characters as "=0D" + and "=0A", respectively. In particular, a CRLF sequence in binary + data should be encoded as "=0D=0A". Otherwise, if CRLF were + represented as a hard line break, it might be incorrectly decoded on + + + +Borenstein & Freed [Page 20] + +RFC 1521 MIME September 1993 + + + platforms with different line break conventions. + + For formalists, the syntax of quoted-printable data is described by + the following grammar: + + quoted-printable := ([*(ptext / SPACE / TAB) ptext] ["="] CRLF) + ; Maximum line length of 76 characters excluding CRLF + + ptext := octet / 127, =, SPACE, or TAB, + ; and is recommended for any characters not listed in + ; Appendix B as "mail-safe". + +5.2. Base64 Content-Transfer-Encoding + + The Base64 Content-Transfer-Encoding is designed to represent + arbitrary sequences of octets in a form that need not be humanly + readable. The encoding and decoding algorithms are simple, but the + encoded data are consistently only about 33 percent larger than the + unencoded data. This encoding is virtually identical to the one used + in Privacy Enhanced Mail (PEM) applications, as defined in RFC 1421. + The base64 encoding is adapted from RFC 1421, with one change: base64 + eliminates the "*" mechanism for embedded clear text. + + A 65-character subset of US-ASCII is used, enabling 6 bits to be + represented per printable character. (The extra 65th character, "=", + is used to signify a special processing function.) + + NOTE: This subset has the important property that it is + represented identically in all versions of ISO 646, including US + ASCII, and all characters in the subset are also represented + identically in all versions of EBCDIC. Other popular encodings, + such as the encoding used by the uuencode utility and the base85 + encoding specified as part of Level 2 PostScript, do not share + these properties, and thus do not fulfill the portability + requirements a binary transport encoding for mail must meet. + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8-bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + When encoding a bit stream via the base64 encoding, the bit stream + must be presumed to be ordered with the most-significant-bit first. + + + +Borenstein & Freed [Page 21] + +RFC 1521 MIME September 1993 + + + That is, the first bit in the stream will be the high-order bit in + the first byte, and the eighth bit will be the low-order bit in the + first byte, and so on. + + Each 6-bit group is used as an index into an array of 64 printable + characters. The character referenced by the index is placed in the + output string. These characters, identified in Table 1, below, are + selected so as to be universally representable, and the set excludes + characters with particular significance to SMTP (e.g., ".", CR, LF) + and to the encapsulation boundaries defined in this document (e.g., + "-"). + + Table 1: The Base64 Alphabet + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + The output stream (encoded bytes) must be represented in lines of no + more than 76 characters each. All line breaks or other characters + not found in Table 1 must be ignored by decoding software. In base64 + data, characters other than those in Table 1, line breaks, and other + white space probably indicate a transmission error, about which a + warning message or even a message rejection might be appropriate + under some circumstances. + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a body. When fewer than 24 input bits + are available in an input group, zero bits are added (on the right) + to form an integral number of 6-bit groups. Padding at the end of + the data is performed using the '=' character. Since all base64 + input is an integral number of octets, only the following cases can + + + +Borenstein & Freed [Page 22] + +RFC 1521 MIME September 1993 + + + arise: (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded output will be + an integral multiple of 4 characters with no "=" padding, (2) the + final quantum of encoding input is exactly 8 bits; here, the final + unit of encoded output will be two characters followed by two "=" + padding characters, or (3) the final quantum of encoding input is + exactly 16 bits; here, the final unit of encoded output will be three + characters followed by one "=" padding character. + + Because it is used only for padding at the end of the data, the + occurrence of any '=' characters may be taken as evidence that the + end of the data has been reached (without truncation in transit). No + such assurance is possible, however, when the number of octets + transmitted was a multiple of three. + + Any characters outside of the base64 alphabet are to be ignored in + base64-encoded data. The same applies to any illegal sequence of + characters in the base64 encoding, such as "=====" + + Care must be taken to use the proper octets for line breaks if base64 + encoding is applied directly to text material that has not been + converted to canonical form. In particular, text line breaks must be + converted into CRLF sequences prior to base64 encoding. The important + thing to note is that this may be done directly by the encoder rather + than in a prior canonicalization step in some implementations. + + NOTE: There is no need to worry about quoting apparent + encapsulation boundaries within base64-encoded parts of multipart + entities because no hyphen characters are used in the base64 + encoding. + +6. Additional Content-Header Fields + +6.1. Optional Content-ID Header Field + + In constructing a high-level user agent, it may be desirable to allow + one body to make reference to another. Accordingly, bodies may be + labeled using the "Content-ID" header field, which is syntactically + identical to the "Message-ID" header field: + + id := "Content-ID" ":" msg-id + Like the Message-ID values, Content-ID values must be generated to be + world-unique. + + The Content-ID value may be used for uniquely identifying MIME + entities in several contexts, particularly for cacheing data + referenced by the message/external-body mechanism. Although the + Content-ID header is generally optional, its use is mandatory in + + + +Borenstein & Freed [Page 23] + +RFC 1521 MIME September 1993 + + + implementations which generate data of the optional MIME Content-type + "message/external-body". That is, each message/external-body entity + must have a Content-ID field to permit cacheing of such data. + + It is also worth noting that the Content-ID value has special + semantics in the case of the multipart/alternative content-type. + This is explained in the section of this document dealing with + multipart/alternative. + +6.2. Optional Content-Description Header Field + + The ability to associate some descriptive information with a given + body is often desirable. For example, it may be useful to mark an + "image" body as "a picture of the Space Shuttle Endeavor." Such text + may be placed in the Content-Description header field. + + description := "Content-Description" ":" *text + + The description is presumed to be given in the US-ASCII character + set, although the mechanism specified in [RFC-1522] may be used for + non-US-ASCII Content-Description values. + +7. The Predefined Content-Type Values + + This document defines seven initial Content-Type values and an + extension mechanism for private or experimental types. Further + standard types must be defined by new published specifications. It + is expected that most innovation in new types of mail will take place + as subtypes of the seven types defined here. The most essential + characteristics of the seven content-types are summarized in Appendix + F. + +7.1 The Text Content-Type + + The text Content-Type is intended for sending material which is + principally textual in form. It is the default Content-Type. A + "charset" parameter may be used to indicate the character set of the + body text for some text subtypes, notably including the primary + subtype, "text/plain", which indicates plain (unformatted) text. The + default Content-Type for Internet mail is "text/plain; charset=us- + ascii". + + Beyond plain text, there are many formats for representing what might + be known as "extended text" -- text with embedded formatting and + presentation information. An interesting characteristic of many such + representations is that they are to some extent readable even without + the software that interprets them. It is useful, then, to + distinguish them, at the highest level, from such unreadable data as + + + +Borenstein & Freed [Page 24] + +RFC 1521 MIME September 1993 + + + images, audio, or text represented in an unreadable form. In the + absence of appropriate interpretation software, it is reasonable to + show subtypes of text to the user, while it is not reasonable to do + so with most nontextual data. + + Such formatted textual data should be represented using subtypes of + text. Plausible subtypes of text are typically given by the common + name of the representation format, e.g., "text/richtext" [RFC-1341]. + +7.1.1. The charset parameter + + A critical parameter that may be specified in the Content-Type field + for text/plain data is the character set. This is specified with a + "charset" parameter, as in: + + Content-type: text/plain; charset=us-ascii + + Unlike some other parameter values, the values of the charset + parameter are NOT case sensitive. The default character set, which + must be assumed in the absence of a charset parameter, is US-ASCII. + + The specification for any future subtypes of "text" must specify + whether or not they will also utilize a "charset" parameter, and may + possibly restrict its values as well. When used with a particular + body, the semantics of the "charset" parameter should be identical to + those specified here for "text/plain", i.e., the body consists + entirely of characters in the given charset. In particular, definers + of future text subtypes should pay close attention the the + implications of multibyte character sets for their subtype + definitions. + + This RFC specifies the definition of the charset parameter for the + purposes of MIME to be a unique mapping of a byte stream to glyphs, a + mapping which does not require external profiling information. + + An initial list of predefined character set names can be found at the + end of this section. Additional character sets may be registered + with IANA, although the standardization of their use requires the + usual IESG [RFC-1340] review and approval. Note that if the + specified character set includes 8-bit data, a Content-Transfer- + Encoding header field and a corresponding encoding on the data are + required in order to transmit the body via some mail transfer + protocols, such as SMTP. + + The default character set, US-ASCII, has been the subject of some + confusion and ambiguity in the past. Not only were there some + ambiguities in the definition, there have been wide variations in + practice. In order to eliminate such ambiguity and variations in the + + + +Borenstein & Freed [Page 25] + +RFC 1521 MIME September 1993 + + + future, it is strongly recommended that new user agents explicitly + specify a character set via the Content-Type header field. "US- + ASCII" does not indicate an arbitrary seven-bit character code, but + specifies that the body uses character coding that uses the exact + correspondence of codes to characters specified in ASCII. National + use variations of ISO 646 [ISO-646] are NOT ASCII and their use in + Internet mail is explicitly discouraged. The omission of the ISO 646 + character set is deliberate in this regard. The character set name + of "US-ASCII" explicitly refers to ANSI X3.4-1986 [US-ASCII] only. + The character set name "ASCII" is reserved and must not be used for + any purpose. + + NOTE: RFC 821 explicitly specifies "ASCII", and references an + earlier version of the American Standard. Insofar as one of the + purposes of specifying a Content-Type and character set is to + permit the receiver to unambiguously determine how the sender + intended the coded message to be interpreted, assuming anything + other than "strict ASCII" as the default would risk unintentional + and incompatible changes to the semantics of messages now being + transmitted. This also implies that messages containing + characters coded according to national variations on ISO 646, or + using code-switching procedures (e.g., those of ISO 2022), as well + as 8-bit or multiple octet character encodings MUST use an + appropriate character set specification to be consistent with this + specification. + + The complete US-ASCII character set is listed in [US-ASCII]. Note + that the control characters including DEL (0-31, 127) have no defined + meaning apart from the combination CRLF (ASCII values 13 and 10) + indicating a new line. Two of the characters have de facto meanings + in wide use: FF (12) often means "start subsequent text on the + beginning of a new page"; and TAB or HT (9) often (though not always) + means "move the cursor to the next available column after the current + position where the column number is a multiple of 8 (counting the + first column as column 0)." Apart from this, any use of the control + characters or DEL in a body must be part of a private agreement + between the sender and recipient. Such private agreements are + discouraged and should be replaced by the other capabilities of this + document. + + NOTE: Beyond US-ASCII, an enormous proliferation of character sets + is possible. It is the opinion of the IETF working group that a + large number of character sets is NOT a good thing. We would + prefer to specify a single character set that can be used + universally for representing all of the world's languages in + electronic mail. Unfortunately, existing practice in several + communities seems to point to the continued use of multiple + character sets in the near future. For this reason, we define + + + +Borenstein & Freed [Page 26] + +RFC 1521 MIME September 1993 + + + names for a small number of character sets for which a strong + constituent base exists. + + The defined charset values are: + + US-ASCII -- as defined in [US-ASCII]. + + ISO-8859-X -- where "X" is to be replaced, as necessary, for the + parts of ISO-8859 [ISO-8859]. Note that the ISO 646 + character sets have deliberately been omitted in favor of + their 8859 replacements, which are the designated character + sets for Internet mail. As of the publication of this + document, the legitimate values for "X" are the digits 1 + through 9. + + The character sets specified above are the ones that were relatively + uncontroversial during the drafting of MIME. This document does not + endorse the use of any particular character set other than US-ASCII, + and recognizes that the future evolution of world character sets + remains unclear. It is expected that in the future, additional + character sets will be registered for use in MIME. + + Note that the character set used, if anything other than US-ASCII, + must always be explicitly specified in the Content-Type field. + + No other character set name may be used in Internet mail without the + publication of a formal specification and its registration with IANA, + or by private agreement, in which case the character set name must + begin with "X-". + + Implementors are discouraged from defining new character sets for + mail use unless absolutely necessary. + + The "charset" parameter has been defined primarily for the purpose of + textual data, and is described in this section for that reason. + However, it is conceivable that non-textual data might also wish to + specify a charset value for some purpose, in which case the same + syntax and values should be used. + + In general, mail-sending software must always use the "lowest common + denominator" character set possible. For example, if a body contains + only US-ASCII characters, it must be marked as being in the US-ASCII + character set, not ISO-8859-1, which, like all the ISO-8859 family of + character sets, is a superset of US-ASCII. More generally, if a + widely-used character set is a subset of another character set, and a + body contains only characters in the widely-used subset, it must be + labeled as being in that subset. This will increase the chances that + the recipient will be able to view the mail correctly. + + + +Borenstein & Freed [Page 27] + +RFC 1521 MIME September 1993 + + +7.1.2. The Text/plain subtype + + The primary subtype of text is "plain". This indicates plain + (unformatted) text. The default Content-Type for Internet mail, + "text/plain; charset=us-ascii", describes existing Internet practice. + That is, it is the type of body defined by RFC 822. + + No other text subtype is defined by this document. + + The formal grammar for the content-type header field for text is as + follows: + + text-type := "text" "/" text-subtype [";" "charset" "=" charset] + + text-subtype := "plain" / extension-token + + charset := "us-ascii"/ "iso-8859-1"/ "iso-8859-2"/ "iso-8859-3" + / "iso-8859-4"/ "iso-8859-5"/ "iso-8859-6"/ "iso-8859-7" + / "iso-8859-8" / "iso-8859-9" / extension-token + ; case insensitive + +7.2. The Multipart Content-Type + + In the case of multiple part entities, in which one or more different + sets of data are combined in a single body, a "multipart" Content- + Type field must appear in the entity's header. The body must then + contain one or more "body parts," each preceded by an encapsulation + boundary, and the last one followed by a closing boundary. Each part + starts with an encapsulation boundary, and then contains a body part + consisting of header area, a blank line, and a body area. Thus a + body part is similar to an RFC 822 message in syntax, but different + in meaning. + + A body part is NOT to be interpreted as actually being an RFC 822 + message. To begin with, NO header fields are actually required in + body parts. A body part that starts with a blank line, therefore, is + allowed and is a body part for which all default values are to be + assumed. In such a case, the absence of a Content-Type header field + implies that the corresponding body is plain US-ASCII text. The only + header fields that have defined meaning for body parts are those the + names of which begin with "Content-". All other header fields are + generally to be ignored in body parts. Although they should + generally be retained in mail processing, they may be discarded by + gateways if necessary. Such other fields are permitted to appear in + body parts but must not be depended on. "X-" fields may be created + for experimental or private purposes, with the recognition that the + information they contain may be lost at some gateways. + + + + +Borenstein & Freed [Page 28] + +RFC 1521 MIME September 1993 + + + NOTE: The distinction between an RFC 822 message and a body part + is subtle, but important. A gateway between Internet and X.400 + mail, for example, must be able to tell the difference between a + body part that contains an image and a body part that contains an + encapsulated message, the body of which is an image. In order to + represent the latter, the body part must have "Content-Type: + message", and its body (after the blank line) must be the + encapsulated message, with its own "Content-Type: image" header + field. The use of similar syntax facilitates the conversion of + messages to body parts, and vice versa, but the distinction + between the two must be understood by implementors. (For the + special case in which all parts actually are messages, a "digest" + subtype is also defined.) + + As stated previously, each body part is preceded by an encapsulation + boundary. The encapsulation boundary MUST NOT appear inside any of + the encapsulated parts. Thus, it is crucial that the composing agent + be able to choose and specify the unique boundary that will separate + the parts. + + All present and future subtypes of the "multipart" type must use an + identical syntax. Subtypes may differ in their semantics, and may + impose additional restrictions on syntax, but must conform to the + required syntax for the multipart type. This requirement ensures + that all conformant user agents will at least be able to recognize + and separate the parts of any multipart entity, even of an + unrecognized subtype. + + As stated in the definition of the Content-Transfer-Encoding field, + no encoding other than "7bit", "8bit", or "binary" is permitted for + entities of type "multipart". The multipart delimiters and header + fields are always represented as 7-bit ASCII in any case (though the + header fields may encode non-ASCII header text as per [RFC-1522]), + and data within the body parts can be encoded on a part-by-part + basis, with Content-Transfer-Encoding fields for each appropriate + body part. + + Mail gateways, relays, and other mail handling agents are commonly + known to alter the top-level header of an RFC 822 message. In + particular, they frequently add, remove, or reorder header fields. + Such alterations are explicitly forbidden for the body part headers + embedded in the bodies of messages of type "multipart." + +7.2.1. Multipart: The common syntax + + All subtypes of "multipart" share a common syntax, defined in this + section. A simple example of a multipart message also appears in + this section. An example of a more complex multipart message is + + + +Borenstein & Freed [Page 29] + +RFC 1521 MIME September 1993 + + + given in Appendix C. + + The Content-Type field for multipart entities requires one parameter, + "boundary", which is used to specify the encapsulation boundary. The + encapsulation boundary is defined as a line consisting entirely of + two hyphen characters ("-", decimal code 45) followed by the boundary + parameter value from the Content-Type header field. + + NOTE: The hyphens are for rough compatibility with the earlier RFC + 934 method of message encapsulation, and for ease of searching for + the boundaries in some implementations. However, it should be + noted that multipart messages are NOT completely compatible with + RFC 934 encapsulations; in particular, they do not obey RFC 934 + quoting conventions for embedded lines that begin with hyphens. + This mechanism was chosen over the RFC 934 mechanism because the + latter causes lines to grow with each level of quoting. The + combination of this growth with the fact that SMTP implementations + sometimes wrap long lines made the RFC 934 mechanism unsuitable + for use in the event that deeply-nested multipart structuring is + ever desired. + + WARNING TO IMPLEMENTORS: The grammar for parameters on the Content- + type field is such that it is often necessary to enclose the + boundaries in quotes on the Content-type line. This is not always + necessary, but never hurts. Implementors should be sure to study the + grammar carefully in order to avoid producing illegal Content-type + fields. Thus, a typical multipart Content-Type header field might + look like this: + + Content-Type: multipart/mixed; + boundary=gc0p4Jq0M2Yt08jU534c0p + + But the following is illegal: + + Content-Type: multipart/mixed; + boundary=gc0p4Jq0M:2Yt08jU534c0p + + (because of the colon) and must instead be represented as + + Content-Type: multipart/mixed; + boundary="gc0p4Jq0M:2Yt08jU534c0p" + + This indicates that the entity consists of several parts, each itself + with a structure that is syntactically identical to an RFC 822 + message, except that the header area might be completely empty, and + that the parts are each preceded by the line + + --gc0p4Jq0M:2Yt08jU534c0p + + + +Borenstein & Freed [Page 30] + +RFC 1521 MIME September 1993 + + + Note that the encapsulation boundary must occur at the beginning of a + line, i.e., following a CRLF, and that the initial CRLF is considered + to be attached to the encapsulation boundary rather than part of the + preceding part. The boundary must be followed immediately either by + another CRLF and the header fields for the next part, or by two + CRLFs, in which case there are no header fields for the next part + (and it is therefore assumed to be of Content-Type text/plain). + + NOTE: The CRLF preceding the encapsulation line is conceptually + attached to the boundary so that it is possible to have a part + that does not end with a CRLF (line break). Body parts that must + be considered to end with line breaks, therefore, must have two + CRLFs preceding the encapsulation line, the first of which is part + of the preceding body part, and the second of which is part of the + encapsulation boundary. + + Encapsulation boundaries must not appear within the encapsulations, + and must be no longer than 70 characters, not counting the two + leading hyphens. + + The encapsulation boundary following the last body part is a + distinguished delimiter that indicates that no further body parts + will follow. Such a delimiter is identical to the previous + delimiters, with the addition of two more hyphens at the end of the + line: + + --gc0p4Jq0M2Yt08jU534c0p-- + + There appears to be room for additional information prior to the + first encapsulation boundary and following the final boundary. These + areas should generally be left blank, and implementations must ignore + anything that appears before the first boundary or after the last + one. + + NOTE: These "preamble" and "epilogue" areas are generally not used + because of the lack of proper typing of these parts and the lack + of clear semantics for handling these areas at gateways, + particularly X.400 gateways. However, rather than leaving the + preamble area blank, many MIME implementations have found this to + be a convenient place to insert an explanatory note for recipients + who read the message with pre-MIME software, since such notes will + be ignored by MIME-compliant software. + + NOTE: Because encapsulation boundaries must not appear in the body + parts being encapsulated, a user agent must exercise care to + choose a unique boundary. The boundary in the example above could + have been the result of an algorithm designed to produce + boundaries with a very low probability of already existing in the + + + +Borenstein & Freed [Page 31] + +RFC 1521 MIME September 1993 + + + data to be encapsulated without having to prescan the data. + Alternate algorithms might result in more 'readable' boundaries + for a recipient with an old user agent, but would require more + attention to the possibility that the boundary might appear in the + encapsulated part. The simplest boundary possible is something + like "---", with a closing boundary of "-----". + + As a very simple example, the following multipart message has two + parts, both of them plain text, one of them explicitly typed and one + of them implicitly typed: + + From: Nathaniel Borenstein + To: Ned Freed + Subject: Sample message + MIME-Version: 1.0 + Content-type: multipart/mixed; boundary="simple + boundary" + + This is the preamble. It is to be ignored, though it + is a handy place for mail composers to include an + explanatory note to non-MIME conformant readers. + --simple boundary + + This is implicitly typed plain ASCII text. + It does NOT end with a linebreak. + --simple boundary + Content-type: text/plain; charset=us-ascii + + This is explicitly typed plain ASCII text. + It DOES end with a linebreak. + + --simple boundary-- + This is the epilogue. It is also to be ignored. + + The use of a Content-Type of multipart in a body part within another + multipart entity is explicitly allowed. In such cases, for obvious + reasons, care must be taken to ensure that each nested multipart + entity must use a different boundary delimiter. See Appendix C for an + example of nested multipart entities. + + The use of the multipart Content-Type with only a single body part + may be useful in certain contexts, and is explicitly permitted. + + The only mandatory parameter for the multipart Content-Type is the + boundary parameter, which consists of 1 to 70 characters from a set + of characters known to be very robust through email gateways, and NOT + ending with white space. (If a boundary appears to end with white + space, the white space must be presumed to have been added by a + + + +Borenstein & Freed [Page 32] + +RFC 1521 MIME September 1993 + + + gateway, and must be deleted.) It is formally specified by the + following BNF: + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" /"_" + / "," / "-" / "." / "/" / ":" / "=" / "?" + + Overall, the body of a multipart entity may be specified as + follows: + + multipart-body := preamble 1*encapsulation + close-delimiter epilogue + + encapsulation := delimiter body-part CRLF + + delimiter := "--" boundary CRLF ; taken from Content-Type field. + ; There must be no space + ; between "--" and boundary. + + close-delimiter := "--" boundary "--" CRLF ; Again, no space + by "--", + + preamble := discard-text ; to be ignored upon receipt. + + epilogue := discard-text ; to be ignored upon receipt. + + discard-text := *(*text CRLF) + + body-part := <"message" as defined in RFC 822, + with all header fields optional, and with the + specified delimiter not occurring anywhere in + the message body, either on a line by itself + or as a substring anywhere. Note that the + semantics of a part differ from the semantics + of a message, as described in the text.> + + NOTE: In certain transport enclaves, RFC 822 restrictions such as + the one that limits bodies to printable ASCII characters may not + be in force. (That is, the transport domains may resemble + standard Internet mail transport as specified in RFC821 and + assumed by RFC822, but without certain restrictions.) The + relaxation of these restrictions should be construed as locally + extending the definition of bodies, for example to include octets + outside of the ASCII range, as long as these extensions are + supported by the transport and adequately documented in the + + + +Borenstein & Freed [Page 33] + +RFC 1521 MIME September 1993 + + + Content-Transfer-Encoding header field. However, in no event are + headers (either message headers or body-part headers) allowed to + contain anything other than ASCII characters. + + NOTE: Conspicuously missing from the multipart type is a notion of + structured, related body parts. In general, it seems premature to + try to standardize interpart structure yet. It is recommended + that those wishing to provide a more structured or integrated + multipart messaging facility should define a subtype of multipart + that is syntactically identical, but that always expects the + inclusion of a distinguished part that can be used to specify the + structure and integration of the other parts, probably referring + to them by their Content-ID field. If this approach is used, + other implementations will not recognize the new subtype, but will + treat it as the primary subtype (multipart/mixed) and will thus be + able to show the user the parts that are recognized. + +7.2.2. The Multipart/mixed (primary) subtype + + The primary subtype for multipart, "mixed", is intended for use when + the body parts are independent and need to be bundled in a particular + order. Any multipart subtypes that an implementation does not + recognize must be treated as being of subtype "mixed". + +7.2.3. The Multipart/alternative subtype + + The multipart/alternative type is syntactically identical to + multipart/mixed, but the semantics are different. In particular, + each of the parts is an "alternative" version of the same + information. + + Systems should recognize that the content of the various parts are + interchangeable. Systems should choose the "best" type based on the + local environment and preferences, in some cases even through user + interaction. As with multipart/mixed, the order of body parts is + significant. In this case, the alternatives appear in an order of + increasing faithfulness to the original content. In general, the best + choice is the LAST part of a type supported by the recipient system's + local environment. + + Multipart/alternative may be used, for example, to send mail in a + fancy text format in such a way that it can easily be displayed + anywhere: + + + + + + + + +Borenstein & Freed [Page 34] + +RFC 1521 MIME September 1993 + + + From: Nathaniel Borenstein + To: Ned Freed + Subject: Formatted text mail + MIME-Version: 1.0 + Content-Type: multipart/alternative; boundary=boundary42 + + --boundary42 + + Content-Type: text/plain; charset=us-ascii + + ...plain text version of message goes here.... + --boundary42 + Content-Type: text/richtext + + .... RFC 1341 richtext version of same message goes here ... + --boundary42 + Content-Type: text/x-whatever + + .... fanciest formatted version of same message goes here + ... + --boundary42-- + + In this example, users whose mail system understood the "text/x- + whatever" format would see only the fancy version, while other users + would see only the richtext or plain text version, depending on the + capabilities of their system. + + In general, user agents that compose multipart/alternative entities + must place the body parts in increasing order of preference, that is, + with the preferred format last. For fancy text, the sending user + agent should put the plainest format first and the richest format + last. Receiving user agents should pick and display the last format + they are capable of displaying. In the case where one of the + alternatives is itself of type "multipart" and contains unrecognized + sub-parts, the user agent may choose either to show that alternative, + an earlier alternative, or both. + + NOTE: From an implementor's perspective, it might seem more + sensible to reverse this ordering, and have the plainest + alternative last. However, placing the plainest alternative first + is the friendliest possible option when multipart/alternative + entities are viewed using a non-MIME-conformant mail reader. + While this approach does impose some burden on conformant mail + readers, interoperability with older mail readers was deemed to be + more important in this case. + + It may be the case that some user agents, if they can recognize more + than one of the formats, will prefer to offer the user the choice of + + + +Borenstein & Freed [Page 35] + +RFC 1521 MIME September 1993 + + + which format to view. This makes sense, for example, if mail + includes both a nicely-formatted image version and an easily-edited + text version. What is most critical, however, is that the user not + automatically be shown multiple versions of the same data. Either + the user should be shown the last recognized version or should be + given the choice. + + NOTE ON THE SEMANTICS OF CONTENT-ID IN MULTIPART/ALTERNATIVE: Each + part of a multipart/alternative entity represents the same data, but + the mappings between the two are not necessarily without information + loss. For example, information is lost when translating ODA to + PostScript or plain text. It is recommended that each part should + have a different Content-ID value in the case where the information + content of the two parts is not identical. However, where the + information content is identical -- for example, where several parts + of type "application/external- body" specify alternate ways to access + the identical data -- the same Content-ID field value should be used, + to optimize any cacheing mechanisms that might be present on the + recipient's end. However, it is recommended that the Content-ID + values used by the parts should not be the same Content-ID value that + describes the multipart/alternative as a whole, if there is any such + Content-ID field. That is, one Content-ID value will refer to the + multipart/alternative entity, while one or more other Content-ID + values will refer to the parts inside it. + +7.2.4. The Multipart/digest subtype + + This document defines a "digest" subtype of the multipart Content- + Type. This type is syntactically identical to multipart/mixed, but + the semantics are different. In particular, in a digest, the default + Content-Type value for a body part is changed from "text/plain" to + "message/rfc822". This is done to allow a more readable digest + format that is largely compatible (except for the quoting convention) + with RFC 934. + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 36] + +RFC 1521 MIME September 1993 + + + A digest in this format might, then, look something like this: + + From: Moderator-Address + To: Recipient-List + MIME-Version: 1.0 + Subject: Internet Digest, volume 42 + Content-Type: multipart/digest; + boundary="---- next message ----" + + ------ next message ---- + + From: someone-else + Subject: my opinion + + ...body goes here ... + + ------ next message ---- + + From: someone-else-again + Subject: my different opinion + + ... another body goes here... + + ------ next message ------ + +7.2.5. The Multipart/parallel subtype + + This document defines a "parallel" subtype of the multipart Content- + Type. This type is syntactically identical to multipart/mixed, but + the semantics are different. In particular, in a parallel entity, + the order of body parts is not significant. + + A common presentation of this type is to display all of the parts + simultaneously on hardware and software that are capable of doing so. + However, composing agents should be aware that many mail readers will + lack this capability and will show the parts serially in any event. + +7.2.6. Other Multipart subtypes + + Other multipart subtypes are expected in the future. MIME + implementations must in general treat unrecognized subtypes of + multipart as being equivalent to "multipart/mixed". + + The formal grammar for content-type header fields for multipart data + is given by: + + multipart-type := "multipart" "/" multipart-subtype + ";" "boundary" "=" boundary + + + +Borenstein & Freed [Page 37] + +RFC 1521 MIME September 1993 + + + multipart-subtype := "mixed" / "parallel" / "digest" + / "alternative" / extension-token + +7.3. The Message Content-Type + + It is frequently desirable, in sending mail, to encapsulate another + mail message. For this common operation, a special Content-Type, + "message", is defined. The primary subtype, message/rfc822, has no + required parameters in the Content-Type field. Additional subtypes, + "partial" and "External-body", do have required parameters. These + subtypes are explained below. + + NOTE: It has been suggested that subtypes of message might be + defined for forwarded or rejected messages. However, forwarded + and rejected messages can be handled as multipart messages in + which the first part contains any control or descriptive + information, and a second part, of type message/rfc822, is the + forwarded or rejected message. Composing rejection and forwarding + messages in this manner will preserve the type information on the + original message and allow it to be correctly presented to the + recipient, and hence is strongly encouraged. + + As stated in the definition of the Content-Transfer-Encoding field, + no encoding other than "7bit", "8bit", or "binary" is permitted for + messages or parts of type "message". Even stronger restrictions + apply to the subtypes "message/partial" and "message/external-body", + as specified below. The message header fields are always US-ASCII in + any case, and data within the body can still be encoded, in which + case the Content-Transfer-Encoding header field in the encapsulated + message will reflect this. Non-ASCII text in the headers of an + encapsulated message can be specified using the mechanisms described + in [RFC-1522]. + + Mail gateways, relays, and other mail handling agents are commonly + known to alter the top-level header of an RFC 822 message. In + particular, they frequently add, remove, or reorder header fields. + Such alterations are explicitly forbidden for the encapsulated + headers embedded in the bodies of messages of type "message." + +7.3.1. The Message/rfc822 (primary) subtype + + A Content-Type of "message/rfc822" indicates that the body contains + an encapsulated message, with the syntax of an RFC 822 message. + However, unlike top-level RFC 822 messages, it is not required that + each message/rfc822 body must include a "From", "Subject", and at + least one destination header. + + It should be noted that, despite the use of the numbers "822", a + + + +Borenstein & Freed [Page 38] + +RFC 1521 MIME September 1993 + + + message/rfc822 entity can include enhanced information as defined in + this document. In other words, a message/rfc822 message may be a + MIME message. + +7.3.2. The Message/Partial subtype + + A subtype of message, "partial", is defined in order to allow large + objects to be delivered as several separate pieces of mail and + automatically reassembled by the receiving user agent. (The concept + is similar to IP fragmentation/reassembly in the basic Internet + Protocols.) This mechanism can be used when intermediate transport + agents limit the size of individual messages that can be sent. + Content-Type "message/partial" thus indicates that the body contains + a fragment of a larger message. + + Three parameters must be specified in the Content-Type field of type + message/partial: The first, "id", is a unique identifier, as close to + a world-unique identifier as possible, to be used to match the parts + together. (In general, the identifier is essentially a message-id; + if placed in double quotes, it can be any message-id, in accordance + with the BNF for "parameter" given earlier in this specification.) + The second, "number", an integer, is the part number, which indicates + where this part fits into the sequence of fragments. The third, + "total", another integer, is the total number of parts. This third + subfield is required on the final part, and is optional (though + encouraged) on the earlier parts. Note also that these parameters + may be given in any order. + + Thus, part 2 of a 3-part message may have either of the following + header fields: + + Content-Type: Message/Partial; + number=2; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com" + + Content-Type: Message/Partial; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com"; + number=2 + + But part 3 MUST specify the total number of parts: + + Content-Type: Message/Partial; + number=3; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com" + + Note that part numbering begins with 1, not 0. + + When the parts of a message broken up in this manner are put + + + +Borenstein & Freed [Page 39] + +RFC 1521 MIME September 1993 + + + together, the result is a complete MIME entity, which may have its + own Content-Type header field, and thus may contain any other data + type. + + Message fragmentation and reassembly: The semantics of a reassembled + partial message must be those of the "inner" message, rather than of + a message containing the inner message. This makes it possible, for + example, to send a large audio message as several partial messages, + and still have it appear to the recipient as a simple audio message + rather than as an encapsulated message containing an audio message. + That is, the encapsulation of the message is considered to be + "transparent". + + When generating and reassembling the parts of a message/partial + message, the headers of the encapsulated message must be merged with + the headers of the enclosing entities. In this process the following + rules must be observed: + + (1) All of the header fields from the initial enclosing entity + (part one), except those that start with "Content-" and the + specific header fields "Message-ID", "Encrypted", and "MIME- + Version", must be copied, in order, to the new message. + + (2) Only those header fields in the enclosed message which start + with "Content-" and "Message-ID", "Encrypted", and "MIME-Version" + must be appended, in order, to the header fields of the new + message. Any header fields in the enclosed message which do not + start with "Content-" (except for "Message-ID", "Encrypted", and + "MIME-Version") will be ignored. + + (3) All of the header fields from the second and any subsequent + messages will be ignored. + + For example, if an audio message is broken into two parts, the first + part might look something like this: + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + Message-ID: + MIME-Version: 1.0 + Content-type: message/partial; + id="ABC@host.com"; + number=1; total=2 + + X-Weird-Header-1: Bar + X-Weird-Header-2: Hello + + + +Borenstein & Freed [Page 40] + +RFC 1521 MIME September 1993 + + + Message-ID: + MIME-Version: 1.0 + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here... + + and the second half might look something like this: + + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + MIME-Version: 1.0 + Message-ID: + Content-type: message/partial; + id="ABC@host.com"; number=2; total=2 + + ... second half of encoded audio data goes here... + + Then, when the fragmented message is reassembled, the resulting + message to be displayed to the user should look something like this: + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Subject: Audio mail + Message-ID: + MIME-Version: 1.0 + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here... + ... second half of encoded audio data goes here... + + Note on encoding of MIME entities encapsulated inside message/partial + entities: Because data of type "message" may never be encoded in + base64 or quoted-printable, a problem might arise if message/partial + entities are constructed in an environment that supports binary or + 8-bit transport. The problem is that the binary data would be split + into multiple message/partial objects, each of them requiring binary + transport. If such objects were encountered at a gateway into a 7- + bit transport environment, there would be no way to properly encode + them for the 7-bit world, aside from waiting for all of the parts, + reassembling the message, and then encoding the reassembled data in + base64 or quoted-printable. Since it is possible that different + parts might go through different gateways, even this is not an + acceptable solution. For this reason, it is specified that MIME + entities of type message/partial must always have a content- + + + +Borenstein & Freed [Page 41] + +RFC 1521 MIME September 1993 + + + transfer-encoding of 7-bit (the default). In particular, even in + environments that support binary or 8-bit transport, the use of a + content-transfer-encoding of "8bit" or "binary" is explicitly + prohibited for entities of type message/partial. + + It should be noted that, because some message transfer agents may + choose to automatically fragment large messages, and because such + agents may use different fragmentation thresholds, it is possible + that the pieces of a partial message, upon reassembly, may prove + themselves to comprise a partial message. This is explicitly + permitted. + + It should also be noted that the inclusion of a "References" field in + the headers of the second and subsequent pieces of a fragmented + message that references the Message-Id on the previous piece may be + of benefit to mail readers that understand and track references. + However, the generation of such "References" fields is entirely + optional. + + Finally, it should be noted that the "Encrypted" header field has + been made obsolete by Privacy Enhanced Messaging (PEM), but the rules + above are believed to describe the correct way to treat it if it is + encountered in the context of conversion to and from message/partial + fragments. + +7.3.3. The Message/External-Body subtype + + The external-body subtype indicates that the actual body data are not + included, but merely referenced. In this case, the parameters + describe a mechanism for accessing the external data. + + When an entity is of type "message/external-body", it consists of a + header, two consecutive CRLFs, and the message header for the + encapsulated message. If another pair of consecutive CRLFs appears, + this of course ends the message header for the encapsulated message. + However, since the encapsulated message's body is itself external, it + does NOT appear in the area that follows. For example, consider the + following message: + + Content-type: message/external-body; access- + type=local-file; + + name="/u/nsb/Me.gif" + + Content-type: image/gif + Content-ID: + Content-Transfer-Encoding: binary + + + + +Borenstein & Freed [Page 42] + +RFC 1521 MIME September 1993 + + + THIS IS NOT REALLY THE BODY! + + The area at the end, which might be called the "phantom body", is + ignored for most external-body messages. However, it may be used to + contain auxiliary information for some such messages, as indeed it is + when the access-type is "mail-server". Of the access-types defined + by this document, the phantom body is used only when the access-type + is "mail-server". In all other cases, the phantom body is ignored. + + The only always-mandatory parameter for message/external-body is + "access-type"; all of the other parameters may be mandatory or + optional depending on the value of access-type. + + ACCESS-TYPE -- A case-insensitive word, indicating the supported + access mechanism by which the file or data may be obtained. + Values include, but are not limited to, "FTP", "ANON-FTP", "TFTP", + "AFS", "LOCAL-FILE", and "MAIL-SERVER". Future values, except for + experimental values beginning with "X-" must be registered with + IANA, as described in Appendix E . + + In addition, the following three parameters are optional for ALL + access-types: + + EXPIRATION -- The date (in the RFC 822 "date-time" syntax, as + extended by RFC 1123 to permit 4 digits in the year field) after + which the existence of the external data is not guaranteed. + + SIZE -- The size (in octets) of the data. The intent of this + parameter is to help the recipient decide whether or not to expend + the necessary resources to retrieve the external data. Note that + this describes the size of the data in its canonical form, that + is, before any Content- Transfer-Encoding has been applied or + after the data have been decoded. + + PERMISSION -- A case-insensitive field that indicates whether or + not it is expected that clients might also attempt to overwrite + the data. By default, or if permission is "read", the assumption + is that they are not, and that if the data is retrieved once, it + is never needed again. If PERMISSION is "read-write", this + assumption is invalid, and any local copy must be considered no + more than a cache. "Read" and "Read-write" are the only defined + values of permission. + + The precise semantics of the access-types defined here are described + in the sections that follow. + + The encapsulated headers in ALL message/external-body entities MUST + include a Content-ID header field to give a unique identifier by + + + +Borenstein & Freed [Page 43] + +RFC 1521 MIME September 1993 + + + which to reference the data. This identifier may be used for + cacheing mechanisms, and for recognizing the receipt of the data when + the access-type is "mail-server". + + Note that, as specified here, the tokens that describe external-body + data, such as file names and mail server commands, are required to be + in the US-ASCII character set. If this proves problematic in + practice, a new mechanism may be required as a future extension to + MIME, either as newly defined access-types for message/external-body + or by some other mechanism. + + As with message/partial, it is specified that MIME entities of type + message/external-body must always have a content-transfer-encoding of + 7-bit (the default). In particular, even in environments that + support binary or 8-bit transport, the use of a content-transfer- + encoding of "8bit" or "binary" is explicitly prohibited for entities + of type message/external-body. + +7.3.3.1. The "ftp" and "tftp" access-types + + An access-type of FTP or TFTP indicates that the message body is + accessible as a file using the FTP [RFC-959] or TFTP [RFC-783] + protocols, respectively. For these access-types, the following + additional parameters are mandatory: + + NAME -- The name of the file that contains the actual body data. + + SITE -- A machine from which the file may be obtained, using the + given protocol. This must be a fully qualified domain name, not a + nickname. + + Before any data are retrieved, using FTP, the user will generally + need to be asked to provide a login id and a password for the machine + named by the site parameter. For security reasons, such an id and + password are not specified as content-type parameters, but must be + obtained from the user. + + In addition, the following parameters are optional: + + DIRECTORY -- A directory from which the data named by NAME should + be retrieved. + + MODE -- A case-insensitive string indicating the mode to be used + when retrieving the information. The legal values for access-type + "TFTP" are "NETASCII", "OCTET", and "MAIL", as specified by the + TFTP protocol [RFC-783]. The legal values for access-type "FTP" + are "ASCII", "EBCDIC", "IMAGE", and "LOCALn" where "n" is a + decimal integer, typically 8. These correspond to the + + + +Borenstein & Freed [Page 44] + +RFC 1521 MIME September 1993 + + + representation types "A" "E" "I" and "L n" as specified by the FTP + protocol [RFC-959]. Note that "BINARY" and "TENEX" are not valid + values for MODE, but that "OCTET" or "IMAGE" or "LOCAL8" should be + used instead. IF MODE is not specified, the default value is + "NETASCII" for TFTP and "ASCII" otherwise. + +7.3.3.2. The "anon-ftp" access-type + + The "anon-ftp" access-type is identical to the "ftp" access type, + except that the user need not be asked to provide a name and password + for the specified site. Instead, the ftp protocol will be used with + login "anonymous" and a password that corresponds to the user's email + address. + +7.3.3.3. The "local-file" and "afs" access-types + + An access-type of "local-file" indicates that the actual body is + accessible as a file on the local machine. An access-type of "afs" + indicates that the file is accessible via the global AFS file system. + In both cases, only a single parameter is required: + + NAME -- The name of the file that contains the actual body data. + + The following optional parameter may be used to describe the locality + of reference for the data, that is, the site or sites at which the + file is expected to be visible: + + SITE -- A domain specifier for a machine or set of machines that + are known to have access to the data file. Asterisks may be used + for wildcard matching to a part of a domain name, such as + "*.bellcore.com", to indicate a set of machines on which the data + should be directly visible, while a single asterisk may be used to + indicate a file that is expected to be universally available, + e.g., via a global file system. + +7.3.3.4. The "mail-server" access-type + + The "mail-server" access-type indicates that the actual body is + available from a mail server. The mandatory parameter for this + access-type is: + + SERVER -- The email address of the mail server from which the + actual body data can be obtained. + + Because mail servers accept a variety of syntaxes, some of which is + multiline, the full command to be sent to a mail server is not + included as a parameter on the content-type line. Instead, it is + provided as the "phantom body" when the content-type is + + + +Borenstein & Freed [Page 45] + +RFC 1521 MIME September 1993 + + + message/external-body and the access- type is mail-server. + + An optional parameter for this access-type is: + + SUBJECT -- The subject that is to be used in the mail that is sent + to obtain the data. Note that keying mail servers on Subject lines + is NOT recommended, but such mail servers are known to exist. + + Note that MIME does not define a mail server syntax. Rather, it + allows the inclusion of arbitrary mail server commands in the phantom + body. Implementations must include the phantom body in the body of + the message it sends to the mail server address to retrieve the + relevant data. + + It is worth noting that, unlike other access-types, mail-server + access is asynchronous and will happen at an unpredictable time in + the future. For this reason, it is important that there be a + mechanism by which the returned data can be matched up with the + original message/external-body entity. MIME mailservers must use the + same Content-ID field on the returned message that was used in the + original message/external-body entity, to facilitate such matching. + +7.3.3.5. Examples and Further Explanations + + With the emerging possibility of very wide-area file systems, it + becomes very hard to know in advance the set of machines where a file + will and will not be accessible directly from the file system. + Therefore it may make sense to provide both a file name, to be tried + directly, and the name of one or more sites from which the file is + known to be accessible. An implementation can try to retrieve remote + files using FTP or any other protocol, using anonymous file retrieval + or prompting the user for the necessary name and password. If an + external body is accessible via multiple mechanisms, the sender may + include multiple parts of type message/external-body within an entity + of type multipart/alternative. + + However, the external-body mechanism is not intended to be limited to + file retrieval, as shown by the mail-server access-type. Beyond + this, one can imagine, for example, using a video server for external + references to video clips. + + If an entity is of type "message/external-body", then the body of the + entity will contain the header fields of the encapsulated message. + The body itself is to be found in the external location. This means + that if the body of the "message/external-body" message contains two + consecutive CRLFs, everything after those pairs is NOT part of the + message itself. For most message/external-body messages, this + trailing area must simply be ignored. However, it is a convenient + + + +Borenstein & Freed [Page 46] + +RFC 1521 MIME September 1993 + + + place for additional data that cannot be included in the content-type + header field. In particular, if the "access-type" value is "mail- + server", then the trailing area must contain commands to be sent to + the mail server at the address given by the value of the SERVER + parameter. + + The embedded message header fields which appear in the body of the + message/external-body data must be used to declare the Content-type + of the external body if it is anything other than plain ASCII text, + since the external body does not have a header section to declare its + type. Similarly, any Content-transfer-encoding other than "7bit" + must also be declared here. Thus a complete message/external-body + message, referring to a document in PostScript format, might look + like this: + + From: Whomever + To: Someone + Subject: whatever + MIME-Version: 1.0 + Message-ID: + Content-Type: multipart/alternative; boundary=42 + Content-ID: + + --42 + Content-Type: message/external-body; + name="BodyFormats.ps"; + site="thumper.bellcore.com"; + access-type=ANON-FTP; + directory="pub"; + mode="image"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + --42 + Content-Type: message/external-body; + name="/u/nsb/writing/rfcs/RFC-MIME.ps"; + site="thumper.bellcore.com"; + access-type=AFS + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + --42 + Content-Type: message/external-body; + access-type=mail-server + + + +Borenstein & Freed [Page 47] + +RFC 1521 MIME September 1993 + + + server="listserv@bogus.bitnet"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + get RFC-MIME.DOC + + --42-- + + Note that in the above examples, the default Content-transfer- + encoding of "7bit" is assumed for the external postscript data. + + Like the message/partial type, the message/external-body type is + intended to be transparent, that is, to convey the data type in the + external body rather than to convey a message with a body of that + type. Thus the headers on the outer and inner parts must be merged + using the same rules as for message/partial. In particular, this + means that the Content-type header is overridden, but the From and + Subject headers are preserved. + + Note that since the external bodies are not transported as mail, they + need not conform to the 7-bit and line length requirements, but might + in fact be binary files. Thus a Content-Transfer-Encoding is not + generally necessary, though it is permitted. + + Note that the body of a message of type "message/external-body" is + governed by the basic syntax for an RFC 822 message. In particular, + anything before the first consecutive pair of CRLFs is header + information, while anything after it is body information, which is + ignored for most access-types. + + The formal grammar for content-type header fields for data of type + message is given by: + + message-type := "message" "/" message-subtype + + message-subtype := "rfc822" + / "partial" 2#3partial-param + / "external-body" 1*external-param + / extension-token + + partial-param := (";" "id" "=" value) + / (";" "number" "=" 1*DIGIT) + / (";" "total" "=" 1*DIGIT) + ; id & number required; total required for last part + + external-param := (";" "access-type" "=" atype) + + + +Borenstein & Freed [Page 48] + +RFC 1521 MIME September 1993 + + + / (";" "expiration" "=" date-time) + ; Note that date-time is quoted + / (";" "size" "=" 1*DIGIT) + / (";" "permission" "=" ("read" / "read-write")) + ; Permission is case-insensitive + / (";" "name" "=" value) + / (";" "site" "=" value) + / (";" "dir" "=" value) + / (";" "mode" "=" value) + / (";" "server" "=" value) + / (";" "subject" "=" value) + ; access-type required;others required based on access-type + + atype := "ftp" / "anon-ftp" / "tftp" / "local-file" + / "afs" / "mail-server" / extension-token + ; Case-insensitive + +7.4. The Application Content-Type + + The "application" Content-Type is to be used for data which do not + fit in any of the other categories, and particularly for data to be + processed by mail-based uses of application programs. This is + information which must be processed by an application before it is + viewable or usable to a user. Expected uses for Content-Type + application include mail-based file transfer, spreadsheets, data for + mail-based scheduling systems, and languages for "active" + (computational) email. (The latter, in particular, can pose security + problems which must be understood by implementors, and are considered + in detail in the discussion of the application/PostScript content- + type.) + + For example, a meeting scheduler might define a standard + representation for information about proposed meeting dates. An + intelligent user agent would use this information to conduct a dialog + with the user, and might then send further mail based on that dialog. + More generally, there have been several "active" messaging languages + developed in which programs in a suitably specialized language are + sent through the mail and automatically run in the recipient's + environment. + + Such applications may be defined as subtypes of the "application" + Content-Type. This document defines two subtypes: octet-stream, and + PostScript. + + In general, the subtype of application will often be the name of the + application for which the data are intended. This does not mean, + however, that any application program name may be used freely as a + subtype of application. Such usages (other than subtypes beginning + + + +Borenstein & Freed [Page 49] + +RFC 1521 MIME September 1993 + + + with "x-") must be registered with IANA, as described in Appendix E. + +7.4.1. The Application/Octet-Stream (primary) subtype + + The primary subtype of application, "octet-stream", may be used to + indicate that a body contains binary data. The set of possible + parameters includes, but is not limited to: + + TYPE -- the general type or category of binary data. This is + intended as information for the human recipient rather than for + any automatic processing. + + PADDING -- the number of bits of padding that were appended to the + bit-stream comprising the actual contents to produce the enclosed + byte-oriented data. This is useful for enclosing a bit-stream in + a body when the total number of bits is not a multiple of the byte + size. + + An additional parameter, "conversions", was defined in [RFC-1341] but + has been removed. + + RFC 1341 also defined the use of a "NAME" parameter which gave a + suggested file name to be used if the data were to be written to a + file. This has been deprecated in anticipation of a separate + Content-Disposition header field, to be defined in a subsequent RFC. + + The recommended action for an implementation that receives + application/octet-stream mail is to simply offer to put the data in a + file, with any Content-Transfer-Encoding undone, or perhaps to use it + as input to a user-specified process. + + To reduce the danger of transmitting rogue programs through the mail, + it is strongly recommended that implementations NOT implement a + path-search mechanism whereby an arbitrary program named in the + Content-Type parameter (e.g., an "interpreter=" parameter) is found + and executed using the mail body as input. + +7.4.2. The Application/PostScript subtype + + A Content-Type of "application/postscript" indicates a PostScript + program. Currently two variants of the PostScript language are + allowed; the original level 1 variant is described in [POSTSCRIPT] + and the more recent level 2 variant is described in [POSTSCRIPT2]. + + PostScript is a registered trademark of Adobe Systems, Inc. Use of + the MIME content-type "application/postscript" implies recognition of + that trademark and all the rights it entails. + + + + +Borenstein & Freed [Page 50] + +RFC 1521 MIME September 1993 + + + The PostScript language definition provides facilities for internal + labeling of the specific language features a given program uses. This + labeling, called the PostScript document structuring conventions, is + very general and provides substantially more information than just + the language level. + + The use of document structuring conventions, while not required, is + strongly recommended as an aid to interoperability. Documents which + lack proper structuring conventions cannot be tested to see whether + or not they will work in a given environment. As such, some systems + may assume the worst and refuse to process unstructured documents. + + The execution of general-purpose PostScript interpreters entails + serious security risks, and implementors are discouraged from simply + sending PostScript email bodies to "off-the-shelf" interpreters. + While it is usually safe to send PostScript to a printer, where the + potential for harm is greatly constrained, implementors should + consider all of the following before they add interactive display of + PostScript bodies to their mail readers. + + The remainder of this section outlines some, though probably not all, + of the possible problems with sending PostScript through the mail. + + Dangerous operations in the PostScript language include, but may not + be limited to, the PostScript operators deletefile, renamefile, + filenameforall, and file. File is only dangerous when applied to + something other than standard input or output. Implementations may + also define additional nonstandard file operators; these may also + pose a threat to security. Filenameforall, the wildcard file search + operator, may appear at first glance to be harmless. Note, however, + that this operator has the potential to reveal information about what + files the recipient has access to, and this information may itself be + sensitive. Message senders should avoid the use of potentially + dangerous file operators, since these operators are quite likely to + be unavailable in secure PostScript implementations. Message- + receiving and -displaying software should either completely disable + all potentially dangerous file operators or take special care not to + delegate any special authority to their operation. These operators + should be viewed as being done by an outside agency when interpreting + PostScript documents. Such disabling and/or checking should be done + completely outside of the reach of the PostScript language itself; + care should be taken to insure that no method exists for re-enabling + full-function versions of these operators. + + The PostScript language provides facilities for exiting the normal + interpreter, or server, loop. Changes made in this "outer" + environment are customarily retained across documents, and may in + some cases be retained semipermanently in nonvolatile memory. The + + + +Borenstein & Freed [Page 51] + +RFC 1521 MIME September 1993 + + + operators associated with exiting the interpreter loop have the + potential to interfere with subsequent document processing. As such, + their unrestrained use constitutes a threat of service denial. + PostScript operators that exit the interpreter loop include, but may + not be limited to, the exitserver and startjob operators. Message- + sending software should not generate PostScript that depends on + exiting the interpreter loop to operate. The ability to exit will + probably be unavailable in secure PostScript implementations. + Message-receiving and -displaying software should, if possible, + disable the ability to make retained changes to the PostScript + environment, and eliminate the startjob and exitserver commands. If + these commands cannot be eliminated, the password associated with + them should at least be set to a hard-to-guess value. + + PostScript provides operators for setting system-wide and device- + specific parameters. These parameter settings may be retained across + jobs and may potentially pose a threat to the correct operation of + the interpreter. The PostScript operators that set system and device + parameters include, but may not be limited to, the setsystemparams + and setdevparams operators. Message-sending software should not + generate PostScript that depends on the setting of system or device + parameters to operate correctly. The ability to set these parameters + will probably be unavailable in secure PostScript implementations. + Message-receiving and -displaying software should, if possible, + disable the ability to change system and device parameters. If these + operators cannot be disabled, the password associated with them + should at least be set to a hard-to-guess value. + + Some PostScript implementations provide nonstandard facilities for + the direct loading and execution of machine code. Such facilities + are quite obviously open to substantial abuse. Message-sending + software should not make use of such features. Besides being totally + hardware- specific, they are also likely to be unavailable in secure + implementations of PostScript. Message-receiving and -displaying + software should not allow such operators to be used if they exist. + + PostScript is an extensible language, and many, if not most, + implementations of it provide a number of their own extensions. This + document does not deal with such extensions explicitly since they + constitute an unknown factor. Message-sending software should not + make use of nonstandard extensions; they are likely to be missing + from some implementations. Message-receiving and -displaying software + should make sure that any nonstandard PostScript operators are secure + and don't present any kind of threat. + + It is possible to write PostScript that consumes huge amounts of + various system resources. It is also possible to write PostScript + programs that loop infinitely. Both types of programs have the + + + +Borenstein & Freed [Page 52] + +RFC 1521 MIME September 1993 + + + potential to cause damage if sent to unsuspecting recipients. + Message-sending software should avoid the construction and + dissemination of such programs, which is antisocial. Message- + receiving and -displaying software should provide appropriate + mechanisms to abort processing of a document after a reasonable + amount of time has elapsed. In addition, PostScript interpreters + should be limited to the consumption of only a reasonable amount of + any given system resource. + + Finally, bugs may exist in some PostScript interpreters which could + possibly be exploited to gain unauthorized access to a recipient's + system. Apart from noting this possibility, there is no specific + action to take to prevent this, apart from the timely correction of + such bugs if any are found. + +7.4.3. Other Application subtypes + + It is expected that many other subtypes of application will be + defined in the future. MIME implementations must generally treat any + unrecognized subtypes as being equivalent to application/octet- + stream. + + The formal grammar for content-type header fields for application + data is given by: + + application-type := "application" "/" application-subtype + + application-subtype := ("octet-stream" *stream-param) + / "postscript" / extension-token + + stream-param := (";" "type" "=" value) + / (";" "padding" "=" padding) + + padding := "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" + +7.5. The Image Content-Type + + A Content-Type of "image" indicates that the body contains an image. + The subtype names the specific image format. These names are case + insensitive. Two initial subtypes are "jpeg" for the JPEG format, + JFIF encoding, and "gif" for GIF format [GIF]. + + The list of image subtypes given here is neither exclusive nor + exhaustive, and is expected to grow as more types are registered with + IANA, as described in Appendix E. + + The formal grammar for the content-type header field for data of type + image is given by: + + + +Borenstein & Freed [Page 53] + +RFC 1521 MIME September 1993 + + + image-type := "image" "/" ("gif" / "jpeg" / extension-token) + +7.6. The Audio Content-Type + + A Content-Type of "audio" indicates that the body contains audio + data. Although there is not yet a consensus on an "ideal" audio + format for use with computers, there is a pressing need for a format + capable of providing interoperable behavior. + + The initial subtype of "basic" is specified to meet this requirement + by providing an absolutely minimal lowest common denominator audio + format. It is expected that richer formats for higher quality and/or + lower bandwidth audio will be defined by a later document. + + The content of the "audio/basic" subtype is audio encoded using 8-bit + ISDN mu-law [PCM]. When this subtype is present, a sample rate of + 8000 Hz and a single channel is assumed. + + The formal grammar for the content-type header field for data of type + audio is given by: + + audio-type := "audio" "/" ("basic" / extension-token) + +7.7. The Video Content-Type + + A Content-Type of "video" indicates that the body contains a time- + varying-picture image, possibly with color and coordinated sound. + The term "video" is used extremely generically, rather than with + reference to any particular technology or format, and is not meant to + preclude subtypes such as animated drawings encoded compactly. The + subtype "mpeg" refers to video coded according to the MPEG standard + [MPEG]. + + Note that although in general this document strongly discourages the + mixing of multiple media in a single body, it is recognized that many + so-called "video" formats include a representation for synchronized + audio, and this is explicitly permitted for subtypes of "video". + + The formal grammar for the content-type header field for data of type + video is given by: + + video-type := "video" "/" ("mpeg" / extension-token) + +7.8. Experimental Content-Type Values + + A Content-Type value beginning with the characters "X-" is a private + value, to be used by consenting mail systems by mutual agreement. + Any format without a rigorous and public definition must be named + + + +Borenstein & Freed [Page 54] + +RFC 1521 MIME September 1993 + + + with an "X-" prefix, and publicly specified values shall never begin + with "X-". (Older versions of the widely-used Andrew system use the + "X-BE2" name, so new systems should probably choose a different + name.) + + In general, the use of "X-" top-level types is strongly discouraged. + Implementors should invent subtypes of the existing types whenever + possible. The invention of new types is intended to be restricted + primarily to the development of new media types for email, such as + digital odors or holography, and not for new data formats in general. + In many cases, a subtype of application will be more appropriate than + a new top-level type. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 55] + +RFC 1521 MIME September 1993 + + +8. Summary + + Using the MIME-Version, Content-Type, and Content-Transfer-Encoding + header fields, it is possible to include, in a standardized way, + arbitrary types of data objects with RFC 822 conformant mail + messages. No restrictions imposed by either RFC 821 or RFC 822 are + violated, and care has been taken to avoid problems caused by + additional restrictions imposed by the characteristics of some + Internet mail transport mechanisms (see Appendix B). The "multipart" + and "message" Content-Types allow mixing and hierarchical structuring + of objects of different types in a single message. Further Content- + Types provide a standardized mechanism for tagging messages or body + parts as audio, image, or several other kinds of data. A + distinguished parameter syntax allows further specification of data + format details, particularly the specification of alternate character + sets. Additional optional header fields provide mechanisms for + certain extensions deemed desirable by many implementors. Finally, a + number of useful Content-Types are defined for general use by + consenting user agents, notably message/partial, and + message/external-body. + +9. Security Considerations + + Security issues are discussed in Section 7.4.2 and in Appendix F. + Implementors should pay special attention to the security + implications of any mail content-types that can cause the remote + execution of any actions in the recipient's environment. In such + cases, the discussion of the application/postscript content-type in + Section 7.4.2 may serve as a model for considering other content- + types with remote execution capabilities. + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 56] + +RFC 1521 MIME September 1993 + + +10. Authors' Addresses + + For more information, the authors of this document may be contacted + via Internet mail: + + Nathaniel S. Borenstein + MRE 2D-296, Bellcore + 445 South St. + Morristown, NJ 07962-1910 + + Phone: +1 201 829 4270 + Fax: +1 201 829 7019 + Email: nsb@bellcore.com + + + Ned Freed + Innosoft International, Inc. + 250 West First Street + Suite 240 + Claremont, CA 91711 + + Phone: +1 909 624 7907 + Fax: +1 909 621 5319 + Email: ned@innosoft.com + + MIME is a result of the work of the Internet Engineering Task Force + Working Group on Email Extensions. The chairman of that group, Greg + Vaudreuil, may be reached at: + + Gregory M. Vaudreuil + Tigon Corporation + 17060 Dallas Parkway + Dallas Texas, 75248 + + Phone: +1 214-733-2722 + EMail: gvaudre@cnri.reston.va.us + + + + + + + + + + + + + + + +Borenstein & Freed [Page 57] + +RFC 1521 MIME September 1993 + + +11. Acknowledgements + + This document is the result of the collective effort of a large + number of people, at several IETF meetings, on the IETF-SMTP and + IETF-822 mailing lists, and elsewhere. Although any enumeration + seems doomed to suffer from egregious omissions, the following are + among the many contributors to this effort: + + Harald Tveit Alvestrand Timo Lehtinen + Randall Atkinson John R. MacMillan + Philippe Brandon Rick McGowan + Kevin Carosso Leo Mclaughlin + Uhhyung Choi Goli Montaser-Kohsari + Cristian Constantinof Keith Moore + Mark Crispin Tom Moore + Dave Crocker Erik Naggum + Terry Crowley Mark Needleman + Walt Daniels John Noerenberg + Frank Dawson Mats Ohrman + Hitoshi Doi Julian Onions + Kevin Donnelly Michael Patton + Keith Edwards David J. Pepper + Chris Eich Blake C. Ramsdell + Johnny Eriksson Luc Rooijakkers + Craig Everhart Marshall T. Rose + Patrik Faeltstroem Jonathan Rosenberg + Erik E. Fair Jan Rynning + Roger Fajman Harri Salminen + Alain Fontaine Michael Sanderson + James M. Galvin Masahiro Sekiguchi + Philip Gladstone Mark Sherman + Thomas Gordon Keld Simonsen + Phill Gross Bob Smart + James Hamilton Peter Speck + Steve Hardcastle-Kille Henry Spencer + David Herron Einar Stefferud + Bruce Howard Michael Stein + Bill Janssen Klaus Steinberger + Olle Jaernefors Peter Svanberg + Risto Kankkunen James Thompson + Phil Karn Steve Uhler + Alan Katz Stuart Vance + Tim Kehres Erik van der Poel + Neil Katin Guido van Rossum + Kyuho Kim Peter Vanderbilt + Anders Klemets Greg Vaudreuil + John Klensin Ed Vielmetti + Valdis Kletniek Ryan Waldron + + + +Borenstein & Freed [Page 58] + +RFC 1521 MIME September 1993 + + + Jim Knowles Wally Wedel + Stev Knowles Sven-Ove Westberg + Bob Kummerfeld Brian Wideen + Pekka Kytolaakso John Wobus + Stellan Lagerstrom Glenn Wright + Vincent Lau Rayan Zachariassen + Donald Lindsay David Zimmerman + Marc Andreessen Bob Braden + Brian Capouch Peter Clitherow + Dave Collier-Brown John Coonrod + Stephen Crocker Jim Davis + Axel Deininger Dana S Emery + Martin Forssen Stephen Gildea + Terry Gray Mark Horton + Warner Losh Carlyn Lowery + Laurence Lundblade Charles Lynn + Larry Masinter Michael J. McInerny + Jon Postel Christer Romson + Yutaka Sato Markku Savela + Richard Alan Schafer Larry W. Virden + Rhys Weatherly Jay Weber + Dave Wecker + +The authors apologize for any omissions from this list, which are +certainly unintentional. + + + + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 59] + +RFC 1521 MIME September 1993 + + +Appendix A -- Minimal MIME-Conformance + + The mechanisms described in this document are open-ended. It is + definitely not expected that all implementations will support all of + the Content-Types described, nor that they will all share the same + extensions. In order to promote interoperability, however, it is + useful to define the concept of "MIME-conformance" to define a + certain level of implementation that allows the useful interworking + of messages with content that differs from US ASCII text. In this + section, we specify the requirements for such conformance. + + A mail user agent that is MIME-conformant MUST: + + 1. Always generate a "MIME-Version: 1.0" header field. + + 2. Recognize the Content-Transfer-Encoding header field, and + decode all received data encoded with either the quoted-printable + or base64 implementations. Encode any data sent that is not in + seven-bit mail-ready representation using one of these + transformations and include the appropriate Content-Transfer- + Encoding header field, unless the underlying transport mechanism + supports non-seven-bit data, as SMTP does not. + + 3. Recognize and interpret the Content-Type header field, and + avoid showing users raw data with a Content-Type field other than + text. Be able to send at least text/plain messages, with the + character set specified as a parameter if it is not US-ASCII. + + 4. Explicitly handle the following Content-Type values, to at + least the following extents: + + Text: + + -- Recognize and display "text" mail + with the character set "US-ASCII." + + -- Recognize other character sets at + least to the extent of being able + to inform the user about what + character set the message uses. + + -- Recognize the "ISO-8859-*" character + sets to the extent of being able to + display those characters that are + common to ISO-8859-* and US-ASCII, + namely all characters represented + by octet values 0-127. + + + + +Borenstein & Freed [Page 60] + +RFC 1521 MIME September 1993 + + + -- For unrecognized subtypes, show or + offer to show the user the "raw" + version of the data after + conversion of the content from + canonical form to local form. + + Message: + + -- Recognize and display at least the + primary (822) encapsulation. + + Multipart: + + -- Recognize the primary (mixed) + subtype. Display all relevant + information on the message level + and the body part header level and + then display or offer to display + each of the body parts individually. + + -- Recognize the "alternative" subtype, + and avoid showing the user + redundant parts of + multipart/alternative mail. + + -- Treat any unrecognized subtypes as if + they were "mixed". + + Application: + + -- Offer the ability to remove either of + the two types of Content-Transfer- + Encoding defined in this document + and put the resulting information + in a user file. + + 5. Upon encountering any unrecognized Content- Type, an + implementation must treat it as if it had a Content-Type of + "application/octet-stream" with no parameter sub-arguments. How + such data are handled is up to an implementation, but likely + options for handling such unrecognized data include offering the + user to write it into a file (decoded from its mail transport + format) or offering the user to name a program to which the + decoded data should be passed as input. Unrecognized predefined + types, which in a MIME-conformant mailer might still include + audio, image, or video, should also be treated in this way. + + A user agent that meets the above conditions is said to be MIME- + + + +Borenstein & Freed [Page 61] + +RFC 1521 MIME September 1993 + + + conformant. The meaning of this phrase is that it is assumed to be + "safe" to send virtually any kind of properly-marked data to users of + such mail systems, because such systems will at least be able to + treat the data as undifferentiated binary, and will not simply splash + it onto the screen of unsuspecting users. There is another sense in + which it is always "safe" to send data in a format that is MIME- + conformant, which is that such data will not break or be broken by + any known systems that are conformant with RFC 821 and RFC 822. User + agents that are MIME-conformant have the additional guarantee that + the user will not be shown data that were never intended to be viewed + as text. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 62] + +RFC 1521 MIME September 1993 + + +Appendix B -- General Guidelines For Sending Email Data + + Internet email is not a perfect, homogeneous system. Mail may become + corrupted at several stages in its travel to a final destination. + Specifically, email sent throughout the Internet may travel across + many networking technologies. Many networking and mail technologies + do not support the full functionality possible in the SMTP transport + environment. Mail traversing these systems is likely to be modified + in such a way that it can be transported. + + There exist many widely-deployed non-conformant MTAs in the Internet. + These MTAs, speaking the SMTP protocol, alter messages on the fly to + take advantage of the internal data structure of the hosts they are + implemented on, or are just plain broken. + + The following guidelines may be useful to anyone devising a data + format (Content-Type) that will survive the widest range of + networking technologies and known broken MTAs unscathed. Note that + anything encoded in the base64 encoding will satisfy these rules, but + that some well-known mechanisms, notably the UNIX uuencode facility, + will not. Note also that anything encoded in the Quoted-Printable + encoding will survive most gateways intact, but possibly not some + gateways to systems that use the EBCDIC character set. + + (1) Under some circumstances the encoding used for data may change + as part of normal gateway or user agent operation. In particular, + conversion from base64 to quoted-printable and vice versa may be + necessary. This may result in the confusion of CRLF sequences with + line breaks in text bodies. As such, the persistence of CRLF as + something other than a line break must not be relied on. + + (2) Many systems may elect to represent and store text data using + local newline conventions. Local newline conventions may not match + the RFC822 CRLF convention -- systems are known that use plain CR, + plain LF, CRLF, or counted records. The result is that isolated + CR and LF characters are not well tolerated in general; they may + be lost or converted to delimiters on some systems, and hence must + not be relied on. + + (3) TAB (HT) characters may be misinterpreted or may be + automatically converted to variable numbers of spaces. This is + unavoidable in some environments, notably those not based on the + ASCII character set. Such conversion is STRONGLY DISCOURAGED, but + it may occur, and mail formats must not rely on the persistence of + TAB (HT) characters. + + (4) Lines longer than 76 characters may be wrapped or truncated in + some environments. Line wrapping and line truncation are STRONGLY + + + +Borenstein & Freed [Page 63] + +RFC 1521 MIME September 1993 + + + DISCOURAGED, but unavoidable in some cases. Applications which + require long lines must somehow differentiate between soft and + hard line breaks. (A simple way to do this is to use the quoted- + printable encoding.) + + (5) Trailing "white space" characters (SPACE, TAB (HT)) on a line + may be discarded by some transport agents, while other transport + agents may pad lines with these characters so that all lines in a + mail file are of equal length. The persistence of trailing white + space, therefore, must not be relied on. + + (6) Many mail domains use variations on the ASCII character set, + or use character sets such as EBCDIC which contain most but not + all of the US-ASCII characters. The correct translation of + characters not in the "invariant" set cannot be depended on across + character converting gateways. For example, this situation is a + problem when sending uuencoded information across BITNET, an + EBCDIC system. Similar problems can occur without crossing a + gateway, since many Internet hosts use character sets other than + ASCII internally. The definition of Printable Strings in X.400 + adds further restrictions in certain special cases. In + particular, the only characters that are known to be consistent + across all gateways are the 73 characters that correspond to the + upper and lower case letters A-Z and a-z, the 10 digits 0-9, and + the following eleven special characters: + + "'" (ASCII code 39) + "(" (ASCII code 40) + ")" (ASCII code 41) + "+" (ASCII code 43) + "," (ASCII code 44) + "-" (ASCII code 45) + "." (ASCII code 46) + "/" (ASCII code 47) + ":" (ASCII code 58) + "=" (ASCII code 61) + "?" (ASCII code 63) + + A maximally portable mail representation, such as the base64 + encoding, will confine itself to relatively short lines of text in + which the only meaningful characters are taken from this set of 73 + characters. + + (7) Some mail transport agents will corrupt data that includes + certain literal strings. In particular, a period (".") alone on a + line is known to be corrupted by some (incorrect) SMTP + implementations, and a line that starts with the five characters + "From " (the fifth character is a SPACE) are commonly corrupted as + + + +Borenstein & Freed [Page 64] + +RFC 1521 MIME September 1993 + + + well. A careful composition agent can prevent these corruptions + by encoding the data (e.g., in the quoted-printable encoding, + "=46rom " in place of "From " at the start of a line, and "=2E" in + place of "." alone on a line. + + Please note that the above list is NOT a list of recommended + practices for MTAs. RFC 821 MTAs are prohibited from altering the + character of white space or wrapping long lines. These BAD and + illegal practices are known to occur on established networks, and + implementations should be robust in dealing with the bad effects they + can cause. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 65] + +RFC 1521 MIME September 1993 + + +Appendix C -- A Complex Multipart Example + + What follows is the outline of a complex multipart message. This + message has five parts to be displayed serially: two introductory + plain text parts, an embedded multipart message, a richtext part, and + a closing encapsulated text message in a non-ASCII character set. + The embedded multipart message has two parts to be displayed in + parallel, a picture and an audio fragment. + + MIME-Version: 1.0 + From: Nathaniel Borenstein + To: Ned Freed + Subject: A multipart example + Content-Type: multipart/mixed; + boundary=unique-boundary-1 + + This is the preamble area of a multipart message. + Mail readers that understand multipart format + should ignore this preamble. + If you are reading this text, you might want to + consider changing to a mail reader that understands + how to properly display multipart messages. + --unique-boundary-1 + + ...Some text appears here... + [Note that the preceding blank line means + no header fields were given and this is text, + with charset US ASCII. It could have been + done with explicit typing as in the next part.] + + --unique-boundary-1 + Content-type: text/plain; charset=US-ASCII + + This could have been part of the previous part, + but illustrates explicit versus implicit + typing of body parts. + + --unique-boundary-1 + Content-Type: multipart/parallel; + boundary=unique-boundary-2 + + + --unique-boundary-2 + Content-Type: audio/basic + Content-Transfer-Encoding: base64 + + ... base64-encoded 8000 Hz single-channel + mu-law-format audio data goes here.... + + + +Borenstein & Freed [Page 66] + +RFC 1521 MIME September 1993 + + + --unique-boundary-2 + Content-Type: image/gif + Content-Transfer-Encoding: base64 + + ... base64-encoded image data goes here.... + + --unique-boundary-2-- + + --unique-boundary-1 + Content-type: text/richtext + + This is richtext. + as defined in RFC 1341 + Isn't it + cool? + + --unique-boundary-1 + Content-Type: message/rfc822 + + From: (mailbox in US-ASCII) + To: (address in US-ASCII) + Subject: (subject in US-ASCII) + Content-Type: Text/plain; charset=ISO-8859-1 + Content-Transfer-Encoding: Quoted-printable + + ... Additional text in ISO-8859-1 goes here ... + + --unique-boundary-1-- + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 67] + +RFC 1521 MIME September 1993 + + +Appendix D -- Collected Grammar + + This appendix contains the complete BNF grammar for all the syntax + specified by this document. + + By itself, however, this grammar is incomplete. It refers to several + entities that are defined by RFC 822. Rather than reproduce those + definitions here, and risk unintentional differences between the two, + this document simply refers the reader to RFC 822 for the remaining + definitions. Wherever a term is undefined, it refers to the RFC 822 + definition. + + application-subtype := ("octet-stream" *stream-param) + / "postscript" / extension-token + + application-type := "application" "/" application-subtype + + attribute := token ; case-insensitive + + atype := "ftp" / "anon-ftp" / "tftp" / "local-file" + / "afs" / "mail-server" / extension-token + ; Case-insensitive + + audio-type := "audio" "/" ("basic" / extension-token) + + body-part := <"message" as defined in RFC 822, + with all header fields optional, and with the + specified delimiter not occurring anywhere in + the message body, either on a line by itself + or as a substring anywhere.> + + NOTE: In certain transport enclaves, RFC 822 restrictions such as + the one that limits bodies to printable ASCII characters may not + be in force. (That is, the transport domains may resemble + standard Internet mail transport as specified in RFC821 and + assumed by RFC822, but without certain restrictions.) The + relaxation of these restrictions should be construed as locally + extending the definition of bodies, for example to include octets + outside of the ASCII range, as long as these extensions are + supported by the transport and adequately documented in the + Content-Transfer-Encoding header field. However, in no event are + headers (either message headers or body-part headers) allowed to + contain anything other than ASCII characters. + + + + + + + + +Borenstein & Freed [Page 68] + +RFC 1521 MIME September 1993 + + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" + / "," / "-" / "." / "/" / ":" / "=" / "?" + + charset := "us-ascii" / "iso-8859-1" / "iso-8859-2"/ "iso-8859-3" + / "iso-8859-4" / "iso-8859-5" / "iso-8859-6" / "iso-8859-7" + / "iso-8859-8" / "iso-8859-9" / extension-token + ; case insensitive + + close-delimiter := "--" boundary "--" CRLF;Again,no space by "--", + + content := "Content-Type" ":" type "/" subtype *(";" parameter) + ; case-insensitive matching of type and subtype + + delimiter := "--" boundary CRLF ;taken from Content-Type field. + ; There must be no space + ; between "--" and boundary. + + description := "Content-Description" ":" *text + + discard-text := *(*text CRLF) + + encapsulation := delimiter body-part CRLF + + encoding := "Content-Transfer-Encoding" ":" mechanism + + epilogue := discard-text ; to be ignored upon receipt. + + extension-token := x-token / iana-token + + external-param := (";" "access-type" "=" atype) + / (";" "expiration" "=" date-time) + + ; Note that date-time is quoted + / (";" "size" "=" 1*DIGIT) + / (";" "permission" "=" ("read" / "read-write")) + ; Permission is case-insensitive + / (";" "name" "=" value) + / (";" "site" "=" value) + / (";" "dir" "=" value) + / (";" "mode" "=" value) + / (";" "server" "=" value) + / (";" "subject" "=" value) + ;access-type required; others required based on access-type + + + + +Borenstein & Freed [Page 69] + +RFC 1521 MIME September 1993 + + + iana-token := + + id := "Content-ID" ":" msg-id + + image-type := "image" "/" ("gif" / "jpeg" / extension-token) + + mechanism := "7bit" ; case-insensitive + / "quoted-printable" + / "base64" + / "8bit" + / "binary" + / x-token + + message-subtype := "rfc822" + / "partial" 2#3partial-param + / "external-body" 1*external-param + / extension-token + + message-type := "message" "/" message-subtype + + multipart-body :=preamble 1*encapsulation close-delimiter epilogue + + multipart-subtype := "mixed" / "parallel" / "digest" + / "alternative" / extension-token + + multipart-type := "multipart" "/" multipart-subtype + ";" "boundary" "=" boundary + + octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F") + ; octet must be used for characters > 127, =, SPACE, or + TAB, + ; and is recommended for any characters not listed in + ; Appendix B as "mail-safe". + + padding := "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" + + parameter := attribute "=" value + + partial-param := (";" "id" "=" value) + / (";" "number" "=" 1*DIGIT) + / (";" "total" "=" 1*DIGIT) + ; id & number required;total required for last part + + preamble := discard-text ; to be ignored upon receipt. + + ptext := octet / " / "@" + / "," / ";" / ":" / "\" / <"> + / "/" / "[" / "]" / "?" / "=" + ; Must be in quoted-string, + ; to use within parameter values + + + type := "application" / "audio" ; case-insensitive + / "image" / "message" + / "multipart" / "text" + / "video" / extension-token + ; All values case-insensitive + + value := token / quoted-string + + version := "MIME-Version" ":" 1*DIGIT "." 1*DIGIT + + video-type := "video" "/" ("mpeg" / extension-token) + + x-token := + + + + + + + + + + + + + +Borenstein & Freed [Page 71] + +RFC 1521 MIME September 1993 + + +Appendix E -- IANA Registration Procedures + + MIME has been carefully designed to have extensible mechanisms, and + it is expected that the set of content-type/subtype pairs and their + associated parameters will grow significantly with time. Several + other MIME fields, notably character set names, access-type + parameters for the message/external-body type, and possibly even + Content-Transfer-Encoding values, are likely to have new values + defined over time. In order to ensure that the set of such values is + developed in an orderly, well-specified, and public manner, MIME + defines a registration process which uses the Internet Assigned + Numbers Authority (IANA) as a central registry for such values. + + In general, parameters in the content-type header field are used to + convey supplemental information for various content types, and their + use is defined when the content-type and subtype are defined. New + parameters should not be defined as a way to introduce new + functionality. + + In order to simplify and standardize the registration process, this + appendix gives templates for the registration of new values with + IANA. Each of these is given in the form of an email message + template, to be filled in by the registering party. + + E.1 Registration of New Content-type/subtype Values + + Note that MIME is generally expected to be extended by subtypes. If + a new fundamental top-level type is needed, its specification must be + published as an RFC or submitted in a form suitable to become an RFC, + and be subject to the Internet standards process. + + To: IANA@isi.edu + Subject: Registration of new MIME + content-type/subtype + + MIME type name: + + (If the above is not an existing top-level MIME type, + please explain why an existing type cannot be used.) + + MIME subtype name: + + Required parameters: + + Optional parameters: + + Encoding considerations: + + + + +Borenstein & Freed [Page 72] + +RFC 1521 MIME September 1993 + + + Security considerations: + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be if a new top-level type is being defined, and + must be a publicly available specification in any + case.) + + Person & email address to contact for further information: + + E.2 Registration of New Access-type Values + for Message/external-body + + To: IANA@isi.edu + Subject: Registration of new MIME Access-type for + Message/external-body content-type + + MIME access-type name: + + Required parameters: + + Optional parameters: + + Published specification: + + (The published specification must be an Internet RFC or + RFC-to-be.) + + Person & email address to contact for further information: + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 73] + +RFC 1521 MIME September 1993 + + +Appendix F -- Summary of the Seven Content-types + + Content-type: text + + Subtypes defined by this document: plain + + Important Parameters: charset + + Encoding notes: quoted-printable generally preferred if an encoding + is needed and the character set is mostly an ASCII superset. + + Security considerations: Rich text formats such as TeX and Troff + often contain mechanisms for executing arbitrary commands or file + system operations, and should not be used automatically unless + these security problems have been addressed. Even plain text may + contain control characters that can be used to exploit the + capabilities of "intelligent" terminals and cause security + violations. User interfaces designed to run on such terminals + should be aware of and try to prevent such problems. + + ________________________________________________________ + Content-type: multipart + + Subtypes defined by this document: mixed, alternative, + digest, parallel. + + Important Parameters: boundary + + Encoding notes: No content-transfer-encoding is permitted. + + ________________________________________________________ + Content-type: message + + Subtypes defined by this document: rfc822, partial, external-body + + Important Parameters: id, number, total, access-type, expiration, + size, permission, name, site, directory, mode, server, subject + + Encoding notes: No content-transfer-encoding is permitted. + Specifically, only "7bit" is permitted for "message/partial" or + "message/external-body", and only "7bit", "8bit", or "binary" are + permitted for other subtypes of "message". + ______________________________________________________________ + Content-type: application + + Subtypes defined by this document: octet-stream, postscript + + Important Parameters: type, padding + + + +Borenstein & Freed [Page 74] + +RFC 1521 MIME September 1993 + + + Deprecated Parameters: name and conversions were + defined in RFC 1341. + + Encoding notes: base64 preferred for unreadable subtypes. + + Security considerations: This type is intended for the + transmission of data to be interpreted by locally-installed + programs. If used, for example, to transmit executable + binary programs or programs in general-purpose interpreted + languages, such as LISP programs or shell scripts, severe + security problems could result. Authors of mail-reading + agents are cautioned against giving their systems the power + to execute mail-based application data without carefully + considering the security implications. While it is + certainly possible to define safe application formats and + even safe interpreters for unsafe formats, each interpreter + should be evaluated separately for possible security + problems. + ________________________________________________________________ + Content-type: image + + Subtypes defined by this document: jpeg, gif + + Important Parameters: none + + Encoding notes: base64 generally preferred + ________________________________________________________________ + Content-type: audio + + Subtypes defined by this document: basic + + Important Parameters: none + + Encoding notes: base64 generally preferred + ________________________________________________________________ + Content-type: video + + Subtypes defined by this document: mpeg + + Important Parameters: none + + Encoding notes: base64 generally preferred + + + + + + + + + +Borenstein & Freed [Page 75] + +RFC 1521 MIME September 1993 + + +Appendix G -- Canonical Encoding Model + + There was some confusion, in earlier drafts of this memo, regarding + the model for when email data was to be converted to canonical form + and encoded, and in particular how this process would affect the + treatment of CRLFs, given that the representation of newlines varies + greatly from system to system. For this reason, a canonical model + for encoding is presented below. + + The process of composing a MIME entity can be modeled as being done + in a number of steps. Note that these steps are roughly similar to + those steps used in RFC 1421 and are performed for each 'innermost + level' body: + + Step 1. Creation of local form. + + The body to be transmitted is created in the system's native format. + The native character set is used, and where appropriate local end of + line conventions are used as well. The body may be a UNIX-style text + file, or a Sun raster image, or a VMS indexed file, or audio data in + a system-dependent format stored only in memory, or anything else + that corresponds to the local model for the representation of some + form of information. Fundamentally, the data is created in the + "native" form specified by the type/subtype information. + + Step 2. Conversion to canonical form. + + The entire body, including "out-of-band" information such as record + lengths and possibly file attribute information, is converted to a + universal canonical form. The specific content type of the body as + well as its associated attributes dictate the nature of the canonical + form that is used. Conversion to the proper canonical form may + involve character set conversion, transformation of audio data, + compression, or various other operations specific to the various + content types. If character set conversion is involved, however, + care must be taken to understand the semantics of the content-type, + which may have strong implications for any character set conversion, + e.g. with regard to syntactically meaningful characters in a text + subtype other than "plain". + + For example, in the case of text/plain data, the text must be + converted to a supported character set and lines must be delimited + with CRLF delimiters in accordance with RFC822. Note that the + restriction on line lengths implied by RFC822 is eliminated if the + next step employs either quoted-printable or base64 encoding. + + + + + + +Borenstein & Freed [Page 76] + +RFC 1521 MIME September 1993 + + + Step 3. Apply transfer encoding. + + A Content-Transfer-Encoding appropriate for this body is applied. + Note that there is no fixed relationship between the content type and + the transfer encoding. In particular, it may be appropriate to base + the choice of base64 or quoted-printable on character frequency + counts which are specific to a given instance of a body. + + Step 4. Insertion into entity. + + The encoded object is inserted into a MIME entity with appropriate + headers. The entity is then inserted into the body of a higher-level + entity (message or multipart) if needed. + + It is vital to note that these steps are only a model; they are + specifically NOT a blueprint for how an actual system would be built. + In particular, the model fails to account for two common designs: + + 1. In many cases the conversion to a canonical form prior to + encoding will be subsumed into the encoder itself, which + understands local formats directly. For example, the local + newline convention for text bodies might be carried through to the + encoder itself along with knowledge of what that format is. + + 2. The output of the encoders may have to pass through one or + more additional steps prior to being transmitted as a message. As + such, the output of the encoder may not be conformant with the + formats specified by RFC822. In particular, once again it may be + appropriate for the converter's output to be expressed using local + newline conventions rather than using the standard RFC822 CRLF + delimiters. + + Other implementation variations are conceivable as well. The vital + aspect of this discussion is that, in spite of any optimizations, + collapsings of required steps, or insertion of additional processing, + the resulting messages must be consistent with those produced by the + model described here. For example, a message with the following + header fields: + + Content-type: text/foo; charset=bar + Content-Transfer-Encoding: base64 + + must be first represented in the text/foo form, then (if necessary) + represented in the "bar" character set, and finally transformed via + the base64 algorithm into a mail-safe form. + + + + + + +Borenstein & Freed [Page 77] + +RFC 1521 MIME September 1993 + + +Appendix H -- Changes from RFC 1341 + + This document is a relatively minor revision of RFC 1341. For + the convenience of those familiar with RFC 1341, the technical + changes from that document are summarized in this appendix. + + 1. The definition of "tspecials" has been changed to no longer + include ".". + + 2. The Content-ID field is now mandatory for message/external-body + parts. + + 3. The text/richtext type (including the old Section 7.1.3 and + Appendix D) has been moved to a separate document. + + 4. The rules on header merging for message/partial data have been + changed to treat the Encrypted and MIME-Version headers as special + cases. + + 5. The definition of the external-body access-type parameter has + been changed so that it can only indicate a single access method + (which was all that made sense). + + 6. There is a new "Subject" parameter for message/external-body, + access-type mail-server, to permit MIME-based use of mail servers + that rely on Subject field information. + + 7. The "conversions" parameter for application/octet-stream has been + removed. + + 8. Section 7.4.1 now deprecates the use of the "name" parameter for + application/octet-stream, as this will be superseded in the future by + a Content-Disposition header. + + 9. The formal grammar for multipart bodies has been changed so that + a CRLF is no longer required before the first boundary line. + + 10. MIME entities of type "message/partial" and "message/external- + body" are now required to use only the "7bit" transfer-encoding. + (Specifically, "binary" and "8bit" are not permitted.) + + 11. The "application/oda" content-type has been removed. + + 12. A note has been added to the end of section 7.2.3, explaining + the semantics of Content-ID in a multipart/alternative MIME entity. + + 13. The formal syntax for the "MIME-Version" field has been + tightened, but in a way that is completely compatible with the only + + + +Borenstein & Freed [Page 78] + +RFC 1521 MIME September 1993 + + + version number defined in RFC 1341. + + 14. In Section 7.3.1, the definition of message/rfc822 has been + relaxed regarding mandatory fields. + + All other changes from RFC 1341 were editorial changes and do not + affect the technical content of MIME. Considerable formal grammar + has been added, but this reflects the prose specification that was + already in place. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Borenstein & Freed [Page 79] + +RFC 1521 MIME September 1993 + + +References + + [US-ASCII] Coded Character Set--7-Bit American Standard Code for + Information Interchange, ANSI X3.4-1986. + + [ATK] Borenstein, Nathaniel S., Multimedia Applications Development + with the Andrew Toolkit, Prentice-Hall, 1990. + + [GIF] Graphics Interchange Format (Version 89a), Compuserve, Inc., + Columbus, Ohio, 1990. + + [ISO-2022] International Standard--Information Processing--ISO 7-bit + and 8-bit coded character sets--Code extension techniques, ISO + 2022:1986. + + [ISO-8859] Information Processing -- 8-bit Single-Byte Coded Graphic + Character Sets -- Part 1: Latin Alphabet No. 1, ISO 8859-1:1987. Part + 2: Latin alphabet No. 2, ISO 8859-2, 1987. Part 3: Latin alphabet + No. 3, ISO 8859-3, 1988. Part 4: Latin alphabet No. 4, ISO 8859-4, + 1988. Part 5: Latin/Cyrillic alphabet, ISO 8859-5, 1988. Part 6: + Latin/Arabic alphabet, ISO 8859-6, 1987. Part 7: Latin/Greek + alphabet, ISO 8859-7, 1987. Part 8: Latin/Hebrew alphabet, ISO + 8859-8, 1988. Part 9: Latin alphabet No. 5, ISO 8859-9, 1990. + + [ISO-646] International Standard--Information Processing--ISO 7-bit + coded character set for information interchange, ISO 646:1983. + + [MPEG] Video Coding Draft Standard ISO 11172 CD, ISO IEC/TJC1/SC2/WG11 + (Motion Picture Experts Group), May, 1991. + + [PCM] CCITT, Fascicle III.4 - Recommendation G.711, Geneva, 1972, + "Pulse Code Modulation (PCM) of Voice Frequencies". + + [POSTSCRIPT] Adobe Systems, Inc., PostScript Language Reference + Manual, Addison-Wesley, 1985. + + [POSTSCRIPT2] Adobe Systems, Inc., PostScript Language Reference + Manual, Addison-Wesley, Second Edition, 1990. + + [X400] Schicker, Pietro, "Message Handling Systems, X.400", Message + Handling Systems and Distributed Applications, E. Stefferud, O-j. + Jacobsen, and P. Schicker, eds., North-Holland, 1989, pp. 3-41. + + [RFC-783] Sollins, K., "TFTP Protocol (revision 2)", RFC 783, MIT, + June 1981. + + [RFC-821] Postel, J., "Simple Mail Transfer Protocol", STD 10, RFC + 821, USC/Information Sciences Institute, August 1982. + + + +Borenstein & Freed [Page 80] + +RFC 1521 MIME September 1993 + + + [RFC-822] Crocker, D., "Standard for the Format of ARPA Internet Text + Messages", STD 11, RFC 822, UDEL, August 1982. + + [RFC-934] Rose, M., and E. Stefferud, "Proposed Standard for Message + Encapsulation", RFC 934, Delaware and NMA, January 1985. + + [RFC-959] Postel, J. and J. Reynolds, "File Transfer Protocol", + STD 9, RFC 959, USC/Information Sciences Institute, October 1985. + + [RFC-1049] Sirbu, M., "Content-Type Header Field for Internet + Messages", STD 11, RFC 1049, CMU, March 1988. + + [RFC-1421] Linn, J., "Privacy Enhancement for Internet Electronic Mail: + Part I - Message Encryption and Authentication Procedures", RFC + 1421, IAB IRTF PSRG, IETF PEM WG, February 1993. + + [RFC-1154] Robinson, D. and R. Ullmann, "Encoding Header Field for + Internet Messages", RFC 1154, Prime Computer, Inc., April 1990. + + [RFC-1341] Borenstein, N., and N. Freed, "MIME (Multipurpose Internet + Mail Extensions): Mechanisms for Specifying and Describing the Format + of Internet Message Bodies", RFC 1341, Bellcore, Innosoft, June 1992. + + [RFC-1342] Moore, K., "Representation of Non-Ascii Text in Internet + Message Headers", RFC 1342, University of Tennessee, June 1992. + + [RFC-1343] Borenstein, N., "A User Agent Configuration Mechanism + for Multimedia Mail Format Information", RFC 1343, Bellcore, June + 1992. + + [RFC-1344] Borenstein, N., "Implications of MIME for Internet + Mail Gateways", RFC 1344, Bellcore, June 1992. + + [RFC-1345] Simonsen, K., "Character Mnemonics & Character Sets", + RFC 1345, Rationel Almen Planlaegning, June 1992. + + [RFC-1426] Klensin, J., (WG Chair), Freed, N., (Editor), Rose, M., + Stefferud, E., and D. Crocker, "SMTP Service Extension for 8bit-MIME + transport", RFC 1426, United Nations Universit, Innosoft, Dover Beach + Consulting, Inc., Network Management Associates, Inc., The Branch + Office, February 1993. + + [RFC-1522] Moore, K., "Representation of Non-Ascii Text in Internet + Message Headers" RFC 1522, University of Tennessee, September 1993. + + [RFC-1340] Reynolds, J., and J. Postel, "Assigned Numbers", STD 2, RFC + 1340, USC/Information Sciences Institute, July 1992. + + + + +Borenstein & Freed [Page 81] + \ No newline at end of file diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1854.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1854.txt new file mode 100644 index 00000000..7b1a9751 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc1854.txt @@ -0,0 +1,395 @@ + + + + + + +Network Working Group N. Freed +Request For Comments: 1854 Innosoft International, Inc. +Category: Standards Track A. Cargille, WG Chair + October 1995 + + + SMTP Service Extension + for Command Pipelining + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + This memo defines an extension to the SMTP service whereby a server + can indicate the extent of its ability to accept multiple commands in + a single TCP send operation. Using a single TCP send operation for + multiple commands can improve SMTP performance significantly. + +Introduction + + Although SMTP is widely and robustly deployed, certain extensions may + nevertheless prove useful. In particular, many parts of the Internet + make use of high latency network links. + + SMTP's intrinsic one command-one response structure is significantly + penalized by high latency links, often to the point where the factors + contributing to overall connection time are dominated by the time + spent waiting for responses to individual commands (turnaround time). + + In the best of all worlds it would be possible to simply deploy SMTP + client software that makes use of command pipelining: batching up + multiple commands into single TCP send operations. Unfortunately, the + original SMTP specification [1] did not explicitly state that SMTP + servers must support this. As a result a non-trivial number of + Internet SMTP servers cannot adequately handle command pipelining. + Flaws known to exist in deployed servers include: + + (1) Connection handoff and buffer flushes in the middle of + the SMTP dialogue. Creation of server processes for + incoming SMTP connections is a useful, obvious, and + harmless implementation technique. However, some SMTP + servers defer process forking and connection handoff + + + +Freed & Cargille Standards Track [Page 1] + +RFC 1854 SMTP Pipelining October 1995 + + + until some intermediate point in the SMTP dialogue. + When this is done material read from the TCP connection + and kept in process buffers can be lost. + + (2) Flushing the TCP input buffer when an SMTP command + fails. SMTP commands often fail but there is no reason + to flush the TCP input buffer when this happens. + Nevertheless, some SMTP servers do this. + + (3) Improper processing and promulgation of SMTP command + failures. For example, some SMTP servers will refuse to + accept a DATA command if the last RCPT TO command + fails, paying no attention to the success or failure of + prior RCPT TO command results. Other servers will + accept a DATA command even when all previous RCPT TO + commands have failed. Although it is possible to + accommodate this sort of behavior in a client that + employs command pipelining, it does complicate the + construction of the client unnecessarily. + + This memo uses the mechanism described in [2] to define an extension + to the SMTP service whereby an SMTP server can declare that it is + capable of handling pipelined commands. The SMTP client can then + check for this declaration and use pipelining only when the server + declares itself capable of handling it. + +1. Framework for the Command Pipelining Extension + + The Command Pipelining extension is defined as follows: + + (1) the name of the SMTP service extension is Pipelining; + + (2) the EHLO keyword value associated with the extension is + PIPELINING; + + (3) no parameter is used with the PIPELINING EHLO keyword; + + (4) no additional parameters are added to either the MAIL + FROM or RCPT TO commands. + + (5) no additional SMTP verbs are defined by this extension; + and, + + (6) the next section specifies how support for the + extension affects the behavior of a server and client + SMTP. + + + + + +Freed & Cargille Standards Track [Page 2] + +RFC 1854 SMTP Pipelining October 1995 + + +2. The Pipelining Service Extension + + When a client SMTP wishes to employ command pipelining, it first + issues the EHLO command to the server SMTP. If the server SMTP + responds with code 250 to the EHLO command, and the response includes + the EHLO keyword value PIPELINING, then the server SMTP has indicated + that it can accommodate SMTP command pipelining. + +2.1. Client use of pipelining + + Once the client SMTP has confirmed that support exists for the + pipelining extension, the client SMTP may then elect to transmit + groups of SMTP commands in batches without waiting for a response to + each individual command. In particular, the commands RSET, MAIL FROM, + SEND FROM, SOML FROM, SAML FROM, and RCPT TO can all appear anywhere + in a pipelined command group. The EHLO, DATA, VRFY, EXPN, TURN, + QUIT, and NOOP commands can only appear as the last command in a + group since their success or failure produces a change of state which + the client SMTP must accommodate. (NOOP is included in this group so + it can be used as a synchronization point.) + + Additional commands added by other SMTP extensions may only appear as + the last command in a group unless otherwise specified by the + extensions that define the commands. + + The actual transfer of message content is explicitly allowed to be + the first "command" in a group. That is, the RSET/MAIL FROM sequence + necessary to initiate a new message transaction can be placed in the + same group as the final transfer of the headers and body of the + previous message. + + Client SMTP implementations that employ pipelining MUST check ALL + statuses associated with each command in a group. For example, if + none of the RCPT TO recipient addresses were accepted the client must + then check the response to the DATA command -- the client cannot + assume that the DATA command will be rejected just because none of + the RCPT TO commands worked. If the DATA command was properly + rejected the client SMTP can just issue RSET, but if the DATA command + was accepted the client SMTP should send a single dot. + + Command statuses MUST be coordinated with responses by counting each + separate response and correlating that count with the number of + commands known to have been issued. Multiline responses MUST be + supported. Matching on the basis of either the error code value or + associated text is expressly forbidden. + + Client SMTP implementations MAY elect to operate in a nonblocking + fashion, processing server responses immediately upon receipt, even + + + +Freed & Cargille Standards Track [Page 3] + +RFC 1854 SMTP Pipelining October 1995 + + + if there is still data pending transmission from the client's + previous TCP send operation. If nonblocking operation is not + supported, however, client SMTP implementations MUST also check the + TCP window size and make sure that each group of commands fits + entirely within the window. The window size is usually, but not + always, 4K octets. Failure to perform this check can lead to + deadlock conditions. + + Clients MUST NOT confuse responses to multiple commands with + multiline responses. Each command requires one or more lines of + response, the last line not containing a dash between the response + code and the response string. + +2.2. Server support of pipelining + + A server SMTP implementation that offers the pipelining extension: + + (1) MUST NOT flush or otherwise lose the contents of the + TCP input buffer under any circumstances whatsoever. + + (2) SHOULD issue a positive response to the DATA command if + and only if one or more valid RCPT TO addresses have + been previously received. + + (3) MUST NOT, after issuing a positive response to a DATA + command with no valid recipients and subsequently + receiving an empty message, send any message whatsoever + to anybody. + + (4) SHOULD elect to store responses to grouped RSET, MAIL + FROM, SEND FROM, SOML FROM, SAML FROM, and RCPT TO + commands in an internal buffer so they can sent as a + unit. + + (5) MUST NOT buffer responses to EHLO, DATA, VRFY, EXPN, + TURN, QUIT, and NOOP. + + (6) MUST NOT buffer responses to unrecognized commands. + + (7) MUST send all pending responses immediately whenever + the local TCP input buffer is emptied. + + (8) MUST NOT make assumptions about commands that are yet + to be received. + + (9) SHOULD issue response text that indicates, either + implicitly or explicitly, what command the response + matches. + + + +Freed & Cargille Standards Track [Page 4] + +RFC 1854 SMTP Pipelining October 1995 + + + The overriding intent of these server requirements is to make it as + easy as possible for servers to conform to these pipelining + extensions. + +3. Examples + + Consider the following SMTP dialogue that does not use pipelining: + + S: + C: + S: 220 innosoft.com SMTP service ready + C: HELO dbc.mtview.ca.us + S: 250 innosoft.com + C: MAIL FROM: + S: 250 sender OK + C: RCPT TO: + S: 250 recipient OK + C: RCPT TO: + S: 250 recipient OK + C: RCPT TO: + S: 250 recipient OK + C: DATA + S: 354 enter mail, end with line containing only "." + ... + C: . + S: 250 message sent + C: QUIT + S: 221 goodbye + + The client waits for a server response a total of 9 times in this + simple example. But if pipelining is employed the following dialogue + is possible: + + S: + C: + S: 220 innosoft.com SMTP service ready + C: EHLO dbc.mtview.ca.us + S: 250-innosoft.com + S: 250 PIPELINING + C: MAIL FROM: + C: RCPT TO: + C: RCPT TO: + C: RCPT TO: + C: DATA + S: 250 sender OK + S: 250 recipient OK + S: 250 recipient OK + S: 250 recipient OK + + + +Freed & Cargille Standards Track [Page 5] + +RFC 1854 SMTP Pipelining October 1995 + + + S: 354 enter mail, end with line containing only "." + ... + C: . + C: QUIT + S: 250 message sent + S: 221 goodbye + + The total number of turnarounds has been reduced from 9 to 4. + + The next example illustrates one possible form of behavior when + pipelining is used and all recipients are rejected: + + S: + C: + S: 220 innosoft.com SMTP service ready + C: EHLO dbc.mtview.ca.us + S: 250-innosoft.com + S: 250 PIPELINING + C: MAIL FROM: + C: RCPT TO: + C: RCPT TO: + C: DATA + S: 250 sender OK + S: 550 remote mail to not allowed + S: 550 remote mail to not allowed + S: 554 no valid recipients given + C: QUIT + S: 221 goodbye + + The client SMTP waits for the server 4 times here as well. If the + server SMTP does not check for at least one valid recipient prior to + accepting the DATA command, the following dialogue would result: + + S: + C: + S: 220 innosoft.com SMTP service ready + C: EHLO dbc.mtview.ca.us + S: 250-innosoft.com + S: 250 PIPELINING + C: MAIL FROM: + C: RCPT TO: + C: RCPT TO: + C: DATA + S: 250 sender OK + S: 550 remote mail to not allowed + S: 550 remote mail to not allowed + S: 354 enter mail, end with line containing only "." + C: . + + + +Freed & Cargille Standards Track [Page 6] + +RFC 1854 SMTP Pipelining October 1995 + + + C: QUIT + S: 554 no valid recipients + S: 221 goodbye + +4. Security Considerations + + This RFC does not discuss security issues and is not believed to + raise any security issues not endemic in electronic mail and present + in fully conforming implementations of [1]. + +5. Acknowledgements + + This document is based on the SMTP service extension model presented + in RFC 1425. Marshall Rose's description of SMTP command pipelining + in his book "The Internet Message" also served as a source of + inspiration for this extension. + +6. References + + [1] Postel, J., "Simple Mail Transfer Protocol", STD 10 + RFC 821, USC/Information Sciences Institute, August + 1982. + + [2] Klensin, J., Freed, N., Rose, M., Stefferud, E., + and D. Crocker, "SMTP Service Extensions", RFC 1651, + MCI, Innosoft, Dover Beach Consulting, Inc., + Network Management Associates, Inc., Silicon Graphics, + Inc., July 1994. + +7. Author's Address + + Ned Freed + Innosoft International, Inc. + 1050 East Garvey Avenue South + West Covina, CA 91790 + USA + + Phone: +1 818 919 3600 + Fax: +1 818 919 3614 + EMail: ned@innosoft.com + + + + + + + + + + + +Freed & Cargille Standards Track [Page 7] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2015.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2015.txt new file mode 100644 index 00000000..d075983f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2015.txt @@ -0,0 +1,450 @@ + + + + + +Network Working Group M. Elkins +Request for Comments: 2015 The Aerospace Corporation +Category: Standards Track October 1996 + + + MIME Security with Pretty Good Privacy (PGP) + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + This document describes how Pretty Good Privacy (PGP) can be used to + provide privacy and authentication using the Multipurpose Internet + Mail Extensions (MIME) security content types described in RFC1847. + +1. Introduction + + Previous work on integrating PGP with MIME (including the since + withdrawn application/pgp content type) has suffered from a number of + problems, the most significant of which is the inability to recover + signed message bodies without parsing data structures specific to + PGP. This work makes use of the elegant solution proposed in + RFC1847, which defines security multipart formats for MIME. The + security multiparts clearly separate the signed message body from the + signature, and have a number of other desirable properties. This + document is styled after RFC 1848, which defines MIME Object Security + Services (MOSS) for providing security and authentication. + + This document defines three new content types for implementing + security and privacy with PGP: application/pgp-encrypted, + application/pgp-signature and application/pgp-keys. + +1.1 Compliance + + In order for an implementation to be compliant with this + specification, is it absolutely necessary for it to obey all items + labeled as MUST or REQUIRED. + + + + + + + + +Elkins Standards Track [Page 1] + +RFC 2015 MIME Security with PGP October 1996 + + +2. PGP data formats + + PGP can generate either ASCII armor (described in [3]) or 8-bit + binary output when encrypting data, generating a digital signature, + or extracting public key data. The ASCII armor output is the + REQUIRED method for data transfer. This allows those users who do + not have the means to interpret the formats described in this + document to be able extract and use the PGP information in the + message. + + When the amount of data to be transmitted requires that it be sent in + many parts, the MIME message/partial mechanism should be used rather + than the multipart ASCII armor PGP format. + +3. Content-Transfer-Encoding restrictions + + Multipart/signed and multipart/encrypted are to be treated by agents + as opaque, meaning that the data is not to be altered in any way [1]. + However, many existing mail gateways will detect if the next hop does + not support MIME or 8-bit data and perform conversion to either + Quoted-Printable or Base64. This presents serious problems for + multipart/signed, in particular, where the signature is invalidated + when such an operation occurs. For this reason all data signed + according to this protocol MUST be constrained to 7 bits (8- bit data + should be encoded using either Quoted-Printable or Base64). Note + that this also includes the case where a signed object is also + encrypted (see section 6). This restriction will increase the + likelihood that the signature will be valid upon receipt. + + Data that is ONLY to be encrypted is allowed to contain 8-bit + characters and therefore need not be converted to a 7-bit format. + + Implementor's note: It cannot be stressed enough that applications + using this standard should follow MIME's suggestion that you "be + conservative in what you generate, and liberal in what you accept." + In this particular case it means it would be wise for an + implementation to accept messages with any content-transfer- + encoding, but restrict generation to the 7-bit format required by + this memo. This will allow future compatibility in the event the + Internet SMTP framework becomes 8-bit friendly. + +4. PGP encrypted data + + Before encryption with PGP, the data should be written in MIME + canonical format (body and headers). + + PGP encrypted data is denoted by the "multipart/encrypted" content + type, described in [1], and MUST have a "protocol" parameter value of + + + +Elkins Standards Track [Page 2] + +RFC 2015 MIME Security with PGP October 1996 + + + "application/pgp-encrypted". Note that the value of the parameter + MUST be enclosed in quotes. + + The multipart/encrypted MUST consist of exactly two parts. The first + MIME body part must have a content type of "application/pgp- + encrypted". This body contains the control information. A message + complying with this standard MUST contain a "Version: 1" field in + this body. Since the PGP packet format contains all other + information necessary for decrypting, no other information is + required here. + + The second MIME body part MUST contain the actual encrypted data. It + must be labeled with a content type of "application/octet- stream". + + Example message: + + From: Michael Elkins + To: Michael Elkins + Mime-Version: 1.0 + Content-Type: multipart/encrypted; boundary=foo; + protocol="application/pgp-encrypted" + + --foo + Content-Type: application/pgp-encrypted + + Version: 1 + + --foo + Content-Type: application/octet-stream + + -----BEGIN PGP MESSAGE----- + Version: 2.6.2 + + hIwDY32hYGCE8MkBA/wOu7d45aUxF4Q0RKJprD3v5Z9K1YcRJ2fve87lMlDlx4Oj + eW4GDdBfLbJE7VUpp13N19GL8e/AqbyyjHH4aS0YoTk10QQ9nnRvjY8nZL3MPXSZ + g9VGQxFeGqzykzmykU6A26MSMexR4ApeeON6xzZWfo+0yOqAq6lb46wsvldZ96YA + AABH78hyX7YX4uT1tNCWEIIBoqqvCeIMpp7UQ2IzBrXg6GtukS8NxbukLeamqVW3 + 1yt21DYOjuLzcMNe/JNsD9vDVCvOOG3OCi8= + =zzaA + -----END PGP MESSAGE----- + + --foo-- + +5. PGP signed data + + PGP signed messages are denoted by the "multipart/signed" content + type, described in [1], with a "protocol" parameter which MUST have a + value of "application/pgp-signature" (MUST be quoted). The "micalg" + + + +Elkins Standards Track [Page 3] + +RFC 2015 MIME Security with PGP October 1996 + + + parameter MUST have a value of "pgp-", where identifies the message integrity check (MIC) used to generate + the signature. The currently defined values for are + "md5" for the MD5 checksum, and "sha1" for the SHA.1 algorithm. + + The multipart/signed body MUST consist of exactly two parts. The + first part contains the signed data in MIME canonical format, + including a set of appropriate content headers describing the data. + + The second body MUST contain the PGP digital signature. It MUST be + labeled with a content type of "application/pgp-signature". + + When the PGP digital signature is generated: + + (1) The data to be signed must first be converted to its + type/subtype specific canonical form. For text/plain, this + means conversion to an appropriate character set and conversion + of line endings to the canonical sequence. + + (2) An appropriate Content-Transfer-Encoding is then applied. Each + line of the encoded data MUST end with the canonical + sequence. + + (3) MIME content headers are then added to the body, each ending + with the canonical sequence. + + (4) As described in [1], the digital signature MUST be calculated + over both the data to be signed and its set of content headers. + + (5) The signature MUST be generated detached from the signed data + so that the process does not alter the signed data in any way. + + Example message: + + From: Michael Elkins + To: Michael Elkins + Mime-Version: 1.0 + Content-Type: multipart/signed; boundary=bar; micalg=pgp-md5; + protocol="application/pgp-signature" + + --bar + & Content-Type: text/plain; charset=iso-8859-1 + & Content-Transfer-Encoding: quoted-printable + & + & =A1Hola! + & + & Did you know that talking to yourself is a sign of senility? + & + + + +Elkins Standards Track [Page 4] + +RFC 2015 MIME Security with PGP October 1996 + + + & It's generally a good idea to encode lines that begin with + & From=20because some mail transport agents will insert a greater- + & than (>) sign, thus invalidating the signature. + & + & Also, in some cases it might be desirable to encode any =20 + &railing whitespace that occurs on lines in order to ensure =20 + & that the message signature is not invalidated when passing =20 + & a gateway that modifies such whitespace (like BITNET). =20 + & + & me + + --bar + Content-Type: application/pgp-signature + + -----BEGIN PGP MESSAGE----- + Version: 2.6.2 + + iQCVAwUBMJrRF2N9oWBghPDJAQE9UQQAtl7LuRVndBjrk4EqYBIb3h5QXIX/LC// + jJV5bNvkZIGPIcEmI5iFd9boEgvpirHtIREEqLQRkYNoBActFBZmh9GC3C041WGq + uMbrbxc+nIs1TIKlA08rVi9ig/2Yh7LFrK5Ein57U/W72vgSxLhe/zhdfolT9Brn + HOxEa44b+EI= + =ndaj + -----END PGP MESSAGE----- + + --bar-- + + The "&"s in the previous example indicate the portion of the data + over which the signature was calculated. + + Though not required, it is generally a good idea to use Quoted- + Printable encoding in the first step (writing out the data to be + signed in MIME canonical format) if any of the lines in the data + begin with "From ", and encode the "F". This will avoid an MTA + inserting a ">" in front of the line, thus invalidating the + signature! + + Upon receipt of a signed message, an application MUST: + + (1) Convert line endings to the canonical sequence before + the signature can be verified. This is necessary since the + local MTA may have converted to a local end of line convention. + + (2) Pass both the signed data and its associated content headers + along with the PGP signature to the signature verification + service. + + + + + + +Elkins Standards Track [Page 5] + +RFC 2015 MIME Security with PGP October 1996 + + +6. Encrypted and Signed Data + + Sometimes it is desirable to both digitally sign and then encrypt a + message to be sent. This protocol allows for two methods of + accomplishing this task. + +6.1 RFC1847 Encapsulation + + [1], it is stated that the data should first be signed as a + multipart/signature body, and then encrypted to form the final + multipart/encrypted body, i.e., + + Content-Type: multipart/encrypted; + protocol="application/pgp-encrypted"; boundary=foo + + --foo + Content-Type: application/pgp-encrypted + + Version: 1 + + --foo + Content-Type: application/octet-stream + + -----BEGIN PGP MESSAGE----- + & Content-Type: multipart/signed; micalg=pgp-md5 + & protocol="application/pgp-signature"; boundary=bar + & + & --bar + & Content-Type: text/plain; charset=us-ascii + & + & This message was first signed, and then encrypted. + & + & --bar + & Content-Type: application/pgp-signature + & + & -----BEGIN PGP MESSAGE----- + & Version: 2.6.2 + & + & iQCVAwUBMJrRF2N9oWBghPDJAQE9UQQAtl7LuRVndBjrk4EqYBIb3h5QXIX/LC// + & jJV5bNvkZIGPIcEmI5iFd9boEgvpirHtIREEqLQRkYNoBActFBZmh9GC3C041WGq + & uMbrbxc+nIs1TIKlA08rVi9ig/2Yh7LFrK5Ein57U/W72vgSxLhe/zhdfolT9Brn + & HOxEa44b+EI= + & =ndaj + & -----END PGP MESSAGE----- + & + & --bar-- + -----END PGP MESSAGE----- + + + + +Elkins Standards Track [Page 6] + +RFC 2015 MIME Security with PGP October 1996 + + + --foo-- + + (The text preceded by '&' indicates that it is really + encrypted, but presented as text for clarity.) + +6.2 Combined method + + Versions 2.x of PGP also allow data to be signed and encrypted in one + operation. This method is an acceptable shortcut, and has the + benefit of less overhead. The resulting data should be formed as a + "multipart/encrypted" object as described above. + + Messages which are encrypted and signed in this combined fashion are + REQUIRED to follow the same canonicalization rules as for + multipart/signed objects. + + It is explicitly allowed for an agent to decrypt a combined message + and rewrite it as a multipart/signed object using the signature data + embedded in the encrypted version. + +7. Distribution of PGP public keys + + Content-Type: application/pgp-keys + Required parameters: none + Optional parameters: none + + This is the content type which should be used for relaying public key + blocks. + +8. Notes + + PGP and Pretty Good Privacy are trademarks of Philip Zimmermann. + +9. Security Considerations + + Use of this protocol has the same security considerations as PGP, and + is not known to either increase or decrease the security of messages + using it; see [3] for more information. + +10. Author's Address + + Michael Elkins + P.O. Box 92957 - M1/102 + Los Angeles, CA 90009-2957 + + Phone: +1 310 336 8040 + Fax: +1 310 336 4402 + + + + +Elkins Standards Track [Page 7] + +RFC 2015 MIME Security with PGP October 1996 + + +References + + [1] Galvin, J., Murphy, G., Crocker, S., and N. Freed, "Security + Multiparts for MIME: Multipart/Signed and Multipart/Encrypted", + RFC 1847, October 1995. + + [2] Galvin, J., Murphy, G., Crocker, S., and N. Freed, "MIME Object + Security Services", RFC 1848, October 1995. + + [3] Atkins, D., Stallings, W., and P. Zimmermann, "PGP Message + Exchange Formats", RFC 1991, August 1996. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Elkins Standards Track [Page 8] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2045.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2045.txt new file mode 100644 index 00000000..9f286b1a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2045.txt @@ -0,0 +1,1739 @@ + + + + + + +Network Working Group N. Freed +Request for Comments: 2045 Innosoft +Obsoletes: 1521, 1522, 1590 N. Borenstein +Category: Standards Track First Virtual + November 1996 + + + Multipurpose Internet Mail Extensions + (MIME) Part One: + Format of Internet Message Bodies + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822, defines a message representation protocol specifying + considerable detail about US-ASCII message headers, and leaves the + message content, or message body, as flat US-ASCII text. This set of + documents, collectively called the Multipurpose Internet Mail + Extensions, or MIME, redefines the format of messages to allow for + + (1) textual message bodies in character sets other than + US-ASCII, + + (2) an extensible set of different formats for non-textual + message bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than + US-ASCII. + + These documents are based on earlier work documented in RFC 934, STD + 11, and RFC 1049, but extends and revises them. Because RFC 822 said + so little about message bodies, these documents are largely + orthogonal to (rather than a revision of) RFC 822. + + This initial document specifies the various headers used to describe + the structure of MIME messages. The second document, RFC 2046, + defines the general structure of the MIME media typing system and + defines an initial set of media types. The third document, RFC 2047, + describes extensions to RFC 822 to allow non-US-ASCII text data in + + + +Freed & Borenstein Standards Track [Page 1] + +RFC 2045 Internet Message Bodies November 1996 + + + Internet mail header fields. The fourth document, RFC 2048, specifies + various IANA registration procedures for MIME-related facilities. The + fifth and final document, RFC 2049, describes MIME conformance + criteria as well as providing some illustrative examples of MIME + message formats, acknowledgements, and the bibliography. + + These documents are revisions of RFCs 1521, 1522, and 1590, which + themselves were revisions of RFCs 1341 and 1342. An appendix in RFC + 2049 describes differences and changes from previous versions. + +Table of Contents + + 1. Introduction ......................................... 3 + 2. Definitions, Conventions, and Generic BNF Grammar .... 5 + 2.1 CRLF ................................................ 5 + 2.2 Character Set ....................................... 6 + 2.3 Message ............................................. 6 + 2.4 Entity .............................................. 6 + 2.5 Body Part ........................................... 7 + 2.6 Body ................................................ 7 + 2.7 7bit Data ........................................... 7 + 2.8 8bit Data ........................................... 7 + 2.9 Binary Data ......................................... 7 + 2.10 Lines .............................................. 7 + 3. MIME Header Fields ................................... 8 + 4. MIME-Version Header Field ............................ 8 + 5. Content-Type Header Field ............................ 10 + 5.1 Syntax of the Content-Type Header Field ............. 12 + 5.2 Content-Type Defaults ............................... 14 + 6. Content-Transfer-Encoding Header Field ............... 14 + 6.1 Content-Transfer-Encoding Syntax .................... 14 + 6.2 Content-Transfer-Encodings Semantics ................ 15 + 6.3 New Content-Transfer-Encodings ...................... 16 + 6.4 Interpretation and Use .............................. 16 + 6.5 Translating Encodings ............................... 18 + 6.6 Canonical Encoding Model ............................ 19 + 6.7 Quoted-Printable Content-Transfer-Encoding .......... 19 + 6.8 Base64 Content-Transfer-Encoding .................... 24 + 7. Content-ID Header Field .............................. 26 + 8. Content-Description Header Field ..................... 27 + 9. Additional MIME Header Fields ........................ 27 + 10. Summary ............................................. 27 + 11. Security Considerations ............................. 27 + 12. Authors' Addresses .................................. 28 + A. Collected Grammar .................................... 29 + + + + + + +Freed & Borenstein Standards Track [Page 2] + +RFC 2045 Internet Message Bodies November 1996 + + +1. Introduction + + Since its publication in 1982, RFC 822 has defined the standard + format of textual mail messages on the Internet. Its success has + been such that the RFC 822 format has been adopted, wholly or + partially, well beyond the confines of the Internet and the Internet + SMTP transport defined by RFC 821. As the format has seen wider use, + a number of limitations have proven increasingly restrictive for the + user community. + + RFC 822 was intended to specify a format for text messages. As such, + non-text messages, such as multimedia messages that might include + audio or images, are simply not mentioned. Even in the case of text, + however, RFC 822 is inadequate for the needs of mail users whose + languages require the use of character sets richer than US-ASCII. + Since RFC 822 does not specify mechanisms for mail containing audio, + video, Asian language text, or even text in most European languages, + additional specifications are needed. + + One of the notable limitations of RFC 821/822 based mail systems is + the fact that they limit the contents of electronic mail messages to + relatively short lines (e.g. 1000 characters or less [RFC-821]) of + 7bit US-ASCII. This forces users to convert any non-textual data + that they may wish to send into seven-bit bytes representable as + printable US-ASCII characters before invoking a local mail UA (User + Agent, a program with which human users send and receive mail). + Examples of such encodings currently used in the Internet include + pure hexadecimal, uuencode, the 3-in-4 base 64 scheme specified in + RFC 1421, the Andrew Toolkit Representation [ATK], and many others. + + The limitations of RFC 822 mail become even more apparent as gateways + are designed to allow for the exchange of mail messages between RFC + 822 hosts and X.400 hosts. X.400 [X400] specifies mechanisms for the + inclusion of non-textual material within electronic mail messages. + The current standards for the mapping of X.400 messages to RFC 822 + messages specify either that X.400 non-textual material must be + converted to (not encoded in) IA5Text format, or that they must be + discarded, notifying the RFC 822 user that discarding has occurred. + This is clearly undesirable, as information that a user may wish to + receive is lost. Even though a user agent may not have the + capability of dealing with the non-textual material, the user might + have some mechanism external to the UA that can extract useful + information from the material. Moreover, it does not allow for the + fact that the message may eventually be gatewayed back into an X.400 + message handling system (i.e., the X.400 message is "tunneled" + through Internet mail), where the non-textual information would + definitely become useful again. + + + + +Freed & Borenstein Standards Track [Page 3] + +RFC 2045 Internet Message Bodies November 1996 + + + This document describes several mechanisms that combine to solve most + of these problems without introducing any serious incompatibilities + with the existing world of RFC 822 mail. In particular, it + describes: + + (1) A MIME-Version header field, which uses a version + number to declare a message to be conformant with MIME + and allows mail processing agents to distinguish + between such messages and those generated by older or + non-conformant software, which are presumed to lack + such a field. + + (2) A Content-Type header field, generalized from RFC 1049, + which can be used to specify the media type and subtype + of data in the body of a message and to fully specify + the native representation (canonical form) of such + data. + + (3) A Content-Transfer-Encoding header field, which can be + used to specify both the encoding transformation that + was applied to the body and the domain of the result. + Encoding transformations other than the identity + transformation are usually applied to data in order to + allow it to pass through mail transport mechanisms + which may have data or character set limitations. + + (4) Two additional header fields that can be used to + further describe the data in a body, the Content-ID and + Content-Description header fields. + + All of the header fields defined in this document are subject to the + general syntactic rules for header fields specified in RFC 822. In + particular, all of these header fields except for Content-Disposition + can include RFC 822 comments, which have no semantic content and + should be ignored during MIME processing. + + Finally, to specify and promote interoperability, RFC 2049 provides a + basic applicability statement for a subset of the above mechanisms + that defines a minimal level of "conformance" with this document. + + HISTORICAL NOTE: Several of the mechanisms described in this set of + documents may seem somewhat strange or even baroque at first reading. + It is important to note that compatibility with existing standards + AND robustness across existing practice were two of the highest + priorities of the working group that developed this set of documents. + In particular, compatibility was always favored over elegance. + + + + + +Freed & Borenstein Standards Track [Page 4] + +RFC 2045 Internet Message Bodies November 1996 + + + Please refer to the current edition of the "Internet Official + Protocol Standards" for the standardization state and status of this + protocol. RFC 822 and STD 3, RFC 1123 also provide essential + background for MIME since no conforming implementation of MIME can + violate them. In addition, several other informational RFC documents + will be of interest to the MIME implementor, in particular RFC 1344, + RFC 1345, and RFC 1524. + +2. Definitions, Conventions, and Generic BNF Grammar + + Although the mechanisms specified in this set of documents are all + described in prose, most are also described formally in the augmented + BNF notation of RFC 822. Implementors will need to be familiar with + this notation in order to understand this set of documents, and are + referred to RFC 822 for a complete explanation of the augmented BNF + notation. + + Some of the augmented BNF in this set of documents makes named + references to syntax rules defined in RFC 822. A complete formal + grammar, then, is obtained by combining the collected grammar + appendices in each document in this set with the BNF of RFC 822 plus + the modifications to RFC 822 defined in RFC 1123 (which specifically + changes the syntax for `return', `date' and `mailbox'). + + All numeric and octet values are given in decimal notation in this + set of documents. All media type values, subtype values, and + parameter names as defined are case-insensitive. However, parameter + values are case-sensitive unless otherwise specified for the specific + parameter. + + FORMATTING NOTE: Notes, such at this one, provide additional + nonessential information which may be skipped by the reader without + missing anything essential. The primary purpose of these non- + essential notes is to convey information about the rationale of this + set of documents, or to place these documents in the proper + historical or evolutionary context. Such information may in + particular be skipped by those who are focused entirely on building a + conformant implementation, but may be of use to those who wish to + understand why certain design choices were made. + +2.1. CRLF + + The term CRLF, in this set of documents, refers to the sequence of + octets corresponding to the two US-ASCII characters CR (decimal value + 13) and LF (decimal value 10) which, taken together, in this order, + denote a line break in RFC 822 mail. + + + + + +Freed & Borenstein Standards Track [Page 5] + +RFC 2045 Internet Message Bodies November 1996 + + +2.2. Character Set + + The term "character set" is used in MIME to refer to a method of + converting a sequence of octets into a sequence of characters. Note + that unconditional and unambiguous conversion in the other direction + is not required, in that not all characters may be representable by a + given character set and a character set may provide more than one + sequence of octets to represent a particular sequence of characters. + + This definition is intended to allow various kinds of character + encodings, from simple single-table mappings such as US-ASCII to + complex table switching methods such as those that use ISO 2022's + techniques, to be used as character sets. However, the definition + associated with a MIME character set name must fully specify the + mapping to be performed. In particular, use of external profiling + information to determine the exact mapping is not permitted. + + NOTE: The term "character set" was originally to describe such + straightforward schemes as US-ASCII and ISO-8859-1 which have a + simple one-to-one mapping from single octets to single characters. + Multi-octet coded character sets and switching techniques make the + situation more complex. For example, some communities use the term + "character encoding" for what MIME calls a "character set", while + using the phrase "coded character set" to denote an abstract mapping + from integers (not octets) to characters. + +2.3. Message + + The term "message", when not further qualified, means either a + (complete or "top-level") RFC 822 message being transferred on a + network, or a message encapsulated in a body of type "message/rfc822" + or "message/partial". + +2.4. Entity + + The term "entity", refers specifically to the MIME-defined header + fields and contents of either a message or one of the parts in the + body of a multipart entity. The specification of such entities is + the essence of MIME. Since the contents of an entity are often + called the "body", it makes sense to speak about the body of an + entity. Any sort of field may be present in the header of an entity, + but only those fields whose names begin with "content-" actually have + any MIME-related meaning. Note that this does NOT imply thay they + have no meaning at all -- an entity that is also a message has non- + MIME header fields whose meanings are defined by RFC 822. + + + + + + +Freed & Borenstein Standards Track [Page 6] + +RFC 2045 Internet Message Bodies November 1996 + + +2.5. Body Part + + The term "body part" refers to an entity inside of a multipart + entity. + +2.6. Body + + The term "body", when not further qualified, means the body of an + entity, that is, the body of either a message or of a body part. + + NOTE: The previous four definitions are clearly circular. This is + unavoidable, since the overall structure of a MIME message is indeed + recursive. + +2.7. 7bit Data + + "7bit data" refers to data that is all represented as relatively + short lines with 998 octets or less between CRLF line separation + sequences [RFC-821]. No octets with decimal values greater than 127 + are allowed and neither are NULs (octets with decimal value 0). CR + (decimal value 13) and LF (decimal value 10) octets only occur as + part of CRLF line separation sequences. + +2.8. 8bit Data + + "8bit data" refers to data that is all represented as relatively + short lines with 998 octets or less between CRLF line separation + sequences [RFC-821]), but octets with decimal values greater than 127 + may be used. As with "7bit data" CR and LF octets only occur as part + of CRLF line separation sequences and no NULs are allowed. + +2.9. Binary Data + + "Binary data" refers to data where any sequence of octets whatsoever + is allowed. + +2.10. Lines + + "Lines" are defined as sequences of octets separated by a CRLF + sequences. This is consistent with both RFC 821 and RFC 822. + "Lines" only refers to a unit of data in a message, which may or may + not correspond to something that is actually displayed by a user + agent. + + + + + + + + +Freed & Borenstein Standards Track [Page 7] + +RFC 2045 Internet Message Bodies November 1996 + + +3. MIME Header Fields + + MIME defines a number of new RFC 822 header fields that are used to + describe the content of a MIME entity. These header fields occur in + at least two contexts: + + (1) As part of a regular RFC 822 message header. + + (2) In a MIME body part header within a multipart + construct. + + The formal definition of these header fields is as follows: + + entity-headers := [ content CRLF ] + [ encoding CRLF ] + [ id CRLF ] + [ description CRLF ] + *( MIME-extension-field CRLF ) + + MIME-message-headers := entity-headers + fields + version CRLF + ; The ordering of the header + ; fields implied by this BNF + ; definition should be ignored. + + MIME-part-headers := entity-headers + [ fields ] + ; Any field not beginning with + ; "content-" can have no defined + ; meaning and may be ignored. + ; The ordering of the header + ; fields implied by this BNF + ; definition should be ignored. + + The syntax of the various specific MIME header fields will be + described in the following sections. + +4. MIME-Version Header Field + + Since RFC 822 was published in 1982, there has really been only one + format standard for Internet messages, and there has been little + perceived need to declare the format standard in use. This document + is an independent specification that complements RFC 822. Although + the extensions in this document have been defined in such a way as to + be compatible with RFC 822, there are still circumstances in which it + might be desirable for a mail-processing agent to know whether a + message was composed with the new standard in mind. + + + +Freed & Borenstein Standards Track [Page 8] + +RFC 2045 Internet Message Bodies November 1996 + + + Therefore, this document defines a new header field, "MIME-Version", + which is to be used to declare the version of the Internet message + body format standard in use. + + Messages composed in accordance with this document MUST include such + a header field, with the following verbatim text: + + MIME-Version: 1.0 + + The presence of this header field is an assertion that the message + has been composed in compliance with this document. + + Since it is possible that a future document might extend the message + format standard again, a formal BNF is given for the content of the + MIME-Version field: + + version := "MIME-Version" ":" 1*DIGIT "." 1*DIGIT + + Thus, future format specifiers, which might replace or extend "1.0", + are constrained to be two integer fields, separated by a period. If + a message is received with a MIME-version value other than "1.0", it + cannot be assumed to conform with this document. + + Note that the MIME-Version header field is required at the top level + of a message. It is not required for each body part of a multipart + entity. It is required for the embedded headers of a body of type + "message/rfc822" or "message/partial" if and only if the embedded + message is itself claimed to be MIME-conformant. + + It is not possible to fully specify how a mail reader that conforms + with MIME as defined in this document should treat a message that + might arrive in the future with some value of MIME-Version other than + "1.0". + + It is also worth noting that version control for specific media types + is not accomplished using the MIME-Version mechanism. In particular, + some formats (such as application/postscript) have version numbering + conventions that are internal to the media format. Where such + conventions exist, MIME does nothing to supersede them. Where no + such conventions exist, a MIME media type might use a "version" + parameter in the content-type field if necessary. + + + + + + + + + + +Freed & Borenstein Standards Track [Page 9] + +RFC 2045 Internet Message Bodies November 1996 + + + NOTE TO IMPLEMENTORS: When checking MIME-Version values any RFC 822 + comment strings that are present must be ignored. In particular, the + following four MIME-Version fields are equivalent: + + MIME-Version: 1.0 + + MIME-Version: 1.0 (produced by MetaSend Vx.x) + + MIME-Version: (produced by MetaSend Vx.x) 1.0 + + MIME-Version: 1.(produced by MetaSend Vx.x)0 + + In the absence of a MIME-Version field, a receiving mail user agent + (whether conforming to MIME requirements or not) may optionally + choose to interpret the body of the message according to local + conventions. Many such conventions are currently in use and it + should be noted that in practice non-MIME messages can contain just + about anything. + + It is impossible to be certain that a non-MIME mail message is + actually plain text in the US-ASCII character set since it might well + be a message that, using some set of nonstandard local conventions + that predate MIME, includes text in another character set or non- + textual data presented in a manner that cannot be automatically + recognized (e.g., a uuencoded compressed UNIX tar file). + +5. Content-Type Header Field + + The purpose of the Content-Type field is to describe the data + contained in the body fully enough that the receiving user agent can + pick an appropriate agent or mechanism to present the data to the + user, or otherwise deal with the data in an appropriate manner. The + value in this field is called a media type. + + HISTORICAL NOTE: The Content-Type header field was first defined in + RFC 1049. RFC 1049 used a simpler and less powerful syntax, but one + that is largely compatible with the mechanism given here. + + The Content-Type header field specifies the nature of the data in the + body of an entity by giving media type and subtype identifiers, and + by providing auxiliary information that may be required for certain + media types. After the media type and subtype names, the remainder + of the header field is simply a set of parameters, specified in an + attribute=value notation. The ordering of parameters is not + significant. + + + + + + +Freed & Borenstein Standards Track [Page 10] + +RFC 2045 Internet Message Bodies November 1996 + + + In general, the top-level media type is used to declare the general + type of data, while the subtype specifies a specific format for that + type of data. Thus, a media type of "image/xyz" is enough to tell a + user agent that the data is an image, even if the user agent has no + knowledge of the specific image format "xyz". Such information can + be used, for example, to decide whether or not to show a user the raw + data from an unrecognized subtype -- such an action might be + reasonable for unrecognized subtypes of text, but not for + unrecognized subtypes of image or audio. For this reason, registered + subtypes of text, image, audio, and video should not contain embedded + information that is really of a different type. Such compound + formats should be represented using the "multipart" or "application" + types. + + Parameters are modifiers of the media subtype, and as such do not + fundamentally affect the nature of the content. The set of + meaningful parameters depends on the media type and subtype. Most + parameters are associated with a single specific subtype. However, a + given top-level media type may define parameters which are applicable + to any subtype of that type. Parameters may be required by their + defining content type or subtype or they may be optional. MIME + implementations must ignore any parameters whose names they do not + recognize. + + For example, the "charset" parameter is applicable to any subtype of + "text", while the "boundary" parameter is required for any subtype of + the "multipart" media type. + + There are NO globally-meaningful parameters that apply to all media + types. Truly global mechanisms are best addressed, in the MIME + model, by the definition of additional Content-* header fields. + + An initial set of seven top-level media types is defined in RFC 2046. + Five of these are discrete types whose content is essentially opaque + as far as MIME processing is concerned. The remaining two are + composite types whose contents require additional handling by MIME + processors. + + This set of top-level media types is intended to be substantially + complete. It is expected that additions to the larger set of + supported types can generally be accomplished by the creation of new + subtypes of these initial types. In the future, more top-level types + may be defined only by a standards-track extension to this standard. + If another top-level type is to be used for any reason, it must be + given a name starting with "X-" to indicate its non-standard status + and to avoid a potential conflict with a future official name. + + + + + +Freed & Borenstein Standards Track [Page 11] + +RFC 2045 Internet Message Bodies November 1996 + + +5.1. Syntax of the Content-Type Header Field + + In the Augmented BNF notation of RFC 822, a Content-Type header field + value is defined as follows: + + content := "Content-Type" ":" type "/" subtype + *(";" parameter) + ; Matching of media type and subtype + ; is ALWAYS case-insensitive. + + type := discrete-type / composite-type + + discrete-type := "text" / "image" / "audio" / "video" / + "application" / extension-token + + composite-type := "message" / "multipart" / extension-token + + extension-token := ietf-token / x-token + + ietf-token := + + x-token := + + subtype := extension-token / iana-token + + iana-token := + + parameter := attribute "=" value + + attribute := token + ; Matching of attributes + ; is ALWAYS case-insensitive. + + value := token / quoted-string + + token := 1* + + tspecials := "(" / ")" / "<" / ">" / "@" / + "," / ";" / ":" / "\" / <"> + "/" / "[" / "]" / "?" / "=" + ; Must be in quoted-string, + ; to use within parameter values + + + +Freed & Borenstein Standards Track [Page 12] + +RFC 2045 Internet Message Bodies November 1996 + + + Note that the definition of "tspecials" is the same as the RFC 822 + definition of "specials" with the addition of the three characters + "/", "?", and "=", and the removal of ".". + + Note also that a subtype specification is MANDATORY -- it may not be + omitted from a Content-Type header field. As such, there are no + default subtypes. + + The type, subtype, and parameter names are not case sensitive. For + example, TEXT, Text, and TeXt are all equivalent top-level media + types. Parameter values are normally case sensitive, but sometimes + are interpreted in a case-insensitive fashion, depending on the + intended use. (For example, multipart boundaries are case-sensitive, + but the "access-type" parameter for message/External-body is not + case-sensitive.) + + Note that the value of a quoted string parameter does not include the + quotes. That is, the quotation marks in a quoted-string are not a + part of the value of the parameter, but are merely used to delimit + that parameter value. In addition, comments are allowed in + accordance with RFC 822 rules for structured header fields. Thus the + following two forms + + Content-type: text/plain; charset=us-ascii (Plain text) + + Content-type: text/plain; charset="us-ascii" + + are completely equivalent. + + Beyond this syntax, the only syntactic constraint on the definition + of subtype names is the desire that their uses must not conflict. + That is, it would be undesirable to have two different communities + using "Content-Type: application/foobar" to mean two different + things. The process of defining new media subtypes, then, is not + intended to be a mechanism for imposing restrictions, but simply a + mechanism for publicizing their definition and usage. There are, + therefore, two acceptable mechanisms for defining new media subtypes: + + (1) Private values (starting with "X-") may be defined + bilaterally between two cooperating agents without + outside registration or standardization. Such values + cannot be registered or standardized. + + (2) New standard values should be registered with IANA as + described in RFC 2048. + + The second document in this set, RFC 2046, defines the initial set of + media types for MIME. + + + +Freed & Borenstein Standards Track [Page 13] + +RFC 2045 Internet Message Bodies November 1996 + + +5.2. Content-Type Defaults + + Default RFC 822 messages without a MIME Content-Type header are taken + by this protocol to be plain text in the US-ASCII character set, + which can be explicitly specified as: + + Content-type: text/plain; charset=us-ascii + + This default is assumed if no Content-Type header field is specified. + It is also recommend that this default be assumed when a + syntactically invalid Content-Type header field is encountered. In + the presence of a MIME-Version header field and the absence of any + Content-Type header field, a receiving User Agent can also assume + that plain US-ASCII text was the sender's intent. Plain US-ASCII + text may still be assumed in the absence of a MIME-Version or the + presence of an syntactically invalid Content-Type header field, but + the sender's intent might have been otherwise. + +6. Content-Transfer-Encoding Header Field + + Many media types which could be usefully transported via email are + represented, in their "natural" format, as 8bit character or binary + data. Such data cannot be transmitted over some transfer protocols. + For example, RFC 821 (SMTP) restricts mail messages to 7bit US-ASCII + data with lines no longer than 1000 characters including any trailing + CRLF line separator. + + It is necessary, therefore, to define a standard mechanism for + encoding such data into a 7bit short line format. Proper labelling + of unencoded material in less restrictive formats for direct use over + less restrictive transports is also desireable. This document + specifies that such encodings will be indicated by a new "Content- + Transfer-Encoding" header field. This field has not been defined by + any previous standard. + +6.1. Content-Transfer-Encoding Syntax + + The Content-Transfer-Encoding field's value is a single token + specifying the type of encoding, as enumerated below. Formally: + + encoding := "Content-Transfer-Encoding" ":" mechanism + + mechanism := "7bit" / "8bit" / "binary" / + "quoted-printable" / "base64" / + ietf-token / x-token + + These values are not case sensitive -- Base64 and BASE64 and bAsE64 + are all equivalent. An encoding type of 7BIT requires that the body + + + +Freed & Borenstein Standards Track [Page 14] + +RFC 2045 Internet Message Bodies November 1996 + + + is already in a 7bit mail-ready representation. This is the default + value -- that is, "Content-Transfer-Encoding: 7BIT" is assumed if the + Content-Transfer-Encoding header field is not present. + +6.2. Content-Transfer-Encodings Semantics + + This single Content-Transfer-Encoding token actually provides two + pieces of information. It specifies what sort of encoding + transformation the body was subjected to and hence what decoding + operation must be used to restore it to its original form, and it + specifies what the domain of the result is. + + The transformation part of any Content-Transfer-Encodings specifies, + either explicitly or implicitly, a single, well-defined decoding + algorithm, which for any sequence of encoded octets either transforms + it to the original sequence of octets which was encoded, or shows + that it is illegal as an encoded sequence. Content-Transfer- + Encodings transformations never depend on any additional external + profile information for proper operation. Note that while decoders + must produce a single, well-defined output for a valid encoding no + such restrictions exist for encoders: Encoding a given sequence of + octets to different, equivalent encoded sequences is perfectly legal. + + Three transformations are currently defined: identity, the "quoted- + printable" encoding, and the "base64" encoding. The domains are + "binary", "8bit" and "7bit". + + The Content-Transfer-Encoding values "7bit", "8bit", and "binary" all + mean that the identity (i.e. NO) encoding transformation has been + performed. As such, they serve simply as indicators of the domain of + the body data, and provide useful information about the sort of + encoding that might be needed for transmission in a given transport + system. The terms "7bit data", "8bit data", and "binary data" are + all defined in Section 2. + + The quoted-printable and base64 encodings transform their input from + an arbitrary domain into material in the "7bit" range, thus making it + safe to carry over restricted transports. The specific definition of + the transformations are given below. + + The proper Content-Transfer-Encoding label must always be used. + Labelling unencoded data containing 8bit characters as "7bit" is not + allowed, nor is labelling unencoded non-line-oriented data as + anything other than "binary" allowed. + + Unlike media subtypes, a proliferation of Content-Transfer-Encoding + values is both undesirable and unnecessary. However, establishing + only a single transformation into the "7bit" domain does not seem + + + +Freed & Borenstein Standards Track [Page 15] + +RFC 2045 Internet Message Bodies November 1996 + + + possible. There is a tradeoff between the desire for a compact and + efficient encoding of largely- binary data and the desire for a + somewhat readable encoding of data that is mostly, but not entirely, + 7bit. For this reason, at least two encoding mechanisms are + necessary: a more or less readable encoding (quoted-printable) and a + "dense" or "uniform" encoding (base64). + + Mail transport for unencoded 8bit data is defined in RFC 1652. As of + the initial publication of this document, there are no standardized + Internet mail transports for which it is legitimate to include + unencoded binary data in mail bodies. Thus there are no + circumstances in which the "binary" Content-Transfer-Encoding is + actually valid in Internet mail. However, in the event that binary + mail transport becomes a reality in Internet mail, or when MIME is + used in conjunction with any other binary-capable mail transport + mechanism, binary bodies must be labelled as such using this + mechanism. + + NOTE: The five values defined for the Content-Transfer-Encoding field + imply nothing about the media type other than the algorithm by which + it was encoded or the transport system requirements if unencoded. + +6.3. New Content-Transfer-Encodings + + Implementors may, if necessary, define private Content-Transfer- + Encoding values, but must use an x-token, which is a name prefixed by + "X-", to indicate its non-standard status, e.g., "Content-Transfer- + Encoding: x-my-new-encoding". Additional standardized Content- + Transfer-Encoding values must be specified by a standards-track RFC. + The requirements such specifications must meet are given in RFC 2048. + As such, all content-transfer-encoding namespace except that + beginning with "X-" is explicitly reserved to the IETF for future + use. + + Unlike media types and subtypes, the creation of new Content- + Transfer-Encoding values is STRONGLY discouraged, as it seems likely + to hinder interoperability with little potential benefit + +6.4. Interpretation and Use + + If a Content-Transfer-Encoding header field appears as part of a + message header, it applies to the entire body of that message. If a + Content-Transfer-Encoding header field appears as part of an entity's + headers, it applies only to the body of that entity. If an entity is + of type "multipart" the Content-Transfer-Encoding is not permitted to + have any value other than "7bit", "8bit" or "binary". Even more + severe restrictions apply to some subtypes of the "message" type. + + + + +Freed & Borenstein Standards Track [Page 16] + +RFC 2045 Internet Message Bodies November 1996 + + + It should be noted that most media types are defined in terms of + octets rather than bits, so that the mechanisms described here are + mechanisms for encoding arbitrary octet streams, not bit streams. If + a bit stream is to be encoded via one of these mechanisms, it must + first be converted to an 8bit byte stream using the network standard + bit order ("big-endian"), in which the earlier bits in a stream + become the higher-order bits in a 8bit byte. A bit stream not ending + at an 8bit boundary must be padded with zeroes. RFC 2046 provides a + mechanism for noting the addition of such padding in the case of the + application/octet-stream media type, which has a "padding" parameter. + + The encoding mechanisms defined here explicitly encode all data in + US-ASCII. Thus, for example, suppose an entity has header fields + such as: + + Content-Type: text/plain; charset=ISO-8859-1 + Content-transfer-encoding: base64 + + This must be interpreted to mean that the body is a base64 US-ASCII + encoding of data that was originally in ISO-8859-1, and will be in + that character set again after decoding. + + Certain Content-Transfer-Encoding values may only be used on certain + media types. In particular, it is EXPRESSLY FORBIDDEN to use any + encodings other than "7bit", "8bit", or "binary" with any composite + media type, i.e. one that recursively includes other Content-Type + fields. Currently the only composite media types are "multipart" and + "message". All encodings that are desired for bodies of type + multipart or message must be done at the innermost level, by encoding + the actual body that needs to be encoded. + + It should also be noted that, by definition, if a composite entity + has a transfer-encoding value such as "7bit", but one of the enclosed + entities has a less restrictive value such as "8bit", then either the + outer "7bit" labelling is in error, because 8bit data are included, + or the inner "8bit" labelling placed an unnecessarily high demand on + the transport system because the actual included data were actually + 7bit-safe. + + NOTE ON ENCODING RESTRICTIONS: Though the prohibition against using + content-transfer-encodings on composite body data may seem overly + restrictive, it is necessary to prevent nested encodings, in which + data are passed through an encoding algorithm multiple times, and + must be decoded multiple times in order to be properly viewed. + Nested encodings add considerable complexity to user agents: Aside + from the obvious efficiency problems with such multiple encodings, + they can obscure the basic structure of a message. In particular, + they can imply that several decoding operations are necessary simply + + + +Freed & Borenstein Standards Track [Page 17] + +RFC 2045 Internet Message Bodies November 1996 + + + to find out what types of bodies a message contains. Banning nested + encodings may complicate the job of certain mail gateways, but this + seems less of a problem than the effect of nested encodings on user + agents. + + Any entity with an unrecognized Content-Transfer-Encoding must be + treated as if it has a Content-Type of "application/octet-stream", + regardless of what the Content-Type header field actually says. + + NOTE ON THE RELATIONSHIP BETWEEN CONTENT-TYPE AND CONTENT-TRANSFER- + ENCODING: It may seem that the Content-Transfer-Encoding could be + inferred from the characteristics of the media that is to be encoded, + or, at the very least, that certain Content-Transfer-Encodings could + be mandated for use with specific media types. There are several + reasons why this is not the case. First, given the varying types of + transports used for mail, some encodings may be appropriate for some + combinations of media types and transports but not for others. (For + example, in an 8bit transport, no encoding would be required for text + in certain character sets, while such encodings are clearly required + for 7bit SMTP.) + + Second, certain media types may require different types of transfer + encoding under different circumstances. For example, many PostScript + bodies might consist entirely of short lines of 7bit data and hence + require no encoding at all. Other PostScript bodies (especially + those using Level 2 PostScript's binary encoding mechanism) may only + be reasonably represented using a binary transport encoding. + Finally, since the Content-Type field is intended to be an open-ended + specification mechanism, strict specification of an association + between media types and encodings effectively couples the + specification of an application protocol with a specific lower-level + transport. This is not desirable since the developers of a media + type should not have to be aware of all the transports in use and + what their limitations are. + +6.5. Translating Encodings + + The quoted-printable and base64 encodings are designed so that + conversion between them is possible. The only issue that arises in + such a conversion is the handling of hard line breaks in quoted- + printable encoding output. When converting from quoted-printable to + base64 a hard line break in the quoted-printable form represents a + CRLF sequence in the canonical form of the data. It must therefore be + converted to a corresponding encoded CRLF in the base64 form of the + data. Similarly, a CRLF sequence in the canonical form of the data + obtained after base64 decoding must be converted to a quoted- + printable hard line break, but ONLY when converting text data. + + + + +Freed & Borenstein Standards Track [Page 18] + +RFC 2045 Internet Message Bodies November 1996 + + +6.6. Canonical Encoding Model + + There was some confusion, in the previous versions of this RFC, + regarding the model for when email data was to be converted to + canonical form and encoded, and in particular how this process would + affect the treatment of CRLFs, given that the representation of + newlines varies greatly from system to system, and the relationship + between content-transfer-encodings and character sets. A canonical + model for encoding is presented in RFC 2049 for this reason. + +6.7. Quoted-Printable Content-Transfer-Encoding + + The Quoted-Printable encoding is intended to represent data that + largely consists of octets that correspond to printable characters in + the US-ASCII character set. It encodes the data in such a way that + the resulting octets are unlikely to be modified by mail transport. + If the data being encoded are mostly US-ASCII text, the encoded form + of the data remains largely recognizable by humans. A body which is + entirely US-ASCII may also be encoded in Quoted-Printable to ensure + the integrity of the data should the message pass through a + character-translating, and/or line-wrapping gateway. + + In this encoding, octets are to be represented as determined by the + following rules: + + (1) (General 8bit representation) Any octet, except a CR or + LF that is part of a CRLF line break of the canonical + (standard) form of the data being encoded, may be + represented by an "=" followed by a two digit + hexadecimal representation of the octet's value. The + digits of the hexadecimal alphabet, for this purpose, + are "0123456789ABCDEF". Uppercase letters must be + used; lowercase letters are not allowed. Thus, for + example, the decimal value 12 (US-ASCII form feed) can + be represented by "=0C", and the decimal value 61 (US- + ASCII EQUAL SIGN) can be represented by "=3D". This + rule must be followed except when the following rules + allow an alternative encoding. + + (2) (Literal representation) Octets with decimal values of + 33 through 60 inclusive, and 62 through 126, inclusive, + MAY be represented as the US-ASCII characters which + correspond to those octets (EXCLAMATION POINT through + LESS THAN, and GREATER THAN through TILDE, + respectively). + + (3) (White Space) Octets with values of 9 and 32 MAY be + represented as US-ASCII TAB (HT) and SPACE characters, + + + +Freed & Borenstein Standards Track [Page 19] + +RFC 2045 Internet Message Bodies November 1996 + + + respectively, but MUST NOT be so represented at the end + of an encoded line. Any TAB (HT) or SPACE characters + on an encoded line MUST thus be followed on that line + by a printable character. In particular, an "=" at the + end of an encoded line, indicating a soft line break + (see rule #5) may follow one or more TAB (HT) or SPACE + characters. It follows that an octet with decimal + value 9 or 32 appearing at the end of an encoded line + must be represented according to Rule #1. This rule is + necessary because some MTAs (Message Transport Agents, + programs which transport messages from one user to + another, or perform a portion of such transfers) are + known to pad lines of text with SPACEs, and others are + known to remove "white space" characters from the end + of a line. Therefore, when decoding a Quoted-Printable + body, any trailing white space on a line must be + deleted, as it will necessarily have been added by + intermediate transport agents. + + (4) (Line Breaks) A line break in a text body, represented + as a CRLF sequence in the text canonical form, must be + represented by a (RFC 822) line break, which is also a + CRLF sequence, in the Quoted-Printable encoding. Since + the canonical representation of media types other than + text do not generally include the representation of + line breaks as CRLF sequences, no hard line breaks + (i.e. line breaks that are intended to be meaningful + and to be displayed to the user) can occur in the + quoted-printable encoding of such types. Sequences + like "=0D", "=0A", "=0A=0D" and "=0D=0A" will routinely + appear in non-text data represented in quoted- + printable, of course. + + Note that many implementations may elect to encode the + local representation of various content types directly + rather than converting to canonical form first, + encoding, and then converting back to local + representation. In particular, this may apply to plain + text material on systems that use newline conventions + other than a CRLF terminator sequence. Such an + implementation optimization is permissible, but only + when the combined canonicalization-encoding step is + equivalent to performing the three steps separately. + + (5) (Soft Line Breaks) The Quoted-Printable encoding + REQUIRES that encoded lines be no more than 76 + characters long. If longer lines are to be encoded + with the Quoted-Printable encoding, "soft" line breaks + + + +Freed & Borenstein Standards Track [Page 20] + +RFC 2045 Internet Message Bodies November 1996 + + + must be used. An equal sign as the last character on a + encoded line indicates such a non-significant ("soft") + line break in the encoded text. + + Thus if the "raw" form of the line is a single unencoded line that + says: + + Now's the time for all folk to come to the aid of their country. + + This can be represented, in the Quoted-Printable encoding, as: + + Now's the time = + for all folk to come= + to the aid of their country. + + This provides a mechanism with which long lines are encoded in such a + way as to be restored by the user agent. The 76 character limit does + not count the trailing CRLF, but counts all other characters, + including any equal signs. + + Since the hyphen character ("-") may be represented as itself in the + Quoted-Printable encoding, care must be taken, when encapsulating a + quoted-printable encoded body inside one or more multipart entities, + to ensure that the boundary delimiter does not appear anywhere in the + encoded body. (A good strategy is to choose a boundary that includes + a character sequence such as "=_" which can never appear in a + quoted-printable body. See the definition of multipart messages in + RFC 2046.) + + NOTE: The quoted-printable encoding represents something of a + compromise between readability and reliability in transport. Bodies + encoded with the quoted-printable encoding will work reliably over + most mail gateways, but may not work perfectly over a few gateways, + notably those involving translation into EBCDIC. A higher level of + confidence is offered by the base64 Content-Transfer-Encoding. A way + to get reasonably reliable transport through EBCDIC gateways is to + also quote the US-ASCII characters + + !"#$@[\]^`{|}~ + + according to rule #1. + + Because quoted-printable data is generally assumed to be line- + oriented, it is to be expected that the representation of the breaks + between the lines of quoted-printable data may be altered in + transport, in the same manner that plain text mail has always been + altered in Internet mail when passing between systems with differing + newline conventions. If such alterations are likely to constitute a + + + +Freed & Borenstein Standards Track [Page 21] + +RFC 2045 Internet Message Bodies November 1996 + + + corruption of the data, it is probably more sensible to use the + base64 encoding rather than the quoted-printable encoding. + + NOTE: Several kinds of substrings cannot be generated according to + the encoding rules for the quoted-printable content-transfer- + encoding, and hence are formally illegal if they appear in the output + of a quoted-printable encoder. This note enumerates these cases and + suggests ways to handle such illegal substrings if any are + encountered in quoted-printable data that is to be decoded. + + (1) An "=" followed by two hexadecimal digits, one or both + of which are lowercase letters in "abcdef", is formally + illegal. A robust implementation might choose to + recognize them as the corresponding uppercase letters. + + (2) An "=" followed by a character that is neither a + hexadecimal digit (including "abcdef") nor the CR + character of a CRLF pair is illegal. This case can be + the result of US-ASCII text having been included in a + quoted-printable part of a message without itself + having been subjected to quoted-printable encoding. A + reasonable approach by a robust implementation might be + to include the "=" character and the following + character in the decoded data without any + transformation and, if possible, indicate to the user + that proper decoding was not possible at this point in + the data. + + (3) An "=" cannot be the ultimate or penultimate character + in an encoded object. This could be handled as in case + (2) above. + + (4) Control characters other than TAB, or CR and LF as + parts of CRLF pairs, must not appear. The same is true + for octets with decimal values greater than 126. If + found in incoming quoted-printable data by a decoder, a + robust implementation might exclude them from the + decoded data and warn the user that illegal characters + were discovered. + + (5) Encoded lines must not be longer than 76 characters, + not counting the trailing CRLF. If longer lines are + found in incoming, encoded data, a robust + implementation might nevertheless decode the lines, and + might report the erroneous encoding to the user. + + + + + + +Freed & Borenstein Standards Track [Page 22] + +RFC 2045 Internet Message Bodies November 1996 + + + WARNING TO IMPLEMENTORS: If binary data is encoded in quoted- + printable, care must be taken to encode CR and LF characters as "=0D" + and "=0A", respectively. In particular, a CRLF sequence in binary + data should be encoded as "=0D=0A". Otherwise, if CRLF were + represented as a hard line break, it might be incorrectly decoded on + platforms with different line break conventions. + + For formalists, the syntax of quoted-printable data is described by + the following grammar: + + quoted-printable := qp-line *(CRLF qp-line) + + qp-line := *(qp-segment transport-padding CRLF) + qp-part transport-padding + + qp-part := qp-section + ; Maximum length of 76 characters + + qp-segment := qp-section *(SPACE / TAB) "=" + ; Maximum length of 76 characters + + qp-section := [*(ptext / SPACE / TAB) ptext] + + ptext := hex-octet / safe-char + + safe-char := + ; Characters not listed as "mail-safe" in + ; RFC 2049 are also not recommended. + + hex-octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F") + ; Octet must be used for characters > 127, =, + ; SPACEs or TABs at the ends of lines, and is + ; recommended for any character not listed in + ; RFC 2049 as "mail-safe". + + transport-padding := *LWSP-char + ; Composers MUST NOT generate + ; non-zero length transport + ; padding, but receivers MUST + ; be able to handle padding + ; added by message transports. + + IMPORTANT: The addition of LWSP between the elements shown in this + BNF is NOT allowed since this BNF does not specify a structured + header field. + + + + + +Freed & Borenstein Standards Track [Page 23] + +RFC 2045 Internet Message Bodies November 1996 + + +6.8. Base64 Content-Transfer-Encoding + + The Base64 Content-Transfer-Encoding is designed to represent + arbitrary sequences of octets in a form that need not be humanly + readable. The encoding and decoding algorithms are simple, but the + encoded data are consistently only about 33 percent larger than the + unencoded data. This encoding is virtually identical to the one used + in Privacy Enhanced Mail (PEM) applications, as defined in RFC 1421. + + A 65-character subset of US-ASCII is used, enabling 6 bits to be + represented per printable character. (The extra 65th character, "=", + is used to signify a special processing function.) + + NOTE: This subset has the important property that it is represented + identically in all versions of ISO 646, including US-ASCII, and all + characters in the subset are also represented identically in all + versions of EBCDIC. Other popular encodings, such as the encoding + used by the uuencode utility, Macintosh binhex 4.0 [RFC-1741], and + the base85 encoding specified as part of Level 2 PostScript, do not + share these properties, and thus do not fulfill the portability + requirements a binary transport encoding for mail must meet. + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + When encoding a bit stream via the base64 encoding, the bit stream + must be presumed to be ordered with the most-significant-bit first. + That is, the first bit in the stream will be the high-order bit in + the first 8bit byte, and the eighth bit will be the low-order bit in + the first 8bit byte, and so on. + + Each 6-bit group is used as an index into an array of 64 printable + characters. The character referenced by the index is placed in the + output string. These characters, identified in Table 1, below, are + selected so as to be universally representable, and the set excludes + characters with particular significance to SMTP (e.g., ".", CR, LF) + and to the multipart boundary delimiters defined in RFC 2046 (e.g., + "-"). + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 24] + +RFC 2045 Internet Message Bodies November 1996 + + + Table 1: The Base64 Alphabet + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + The encoded output stream must be represented in lines of no more + than 76 characters each. All line breaks or other characters not + found in Table 1 must be ignored by decoding software. In base64 + data, characters other than those in Table 1, line breaks, and other + white space probably indicate a transmission error, about which a + warning message or even a message rejection might be appropriate + under some circumstances. + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a body. When fewer than 24 input bits + are available in an input group, zero bits are added (on the right) + to form an integral number of 6-bit groups. Padding at the end of + the data is performed using the "=" character. Since all base64 + input is an integral number of octets, only the following cases can + arise: (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded output will be + an integral multiple of 4 characters with no "=" padding, (2) the + final quantum of encoding input is exactly 8 bits; here, the final + unit of encoded output will be two characters followed by two "=" + padding characters, or (3) the final quantum of encoding input is + exactly 16 bits; here, the final unit of encoded output will be three + characters followed by one "=" padding character. + + Because it is used only for padding at the end of the data, the + occurrence of any "=" characters may be taken as evidence that the + end of the data has been reached (without truncation in transit). No + + + +Freed & Borenstein Standards Track [Page 25] + +RFC 2045 Internet Message Bodies November 1996 + + + such assurance is possible, however, when the number of octets + transmitted was a multiple of three and no "=" characters are + present. + + Any characters outside of the base64 alphabet are to be ignored in + base64-encoded data. + + Care must be taken to use the proper octets for line breaks if base64 + encoding is applied directly to text material that has not been + converted to canonical form. In particular, text line breaks must be + converted into CRLF sequences prior to base64 encoding. The + important thing to note is that this may be done directly by the + encoder rather than in a prior canonicalization step in some + implementations. + + NOTE: There is no need to worry about quoting potential boundary + delimiters within base64-encoded bodies within multipart entities + because no hyphen characters are used in the base64 encoding. + +7. Content-ID Header Field + + In constructing a high-level user agent, it may be desirable to allow + one body to make reference to another. Accordingly, bodies may be + labelled using the "Content-ID" header field, which is syntactically + identical to the "Message-ID" header field: + + id := "Content-ID" ":" msg-id + + Like the Message-ID values, Content-ID values must be generated to be + world-unique. + + The Content-ID value may be used for uniquely identifying MIME + entities in several contexts, particularly for caching data + referenced by the message/external-body mechanism. Although the + Content-ID header is generally optional, its use is MANDATORY in + implementations which generate data of the optional MIME media type + "message/external-body". That is, each message/external-body entity + must have a Content-ID field to permit caching of such data. + + It is also worth noting that the Content-ID value has special + semantics in the case of the multipart/alternative media type. This + is explained in the section of RFC 2046 dealing with + multipart/alternative. + + + + + + + + +Freed & Borenstein Standards Track [Page 26] + +RFC 2045 Internet Message Bodies November 1996 + + +8. Content-Description Header Field + + The ability to associate some descriptive information with a given + body is often desirable. For example, it may be useful to mark an + "image" body as "a picture of the Space Shuttle Endeavor." Such text + may be placed in the Content-Description header field. This header + field is always optional. + + description := "Content-Description" ":" *text + + The description is presumed to be given in the US-ASCII character + set, although the mechanism specified in RFC 2047 may be used for + non-US-ASCII Content-Description values. + +9. Additional MIME Header Fields + + Future documents may elect to define additional MIME header fields + for various purposes. Any new header field that further describes + the content of a message should begin with the string "Content-" to + allow such fields which appear in a message header to be + distinguished from ordinary RFC 822 message header fields. + + MIME-extension-field := + +10. Summary + + Using the MIME-Version, Content-Type, and Content-Transfer-Encoding + header fields, it is possible to include, in a standardized way, + arbitrary types of data with RFC 822 conformant mail messages. No + restrictions imposed by either RFC 821 or RFC 822 are violated, and + care has been taken to avoid problems caused by additional + restrictions imposed by the characteristics of some Internet mail + transport mechanisms (see RFC 2049). + + The next document in this set, RFC 2046, specifies the initial set of + media types that can be labelled and transported using these headers. + +11. Security Considerations + + Security issues are discussed in the second document in this set, RFC + 2046. + + + + + + + + +Freed & Borenstein Standards Track [Page 27] + +RFC 2045 Internet Message Bodies November 1996 + + +12. Authors' Addresses + + For more information, the authors of this document are best contacted + via Internet mail: + + Ned Freed + Innosoft International, Inc. + 1050 East Garvey Avenue South + West Covina, CA 91790 + USA + + Phone: +1 818 919 3600 + Fax: +1 818 919 3614 + EMail: ned@innosoft.com + + + Nathaniel S. Borenstein + First Virtual Holdings + 25 Washington Avenue + Morristown, NJ 07960 + USA + + Phone: +1 201 540 8967 + Fax: +1 201 993 3032 + EMail: nsb@nsb.fv.com + + + MIME is a result of the work of the Internet Engineering Task Force + Working Group on RFC 822 Extensions. The chairman of that group, + Greg Vaudreuil, may be reached at: + + Gregory M. Vaudreuil + Octel Network Services + 17080 Dallas Parkway + Dallas, TX 75248-1905 + USA + + EMail: Greg.Vaudreuil@Octel.Com + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 28] + +RFC 2045 Internet Message Bodies November 1996 + + +Appendix A -- Collected Grammar + + This appendix contains the complete BNF grammar for all the syntax + specified by this document. + + By itself, however, this grammar is incomplete. It refers by name to + several syntax rules that are defined by RFC 822. Rather than + reproduce those definitions here, and risk unintentional differences + between the two, this document simply refers the reader to RFC 822 + for the remaining definitions. Wherever a term is undefined, it + refers to the RFC 822 definition. + + attribute := token + ; Matching of attributes + ; is ALWAYS case-insensitive. + + composite-type := "message" / "multipart" / extension-token + + content := "Content-Type" ":" type "/" subtype + *(";" parameter) + ; Matching of media type and subtype + ; is ALWAYS case-insensitive. + + description := "Content-Description" ":" *text + + discrete-type := "text" / "image" / "audio" / "video" / + "application" / extension-token + + encoding := "Content-Transfer-Encoding" ":" mechanism + + entity-headers := [ content CRLF ] + [ encoding CRLF ] + [ id CRLF ] + [ description CRLF ] + *( MIME-extension-field CRLF ) + + extension-token := ietf-token / x-token + + hex-octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F") + ; Octet must be used for characters > 127, =, + ; SPACEs or TABs at the ends of lines, and is + ; recommended for any character not listed in + ; RFC 2049 as "mail-safe". + + iana-token := + + + + +Freed & Borenstein Standards Track [Page 29] + +RFC 2045 Internet Message Bodies November 1996 + + + ietf-token := + + id := "Content-ID" ":" msg-id + + mechanism := "7bit" / "8bit" / "binary" / + "quoted-printable" / "base64" / + ietf-token / x-token + + MIME-extension-field := + + MIME-message-headers := entity-headers + fields + version CRLF + ; The ordering of the header + ; fields implied by this BNF + ; definition should be ignored. + + MIME-part-headers := entity-headers + [fields] + ; Any field not beginning with + ; "content-" can have no defined + ; meaning and may be ignored. + ; The ordering of the header + ; fields implied by this BNF + ; definition should be ignored. + + parameter := attribute "=" value + + ptext := hex-octet / safe-char + + qp-line := *(qp-segment transport-padding CRLF) + qp-part transport-padding + + qp-part := qp-section + ; Maximum length of 76 characters + + qp-section := [*(ptext / SPACE / TAB) ptext] + + qp-segment := qp-section *(SPACE / TAB) "=" + ; Maximum length of 76 characters + + quoted-printable := qp-line *(CRLF qp-line) + + + + + +Freed & Borenstein Standards Track [Page 30] + +RFC 2045 Internet Message Bodies November 1996 + + + safe-char := + ; Characters not listed as "mail-safe" in + ; RFC 2049 are also not recommended. + + subtype := extension-token / iana-token + + token := 1* + + transport-padding := *LWSP-char + ; Composers MUST NOT generate + ; non-zero length transport + ; padding, but receivers MUST + ; be able to handle padding + ; added by message transports. + + tspecials := "(" / ")" / "<" / ">" / "@" / + "," / ";" / ":" / "\" / <"> + "/" / "[" / "]" / "?" / "=" + ; Must be in quoted-string, + ; to use within parameter values + + type := discrete-type / composite-type + + value := token / quoted-string + + version := "MIME-Version" ":" 1*DIGIT "." 1*DIGIT + + x-token := + + + + + + + + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 31] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2046.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2046.txt new file mode 100644 index 00000000..84d90c10 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2046.txt @@ -0,0 +1,2467 @@ + + + + + + +Network Working Group N. Freed +Request for Comments: 2046 Innosoft +Obsoletes: 1521, 1522, 1590 N. Borenstein +Category: Standards Track First Virtual + November 1996 + + + Multipurpose Internet Mail Extensions + (MIME) Part Two: + Media Types + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822 defines a message representation protocol specifying + considerable detail about US-ASCII message headers, but which leaves + the message content, or message body, as flat US-ASCII text. This + set of documents, collectively called the Multipurpose Internet Mail + Extensions, or MIME, redefines the format of messages to allow for + + (1) textual message bodies in character sets other than + US-ASCII, + + (2) an extensible set of different formats for non-textual + message bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than + US-ASCII. + + These documents are based on earlier work documented in RFC 934, STD + 11, and RFC 1049, but extends and revises them. Because RFC 822 said + so little about message bodies, these documents are largely + orthogonal to (rather than a revision of) RFC 822. + + The initial document in this set, RFC 2045, specifies the various + headers used to describe the structure of MIME messages. This second + document defines the general structure of the MIME media typing + system and defines an initial set of media types. The third document, + RFC 2047, describes extensions to RFC 822 to allow non-US-ASCII text + + + +Freed & Borenstein Standards Track [Page 1] + +RFC 2046 Media Types November 1996 + + + data in Internet mail header fields. The fourth document, RFC 2048, + specifies various IANA registration procedures for MIME-related + facilities. The fifth and final document, RFC 2049, describes MIME + conformance criteria as well as providing some illustrative examples + of MIME message formats, acknowledgements, and the bibliography. + + These documents are revisions of RFCs 1521 and 1522, which themselves + were revisions of RFCs 1341 and 1342. An appendix in RFC 2049 + describes differences and changes from previous versions. + +Table of Contents + + 1. Introduction ......................................... 3 + 2. Definition of a Top-Level Media Type ................. 4 + 3. Overview Of The Initial Top-Level Media Types ........ 4 + 4. Discrete Media Type Values ........................... 6 + 4.1 Text Media Type ..................................... 6 + 4.1.1 Representation of Line Breaks ..................... 7 + 4.1.2 Charset Parameter ................................. 7 + 4.1.3 Plain Subtype ..................................... 11 + 4.1.4 Unrecognized Subtypes ............................. 11 + 4.2 Image Media Type .................................... 11 + 4.3 Audio Media Type .................................... 11 + 4.4 Video Media Type .................................... 12 + 4.5 Application Media Type .............................. 12 + 4.5.1 Octet-Stream Subtype .............................. 13 + 4.5.2 PostScript Subtype ................................ 14 + 4.5.3 Other Application Subtypes ........................ 17 + 5. Composite Media Type Values .......................... 17 + 5.1 Multipart Media Type ................................ 17 + 5.1.1 Common Syntax ..................................... 19 + 5.1.2 Handling Nested Messages and Multiparts ........... 24 + 5.1.3 Mixed Subtype ..................................... 24 + 5.1.4 Alternative Subtype ............................... 24 + 5.1.5 Digest Subtype .................................... 26 + 5.1.6 Parallel Subtype .................................. 27 + 5.1.7 Other Multipart Subtypes .......................... 28 + 5.2 Message Media Type .................................. 28 + 5.2.1 RFC822 Subtype .................................... 28 + 5.2.2 Partial Subtype ................................... 29 + 5.2.2.1 Message Fragmentation and Reassembly ............ 30 + 5.2.2.2 Fragmentation and Reassembly Example ............ 31 + 5.2.3 External-Body Subtype ............................. 33 + 5.2.4 Other Message Subtypes ............................ 40 + 6. Experimental Media Type Values ....................... 40 + 7. Summary .............................................. 41 + 8. Security Considerations .............................. 41 + 9. Authors' Addresses ................................... 42 + + + +Freed & Borenstein Standards Track [Page 2] + +RFC 2046 Media Types November 1996 + + + A. Collected Grammar .................................... 43 + +1. Introduction + + The first document in this set, RFC 2045, defines a number of header + fields, including Content-Type. The Content-Type field is used to + specify the nature of the data in the body of a MIME entity, by + giving media type and subtype identifiers, and by providing auxiliary + information that may be required for certain media types. After the + type and subtype names, the remainder of the header field is simply a + set of parameters, specified in an attribute/value notation. The + ordering of parameters is not significant. + + In general, the top-level media type is used to declare the general + type of data, while the subtype specifies a specific format for that + type of data. Thus, a media type of "image/xyz" is enough to tell a + user agent that the data is an image, even if the user agent has no + knowledge of the specific image format "xyz". Such information can + be used, for example, to decide whether or not to show a user the raw + data from an unrecognized subtype -- such an action might be + reasonable for unrecognized subtypes of "text", but not for + unrecognized subtypes of "image" or "audio". For this reason, + registered subtypes of "text", "image", "audio", and "video" should + not contain embedded information that is really of a different type. + Such compound formats should be represented using the "multipart" or + "application" types. + + Parameters are modifiers of the media subtype, and as such do not + fundamentally affect the nature of the content. The set of + meaningful parameters depends on the media type and subtype. Most + parameters are associated with a single specific subtype. However, a + given top-level media type may define parameters which are applicable + to any subtype of that type. Parameters may be required by their + defining media type or subtype or they may be optional. MIME + implementations must also ignore any parameters whose names they do + not recognize. + + MIME's Content-Type header field and media type mechanism has been + carefully designed to be extensible, and it is expected that the set + of media type/subtype pairs and their associated parameters will grow + significantly over time. Several other MIME facilities, such as + transfer encodings and "message/external-body" access types, are + likely to have new values defined over time. In order to ensure that + the set of such values is developed in an orderly, well-specified, + and public manner, MIME sets up a registration process which uses the + Internet Assigned Numbers Authority (IANA) as a central registry for + MIME's various areas of extensibility. The registration process for + these areas is described in a companion document, RFC 2048. + + + +Freed & Borenstein Standards Track [Page 3] + +RFC 2046 Media Types November 1996 + + + The initial seven standard top-level media type are defined and + described in the remainder of this document. + +2. Definition of a Top-Level Media Type + + The definition of a top-level media type consists of: + + (1) a name and a description of the type, including + criteria for whether a particular type would qualify + under that type, + + (2) the names and definitions of parameters, if any, which + are defined for all subtypes of that type (including + whether such parameters are required or optional), + + (3) how a user agent and/or gateway should handle unknown + subtypes of this type, + + (4) general considerations on gatewaying entities of this + top-level type, if any, and + + (5) any restrictions on content-transfer-encodings for + entities of this top-level type. + +3. Overview Of The Initial Top-Level Media Types + + The five discrete top-level media types are: + + (1) text -- textual information. The subtype "plain" in + particular indicates plain text containing no + formatting commands or directives of any sort. Plain + text is intended to be displayed "as-is". No special + software is required to get the full meaning of the + text, aside from support for the indicated character + set. Other subtypes are to be used for enriched text in + forms where application software may enhance the + appearance of the text, but such software must not be + required in order to get the general idea of the + content. Possible subtypes of "text" thus include any + word processor format that can be read without + resorting to software that understands the format. In + particular, formats that employ embeddded binary + formatting information are not considered directly + readable. A very simple and portable subtype, + "richtext", was defined in RFC 1341, with a further + revision in RFC 1896 under the name "enriched". + + + + + +Freed & Borenstein Standards Track [Page 4] + +RFC 2046 Media Types November 1996 + + + (2) image -- image data. "Image" requires a display device + (such as a graphical display, a graphics printer, or a + FAX machine) to view the information. An initial + subtype is defined for the widely-used image format + JPEG. . subtypes are defined for two widely-used image + formats, jpeg and gif. + + (3) audio -- audio data. "Audio" requires an audio output + device (such as a speaker or a telephone) to "display" + the contents. An initial subtype "basic" is defined in + this document. + + (4) video -- video data. "Video" requires the capability + to display moving images, typically including + specialized hardware and software. An initial subtype + "mpeg" is defined in this document. + + (5) application -- some other kind of data, typically + either uninterpreted binary data or information to be + processed by an application. The subtype "octet- + stream" is to be used in the case of uninterpreted + binary data, in which case the simplest recommended + action is to offer to write the information into a file + for the user. The "PostScript" subtype is also defined + for the transport of PostScript material. Other + expected uses for "application" include spreadsheets, + data for mail-based scheduling systems, and languages + for "active" (computational) messaging, and word + processing formats that are not directly readable. + Note that security considerations may exist for some + types of application data, most notably + "application/PostScript" and any form of active + messaging. These issues are discussed later in this + document. + + The two composite top-level media types are: + + (1) multipart -- data consisting of multiple entities of + independent data types. Four subtypes are initially + defined, including the basic "mixed" subtype specifying + a generic mixed set of parts, "alternative" for + representing the same data in multiple formats, + "parallel" for parts intended to be viewed + simultaneously, and "digest" for multipart entities in + which each part has a default type of "message/rfc822". + + + + + + +Freed & Borenstein Standards Track [Page 5] + +RFC 2046 Media Types November 1996 + + + (2) message -- an encapsulated message. A body of media + type "message" is itself all or a portion of some kind + of message object. Such objects may or may not in turn + contain other entities. The "rfc822" subtype is used + when the encapsulated content is itself an RFC 822 + message. The "partial" subtype is defined for partial + RFC 822 messages, to permit the fragmented transmission + of bodies that are thought to be too large to be passed + through transport facilities in one piece. Another + subtype, "external-body", is defined for specifying + large bodies by reference to an external data source. + + It should be noted that the list of media type values given here may + be augmented in time, via the mechanisms described above, and that + the set of subtypes is expected to grow substantially. + +4. Discrete Media Type Values + + Five of the seven initial media type values refer to discrete bodies. + The content of these types must be handled by non-MIME mechanisms; + they are opaque to MIME processors. + +4.1. Text Media Type + + The "text" media type is intended for sending material which is + principally textual in form. A "charset" parameter may be used to + indicate the character set of the body text for "text" subtypes, + notably including the subtype "text/plain", which is a generic + subtype for plain text. Plain text does not provide for or allow + formatting commands, font attribute specifications, processing + instructions, interpretation directives, or content markup. Plain + text is seen simply as a linear sequence of characters, possibly + interrupted by line breaks or page breaks. Plain text may allow the + stacking of several characters in the same position in the text. + Plain text in scripts like Arabic and Hebrew may also include + facilitites that allow the arbitrary mixing of text segments with + opposite writing directions. + + Beyond plain text, there are many formats for representing what might + be known as "rich text". An interesting characteristic of many such + representations is that they are to some extent readable even without + the software that interprets them. It is useful, then, to + distinguish them, at the highest level, from such unreadable data as + images, audio, or text represented in an unreadable form. In the + absence of appropriate interpretation software, it is reasonable to + show subtypes of "text" to the user, while it is not reasonable to do + so with most nontextual data. Such formatted textual data should be + represented using subtypes of "text". + + + +Freed & Borenstein Standards Track [Page 6] + +RFC 2046 Media Types November 1996 + + +4.1.1. Representation of Line Breaks + + The canonical form of any MIME "text" subtype MUST always represent a + line break as a CRLF sequence. Similarly, any occurrence of CRLF in + MIME "text" MUST represent a line break. Use of CR and LF outside of + line break sequences is also forbidden. + + This rule applies regardless of format or character set or sets + involved. + + NOTE: The proper interpretation of line breaks when a body is + displayed depends on the media type. In particular, while it is + appropriate to treat a line break as a transition to a new line when + displaying a "text/plain" body, this treatment is actually incorrect + for other subtypes of "text" like "text/enriched" [RFC-1896]. + Similarly, whether or not line breaks should be added during display + operations is also a function of the media type. It should not be + necessary to add any line breaks to display "text/plain" correctly, + whereas proper display of "text/enriched" requires the appropriate + addition of line breaks. + + NOTE: Some protocols defines a maximum line length. E.g. SMTP [RFC- + 821] allows a maximum of 998 octets before the next CRLF sequence. + To be transported by such protocols, data which includes too long + segments without CRLF sequences must be encoded with a suitable + content-transfer-encoding. + +4.1.2. Charset Parameter + + A critical parameter that may be specified in the Content-Type field + for "text/plain" data is the character set. This is specified with a + "charset" parameter, as in: + + Content-type: text/plain; charset=iso-8859-1 + + Unlike some other parameter values, the values of the charset + parameter are NOT case sensitive. The default character set, which + must be assumed in the absence of a charset parameter, is US-ASCII. + + The specification for any future subtypes of "text" must specify + whether or not they will also utilize a "charset" parameter, and may + possibly restrict its values as well. For other subtypes of "text" + than "text/plain", the semantics of the "charset" parameter should be + defined to be identical to those specified here for "text/plain", + i.e., the body consists entirely of characters in the given charset. + In particular, definers of future "text" subtypes should pay close + attention to the implications of multioctet character sets for their + subtype definitions. + + + +Freed & Borenstein Standards Track [Page 7] + +RFC 2046 Media Types November 1996 + + + The charset parameter for subtypes of "text" gives a name of a + character set, as "character set" is defined in RFC 2045. The rules + regarding line breaks detailed in the previous section must also be + observed -- a character set whose definition does not conform to + these rules cannot be used in a MIME "text" subtype. + + An initial list of predefined character set names can be found at the + end of this section. Additional character sets may be registered + with IANA. + + Other media types than subtypes of "text" might choose to employ the + charset parameter as defined here, but with the CRLF/line break + restriction removed. Therefore, all character sets that conform to + the general definition of "character set" in RFC 2045 can be + registered for MIME use. + + Note that if the specified character set includes 8-bit characters + and such characters are used in the body, a Content-Transfer-Encoding + header field and a corresponding encoding on the data are required in + order to transmit the body via some mail transfer protocols, such as + SMTP [RFC-821]. + + The default character set, US-ASCII, has been the subject of some + confusion and ambiguity in the past. Not only were there some + ambiguities in the definition, there have been wide variations in + practice. In order to eliminate such ambiguity and variations in the + future, it is strongly recommended that new user agents explicitly + specify a character set as a media type parameter in the Content-Type + header field. "US-ASCII" does not indicate an arbitrary 7-bit + character set, but specifies that all octets in the body must be + interpreted as characters according to the US-ASCII character set. + National and application-oriented versions of ISO 646 [ISO-646] are + usually NOT identical to US-ASCII, and in that case their use in + Internet mail is explicitly discouraged. The omission of the ISO 646 + character set from this document is deliberate in this regard. The + character set name of "US-ASCII" explicitly refers to the character + set defined in ANSI X3.4-1986 [US- ASCII]. The new international + reference version (IRV) of the 1991 edition of ISO 646 is identical + to US-ASCII. The character set name "ASCII" is reserved and must not + be used for any purpose. + + NOTE: RFC 821 explicitly specifies "ASCII", and references an earlier + version of the American Standard. Insofar as one of the purposes of + specifying a media type and character set is to permit the receiver + to unambiguously determine how the sender intended the coded message + to be interpreted, assuming anything other than "strict ASCII" as the + default would risk unintentional and incompatible changes to the + semantics of messages now being transmitted. This also implies that + + + +Freed & Borenstein Standards Track [Page 8] + +RFC 2046 Media Types November 1996 + + + messages containing characters coded according to other versions of + ISO 646 than US-ASCII and the 1991 IRV, or using code-switching + procedures (e.g., those of ISO 2022), as well as 8bit or multiple + octet character encodings MUST use an appropriate character set + specification to be consistent with MIME. + + The complete US-ASCII character set is listed in ANSI X3.4- 1986. + Note that the control characters including DEL (0-31, 127) have no + defined meaning in apart from the combination CRLF (US-ASCII values + 13 and 10) indicating a new line. Two of the characters have de + facto meanings in wide use: FF (12) often means "start subsequent + text on the beginning of a new page"; and TAB or HT (9) often (though + not always) means "move the cursor to the next available column after + the current position where the column number is a multiple of 8 + (counting the first column as column 0)." Aside from these + conventions, any use of the control characters or DEL in a body must + either occur + + (1) because a subtype of text other than "plain" + specifically assigns some additional meaning, or + + (2) within the context of a private agreement between the + sender and recipient. Such private agreements are + discouraged and should be replaced by the other + capabilities of this document. + + NOTE: An enormous proliferation of character sets exist beyond US- + ASCII. A large number of partially or totally overlapping character + sets is NOT a good thing. A SINGLE character set that can be used + universally for representing all of the world's languages in Internet + mail would be preferrable. Unfortunately, existing practice in + several communities seems to point to the continued use of multiple + character sets in the near future. A small number of standard + character sets are, therefore, defined for Internet use in this + document. + + The defined charset values are: + + (1) US-ASCII -- as defined in ANSI X3.4-1986 [US-ASCII]. + + (2) ISO-8859-X -- where "X" is to be replaced, as + necessary, for the parts of ISO-8859 [ISO-8859]. Note + that the ISO 646 character sets have deliberately been + omitted in favor of their 8859 replacements, which are + the designated character sets for Internet mail. As of + the publication of this document, the legitimate values + for "X" are the digits 1 through 10. + + + + +Freed & Borenstein Standards Track [Page 9] + +RFC 2046 Media Types November 1996 + + + Characters in the range 128-159 has no assigned meaning in ISO-8859- + X. Characters with values below 128 in ISO-8859-X have the same + assigned meaning as they do in US-ASCII. + + Part 6 of ISO 8859 (Latin/Arabic alphabet) and part 8 (Latin/Hebrew + alphabet) includes both characters for which the normal writing + direction is right to left and characters for which it is left to + right, but do not define a canonical ordering method for representing + bi-directional text. The charset values "ISO-8859-6" and "ISO-8859- + 8", however, specify that the visual method is used [RFC-1556]. + + All of these character sets are used as pure 7bit or 8bit sets + without any shift or escape functions. The meaning of shift and + escape sequences in these character sets is not defined. + + The character sets specified above are the ones that were relatively + uncontroversial during the drafting of MIME. This document does not + endorse the use of any particular character set other than US-ASCII, + and recognizes that the future evolution of world character sets + remains unclear. + + Note that the character set used, if anything other than US- ASCII, + must always be explicitly specified in the Content-Type field. + + No character set name other than those defined above may be used in + Internet mail without the publication of a formal specification and + its registration with IANA, or by private agreement, in which case + the character set name must begin with "X-". + + Implementors are discouraged from defining new character sets unless + absolutely necessary. + + The "charset" parameter has been defined primarily for the purpose of + textual data, and is described in this section for that reason. + However, it is conceivable that non-textual data might also wish to + specify a charset value for some purpose, in which case the same + syntax and values should be used. + + In general, composition software should always use the "lowest common + denominator" character set possible. For example, if a body contains + only US-ASCII characters, it SHOULD be marked as being in the US- + ASCII character set, not ISO-8859-1, which, like all the ISO-8859 + family of character sets, is a superset of US-ASCII. More generally, + if a widely-used character set is a subset of another character set, + and a body contains only characters in the widely-used subset, it + should be labelled as being in that subset. This will increase the + chances that the recipient will be able to view the resulting entity + correctly. + + + +Freed & Borenstein Standards Track [Page 10] + +RFC 2046 Media Types November 1996 + + +4.1.3. Plain Subtype + + The simplest and most important subtype of "text" is "plain". This + indicates plain text that does not contain any formatting commands or + directives. Plain text is intended to be displayed "as-is", that is, + no interpretation of embedded formatting commands, font attribute + specifications, processing instructions, interpretation directives, + or content markup should be necessary for proper display. The + default media type of "text/plain; charset=us-ascii" for Internet + mail describes existing Internet practice. That is, it is the type + of body defined by RFC 822. + + No other "text" subtype is defined by this document. + +4.1.4. Unrecognized Subtypes + + Unrecognized subtypes of "text" should be treated as subtype "plain" + as long as the MIME implementation knows how to handle the charset. + Unrecognized subtypes which also specify an unrecognized charset + should be treated as "application/octet- stream". + +4.2. Image Media Type + + A media type of "image" indicates that the body contains an image. + The subtype names the specific image format. These names are not + case sensitive. An initial subtype is "jpeg" for the JPEG format + using JFIF encoding [JPEG]. + + The list of "image" subtypes given here is neither exclusive nor + exhaustive, and is expected to grow as more types are registered with + IANA, as described in RFC 2048. + + Unrecognized subtypes of "image" should at a miniumum be treated as + "application/octet-stream". Implementations may optionally elect to + pass subtypes of "image" that they do not specifically recognize to a + secure and robust general-purpose image viewing application, if such + an application is available. + + NOTE: Using of a generic-purpose image viewing application this way + inherits the security problems of the most dangerous type supported + by the application. + +4.3. Audio Media Type + + A media type of "audio" indicates that the body contains audio data. + Although there is not yet a consensus on an "ideal" audio format for + use with computers, there is a pressing need for a format capable of + providing interoperable behavior. + + + +Freed & Borenstein Standards Track [Page 11] + +RFC 2046 Media Types November 1996 + + + The initial subtype of "basic" is specified to meet this requirement + by providing an absolutely minimal lowest common denominator audio + format. It is expected that richer formats for higher quality and/or + lower bandwidth audio will be defined by a later document. + + The content of the "audio/basic" subtype is single channel audio + encoded using 8bit ISDN mu-law [PCM] at a sample rate of 8000 Hz. + + Unrecognized subtypes of "audio" should at a miniumum be treated as + "application/octet-stream". Implementations may optionally elect to + pass subtypes of "audio" that they do not specifically recognize to a + robust general-purpose audio playing application, if such an + application is available. + +4.4. Video Media Type + + A media type of "video" indicates that the body contains a time- + varying-picture image, possibly with color and coordinated sound. + The term 'video' is used in its most generic sense, rather than with + reference to any particular technology or format, and is not meant to + preclude subtypes such as animated drawings encoded compactly. The + subtype "mpeg" refers to video coded according to the MPEG standard + [MPEG]. + + Note that although in general this document strongly discourages the + mixing of multiple media in a single body, it is recognized that many + so-called video formats include a representation for synchronized + audio, and this is explicitly permitted for subtypes of "video". + + Unrecognized subtypes of "video" should at a minumum be treated as + "application/octet-stream". Implementations may optionally elect to + pass subtypes of "video" that they do not specifically recognize to a + robust general-purpose video display application, if such an + application is available. + +4.5. Application Media Type + + The "application" media type is to be used for discrete data which do + not fit in any of the other categories, and particularly for data to + be processed by some type of application program. This is + information which must be processed by an application before it is + viewable or usable by a user. Expected uses for the "application" + media type include file transfer, spreadsheets, data for mail-based + scheduling systems, and languages for "active" (computational) + material. (The latter, in particular, can pose security problems + which must be understood by implementors, and are considered in + detail in the discussion of the "application/PostScript" media type.) + + + + +Freed & Borenstein Standards Track [Page 12] + +RFC 2046 Media Types November 1996 + + + For example, a meeting scheduler might define a standard + representation for information about proposed meeting dates. An + intelligent user agent would use this information to conduct a dialog + with the user, and might then send additional material based on that + dialog. More generally, there have been several "active" messaging + languages developed in which programs in a suitably specialized + language are transported to a remote location and automatically run + in the recipient's environment. + + Such applications may be defined as subtypes of the "application" + media type. This document defines two subtypes: + + octet-stream, and PostScript. + + The subtype of "application" will often be either the name or include + part of the name of the application for which the data are intended. + This does not mean, however, that any application program name may be + used freely as a subtype of "application". + +4.5.1. Octet-Stream Subtype + + The "octet-stream" subtype is used to indicate that a body contains + arbitrary binary data. The set of currently defined parameters is: + + (1) TYPE -- the general type or category of binary data. + This is intended as information for the human recipient + rather than for any automatic processing. + + (2) PADDING -- the number of bits of padding that were + appended to the bit-stream comprising the actual + contents to produce the enclosed 8bit byte-oriented + data. This is useful for enclosing a bit-stream in a + body when the total number of bits is not a multiple of + 8. + + Both of these parameters are optional. + + An additional parameter, "CONVERSIONS", was defined in RFC 1341 but + has since been removed. RFC 1341 also defined the use of a "NAME" + parameter which gave a suggested file name to be used if the data + were to be written to a file. This has been deprecated in + anticipation of a separate Content-Disposition header field, to be + defined in a subsequent RFC. + + The recommended action for an implementation that receives an + "application/octet-stream" entity is to simply offer to put the data + in a file, with any Content-Transfer-Encoding undone, or perhaps to + use it as input to a user-specified process. + + + +Freed & Borenstein Standards Track [Page 13] + +RFC 2046 Media Types November 1996 + + + To reduce the danger of transmitting rogue programs, it is strongly + recommended that implementations NOT implement a path-search + mechanism whereby an arbitrary program named in the Content-Type + parameter (e.g., an "interpreter=" parameter) is found and executed + using the message body as input. + +4.5.2. PostScript Subtype + + A media type of "application/postscript" indicates a PostScript + program. Currently two variants of the PostScript language are + allowed; the original level 1 variant is described in [POSTSCRIPT] + and the more recent level 2 variant is described in [POSTSCRIPT2]. + + PostScript is a registered trademark of Adobe Systems, Inc. Use of + the MIME media type "application/postscript" implies recognition of + that trademark and all the rights it entails. + + The PostScript language definition provides facilities for internal + labelling of the specific language features a given program uses. + This labelling, called the PostScript document structuring + conventions, or DSC, is very general and provides substantially more + information than just the language level. The use of document + structuring conventions, while not required, is strongly recommended + as an aid to interoperability. Documents which lack proper + structuring conventions cannot be tested to see whether or not they + will work in a given environment. As such, some systems may assume + the worst and refuse to process unstructured documents. + + The execution of general-purpose PostScript interpreters entails + serious security risks, and implementors are discouraged from simply + sending PostScript bodies to "off- the-shelf" interpreters. While it + is usually safe to send PostScript to a printer, where the potential + for harm is greatly constrained by typical printer environments, + implementors should consider all of the following before they add + interactive display of PostScript bodies to their MIME readers. + + The remainder of this section outlines some, though probably not all, + of the possible problems with the transport of PostScript entities. + + (1) Dangerous operations in the PostScript language + include, but may not be limited to, the PostScript + operators "deletefile", "renamefile", "filenameforall", + and "file". "File" is only dangerous when applied to + something other than standard input or output. + Implementations may also define additional nonstandard + file operators; these may also pose a threat to + security. "Filenameforall", the wildcard file search + operator, may appear at first glance to be harmless. + + + +Freed & Borenstein Standards Track [Page 14] + +RFC 2046 Media Types November 1996 + + + Note, however, that this operator has the potential to + reveal information about what files the recipient has + access to, and this information may itself be + sensitive. Message senders should avoid the use of + potentially dangerous file operators, since these + operators are quite likely to be unavailable in secure + PostScript implementations. Message receiving and + displaying software should either completely disable + all potentially dangerous file operators or take + special care not to delegate any special authority to + their operation. These operators should be viewed as + being done by an outside agency when interpreting + PostScript documents. Such disabling and/or checking + should be done completely outside of the reach of the + PostScript language itself; care should be taken to + insure that no method exists for re-enabling full- + function versions of these operators. + + (2) The PostScript language provides facilities for exiting + the normal interpreter, or server, loop. Changes made + in this "outer" environment are customarily retained + across documents, and may in some cases be retained + semipermanently in nonvolatile memory. The operators + associated with exiting the interpreter loop have the + potential to interfere with subsequent document + processing. As such, their unrestrained use + constitutes a threat of service denial. PostScript + operators that exit the interpreter loop include, but + may not be limited to, the exitserver and startjob + operators. Message sending software should not + generate PostScript that depends on exiting the + interpreter loop to operate, since the ability to exit + will probably be unavailable in secure PostScript + implementations. Message receiving and displaying + software should completely disable the ability to make + retained changes to the PostScript environment by + eliminating or disabling the "startjob" and + "exitserver" operations. If these operations cannot be + eliminated or completely disabled the password + associated with them should at least be set to a hard- + to-guess value. + + (3) PostScript provides operators for setting system-wide + and device-specific parameters. These parameter + settings may be retained across jobs and may + potentially pose a threat to the correct operation of + the interpreter. The PostScript operators that set + system and device parameters include, but may not be + + + +Freed & Borenstein Standards Track [Page 15] + +RFC 2046 Media Types November 1996 + + + limited to, the "setsystemparams" and "setdevparams" + operators. Message sending software should not + generate PostScript that depends on the setting of + system or device parameters to operate correctly. The + ability to set these parameters will probably be + unavailable in secure PostScript implementations. + Message receiving and displaying software should + disable the ability to change system and device + parameters. If these operators cannot be completely + disabled the password associated with them should at + least be set to a hard-to-guess value. + + (4) Some PostScript implementations provide nonstandard + facilities for the direct loading and execution of + machine code. Such facilities are quite obviously open + to substantial abuse. Message sending software should + not make use of such features. Besides being totally + hardware-specific, they are also likely to be + unavailable in secure implementations of PostScript. + Message receiving and displaying software should not + allow such operators to be used if they exist. + + (5) PostScript is an extensible language, and many, if not + most, implementations of it provide a number of their + own extensions. This document does not deal with such + extensions explicitly since they constitute an unknown + factor. Message sending software should not make use + of nonstandard extensions; they are likely to be + missing from some implementations. Message receiving + and displaying software should make sure that any + nonstandard PostScript operators are secure and don't + present any kind of threat. + + (6) It is possible to write PostScript that consumes huge + amounts of various system resources. It is also + possible to write PostScript programs that loop + indefinitely. Both types of programs have the + potential to cause damage if sent to unsuspecting + recipients. Message-sending software should avoid the + construction and dissemination of such programs, which + is antisocial. Message receiving and displaying + software should provide appropriate mechanisms to abort + processing after a reasonable amount of time has + elapsed. In addition, PostScript interpreters should be + limited to the consumption of only a reasonable amount + of any given system resource. + + + + + +Freed & Borenstein Standards Track [Page 16] + +RFC 2046 Media Types November 1996 + + + (7) It is possible to include raw binary information inside + PostScript in various forms. This is not recommended + for use in Internet mail, both because it is not + supported by all PostScript interpreters and because it + significantly complicates the use of a MIME Content- + Transfer-Encoding. (Without such binary, PostScript + may typically be viewed as line-oriented data. The + treatment of CRLF sequences becomes extremely + problematic if binary and line-oriented data are mixed + in a single Postscript data stream.) + + (8) Finally, bugs may exist in some PostScript interpreters + which could possibly be exploited to gain unauthorized + access to a recipient's system. Apart from noting this + possibility, there is no specific action to take to + prevent this, apart from the timely correction of such + bugs if any are found. + +4.5.3. Other Application Subtypes + + It is expected that many other subtypes of "application" will be + defined in the future. MIME implementations must at a minimum treat + any unrecognized subtypes as being equivalent to "application/octet- + stream". + +5. Composite Media Type Values + + The remaining two of the seven initial Content-Type values refer to + composite entities. Composite entities are handled using MIME + mechanisms -- a MIME processor typically handles the body directly. + +5.1. Multipart Media Type + + In the case of multipart entities, in which one or more different + sets of data are combined in a single body, a "multipart" media type + field must appear in the entity's header. The body must then contain + one or more body parts, each preceded by a boundary delimiter line, + and the last one followed by a closing boundary delimiter line. + After its boundary delimiter line, each body part then consists of a + header area, a blank line, and a body area. Thus a body part is + similar to an RFC 822 message in syntax, but different in meaning. + + A body part is an entity and hence is NOT to be interpreted as + actually being an RFC 822 message. To begin with, NO header fields + are actually required in body parts. A body part that starts with a + blank line, therefore, is allowed and is a body part for which all + default values are to be assumed. In such a case, the absence of a + Content-Type header usually indicates that the corresponding body has + + + +Freed & Borenstein Standards Track [Page 17] + +RFC 2046 Media Types November 1996 + + + a content-type of "text/plain; charset=US-ASCII". + + The only header fields that have defined meaning for body parts are + those the names of which begin with "Content-". All other header + fields may be ignored in body parts. Although they should generally + be retained if at all possible, they may be discarded by gateways if + necessary. Such other fields are permitted to appear in body parts + but must not be depended on. "X-" fields may be created for + experimental or private purposes, with the recognition that the + information they contain may be lost at some gateways. + + NOTE: The distinction between an RFC 822 message and a body part is + subtle, but important. A gateway between Internet and X.400 mail, + for example, must be able to tell the difference between a body part + that contains an image and a body part that contains an encapsulated + message, the body of which is a JPEG image. In order to represent + the latter, the body part must have "Content-Type: message/rfc822", + and its body (after the blank line) must be the encapsulated message, + with its own "Content-Type: image/jpeg" header field. The use of + similar syntax facilitates the conversion of messages to body parts, + and vice versa, but the distinction between the two must be + understood by implementors. (For the special case in which parts + actually are messages, a "digest" subtype is also defined.) + + As stated previously, each body part is preceded by a boundary + delimiter line that contains the boundary delimiter. The boundary + delimiter MUST NOT appear inside any of the encapsulated parts, on a + line by itself or as the prefix of any line. This implies that it is + crucial that the composing agent be able to choose and specify a + unique boundary parameter value that does not contain the boundary + parameter value of an enclosing multipart as a prefix. + + All present and future subtypes of the "multipart" type must use an + identical syntax. Subtypes may differ in their semantics, and may + impose additional restrictions on syntax, but must conform to the + required syntax for the "multipart" type. This requirement ensures + that all conformant user agents will at least be able to recognize + and separate the parts of any multipart entity, even those of an + unrecognized subtype. + + As stated in the definition of the Content-Transfer-Encoding field + [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is + permitted for entities of type "multipart". The "multipart" boundary + delimiters and header fields are always represented as 7bit US-ASCII + in any case (though the header fields may encode non-US-ASCII header + text as per RFC 2047) and data within the body parts can be encoded + on a part-by-part basis, with Content-Transfer-Encoding fields for + each appropriate body part. + + + +Freed & Borenstein Standards Track [Page 18] + +RFC 2046 Media Types November 1996 + + +5.1.1. Common Syntax + + This section defines a common syntax for subtypes of "multipart". + All subtypes of "multipart" must use this syntax. A simple example + of a multipart message also appears in this section. An example of a + more complex multipart message is given in RFC 2049. + + The Content-Type field for multipart entities requires one parameter, + "boundary". The boundary delimiter line is then defined as a line + consisting entirely of two hyphen characters ("-", decimal value 45) + followed by the boundary parameter value from the Content-Type header + field, optional linear whitespace, and a terminating CRLF. + + NOTE: The hyphens are for rough compatibility with the earlier RFC + 934 method of message encapsulation, and for ease of searching for + the boundaries in some implementations. However, it should be noted + that multipart messages are NOT completely compatible with RFC 934 + encapsulations; in particular, they do not obey RFC 934 quoting + conventions for embedded lines that begin with hyphens. This + mechanism was chosen over the RFC 934 mechanism because the latter + causes lines to grow with each level of quoting. The combination of + this growth with the fact that SMTP implementations sometimes wrap + long lines made the RFC 934 mechanism unsuitable for use in the event + that deeply-nested multipart structuring is ever desired. + + WARNING TO IMPLEMENTORS: The grammar for parameters on the Content- + type field is such that it is often necessary to enclose the boundary + parameter values in quotes on the Content-type line. This is not + always necessary, but never hurts. Implementors should be sure to + study the grammar carefully in order to avoid producing invalid + Content-type fields. Thus, a typical "multipart" Content-Type header + field might look like this: + + Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p + + But the following is not valid: + + Content-Type: multipart/mixed; boundary=gc0pJq0M:08jU534c0p + + (because of the colon) and must instead be represented as + + Content-Type: multipart/mixed; boundary="gc0pJq0M:08jU534c0p" + + This Content-Type value indicates that the content consists of one or + more parts, each with a structure that is syntactically identical to + an RFC 822 message, except that the header area is allowed to be + completely empty, and that the parts are each preceded by the line + + + + +Freed & Borenstein Standards Track [Page 19] + +RFC 2046 Media Types November 1996 + + + --gc0pJq0M:08jU534c0p + + The boundary delimiter MUST occur at the beginning of a line, i.e., + following a CRLF, and the initial CRLF is considered to be attached + to the boundary delimiter line rather than part of the preceding + part. The boundary may be followed by zero or more characters of + linear whitespace. It is then terminated by either another CRLF and + the header fields for the next part, or by two CRLFs, in which case + there are no header fields for the next part. If no Content-Type + field is present it is assumed to be "message/rfc822" in a + "multipart/digest" and "text/plain" otherwise. + + NOTE: The CRLF preceding the boundary delimiter line is conceptually + attached to the boundary so that it is possible to have a part that + does not end with a CRLF (line break). Body parts that must be + considered to end with line breaks, therefore, must have two CRLFs + preceding the boundary delimiter line, the first of which is part of + the preceding body part, and the second of which is part of the + encapsulation boundary. + + Boundary delimiters must not appear within the encapsulated material, + and must be no longer than 70 characters, not counting the two + leading hyphens. + + The boundary delimiter line following the last body part is a + distinguished delimiter that indicates that no further body parts + will follow. Such a delimiter line is identical to the previous + delimiter lines, with the addition of two more hyphens after the + boundary parameter value. + + --gc0pJq0M:08jU534c0p-- + + NOTE TO IMPLEMENTORS: Boundary string comparisons must compare the + boundary value with the beginning of each candidate line. An exact + match of the entire candidate line is not required; it is sufficient + that the boundary appear in its entirety following the CRLF. + + There appears to be room for additional information prior to the + first boundary delimiter line and following the final boundary + delimiter line. These areas should generally be left blank, and + implementations must ignore anything that appears before the first + boundary delimiter line or after the last one. + + NOTE: These "preamble" and "epilogue" areas are generally not used + because of the lack of proper typing of these parts and the lack of + clear semantics for handling these areas at gateways, particularly + X.400 gateways. However, rather than leaving the preamble area + blank, many MIME implementations have found this to be a convenient + + + +Freed & Borenstein Standards Track [Page 20] + +RFC 2046 Media Types November 1996 + + + place to insert an explanatory note for recipients who read the + message with pre-MIME software, since such notes will be ignored by + MIME-compliant software. + + NOTE: Because boundary delimiters must not appear in the body parts + being encapsulated, a user agent must exercise care to choose a + unique boundary parameter value. The boundary parameter value in the + example above could have been the result of an algorithm designed to + produce boundary delimiters with a very low probability of already + existing in the data to be encapsulated without having to prescan the + data. Alternate algorithms might result in more "readable" boundary + delimiters for a recipient with an old user agent, but would require + more attention to the possibility that the boundary delimiter might + appear at the beginning of some line in the encapsulated part. The + simplest boundary delimiter line possible is something like "---", + with a closing boundary delimiter line of "-----". + + As a very simple example, the following multipart message has two + parts, both of them plain text, one of them explicitly typed and one + of them implicitly typed: + + From: Nathaniel Borenstein + To: Ned Freed + Date: Sun, 21 Mar 1993 23:56:48 -0800 (PST) + Subject: Sample message + MIME-Version: 1.0 + Content-type: multipart/mixed; boundary="simple boundary" + + This is the preamble. It is to be ignored, though it + is a handy place for composition agents to include an + explanatory note to non-MIME conformant readers. + + --simple boundary + + This is implicitly typed plain US-ASCII text. + It does NOT end with a linebreak. + --simple boundary + Content-type: text/plain; charset=us-ascii + + This is explicitly typed plain US-ASCII text. + It DOES end with a linebreak. + + --simple boundary-- + + This is the epilogue. It is also to be ignored. + + + + + + +Freed & Borenstein Standards Track [Page 21] + +RFC 2046 Media Types November 1996 + + + The use of a media type of "multipart" in a body part within another + "multipart" entity is explicitly allowed. In such cases, for obvious + reasons, care must be taken to ensure that each nested "multipart" + entity uses a different boundary delimiter. See RFC 2049 for an + example of nested "multipart" entities. + + The use of the "multipart" media type with only a single body part + may be useful in certain contexts, and is explicitly permitted. + + NOTE: Experience has shown that a "multipart" media type with a + single body part is useful for sending non-text media types. It has + the advantage of providing the preamble as a place to include + decoding instructions. In addition, a number of SMTP gateways move + or remove the MIME headers, and a clever MIME decoder can take a good + guess at multipart boundaries even in the absence of the Content-Type + header and thereby successfully decode the message. + + The only mandatory global parameter for the "multipart" media type is + the boundary parameter, which consists of 1 to 70 characters from a + set of characters known to be very robust through mail gateways, and + NOT ending with white space. (If a boundary delimiter line appears to + end with white space, the white space must be presumed to have been + added by a gateway, and must be deleted.) It is formally specified + by the following BNF: + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / + "+" / "_" / "," / "-" / "." / + "/" / ":" / "=" / "?" + + Overall, the body of a "multipart" entity may be specified as + follows: + + dash-boundary := "--" boundary + ; boundary taken from the value of + ; boundary parameter of the + ; Content-Type field. + + multipart-body := [preamble CRLF] + dash-boundary transport-padding CRLF + body-part *encapsulation + close-delimiter transport-padding + [CRLF epilogue] + + + + + +Freed & Borenstein Standards Track [Page 22] + +RFC 2046 Media Types November 1996 + + + transport-padding := *LWSP-char + ; Composers MUST NOT generate + ; non-zero length transport + ; padding, but receivers MUST + ; be able to handle padding + ; added by message transports. + + encapsulation := delimiter transport-padding + CRLF body-part + + delimiter := CRLF dash-boundary + + close-delimiter := delimiter "--" + + preamble := discard-text + + epilogue := discard-text + + discard-text := *(*text CRLF) *text + ; May be ignored or discarded. + + body-part := MIME-part-headers [CRLF *OCTET] + ; Lines in a body-part must not start + ; with the specified dash-boundary and + ; the delimiter must not appear anywhere + ; in the body part. Note that the + ; semantics of a body-part differ from + ; the semantics of a message, as + ; described in the text. + + OCTET := + + IMPORTANT: The free insertion of linear-white-space and RFC 822 + comments between the elements shown in this BNF is NOT allowed since + this BNF does not specify a structured header field. + + NOTE: In certain transport enclaves, RFC 822 restrictions such as + the one that limits bodies to printable US-ASCII characters may not + be in force. (That is, the transport domains may exist that resemble + standard Internet mail transport as specified in RFC 821 and assumed + by RFC 822, but without certain restrictions.) The relaxation of + these restrictions should be construed as locally extending the + definition of bodies, for example to include octets outside of the + US-ASCII range, as long as these extensions are supported by the + transport and adequately documented in the Content- Transfer-Encoding + header field. However, in no event are headers (either message + headers or body part headers) allowed to contain anything other than + US-ASCII characters. + + + +Freed & Borenstein Standards Track [Page 23] + +RFC 2046 Media Types November 1996 + + + NOTE: Conspicuously missing from the "multipart" type is a notion of + structured, related body parts. It is recommended that those wishing + to provide more structured or integrated multipart messaging + facilities should define subtypes of multipart that are syntactically + identical but define relationships between the various parts. For + example, subtypes of multipart could be defined that include a + distinguished part which in turn is used to specify the relationships + between the other parts, probably referring to them by their + Content-ID field. Old implementations will not recognize the new + subtype if this approach is used, but will treat it as + multipart/mixed and will thus be able to show the user the parts that + are recognized. + +5.1.2. Handling Nested Messages and Multiparts + + The "message/rfc822" subtype defined in a subsequent section of this + document has no terminating condition other than running out of data. + Similarly, an improperly truncated "multipart" entity may not have + any terminating boundary marker, and can turn up operationally due to + mail system malfunctions. + + It is essential that such entities be handled correctly when they are + themselves imbedded inside of another "multipart" structure. MIME + implementations are therefore required to recognize outer level + boundary markers at ANY level of inner nesting. It is not sufficient + to only check for the next expected marker or other terminating + condition. + +5.1.3. Mixed Subtype + + The "mixed" subtype of "multipart" is intended for use when the body + parts are independent and need to be bundled in a particular order. + Any "multipart" subtypes that an implementation does not recognize + must be treated as being of subtype "mixed". + +5.1.4. Alternative Subtype + + The "multipart/alternative" type is syntactically identical to + "multipart/mixed", but the semantics are different. In particular, + each of the body parts is an "alternative" version of the same + information. + + Systems should recognize that the content of the various parts are + interchangeable. Systems should choose the "best" type based on the + local environment and references, in some cases even through user + interaction. As with "multipart/mixed", the order of body parts is + significant. In this case, the alternatives appear in an order of + increasing faithfulness to the original content. In general, the + + + +Freed & Borenstein Standards Track [Page 24] + +RFC 2046 Media Types November 1996 + + + best choice is the LAST part of a type supported by the recipient + system's local environment. + + "Multipart/alternative" may be used, for example, to send a message + in a fancy text format in such a way that it can easily be displayed + anywhere: + + From: Nathaniel Borenstein + To: Ned Freed + Date: Mon, 22 Mar 1993 09:41:09 -0800 (PST) + Subject: Formatted text mail + MIME-Version: 1.0 + Content-Type: multipart/alternative; boundary=boundary42 + + --boundary42 + Content-Type: text/plain; charset=us-ascii + + ... plain text version of message goes here ... + + --boundary42 + Content-Type: text/enriched + + ... RFC 1896 text/enriched version of same message + goes here ... + + --boundary42 + Content-Type: application/x-whatever + + ... fanciest version of same message goes here ... + + --boundary42-- + + In this example, users whose mail systems understood the + "application/x-whatever" format would see only the fancy version, + while other users would see only the enriched or plain text version, + depending on the capabilities of their system. + + In general, user agents that compose "multipart/alternative" entities + must place the body parts in increasing order of preference, that is, + with the preferred format last. For fancy text, the sending user + agent should put the plainest format first and the richest format + last. Receiving user agents should pick and display the last format + they are capable of displaying. In the case where one of the + alternatives is itself of type "multipart" and contains unrecognized + sub-parts, the user agent may choose either to show that alternative, + an earlier alternative, or both. + + + + + +Freed & Borenstein Standards Track [Page 25] + +RFC 2046 Media Types November 1996 + + + NOTE: From an implementor's perspective, it might seem more sensible + to reverse this ordering, and have the plainest alternative last. + However, placing the plainest alternative first is the friendliest + possible option when "multipart/alternative" entities are viewed + using a non-MIME-conformant viewer. While this approach does impose + some burden on conformant MIME viewers, interoperability with older + mail readers was deemed to be more important in this case. + + It may be the case that some user agents, if they can recognize more + than one of the formats, will prefer to offer the user the choice of + which format to view. This makes sense, for example, if a message + includes both a nicely- formatted image version and an easily-edited + text version. What is most critical, however, is that the user not + automatically be shown multiple versions of the same data. Either + the user should be shown the last recognized version or should be + given the choice. + + THE SEMANTICS OF CONTENT-ID IN MULTIPART/ALTERNATIVE: Each part of a + "multipart/alternative" entity represents the same data, but the + mappings between the two are not necessarily without information + loss. For example, information is lost when translating ODA to + PostScript or plain text. It is recommended that each part should + have a different Content-ID value in the case where the information + content of the two parts is not identical. And when the information + content is identical -- for example, where several parts of type + "message/external-body" specify alternate ways to access the + identical data -- the same Content-ID field value should be used, to + optimize any caching mechanisms that might be present on the + recipient's end. However, the Content-ID values used by the parts + should NOT be the same Content-ID value that describes the + "multipart/alternative" as a whole, if there is any such Content-ID + field. That is, one Content-ID value will refer to the + "multipart/alternative" entity, while one or more other Content-ID + values will refer to the parts inside it. + +5.1.5. Digest Subtype + + This document defines a "digest" subtype of the "multipart" Content- + Type. This type is syntactically identical to "multipart/mixed", but + the semantics are different. In particular, in a digest, the default + Content-Type value for a body part is changed from "text/plain" to + "message/rfc822". This is done to allow a more readable digest + format that is largely compatible (except for the quoting convention) + with RFC 934. + + Note: Though it is possible to specify a Content-Type value for a + body part in a digest which is other than "message/rfc822", such as a + "text/plain" part containing a description of the material in the + + + +Freed & Borenstein Standards Track [Page 26] + +RFC 2046 Media Types November 1996 + + + digest, actually doing so is undesireble. The "multipart/digest" + Content-Type is intended to be used to send collections of messages. + If a "text/plain" part is needed, it should be included as a seperate + part of a "multipart/mixed" message. + + A digest in this format might, then, look something like this: + + From: Moderator-Address + To: Recipient-List + Date: Mon, 22 Mar 1994 13:34:51 +0000 + Subject: Internet Digest, volume 42 + MIME-Version: 1.0 + Content-Type: multipart/mixed; + boundary="---- main boundary ----" + + ------ main boundary ---- + + ...Introductory text or table of contents... + + ------ main boundary ---- + Content-Type: multipart/digest; + boundary="---- next message ----" + + ------ next message ---- + + From: someone-else + Date: Fri, 26 Mar 1993 11:13:32 +0200 + Subject: my opinion + + ...body goes here ... + + ------ next message ---- + + From: someone-else-again + Date: Fri, 26 Mar 1993 10:07:13 -0500 + Subject: my different opinion + + ... another body goes here ... + + ------ next message ------ + + ------ main boundary ------ + +5.1.6. Parallel Subtype + + This document defines a "parallel" subtype of the "multipart" + Content-Type. This type is syntactically identical to + "multipart/mixed", but the semantics are different. In particular, + + + +Freed & Borenstein Standards Track [Page 27] + +RFC 2046 Media Types November 1996 + + + in a parallel entity, the order of body parts is not significant. + + A common presentation of this type is to display all of the parts + simultaneously on hardware and software that are capable of doing so. + However, composing agents should be aware that many mail readers will + lack this capability and will show the parts serially in any event. + +5.1.7. Other Multipart Subtypes + + Other "multipart" subtypes are expected in the future. MIME + implementations must in general treat unrecognized subtypes of + "multipart" as being equivalent to "multipart/mixed". + +5.2. Message Media Type + + It is frequently desirable, in sending mail, to encapsulate another + mail message. A special media type, "message", is defined to + facilitate this. In particular, the "rfc822" subtype of "message" is + used to encapsulate RFC 822 messages. + + NOTE: It has been suggested that subtypes of "message" might be + defined for forwarded or rejected messages. However, forwarded and + rejected messages can be handled as multipart messages in which the + first part contains any control or descriptive information, and a + second part, of type "message/rfc822", is the forwarded or rejected + message. Composing rejection and forwarding messages in this manner + will preserve the type information on the original message and allow + it to be correctly presented to the recipient, and hence is strongly + encouraged. + + Subtypes of "message" often impose restrictions on what encodings are + allowed. These restrictions are described in conjunction with each + specific subtype. + + Mail gateways, relays, and other mail handling agents are commonly + known to alter the top-level header of an RFC 822 message. In + particular, they frequently add, remove, or reorder header fields. + These operations are explicitly forbidden for the encapsulated + headers embedded in the bodies of messages of type "message." + +5.2.1. RFC822 Subtype + + A media type of "message/rfc822" indicates that the body contains an + encapsulated message, with the syntax of an RFC 822 message. + However, unlike top-level RFC 822 messages, the restriction that each + "message/rfc822" body must include a "From", "Date", and at least one + destination header is removed and replaced with the requirement that + at least one of "From", "Subject", or "Date" must be present. + + + +Freed & Borenstein Standards Track [Page 28] + +RFC 2046 Media Types November 1996 + + + It should be noted that, despite the use of the numbers "822", a + "message/rfc822" entity isn't restricted to material in strict + conformance to RFC822, nor are the semantics of "message/rfc822" + objects restricted to the semantics defined in RFC822. More + specifically, a "message/rfc822" message could well be a News article + or a MIME message. + + No encoding other than "7bit", "8bit", or "binary" is permitted for + the body of a "message/rfc822" entity. The message header fields are + always US-ASCII in any case, and data within the body can still be + encoded, in which case the Content-Transfer-Encoding header field in + the encapsulated message will reflect this. Non-US-ASCII text in the + headers of an encapsulated message can be specified using the + mechanisms described in RFC 2047. + +5.2.2. Partial Subtype + + The "partial" subtype is defined to allow large entities to be + delivered as several separate pieces of mail and automatically + reassembled by a receiving user agent. (The concept is similar to IP + fragmentation and reassembly in the basic Internet Protocols.) This + mechanism can be used when intermediate transport agents limit the + size of individual messages that can be sent. The media type + "message/partial" thus indicates that the body contains a fragment of + a larger entity. + + Because data of type "message" may never be encoded in base64 or + quoted-printable, a problem might arise if "message/partial" entities + are constructed in an environment that supports binary or 8bit + transport. The problem is that the binary data would be split into + multiple "message/partial" messages, each of them requiring binary + transport. If such messages were encountered at a gateway into a + 7bit transport environment, there would be no way to properly encode + them for the 7bit world, aside from waiting for all of the fragments, + reassembling the inner message, and then encoding the reassembled + data in base64 or quoted-printable. Since it is possible that + different fragments might go through different gateways, even this is + not an acceptable solution. For this reason, it is specified that + entities of type "message/partial" must always have a content- + transfer-encoding of 7bit (the default). In particular, even in + environments that support binary or 8bit transport, the use of a + content- transfer-encoding of "8bit" or "binary" is explicitly + prohibited for MIME entities of type "message/partial". This in turn + implies that the inner message must not use "8bit" or "binary" + encoding. + + + + + + +Freed & Borenstein Standards Track [Page 29] + +RFC 2046 Media Types November 1996 + + + Because some message transfer agents may choose to automatically + fragment large messages, and because such agents may use very + different fragmentation thresholds, it is possible that the pieces of + a partial message, upon reassembly, may prove themselves to comprise + a partial message. This is explicitly permitted. + + Three parameters must be specified in the Content-Type field of type + "message/partial": The first, "id", is a unique identifier, as close + to a world-unique identifier as possible, to be used to match the + fragments together. (In general, the identifier is essentially a + message-id; if placed in double quotes, it can be ANY message-id, in + accordance with the BNF for "parameter" given in RFC 2045.) The + second, "number", an integer, is the fragment number, which indicates + where this fragment fits into the sequence of fragments. The third, + "total", another integer, is the total number of fragments. This + third subfield is required on the final fragment, and is optional + (though encouraged) on the earlier fragments. Note also that these + parameters may be given in any order. + + Thus, the second piece of a 3-piece message may have either of the + following header fields: + + Content-Type: Message/Partial; number=2; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com" + + Content-Type: Message/Partial; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com"; + number=2 + + But the third piece MUST specify the total number of fragments: + + Content-Type: Message/Partial; number=3; total=3; + id="oc=jpbe0M2Yt4s@thumper.bellcore.com" + + Note that fragment numbering begins with 1, not 0. + + When the fragments of an entity broken up in this manner are put + together, the result is always a complete MIME entity, which may have + its own Content-Type header field, and thus may contain any other + data type. + +5.2.2.1. Message Fragmentation and Reassembly + + The semantics of a reassembled partial message must be those of the + "inner" message, rather than of a message containing the inner + message. This makes it possible, for example, to send a large audio + message as several partial messages, and still have it appear to the + recipient as a simple audio message rather than as an encapsulated + + + +Freed & Borenstein Standards Track [Page 30] + +RFC 2046 Media Types November 1996 + + + message containing an audio message. That is, the encapsulation of + the message is considered to be "transparent". + + When generating and reassembling the pieces of a "message/partial" + message, the headers of the encapsulated message must be merged with + the headers of the enclosing entities. In this process the following + rules must be observed: + + (1) Fragmentation agents must split messages at line + boundaries only. This restriction is imposed because + splits at points other than the ends of lines in turn + depends on message transports being able to preserve + the semantics of messages that don't end with a CRLF + sequence. Many transports are incapable of preserving + such semantics. + + (2) All of the header fields from the initial enclosing + message, except those that start with "Content-" and + the specific header fields "Subject", "Message-ID", + "Encrypted", and "MIME-Version", must be copied, in + order, to the new message. + + (3) The header fields in the enclosed message which start + with "Content-", plus the "Subject", "Message-ID", + "Encrypted", and "MIME-Version" fields, must be + appended, in order, to the header fields of the new + message. Any header fields in the enclosed message + which do not start with "Content-" (except for the + "Subject", "Message-ID", "Encrypted", and "MIME- + Version" fields) will be ignored and dropped. + + (4) All of the header fields from the second and any + subsequent enclosing messages are discarded by the + reassembly process. + +5.2.2.2. Fragmentation and Reassembly Example + + If an audio message is broken into two pieces, the first piece might + look something like this: + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Date: Fri, 26 Mar 1993 12:59:38 -0500 (EST) + Subject: Audio mail (part 1 of 2) + Message-ID: + MIME-Version: 1.0 + Content-type: message/partial; id="ABC@host.com"; + + + +Freed & Borenstein Standards Track [Page 31] + +RFC 2046 Media Types November 1996 + + + number=1; total=2 + + X-Weird-Header-1: Bar + X-Weird-Header-2: Hello + Message-ID: + Subject: Audio mail + MIME-Version: 1.0 + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here ... + + and the second half might look something like this: + + From: Bill@host.com + To: joe@otherhost.com + Date: Fri, 26 Mar 1993 12:59:38 -0500 (EST) + Subject: Audio mail (part 2 of 2) + MIME-Version: 1.0 + Message-ID: + Content-type: message/partial; + id="ABC@host.com"; number=2; total=2 + + ... second half of encoded audio data goes here ... + + Then, when the fragmented message is reassembled, the resulting + message to be displayed to the user should look something like this: + + X-Weird-Header-1: Foo + From: Bill@host.com + To: joe@otherhost.com + Date: Fri, 26 Mar 1993 12:59:38 -0500 (EST) + Subject: Audio mail + Message-ID: + MIME-Version: 1.0 + Content-type: audio/basic + Content-transfer-encoding: base64 + + ... first half of encoded audio data goes here ... + ... second half of encoded audio data goes here ... + + The inclusion of a "References" field in the headers of the second + and subsequent pieces of a fragmented message that references the + Message-Id on the previous piece may be of benefit to mail readers + that understand and track references. However, the generation of + such "References" fields is entirely optional. + + + + + +Freed & Borenstein Standards Track [Page 32] + +RFC 2046 Media Types November 1996 + + + Finally, it should be noted that the "Encrypted" header field has + been made obsolete by Privacy Enhanced Messaging (PEM) [RFC-1421, + RFC-1422, RFC-1423, RFC-1424], but the rules above are nevertheless + believed to describe the correct way to treat it if it is encountered + in the context of conversion to and from "message/partial" fragments. + +5.2.3. External-Body Subtype + + The external-body subtype indicates that the actual body data are not + included, but merely referenced. In this case, the parameters + describe a mechanism for accessing the external data. + + When a MIME entity is of type "message/external-body", it consists of + a header, two consecutive CRLFs, and the message header for the + encapsulated message. If another pair of consecutive CRLFs appears, + this of course ends the message header for the encapsulated message. + However, since the encapsulated message's body is itself external, it + does NOT appear in the area that follows. For example, consider the + following message: + + Content-type: message/external-body; + access-type=local-file; + name="/u/nsb/Me.jpeg" + + Content-type: image/jpeg + Content-ID: + Content-Transfer-Encoding: binary + + THIS IS NOT REALLY THE BODY! + + The area at the end, which might be called the "phantom body", is + ignored for most external-body messages. However, it may be used to + contain auxiliary information for some such messages, as indeed it is + when the access-type is "mail- server". The only access-type defined + in this document that uses the phantom body is "mail-server", but + other access-types may be defined in the future in other + specifications that use this area. + + The encapsulated headers in ALL "message/external-body" entities MUST + include a Content-ID header field to give a unique identifier by + which to reference the data. This identifier may be used for caching + mechanisms, and for recognizing the receipt of the data when the + access-type is "mail-server". + + Note that, as specified here, the tokens that describe external-body + data, such as file names and mail server commands, are required to be + in the US-ASCII character set. + + + + +Freed & Borenstein Standards Track [Page 33] + +RFC 2046 Media Types November 1996 + + + If this proves problematic in practice, a new mechanism may be + required as a future extension to MIME, either as newly defined + access-types for "message/external-body" or by some other mechanism. + + As with "message/partial", MIME entities of type "message/external- + body" MUST have a content-transfer-encoding of 7bit (the default). + In particular, even in environments that support binary or 8bit + transport, the use of a content- transfer-encoding of "8bit" or + "binary" is explicitly prohibited for entities of type + "message/external-body". + +5.2.3.1. General External-Body Parameters + + The parameters that may be used with any "message/external- body" + are: + + (1) ACCESS-TYPE -- A word indicating the supported access + mechanism by which the file or data may be obtained. + This word is not case sensitive. Values include, but + are not limited to, "FTP", "ANON-FTP", "TFTP", "LOCAL- + FILE", and "MAIL-SERVER". Future values, except for + experimental values beginning with "X-", must be + registered with IANA, as described in RFC 2048. + This parameter is unconditionally mandatory and MUST be + present on EVERY "message/external-body". + + (2) EXPIRATION -- The date (in the RFC 822 "date-time" + syntax, as extended by RFC 1123 to permit 4 digits in + the year field) after which the existence of the + external data is not guaranteed. This parameter may be + used with ANY access-type and is ALWAYS optional. + + (3) SIZE -- The size (in octets) of the data. The intent + of this parameter is to help the recipient decide + whether or not to expend the necessary resources to + retrieve the external data. Note that this describes + the size of the data in its canonical form, that is, + before any Content-Transfer-Encoding has been applied + or after the data have been decoded. This parameter + may be used with ANY access-type and is ALWAYS + optional. + + (4) PERMISSION -- A case-insensitive field that indicates + whether or not it is expected that clients might also + attempt to overwrite the data. By default, or if + permission is "read", the assumption is that they are + not, and that if the data is retrieved once, it is + never needed again. If PERMISSION is "read-write", + + + +Freed & Borenstein Standards Track [Page 34] + +RFC 2046 Media Types November 1996 + + + this assumption is invalid, and any local copy must be + considered no more than a cache. "Read" and "Read- + write" are the only defined values of permission. This + parameter may be used with ANY access-type and is + ALWAYS optional. + + The precise semantics of the access-types defined here are described + in the sections that follow. + +5.2.3.2. The 'ftp' and 'tftp' Access-Types + + An access-type of FTP or TFTP indicates that the message body is + accessible as a file using the FTP [RFC-959] or TFTP [RFC- 783] + protocols, respectively. For these access-types, the following + additional parameters are mandatory: + + (1) NAME -- The name of the file that contains the actual + body data. + + (2) SITE -- A machine from which the file may be obtained, + using the given protocol. This must be a fully + qualified domain name, not a nickname. + + (3) Before any data are retrieved, using FTP, the user will + generally need to be asked to provide a login id and a + password for the machine named by the site parameter. + For security reasons, such an id and password are not + specified as content-type parameters, but must be + obtained from the user. + + In addition, the following parameters are optional: + + (1) DIRECTORY -- A directory from which the data named by + NAME should be retrieved. + + (2) MODE -- A case-insensitive string indicating the mode + to be used when retrieving the information. The valid + values for access-type "TFTP" are "NETASCII", "OCTET", + and "MAIL", as specified by the TFTP protocol [RFC- + 783]. The valid values for access-type "FTP" are + "ASCII", "EBCDIC", "IMAGE", and "LOCALn" where "n" is a + decimal integer, typically 8. These correspond to the + representation types "A" "E" "I" and "L n" as specified + by the FTP protocol [RFC-959]. Note that "BINARY" and + "TENEX" are not valid values for MODE and that "OCTET" + or "IMAGE" or "LOCAL8" should be used instead. IF MODE + is not specified, the default value is "NETASCII" for + TFTP and "ASCII" otherwise. + + + +Freed & Borenstein Standards Track [Page 35] + +RFC 2046 Media Types November 1996 + + +5.2.3.3. The 'anon-ftp' Access-Type + + The "anon-ftp" access-type is identical to the "ftp" access type, + except that the user need not be asked to provide a name and password + for the specified site. Instead, the ftp protocol will be used with + login "anonymous" and a password that corresponds to the user's mail + address. + +5.2.3.4. The 'local-file' Access-Type + + An access-type of "local-file" indicates that the actual body is + accessible as a file on the local machine. Two additional parameters + are defined for this access type: + + (1) NAME -- The name of the file that contains the actual + body data. This parameter is mandatory for the + "local-file" access-type. + + (2) SITE -- A domain specifier for a machine or set of + machines that are known to have access to the data + file. This optional parameter is used to describe the + locality of reference for the data, that is, the site + or sites at which the file is expected to be visible. + Asterisks may be used for wildcard matching to a part + of a domain name, such as "*.bellcore.com", to indicate + a set of machines on which the data should be directly + visible, while a single asterisk may be used to + indicate a file that is expected to be universally + available, e.g., via a global file system. + +5.2.3.5. The 'mail-server' Access-Type + + The "mail-server" access-type indicates that the actual body is + available from a mail server. Two additional parameters are defined + for this access-type: + + (1) SERVER -- The addr-spec of the mail server from which + the actual body data can be obtained. This parameter + is mandatory for the "mail-server" access-type. + + (2) SUBJECT -- The subject that is to be used in the mail + that is sent to obtain the data. Note that keying mail + servers on Subject lines is NOT recommended, but such + mail servers are known to exist. This is an optional + parameter. + + + + + + +Freed & Borenstein Standards Track [Page 36] + +RFC 2046 Media Types November 1996 + + + Because mail servers accept a variety of syntaxes, some of which is + multiline, the full command to be sent to a mail server is not + included as a parameter in the content-type header field. Instead, + it is provided as the "phantom body" when the media type is + "message/external-body" and the access-type is mail-server. + + Note that MIME does not define a mail server syntax. Rather, it + allows the inclusion of arbitrary mail server commands in the phantom + body. Implementations must include the phantom body in the body of + the message it sends to the mail server address to retrieve the + relevant data. + + Unlike other access-types, mail-server access is asynchronous and + will happen at an unpredictable time in the future. For this reason, + it is important that there be a mechanism by which the returned data + can be matched up with the original "message/external-body" entity. + MIME mail servers must use the same Content-ID field on the returned + message that was used in the original "message/external-body" + entities, to facilitate such matching. + +5.2.3.6. External-Body Security Issues + + "Message/external-body" entities give rise to two important security + issues: + + (1) Accessing data via a "message/external-body" reference + effectively results in the message recipient performing + an operation that was specified by the message + originator. It is therefore possible for the message + originator to trick a recipient into doing something + they would not have done otherwise. For example, an + originator could specify a action that attempts + retrieval of material that the recipient is not + authorized to obtain, causing the recipient to + unwittingly violate some security policy. For this + reason, user agents capable of resolving external + references must always take steps to describe the + action they are to take to the recipient and ask for + explicit permisssion prior to performing it. + + The 'mail-server' access-type is particularly + vulnerable, in that it causes the recipient to send a + new message whose contents are specified by the + original message's originator. Given the potential for + abuse, any such request messages that are constructed + should contain a clear indication that they were + generated automatically (e.g. in a Comments: header + field) in an attempt to resolve a MIME + + + +Freed & Borenstein Standards Track [Page 37] + +RFC 2046 Media Types November 1996 + + + "message/external-body" reference. + + (2) MIME will sometimes be used in environments that + provide some guarantee of message integrity and + authenticity. If present, such guarantees may apply + only to the actual direct content of messages -- they + may or may not apply to data accessed through MIME's + "message/external-body" mechanism. In particular, it + may be possible to subvert certain access mechanisms + even when the messaging system itself is secure. + + It should be noted that this problem exists either with + or without the availabilty of MIME mechanisms. A + casual reference to an FTP site containing a document + in the text of a secure message brings up similar + issues -- the only difference is that MIME provides for + automatic retrieval of such material, and users may + place unwarranted trust is such automatic retrieval + mechanisms. + +5.2.3.7. Examples and Further Explanations + + When the external-body mechanism is used in conjunction with the + "multipart/alternative" media type it extends the functionality of + "multipart/alternative" to include the case where the same entity is + provided in the same format but via different accces mechanisms. + When this is done the originator of the message must order the parts + first in terms of preferred formats and then by preferred access + mechanisms. The recipient's viewer should then evaluate the list + both in terms of format and access mechanisms. + + With the emerging possibility of very wide-area file systems, it + becomes very hard to know in advance the set of machines where a file + will and will not be accessible directly from the file system. + Therefore it may make sense to provide both a file name, to be tried + directly, and the name of one or more sites from which the file is + known to be accessible. An implementation can try to retrieve remote + files using FTP or any other protocol, using anonymous file retrieval + or prompting the user for the necessary name and password. If an + external body is accessible via multiple mechanisms, the sender may + include multiple entities of type "message/external-body" within the + body parts of an enclosing "multipart/alternative" entity. + + However, the external-body mechanism is not intended to be limited to + file retrieval, as shown by the mail-server access-type. Beyond + this, one can imagine, for example, using a video server for external + references to video clips. + + + + +Freed & Borenstein Standards Track [Page 38] + +RFC 2046 Media Types November 1996 + + + The embedded message header fields which appear in the body of the + "message/external-body" data must be used to declare the media type + of the external body if it is anything other than plain US-ASCII + text, since the external body does not have a header section to + declare its type. Similarly, any Content-transfer-encoding other + than "7bit" must also be declared here. Thus a complete + "message/external-body" message, referring to an object in PostScript + format, might look like this: + + From: Whomever + To: Someone + Date: Whenever + Subject: whatever + MIME-Version: 1.0 + Message-ID: + Content-Type: multipart/alternative; boundary=42 + Content-ID: + + --42 + Content-Type: message/external-body; name="BodyFormats.ps"; + site="thumper.bellcore.com"; mode="image"; + access-type=ANON-FTP; directory="pub"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + --42 + Content-Type: message/external-body; access-type=local-file; + name="/u/nsb/writing/rfcs/RFC-MIME.ps"; + site="thumper.bellcore.com"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + --42 + Content-Type: message/external-body; + access-type=mail-server + server="listserv@bogus.bitnet"; + expiration="Fri, 14 Jun 1991 19:13:14 -0400 (EDT)" + + Content-type: application/postscript + Content-ID: + + get RFC-MIME.DOC + + --42-- + + + +Freed & Borenstein Standards Track [Page 39] + +RFC 2046 Media Types November 1996 + + + Note that in the above examples, the default Content-transfer- + encoding of "7bit" is assumed for the external postscript data. + + Like the "message/partial" type, the "message/external-body" media + type is intended to be transparent, that is, to convey the data type + in the external body rather than to convey a message with a body of + that type. Thus the headers on the outer and inner parts must be + merged using the same rules as for "message/partial". In particular, + this means that the Content-type and Subject fields are overridden, + but the From field is preserved. + + Note that since the external bodies are not transported along with + the external body reference, they need not conform to transport + limitations that apply to the reference itself. In particular, + Internet mail transports may impose 7bit and line length limits, but + these do not automatically apply to binary external body references. + Thus a Content-Transfer-Encoding is not generally necessary, though + it is permitted. + + Note that the body of a message of type "message/external-body" is + governed by the basic syntax for an RFC 822 message. In particular, + anything before the first consecutive pair of CRLFs is header + information, while anything after it is body information, which is + ignored for most access-types. + +5.2.4. Other Message Subtypes + + MIME implementations must in general treat unrecognized subtypes of + "message" as being equivalent to "application/octet-stream". + + Future subtypes of "message" intended for use with email should be + restricted to "7bit" encoding. A type other than "message" should be + used if restriction to "7bit" is not possible. + +6. Experimental Media Type Values + + A media type value beginning with the characters "X-" is a private + value, to be used by consenting systems by mutual agreement. Any + format without a rigorous and public definition must be named with an + "X-" prefix, and publicly specified values shall never begin with + "X-". (Older versions of the widely used Andrew system use the "X- + BE2" name, so new systems should probably choose a different name.) + + In general, the use of "X-" top-level types is strongly discouraged. + Implementors should invent subtypes of the existing types whenever + possible. In many cases, a subtype of "application" will be more + appropriate than a new top-level type. + + + + +Freed & Borenstein Standards Track [Page 40] + +RFC 2046 Media Types November 1996 + + +7. Summary + + The five discrete media types provide provide a standardized + mechanism for tagging entities as "audio", "image", or several other + kinds of data. The composite "multipart" and "message" media types + allow mixing and hierarchical structuring of entities of different + types in a single message. A distinguished parameter syntax allows + further specification of data format details, particularly the + specification of alternate character sets. Additional optional + header fields provide mechanisms for certain extensions deemed + desirable by many implementors. Finally, a number of useful media + types are defined for general use by consenting user agents, notably + "message/partial" and "message/external-body". + +9. Security Considerations + + Security issues are discussed in the context of the + "application/postscript" type, the "message/external-body" type, and + in RFC 2048. Implementors should pay special attention to the + security implications of any media types that can cause the remote + execution of any actions in the recipient's environment. In such + cases, the discussion of the "application/postscript" type may serve + as a model for considering other media types with remote execution + capabilities. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 41] + +RFC 2046 Media Types November 1996 + + +9. Authors' Addresses + + For more information, the authors of this document are best contacted + via Internet mail: + + Ned Freed + Innosoft International, Inc. + 1050 East Garvey Avenue South + West Covina, CA 91790 + USA + + Phone: +1 818 919 3600 + Fax: +1 818 919 3614 + EMail: ned@innosoft.com + + + Nathaniel S. Borenstein + First Virtual Holdings + 25 Washington Avenue + Morristown, NJ 07960 + USA + + Phone: +1 201 540 8967 + Fax: +1 201 993 3032 + EMail: nsb@nsb.fv.com + + + MIME is a result of the work of the Internet Engineering Task Force + Working Group on RFC 822 Extensions. The chairman of that group, + Greg Vaudreuil, may be reached at: + + Gregory M. Vaudreuil + Octel Network Services + 17080 Dallas Parkway + Dallas, TX 75248-1905 + USA + + EMail: Greg.Vaudreuil@Octel.Com + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 42] + +RFC 2046 Media Types November 1996 + + +Appendix A -- Collected Grammar + + This appendix contains the complete BNF grammar for all the syntax + specified by this document. + + By itself, however, this grammar is incomplete. It refers by name to + several syntax rules that are defined by RFC 822. Rather than + reproduce those definitions here, and risk unintentional differences + between the two, this document simply refers the reader to RFC 822 + for the remaining definitions. Wherever a term is undefined, it + refers to the RFC 822 definition. + + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / + "+" / "_" / "," / "-" / "." / + "/" / ":" / "=" / "?" + + body-part := <"message" as defined in RFC 822, with all + header fields optional, not starting with the + specified dash-boundary, and with the + delimiter not occurring anywhere in the + body part. Note that the semantics of a + part differ from the semantics of a message, + as described in the text.> + + close-delimiter := delimiter "--" + + dash-boundary := "--" boundary + ; boundary taken from the value of + ; boundary parameter of the + ; Content-Type field. + + delimiter := CRLF dash-boundary + + discard-text := *(*text CRLF) + ; May be ignored or discarded. + + encapsulation := delimiter transport-padding + CRLF body-part + + epilogue := discard-text + + multipart-body := [preamble CRLF] + dash-boundary transport-padding CRLF + body-part *encapsulation + + + +Freed & Borenstein Standards Track [Page 43] + +RFC 2046 Media Types November 1996 + + + close-delimiter transport-padding + [CRLF epilogue] + + preamble := discard-text + + transport-padding := *LWSP-char + ; Composers MUST NOT generate + ; non-zero length transport + ; padding, but receivers MUST + ; be able to handle padding + ; added by message transports. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 44] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2047.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2047.txt new file mode 100644 index 00000000..ff9a744b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2047.txt @@ -0,0 +1,843 @@ + + + + + + +Network Working Group K. Moore +Request for Comments: 2047 University of Tennessee +Obsoletes: 1521, 1522, 1590 November 1996 +Category: Standards Track + + + MIME (Multipurpose Internet Mail Extensions) Part Three: + Message Header Extensions for Non-ASCII Text + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822, defines a message representation protocol specifying + considerable detail about US-ASCII message headers, and leaves the + message content, or message body, as flat US-ASCII text. This set of + documents, collectively called the Multipurpose Internet Mail + Extensions, or MIME, redefines the format of messages to allow for + + (1) textual message bodies in character sets other than US-ASCII, + + (2) an extensible set of different formats for non-textual message + bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than US-ASCII. + + These documents are based on earlier work documented in RFC 934, STD + 11, and RFC 1049, but extends and revises them. Because RFC 822 said + so little about message bodies, these documents are largely + orthogonal to (rather than a revision of) RFC 822. + + This particular document is the third document in the series. It + describes extensions to RFC 822 to allow non-US-ASCII text data in + Internet mail header fields. + + + + + + + + + +Moore Standards Track [Page 1] + +RFC 2047 Message Header Extensions November 1996 + + + Other documents in this series include: + + + RFC 2045, which specifies the various headers used to describe + the structure of MIME messages. + + + RFC 2046, which defines the general structure of the MIME media + typing system and defines an initial set of media types, + + + RFC 2048, which specifies various IANA registration procedures + for MIME-related facilities, and + + + RFC 2049, which describes MIME conformance criteria and + provides some illustrative examples of MIME message formats, + acknowledgements, and the bibliography. + + These documents are revisions of RFCs 1521, 1522, and 1590, which + themselves were revisions of RFCs 1341 and 1342. An appendix in RFC + 2049 describes differences and changes from previous versions. + +1. Introduction + + RFC 2045 describes a mechanism for denoting textual body parts which + are coded in various character sets, as well as methods for encoding + such body parts as sequences of printable US-ASCII characters. This + memo describes similar techniques to allow the encoding of non-ASCII + text in various portions of a RFC 822 [2] message header, in a manner + which is unlikely to confuse existing message handling software. + + Like the encoding techniques described in RFC 2045, the techniques + outlined here were designed to allow the use of non-ASCII characters + in message headers in a way which is unlikely to be disturbed by the + quirks of existing Internet mail handling programs. In particular, + some mail relaying programs are known to (a) delete some message + header fields while retaining others, (b) rearrange the order of + addresses in To or Cc fields, (c) rearrange the (vertical) order of + header fields, and/or (d) "wrap" message headers at different places + than those in the original message. In addition, some mail reading + programs are known to have difficulty correctly parsing message + headers which, while legal according to RFC 822, make use of + backslash-quoting to "hide" special characters such as "<", ",", or + ":", or which exploit other infrequently-used features of that + specification. + + While it is unfortunate that these programs do not correctly + interpret RFC 822 headers, to "break" these programs would cause + severe operational problems for the Internet mail system. The + extensions described in this memo therefore do not rely on little- + used features of RFC 822. + + + +Moore Standards Track [Page 2] + +RFC 2047 Message Header Extensions November 1996 + + + Instead, certain sequences of "ordinary" printable ASCII characters + (known as "encoded-words") are reserved for use as encoded data. The + syntax of encoded-words is such that they are unlikely to + "accidentally" appear as normal text in message headers. + Furthermore, the characters used in encoded-words are restricted to + those which do not have special meanings in the context in which the + encoded-word appears. + + Generally, an "encoded-word" is a sequence of printable ASCII + characters that begins with "=?", ends with "?=", and has two "?"s in + between. It specifies a character set and an encoding method, and + also includes the original text encoded as graphic ASCII characters, + according to the rules for that encoding method. + + A mail composer that implements this specification will provide a + means of inputting non-ASCII text in header fields, but will + translate these fields (or appropriate portions of these fields) into + encoded-words before inserting them into the message header. + + A mail reader that implements this specification will recognize + encoded-words when they appear in certain portions of the message + header. Instead of displaying the encoded-word "as is", it will + reverse the encoding and display the original text in the designated + character set. + +NOTES + + This memo relies heavily on notation and terms defined RFC 822 and + RFC 2045. In particular, the syntax for the ABNF used in this memo + is defined in RFC 822, as well as many of the terminal or nonterminal + symbols from RFC 822 are used in the grammar for the header + extensions defined here. Among the symbols defined in RFC 822 and + referenced in this memo are: 'addr-spec', 'atom', 'CHAR', 'comment', + 'CTLs', 'ctext', 'linear-white-space', 'phrase', 'quoted-pair'. + 'quoted-string', 'SPACE', and 'word'. Successful implementation of + this protocol extension requires careful attention to the RFC 822 + definitions of these terms. + + When the term "ASCII" appears in this memo, it refers to the "7-Bit + American Standard Code for Information Interchange", ANSI X3.4-1986. + The MIME charset name for this character set is "US-ASCII". When not + specifically referring to the MIME charset name, this document uses + the term "ASCII", both for brevity and for consistency with RFC 822. + However, implementors are warned that the character set name must be + spelled "US-ASCII" in MIME message and body part headers. + + + + + + +Moore Standards Track [Page 3] + +RFC 2047 Message Header Extensions November 1996 + + + This memo specifies a protocol for the representation of non-ASCII + text in message headers. It specifically DOES NOT define any + translation between "8-bit headers" and pure ASCII headers, nor is + any such translation assumed to be possible. + +2. Syntax of encoded-words + + An 'encoded-word' is defined by the following ABNF grammar. The + notation of RFC 822 is used, with the exception that white space + characters MUST NOT appear between components of an 'encoded-word'. + + encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" + + charset = token ; see section 3 + + encoding = token ; see section 4 + + token = 1* + + especials = "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / " + <"> / "/" / "[" / "]" / "?" / "." / "=" + + encoded-text = 1* + ; (but see "Use of encoded-words in message + ; headers", section 5) + + Both 'encoding' and 'charset' names are case-independent. Thus the + charset name "ISO-8859-1" is equivalent to "iso-8859-1", and the + encoding named "Q" may be spelled either "Q" or "q". + + An 'encoded-word' may not be more than 75 characters long, including + 'charset', 'encoding', 'encoded-text', and delimiters. If it is + desirable to encode more text than will fit in an 'encoded-word' of + 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may + be used. + + While there is no limit to the length of a multiple-line header + field, each line of a header field that contains one or more + 'encoded-word's is limited to 76 characters. + + The length restrictions are included both to ease interoperability + through internetwork mail gateways, and to impose a limit on the + amount of lookahead a header parser must employ (while looking for a + final ?= delimiter) before it can decide whether a token is an + "encoded-word" or something else. + + + + + +Moore Standards Track [Page 4] + +RFC 2047 Message Header Extensions November 1996 + + + IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's + by an RFC 822 parser. As a consequence, unencoded white space + characters (such as SPACE and HTAB) are FORBIDDEN within an + 'encoded-word'. For example, the character sequence + + =?iso-8859-1?q?this is some text?= + + would be parsed as four 'atom's, rather than as a single 'atom' (by + an RFC 822 parser) or 'encoded-word' (by a parser which understands + 'encoded-words'). The correct way to encode the string "this is some + text" is to encode the SPACE characters as well, e.g. + + =?iso-8859-1?q?this=20is=20some=20text?= + + The characters which may appear in 'encoded-text' are further + restricted by the rules in section 5. + +3. Character sets + + The 'charset' portion of an 'encoded-word' specifies the character + set associated with the unencoded text. A 'charset' can be any of + the character set names allowed in an MIME "charset" parameter of a + "text/plain" body part, or any character set name registered with + IANA for use with the MIME text/plain content-type. + + Some character sets use code-switching techniques to switch between + "ASCII mode" and other modes. If unencoded text in an 'encoded-word' + contains a sequence which causes the charset interpreter to switch + out of ASCII mode, it MUST contain additional control codes such that + ASCII mode is again selected at the end of the 'encoded-word'. (This + rule applies separately to each 'encoded-word', including adjacent + 'encoded-word's within a single header field.) + + When there is a possibility of using more than one character set to + represent the text in an 'encoded-word', and in the absence of + private agreements between sender and recipients of a message, it is + recommended that members of the ISO-8859-* series be used in + preference to other character sets. + +4. Encodings + + Initially, the legal values for "encoding" are "Q" and "B". These + encodings are described below. The "Q" encoding is recommended for + use when most of the characters to be encoded are in the ASCII + character set; otherwise, the "B" encoding should be used. + Nevertheless, a mail reader which claims to recognize 'encoded-word's + MUST be able to accept either encoding for any character set which it + supports. + + + +Moore Standards Track [Page 5] + +RFC 2047 Message Header Extensions November 1996 + + + Only a subset of the printable ASCII characters may be used in + 'encoded-text'. Space and tab characters are not allowed, so that + the beginning and end of an 'encoded-word' are obvious. The "?" + character is used within an 'encoded-word' to separate the various + portions of the 'encoded-word' from one another, and thus cannot + appear in the 'encoded-text' portion. Other characters are also + illegal in certain contexts. For example, an 'encoded-word' in a + 'phrase' preceding an address in a From header field may not contain + any of the "specials" defined in RFC 822. Finally, certain other + characters are disallowed in some contexts, to ensure reliability for + messages that pass through internetwork mail gateways. + + The "B" encoding automatically meets these requirements. The "Q" + encoding allows a wide range of printable characters to be used in + non-critical locations in the message header (e.g., Subject), with + fewer characters available for use in other locations. + +4.1. The "B" encoding + + The "B" encoding is identical to the "BASE64" encoding defined by RFC + 2045. + +4.2. The "Q" encoding + + The "Q" encoding is similar to the "Quoted-Printable" content- + transfer-encoding defined in RFC 2045. It is designed to allow text + containing mostly ASCII characters to be decipherable on an ASCII + terminal without decoding. + + (1) Any 8-bit value may be represented by a "=" followed by two + hexadecimal digits. For example, if the character set in use + were ISO-8859-1, the "=" character would thus be encoded as + "=3D", and a SPACE by "=20". (Upper case should be used for + hexadecimal digits "A" through "F".) + + (2) The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) may be + represented as "_" (underscore, ASCII 95.). (This character may + not pass through some internetwork mail gateways, but its use + will greatly enhance readability of "Q" encoded data with mail + readers that do not support this encoding.) Note that the "_" + always represents hexadecimal 20, even if the SPACE character + occupies a different code position in the character set in use. + + (3) 8-bit values which correspond to printable ASCII characters other + than "=", "?", and "_" (underscore), MAY be represented as those + characters. (But see section 5 for restrictions.) In + particular, SPACE and TAB MUST NOT be represented as themselves + within encoded words. + + + +Moore Standards Track [Page 6] + +RFC 2047 Message Header Extensions November 1996 + + +5. Use of encoded-words in message headers + + An 'encoded-word' may appear in a message header or body part header + according to the following rules: + +(1) An 'encoded-word' may replace a 'text' token (as defined by RFC 822) + in any Subject or Comments header field, any extension message + header field, or any MIME body part field for which the field body + is defined as '*text'. An 'encoded-word' may also appear in any + user-defined ("X-") message or body part header field. + + Ordinary ASCII text and 'encoded-word's may appear together in the + same header field. However, an 'encoded-word' that appears in a + header field defined as '*text' MUST be separated from any adjacent + 'encoded-word' or 'text' by 'linear-white-space'. + +(2) An 'encoded-word' may appear within a 'comment' delimited by "(" and + ")", i.e., wherever a 'ctext' is allowed. More precisely, the RFC + 822 ABNF definition for 'comment' is amended as follows: + + comment = "(" *(ctext / quoted-pair / comment / encoded-word) ")" + + A "Q"-encoded 'encoded-word' which appears in a 'comment' MUST NOT + contain the characters "(", ")" or " + 'encoded-word' that appears in a 'comment' MUST be separated from + any adjacent 'encoded-word' or 'ctext' by 'linear-white-space'. + + It is important to note that 'comment's are only recognized inside + "structured" field bodies. In fields whose bodies are defined as + '*text', "(" and ")" are treated as ordinary characters rather than + comment delimiters, and rule (1) of this section applies. (See RFC + 822, sections 3.1.2 and 3.1.3) + +(3) As a replacement for a 'word' entity within a 'phrase', for example, + one that precedes an address in a From, To, or Cc header. The ABNF + definition for 'phrase' from RFC 822 thus becomes: + + phrase = 1*( encoded-word / word ) + + In this case the set of characters that may be used in a "Q"-encoded + 'encoded-word' is restricted to: . An 'encoded-word' that appears within a + 'phrase' MUST be separated from any adjacent 'word', 'text' or + 'special' by 'linear-white-space'. + + + + + + +Moore Standards Track [Page 7] + +RFC 2047 Message Header Extensions November 1996 + + + These are the ONLY locations where an 'encoded-word' may appear. In + particular: + + + An 'encoded-word' MUST NOT appear in any portion of an 'addr-spec'. + + + An 'encoded-word' MUST NOT appear within a 'quoted-string'. + + + An 'encoded-word' MUST NOT be used in a Received header field. + + + An 'encoded-word' MUST NOT be used in parameter of a MIME + Content-Type or Content-Disposition field, or in any structured + field body except within a 'comment' or 'phrase'. + + The 'encoded-text' in an 'encoded-word' must be self-contained; + 'encoded-text' MUST NOT be continued from one 'encoded-word' to + another. This implies that the 'encoded-text' portion of a "B" + 'encoded-word' will be a multiple of 4 characters long; for a "Q" + 'encoded-word', any "=" character that appears in the 'encoded-text' + portion will be followed by two hexadecimal characters. + + Each 'encoded-word' MUST encode an integral number of octets. The + 'encoded-text' in each 'encoded-word' must be well-formed according + to the encoding specified; the 'encoded-text' may not be continued in + the next 'encoded-word'. (For example, "=?charset?Q?=?= + =?charset?Q?AB?=" would be illegal, because the two hex digits "AB" + must follow the "=" in the same 'encoded-word'.) + + Each 'encoded-word' MUST represent an integral number of characters. + A multi-octet character may not be split across adjacent 'encoded- + word's. + + Only printable and white space character data should be encoded using + this scheme. However, since these encoding schemes allow the + encoding of arbitrary octet values, mail readers that implement this + decoding should also ensure that display of the decoded data on the + recipient's terminal will not cause unwanted side-effects. + + Use of these methods to encode non-textual data (e.g., pictures or + sounds) is not defined by this memo. Use of 'encoded-word's to + represent strings of purely ASCII characters is allowed, but + discouraged. In rare cases it may be necessary to encode ordinary + text that looks like an 'encoded-word'. + + + + + + + + + +Moore Standards Track [Page 8] + +RFC 2047 Message Header Extensions November 1996 + + +6. Support of 'encoded-word's by mail readers + +6.1. Recognition of 'encoded-word's in message headers + + A mail reader must parse the message and body part headers according + to the rules in RFC 822 to correctly recognize 'encoded-word's. + + 'encoded-word's are to be recognized as follows: + + (1) Any message or body part header field defined as '*text', or any + user-defined header field, should be parsed as follows: Beginning + at the start of the field-body and immediately following each + occurrence of 'linear-white-space', each sequence of up to 75 + printable characters (not containing any 'linear-white-space') + should be examined to see if it is an 'encoded-word' according to + the syntax rules in section 2. Any other sequence of printable + characters should be treated as ordinary ASCII text. + + (2) Any header field not defined as '*text' should be parsed + according to the syntax rules for that header field. However, + any 'word' that appears within a 'phrase' should be treated as an + 'encoded-word' if it meets the syntax rules in section 2. + Otherwise it should be treated as an ordinary 'word'. + + (3) Within a 'comment', any sequence of up to 75 printable characters + (not containing 'linear-white-space'), that meets the syntax + rules in section 2, should be treated as an 'encoded-word'. + Otherwise it should be treated as normal comment text. + + (4) A MIME-Version header field is NOT required to be present for + 'encoded-word's to be interpreted according to this + specification. One reason for this is that the mail reader is + not expected to parse the entire message header before displaying + lines that may contain 'encoded-word's. + +6.2. Display of 'encoded-word's + + Any 'encoded-word's so recognized are decoded, and if possible, the + resulting unencoded text is displayed in the original character set. + + NOTE: Decoding and display of encoded-words occurs *after* a + structured field body is parsed into tokens. It is therefore + possible to hide 'special' characters in encoded-words which, when + displayed, will be indistinguishable from 'special' characters in the + surrounding text. For this and other reasons, it is NOT generally + possible to translate a message header containing 'encoded-word's to + an unencoded form which can be parsed by an RFC 822 mail reader. + + + + +Moore Standards Track [Page 9] + +RFC 2047 Message Header Extensions November 1996 + + + When displaying a particular header field that contains multiple + 'encoded-word's, any 'linear-white-space' that separates a pair of + adjacent 'encoded-word's is ignored. (This is to allow the use of + multiple 'encoded-word's to represent long strings of unencoded text, + without having to separate 'encoded-word's where spaces occur in the + unencoded text.) + + In the event other encodings are defined in the future, and the mail + reader does not support the encoding used, it may either (a) display + the 'encoded-word' as ordinary text, or (b) substitute an appropriate + message indicating that the text could not be decoded. + + If the mail reader does not support the character set used, it may + (a) display the 'encoded-word' as ordinary text (i.e., as it appears + in the header), (b) make a "best effort" to display using such + characters as are available, or (c) substitute an appropriate message + indicating that the decoded text could not be displayed. + + If the character set being used employs code-switching techniques, + display of the encoded text implicitly begins in "ASCII mode". In + addition, the mail reader must ensure that the output device is once + again in "ASCII mode" after the 'encoded-word' is displayed. + +6.3. Mail reader handling of incorrectly formed 'encoded-word's + + It is possible that an 'encoded-word' that is legal according to the + syntax defined in section 2, is incorrectly formed according to the + rules for the encoding being used. For example: + + (1) An 'encoded-word' which contains characters which are not legal + for a particular encoding (for example, a "-" in the "B" + encoding, or a SPACE or HTAB in either the "B" or "Q" encoding), + is incorrectly formed. + + (2) Any 'encoded-word' which encodes a non-integral number of + characters or octets is incorrectly formed. + + A mail reader need not attempt to display the text associated with an + 'encoded-word' that is incorrectly formed. However, a mail reader + MUST NOT prevent the display or handling of a message because an + 'encoded-word' is incorrectly formed. + +7. Conformance + + A mail composing program claiming compliance with this specification + MUST ensure that any string of non-white-space printable ASCII + characters within a '*text' or '*ctext' that begins with "=?" and + ends with "?=" be a valid 'encoded-word'. ("begins" means: at the + + + +Moore Standards Track [Page 10] + +RFC 2047 Message Header Extensions November 1996 + + + start of the field-body, immediately following 'linear-white-space', + or immediately following a "(" for an 'encoded-word' within '*ctext'; + "ends" means: at the end of the field-body, immediately preceding + 'linear-white-space', or immediately preceding a ")" for an + 'encoded-word' within '*ctext'.) In addition, any 'word' within a + 'phrase' that begins with "=?" and ends with "?=" must be a valid + 'encoded-word'. + + A mail reading program claiming compliance with this specification + must be able to distinguish 'encoded-word's from 'text', 'ctext', or + 'word's, according to the rules in section 6, anytime they appear in + appropriate places in message headers. It must support both the "B" + and "Q" encodings for any character set which it supports. The + program must be able to display the unencoded text if the character + set is "US-ASCII". For the ISO-8859-* character sets, the mail + reading program must at least be able to display the characters which + are also in the ASCII set. + +8. Examples + + The following are examples of message headers containing 'encoded- + word's: + + From: =?US-ASCII?Q?Keith_Moore?= + To: =?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= + CC: =?ISO-8859-1?Q?Andr=E9?= Pirard + Subject: =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?= + =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?= + + Note: In the first 'encoded-word' of the Subject field above, the + last "=" at the end of the 'encoded-text' is necessary because each + 'encoded-word' must be self-contained (the "=" character completes a + group of 4 base64 characters representing 2 octets). An additional + octet could have been encoded in the first 'encoded-word' (so that + the encoded-word would contain an exact multiple of 3 encoded + octets), except that the second 'encoded-word' uses a different + 'charset' than the first one. + + From: =?ISO-8859-1?Q?Olle_J=E4rnefors?= + To: ietf-822@dimacs.rutgers.edu, ojarnef@admin.kth.se + Subject: Time for ISO 10646? + + To: Dave Crocker + Cc: ietf-822@dimacs.rutgers.edu, paf@comsol.se + From: =?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?= + Subject: Re: RFC-HDR care and feeding + + + + + +Moore Standards Track [Page 11] + +RFC 2047 Message Header Extensions November 1996 + + + From: Nathaniel Borenstein + (=?iso-8859-8?b?7eXs+SDv4SDp7Oj08A==?=) + To: Greg Vaudreuil , Ned Freed + , Keith Moore + Subject: Test of new header generator + MIME-Version: 1.0 + Content-type: text/plain; charset=ISO-8859-1 + + The following examples illustrate how text containing 'encoded-word's + which appear in a structured field body. The rules are slightly + different for fields defined as '*text' because "(" and ")" are not + recognized as 'comment' delimiters. [Section 5, paragraph (1)]. + + In each of the following examples, if the same sequence were to occur + in a '*text' field, the "displayed as" form would NOT be treated as + encoded words, but be identical to the "encoded form". This is + because each of the encoded-words in the following examples is + adjacent to a "(" or ")" character. + + encoded form displayed as + --------------------------------------------------------------------- + (=?ISO-8859-1?Q?a?=) (a) + + (=?ISO-8859-1?Q?a?= b) (a b) + + Within a 'comment', white space MUST appear between an + 'encoded-word' and surrounding text. [Section 5, + paragraph (2)]. However, white space is not needed between + the initial "(" that begins the 'comment', and the + 'encoded-word'. + + + (=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=) (ab) + + White space between adjacent 'encoded-word's is not + displayed. + + (=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=) (ab) + + Even multiple SPACEs between 'encoded-word's are ignored + for the purpose of display. + + (=?ISO-8859-1?Q?a?= (ab) + =?ISO-8859-1?Q?b?=) + + Any amount of linear-space-white between 'encoded-word's, + even if it includes a CRLF followed by one or more SPACEs, + is ignored for the purposes of display. + + + +Moore Standards Track [Page 12] + +RFC 2047 Message Header Extensions November 1996 + + + (=?ISO-8859-1?Q?a_b?=) (a b) + + In order to cause a SPACE to be displayed within a portion + of encoded text, the SPACE MUST be encoded as part of the + 'encoded-word'. + + (=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=) (a b) + + In order to cause a SPACE to be displayed between two strings + of encoded text, the SPACE MAY be encoded as part of one of + the 'encoded-word's. + +9. References + + [RFC 822] Crocker, D., "Standard for the Format of ARPA Internet Text + Messages", STD 11, RFC 822, UDEL, August 1982. + + [RFC 2049] Borenstein, N., and N. Freed, "Multipurpose Internet Mail + Extensions (MIME) Part Five: Conformance Criteria and Examples", + RFC 2049, November 1996. + + [RFC 2045] Borenstein, N., and N. Freed, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message Bodies", + RFC 2045, November 1996. + + [RFC 2046] Borenstein N., and N. Freed, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + November 1996. + + [RFC 2048] Freed, N., Klensin, J., and J. Postel, "Multipurpose + Internet Mail Extensions (MIME) Part Four: Registration + Procedures", RFC 2048, November 1996. + + + + + + + + + + + + + + + + + + + +Moore Standards Track [Page 13] + +RFC 2047 Message Header Extensions November 1996 + + +10. Security Considerations + + Security issues are not discussed in this memo. + +11. Acknowledgements + + The author wishes to thank Nathaniel Borenstein, Issac Chan, Lutz + Donnerhacke, Paul Eggert, Ned Freed, Andreas M. Kirchwitz, Olle + Jarnefors, Mike Rosin, Yutaka Sato, Bart Schaefer, and Kazuhiko + Yamamoto, for their helpful advice, insightful comments, and + illuminating questions in response to earlier versions of this + specification. + +12. Author's Address + + Keith Moore + University of Tennessee + 107 Ayres Hall + Knoxville TN 37996-1301 + + EMail: moore@cs.utk.edu + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Moore Standards Track [Page 14] + +RFC 2047 Message Header Extensions November 1996 + + +Appendix - changes since RFC 1522 (in no particular order) + + + explicitly state that the MIME-Version is not requried to use + 'encoded-word's. + + + add explicit note that SPACEs and TABs are not allowed within + 'encoded-word's, explaining that an 'encoded-word' must look like an + 'atom' to an RFC822 parser.values, to be precise). + + + add examples from Olle Jarnefors (thanks!) which illustrate how + encoded-words with adjacent linear-white-space are displayed. + + + explicitly list terms defined in RFC822 and referenced in this memo + + + fix transcription typos that caused one or two lines and a couple of + characters to disappear in the resulting text, due to nroff quirks. + + + clarify that encoded-words are allowed in '*text' fields in both + RFC822 headers and MIME body part headers, but NOT as parameter + values. + + + clarify the requirement to switch back to ASCII within the encoded + portion of an 'encoded-word', for any charset that uses code switching + sequences. + + + add a note about 'encoded-word's being delimited by "(" and ")" + within a comment, but not in a *text (how bizarre!). + + + fix the Andre Pirard example to get rid of the trailing "_" after + the =E9. (no longer needed post-1342). + + + clarification: an 'encoded-word' may appear immediately following + the initial "(" or immediately before the final ")" that delimits a + comment, not just adjacent to "(" and ")" *within* *ctext. + + + add a note to explain that a "B" 'encoded-word' will always have a + multiple of 4 characters in the 'encoded-text' portion. + + + add note about the "=" in the examples + + + note that processing of 'encoded-word's occurs *after* parsing, and + some of the implications thereof. + + + explicitly state that you can't expect to translate between + 1522 and either vanilla 822 or so-called "8-bit headers". + + + explicitly state that 'encoded-word's are not valid within a + 'quoted-string'. + + + +Moore Standards Track [Page 15] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2048.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2048.txt new file mode 100644 index 00000000..a3b18b31 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2048.txt @@ -0,0 +1,1180 @@ + + + + + + +Network Working Group N. Freed +Request for Comments: 2048 Innosoft +BCP: 13 J. Klensin +Obsoletes: 1521, 1522, 1590 MCI +Category: Best Current Practice J. Postel + ISI + November 1996 + + + Multipurpose Internet Mail Extensions + (MIME) Part Four: + Registration Procedures + +Status of this Memo + + This document specifies an Internet Best Current Practices for the + Internet Community, and requests discussion and suggestions for + improvements. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822, defines a message representation protocol specifying + considerable detail about US-ASCII message headers, and leaves the + message content, or message body, as flat US-ASCII text. This set of + documents, collectively called the Multipurpose Internet Mail + Extensions, or MIME, redefines the format of messages to allow for + + (1) textual message bodies in character sets other than + US-ASCII, + + (2) an extensible set of different formats for non-textual + message bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than + US-ASCII. + + These documents are based on earlier work documented in RFC 934, STD + 11, and RFC 1049, but extends and revises them. Because RFC 822 said + so little about message bodies, these documents are largely + orthogonal to (rather than a revision of) RFC 822. + + + + + + + + + +Freed, et. al. Best Current Practice [Page 1] + +RFC 2048 MIME Registration Procedures November 1996 + + + This fourth document, RFC 2048, specifies various IANA registration + procedures for the following MIME facilities: + + (1) media types, + + (2) external body access types, + + (3) content-transfer-encodings. + + Registration of character sets for use in MIME is covered elsewhere + and is no longer addressed by this document. + + These documents are revisions of RFCs 1521 and 1522, which themselves + were revisions of RFCs 1341 and 1342. An appendix in RFC 2049 + describes differences and changes from previous versions. + +Table of Contents + + 1. Introduction ......................................... 3 + 2. Media Type Registration .............................. 4 + 2.1 Registration Trees and Subtype Names ................ 4 + 2.1.1 IETF Tree ......................................... 4 + 2.1.2 Vendor Tree ....................................... 4 + 2.1.3 Personal or Vanity Tree ........................... 5 + 2.1.4 Special `x.' Tree ................................. 5 + 2.1.5 Additional Registration Trees ..................... 6 + 2.2 Registration Requirements ........................... 6 + 2.2.1 Functionality Requirement ......................... 6 + 2.2.2 Naming Requirements ............................... 6 + 2.2.3 Parameter Requirements ............................ 7 + 2.2.4 Canonicalization and Format Requirements .......... 7 + 2.2.5 Interchange Recommendations ....................... 8 + 2.2.6 Security Requirements ............................. 8 + 2.2.7 Usage and Implementation Non-requirements ......... 9 + 2.2.8 Publication Requirements .......................... 10 + 2.2.9 Additional Information ............................ 10 + 2.3 Registration Procedure .............................. 11 + 2.3.1 Present the Media Type to the Community for Review 11 + 2.3.2 IESG Approval ..................................... 12 + 2.3.3 IANA Registration ................................. 12 + 2.4 Comments on Media Type Registrations ................ 12 + 2.5 Location of Registered Media Type List .............. 12 + 2.6 IANA Procedures for Registering Media Types ......... 12 + 2.7 Change Control ...................................... 13 + 2.8 Registration Template ............................... 14 + 3. External Body Access Types ........................... 14 + 3.1 Registration Requirements ........................... 15 + 3.1.1 Naming Requirements ............................... 15 + + + +Freed, et. al. Best Current Practice [Page 2] + +RFC 2048 MIME Registration Procedures November 1996 + + + 3.1.2 Mechanism Specification Requirements .............. 15 + 3.1.3 Publication Requirements .......................... 15 + 3.1.4 Security Requirements ............................. 15 + 3.2 Registration Procedure .............................. 15 + 3.2.1 Present the Access Type to the Community .......... 16 + 3.2.2 Access Type Reviewer .............................. 16 + 3.2.3 IANA Registration ................................. 16 + 3.3 Location of Registered Access Type List ............. 16 + 3.4 IANA Procedures for Registering Access Types ........ 16 + 4. Transfer Encodings ................................... 17 + 4.1 Transfer Encoding Requirements ...................... 17 + 4.1.1 Naming Requirements ............................... 17 + 4.1.2 Algorithm Specification Requirements .............. 18 + 4.1.3 Input Domain Requirements ......................... 18 + 4.1.4 Output Range Requirements ......................... 18 + 4.1.5 Data Integrity and Generality Requirements ........ 18 + 4.1.6 New Functionality Requirements .................... 18 + 4.2 Transfer Encoding Definition Procedure .............. 19 + 4.3 IANA Procedures for Transfer Encoding Registration... 19 + 4.4 Location of Registered Transfer Encodings List ...... 19 + 5. Authors' Addresses ................................... 20 + A. Grandfathered Media Types ............................ 21 + +1. Introduction + + Recent Internet protocols have been carefully designed to be easily + extensible in certain areas. In particular, MIME [RFC 2045] is an + open-ended framework and can accommodate additional object types, + character sets, and access methods without any changes to the basic + protocol. A registration process is needed, however, to ensure that + the set of such values is developed in an orderly, well-specified, + and public manner. + + This document defines registration procedures which use the Internet + Assigned Numbers Authority (IANA) as a central registry for such + values. + + Historical Note: The registration process for media types was + initially defined in the context of the asynchronous Internet mail + environment. In this mail environment there is a need to limit the + number of possible media types to increase the likelihood of + interoperability when the capabilities of the remote mail system are + not known. As media types are used in new environments, where the + proliferation of media types is not a hindrance to interoperability, + the original procedure was excessively restrictive and had to be + generalized. + + + + + +Freed, et. al. Best Current Practice [Page 3] + +RFC 2048 MIME Registration Procedures November 1996 + + +2. Media Type Registration + + Registration of a new media type or types starts with the + construction of a registration proposal. Registration may occur in + several different registration trees, which have different + requirements as discussed below. In general, the new registration + proposal is circulated and reviewed in a fashion appropriate to the + tree involved. The media type is then registered if the proposal is + acceptable. The following sections describe the requirements and + procedures used for each of the different registration trees. + +2.1. Registration Trees and Subtype Names + + In order to increase the efficiency and flexibility of the + registration process, different structures of subtype names may be + registered to accomodate the different natural requirements for, + e.g., a subtype that will be recommended for wide support and + implementation by the Internet Community or a subtype that is used to + move files associated with proprietary software. The following + subsections define registration "trees", distinguished by the use of + faceted names (e.g., names of the form "tree.subtree...type"). Note + that some media types defined prior to this document do not conform + to the naming conventions described below. See Appendix A for a + discussion of them. + +2.1.1. IETF Tree + + The IETF tree is intended for types of general interest to the + Internet Community. Registration in the IETF tree requires approval + by the IESG and publication of the media type registration as some + form of RFC. + + Media types in the IETF tree are normally denoted by names that are + not explicitly faceted, i.e., do not contain period (".", full stop) + characters. + + The "owner" of a media type registration in the IETF tree is assumed + to be the IETF itself. Modification or alteration of the + specification requires the same level of processing (e.g. standards + track) required for the initial registration. + +2.1.2. Vendor Tree + + The vendor tree is used for media types associated with commercially + available products. "Vendor" or "producer" are construed as + equivalent and very broadly in this context. + + + + + +Freed, et. al. Best Current Practice [Page 4] + +RFC 2048 MIME Registration Procedures November 1996 + + + A registration may be placed in the vendor tree by anyone who has + need to interchange files associated with the particular product. + However, the registration formally belongs to the vendor or + organization producing the software or file format. Changes to the + specification will be made at their request, as discussed in + subsequent sections. + + Registrations in the vendor tree will be distinguished by the leading + facet "vnd.". That may be followed, at the discretion of the + registration, by either a media type name from a well-known producer + (e.g., "vnd.mudpie") or by an IANA-approved designation of the + producer's name which is then followed by a media type or product + designation (e.g., vnd.bigcompany.funnypictures). + + While public exposure and review of media types to be registered in + the vendor tree is not required, using the ietf-types list for review + is strongly encouraged to improve the quality of those + specifications. Registrations in the vendor tree may be submitted + directly to the IANA. + +2.1.3. Personal or Vanity Tree + + Registrations for media types created experimentally or as part of + products that are not distributed commercially may be registered in + the personal or vanity tree. The registrations are distinguished by + the leading facet "prs.". + + The owner of "personal" registrations and associated specifications + is the person or entity making the registration, or one to whom + responsibility has been transferred as described below. + + While public exposure and review of media types to be registered in + the personal tree is not required, using the ietf-types list for + review is strongly encouraged to improve the quality of those + specifications. Registrations in the personl tree may be submitted + directly to the IANA. + +2.1.4. Special `x.' Tree + + For convenience and symmetry with this registration scheme, media + type names with "x." as the first facet may be used for the same + purposes for which names starting in "x-" are normally used. These + types are unregistered, experimental, and should be used only with + the active agreement of the parties exchanging them. + + + + + + + +Freed, et. al. Best Current Practice [Page 5] + +RFC 2048 MIME Registration Procedures November 1996 + + + However, with the simplified registration procedures described above + for vendor and personal trees, it should rarely, if ever, be + necessary to use unregistered experimental types, and as such use of + both "x-" and "x." forms is discouraged. + +2.1.5. Additional Registration Trees + + From time to time and as required by the community, the IANA may, + with the advice and consent of the IESG, create new top-level + registration trees. It is explicitly assumed that these trees may be + created for external registration and management by well-known + permanent bodies, such as scientific societies for media types + specific to the sciences they cover. In general, the quality of + review of specifications for one of these additional registration + trees is expected to be equivalent to that which IETF would give to + registrations in its own tree. Establishment of these new trees will + be announced through RFC publication approved by the IESG. + +2.2. Registration Requirements + + Media type registration proposals are all expected to conform to + various requirements laid out in the following sections. Note that + requirement specifics sometimes vary depending on the registration + tree, again as detailed in the following sections. + +2.2.1. Functionality Requirement + + Media types must function as an actual media format: Registration of + things that are better thought of as a transfer encoding, as a + character set, or as a collection of separate entities of another + type, is not allowed. For example, although applications exist to + decode the base64 transfer encoding [RFC 2045], base64 cannot be + registered as a media type. + + This requirement applies regardless of the registration tree + involved. + +2.2.2. Naming Requirements + + All registered media types must be assigned MIME type and subtype + names. The combination of these names then serves to uniquely + identify the media type and the format of the subtype name identifies + the registration tree. + + The choice of top-level type name must take the nature of media type + involved into account. For example, media normally used for + representing still images should be a subtype of the image content + type, whereas media capable of representing audio information belongs + + + +Freed, et. al. Best Current Practice [Page 6] + +RFC 2048 MIME Registration Procedures November 1996 + + + under the audio content type. See RFC 2046 for additional information + on the basic set of top-level types and their characteristics. + + New subtypes of top-level types must conform to the restrictions of + the top-level type, if any. For example, all subtypes of the + multipart content type must use the same encapsulation syntax. + + In some cases a new media type may not "fit" under any currently + defined top-level content type. Such cases are expected to be quite + rare. However, if such a case arises a new top-level type can be + defined to accommodate it. Such a definition must be done via + standards-track RFC; no other mechanism can be used to define + additional top-level content types. + + These requirements apply regardless of the registration tree + involved. + +2.2.3. Parameter Requirements + + Media types may elect to use one or more MIME content type + parameters, or some parameters may be automatically made available to + the media type by virtue of being a subtype of a content type that + defines a set of parameters applicable to any of its subtypes. In + either case, the names, values, and meanings of any parameters must + be fully specified when a media type is registered in the IETF tree, + and should be specified as completely as possible when media types + are registered in the vendor or personal trees. + + New parameters must not be defined as a way to introduce new + functionality in types registered in the IETF tree, although new + parameters may be added to convey additional information that does + not otherwise change existing functionality. An example of this + would be a "revision" parameter to indicate a revision level of an + external specification such as JPEG. Similar behavior is encouraged + for media types registered in the vendor or personal trees but is not + required. + +2.2.4. Canonicalization and Format Requirements + + All registered media types must employ a single, canonical data + format, regardless of registration tree. + + A precise and openly available specification of the format of each + media type is required for all types registered in the IETF tree and + must at a minimum be referenced by, if it isn't actually included in, + the media type registration proposal itself. + + + + + +Freed, et. al. Best Current Practice [Page 7] + +RFC 2048 MIME Registration Procedures November 1996 + + + The specifications of format and processing particulars may or may + not be publically available for media types registered in the vendor + tree, and such registration proposals are explicitly permitted to + include only a specification of which software and version produce or + process such media types. References to or inclusion of format + specifications in registration proposals is encouraged but not + required. + + Format specifications are still required for registration in the + personal tree, but may be either published as RFCs or otherwise + deposited with IANA. The deposited specifications will meet the same + criteria as those required to register a well-known TCP port and, in + particular, need not be made public. + + Some media types involve the use of patented technology. The + registration of media types involving patented technology is + specifically permitted. However, the restrictions set forth in RFC + 1602 on the use of patented technology in standards-track protocols + must be respected when the specification of a media type is part of a + standards-track protocol. + +2.2.5. Interchange Recommendations + + Media types should, whenever possible, interoperate across as many + systems and applications as possible. However, some media types will + inevitably have problems interoperating across different platforms. + Problems with different versions, byte ordering, and specifics of + gateway handling can and will arise. + + Universal interoperability of media types is not required, but known + interoperability issues should be identified whenever possible. + Publication of a media type does not require an exhaustive review of + interoperability, and the interoperability considerations section is + subject to continuing evaluation. + + These recommendations apply regardless of the registration tree + involved. + +2.2.6. Security Requirements + + An analysis of security issues is required for for all types + registered in the IETF Tree. (This is in accordance with the basic + requirements for all IETF protocols.) A similar analysis for media + types registered in the vendor or personal trees is encouraged but + not required. However, regardless of what security analysis has or + has not been done, all descriptions of security issues must be as + accurate as possible regardless of registration tree. In particular, + a statement that there are "no security issues associated with this + + + +Freed, et. al. Best Current Practice [Page 8] + +RFC 2048 MIME Registration Procedures November 1996 + + + type" must not be confused with "the security issues associates with + this type have not been assessed". + + There is absolutely no requirement that media types registered in any + tree be secure or completely free from risks. Nevertheless, all + known security risks must be identified in the registration of a + media type, again regardless of registration tree. + + The security considerations section of all registrations is subject + to continuing evaluation and modification, and in particular may be + extended by use of the "comments on media types" mechanism described + in subsequent sections. + + Some of the issues that should be looked at in a security analysis of + a media type are: + + (1) Complex media types may include provisions for + directives that institute actions on a recipient's + files or other resources. In many cases provision is + made for originators to specify arbitrary actions in an + unrestricted fashion which may then have devastating + effects. See the registration of the + application/postscript media type in RFC 2046 for + an example of such directives and how to handle them. + + (2) Complex media types may include provisions for + directives that institute actions which, while not + directly harmful to the recipient, may result in + disclosure of information that either facilitates a + subsequent attack or else violates a recipient's + privacy in some way. Again, the registration of the + application/postscript media type illustrates how such + directives can be handled. + + (3) A media type might be targeted for applications that + require some sort of security assurance but not provide + the necessary security mechanisms themselves. For + example, a media type could be defined for storage of + confidential medical information which in turn requires + an external confidentiality service. + +2.2.7. Usage and Implementation Non-requirements + + In the asynchronous mail environment, where information on the + capabilities of the remote mail agent is frequently not available to + the sender, maximum interoperability is attained by restricting the + number of media types used to those "common" formats expected to be + widely implemented. This was asserted in the past as a reason to + + + +Freed, et. al. Best Current Practice [Page 9] + +RFC 2048 MIME Registration Procedures November 1996 + + + limit the number of possible media types and resulted in a + registration process with a significant hurdle and delay for those + registering media types. + + However, the need for "common" media types does not require limiting + the registration of new media types. If a limited set of media types + is recommended for a particular application, that should be asserted + by a separate applicability statement specific for the application + and/or environment. + + As such, universal support and implementation of a media type is NOT + a requirement for registration. If, however, a media type is + explicitly intended for limited use, this should be noted in its + registration. + +2.2.8. Publication Requirements + + Proposals for media types registered in the IETF tree must be + published as RFCs. RFC publication of vendor and personal media type + proposals is encouraged but not required. In all cases IANA will + retain copies of all media type proposals and "publish" them as part + of the media types registration tree itself. + + Other than in the IETF tree, the registration of a data type does not + imply endorsement, approval, or recommendation by IANA or IETF or + even certification that the specification is adequate. To become + Internet Standards, protocol, data objects, or whatever must go + through the IETF standards process. This is too difficult and too + lengthy a process for the convenient registration of media types. + + The IETF tree exists for media types that do require require a + substantive review and approval process with the vendor and personal + trees exist for those that do not. It is expected that applicability + statements for particular applications will be published from time to + time that recommend implementation of, and support for, media types + that have proven particularly useful in those contexts. + + As discussed above, registration of a top-level type requires + standards-track processing and, hence, RFC publication. + +2.2.9. Additional Information + + Various sorts of optional information may be included in the + specification of a media type if it is available: + + (1) Magic number(s) (length, octet values). Magic numbers + are byte sequences that are always present and thus can + be used to identify entities as being of a given media + + + +Freed, et. al. Best Current Practice [Page 10] + +RFC 2048 MIME Registration Procedures November 1996 + + + type. + + (2) File extension(s) commonly used on one or more + platforms to indicate that some file containing a given + type of media. + + (3) Macintosh File Type code(s) (4 octets) used to label + files containing a given type of media. + + Such information is often quite useful to implementors and if + available should be provided. + +2.3. Registration Procedure + + The following procedure has been implemented by the IANA for review + and approval of new media types. This is not a formal standards + process, but rather an administrative procedure intended to allow + community comment and sanity checking without excessive time delay. + For registration in the IETF tree, the normal IETF processes should + be followed, treating posting of an internet-draft and announcement + on the ietf-types list (as described in the next subsection) as a + first step. For registrations in the vendor or personal tree, the + initial review step described below may be omitted and the type + registered directly by submitting the template and an explanation + directly to IANA (at iana@iana.org). However, authors of vendor or + personal media type specifications are encouraged to seek community + review and comment whenever that is feasible. + +2.3.1. Present the Media Type to the Community for Review + + Send a proposed media type registration to the "ietf-types@iana.org" + mailing list for a two week review period. This mailing list has + been established for the purpose of reviewing proposed media and + access types. Proposed media types are not formally registered and + must not be used; the "x-" prefix specified in RFC 2045 can be used + until registration is complete. + + The intent of the public posting is to solicit comments and feedback + on the choice of type/subtype name, the unambiguity of the references + with respect to versions and external profiling information, and a + review of any interoperability or security considerations. The + submitter may submit a revised registration, or withdraw the + registration completely, at any time. + + + + + + + + +Freed, et. al. Best Current Practice [Page 11] + +RFC 2048 MIME Registration Procedures November 1996 + + +2.3.2. IESG Approval + + Media types registered in the IETF tree must be submitted to the IESG + for approval. + +2.3.3. IANA Registration + + Provided that the media type meets the requirements for media types + and has obtained approval that is necessary, the author may submit + the registration request to the IANA, which will register the media + type and make the media type registration available to the community. + +2.4. Comments on Media Type Registrations + + Comments on registered media types may be submitted by members of the + community to IANA. These comments will be passed on to the "owner" + of the media type if possible. Submitters of comments may request + that their comment be attached to the media type registration itself, + and if IANA approves of this the comment will be made accessible in + conjunction with the type registration itself. + +2.5. Location of Registered Media Type List + + Media type registrations will be posted in the anonymous FTP + directory "ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/" + and all registered media types will be listed in the periodically + issued "Assigned Numbers" RFC [currently STD 2, RFC 1700]. The media + type description and other supporting material may also be published + as an Informational RFC by sending it to "rfc-editor@isi.edu" (please + follow the instructions to RFC authors [RFC-1543]). + +2.6. IANA Procedures for Registering Media Types + + The IANA will only register media types in the IETF tree in response + to a communication from the IESG stating that a given registration + has been approved. Vendor and personal types will be registered by + the IANA automatically and without any formal review as long as the + following minimal conditions are met: + + (1) Media types must function as an actual media format. + In particular, character sets and transfer encodings + may not be registered as media types. + + (2) All media types must have properly formed type and + subtype names. All type names must be defined by a + standards-track RFC. All subtype names must be unique, + must conform to the MIME grammar for such names, and + must contain the proper tree prefix. + + + +Freed, et. al. Best Current Practice [Page 12] + +RFC 2048 MIME Registration Procedures November 1996 + + + (3) Types registered in the personal tree must either + provide a format specification or a pointer to one. + + (4) Any security considerations given must not be obviously + bogus. (It is neither possible nor necessary for the + IANA to conduct a comprehensive security review of + media type registrations. Nevertheless, IANA has the + authority to identify obviously incompetent material + and exclude it.) + +2.7. Change Control + + Once a media type has been published by IANA, the author may request + a change to its definition. The descriptions of the different + registration trees above designate the "owners" of each type of + registration. The change request follows the same procedure as the + registration request: + + (1) Publish the revised template on the ietf-types list. + + (2) Leave at least two weeks for comments. + + (3) Publish using IANA after formal review if required. + + Changes should be requested only when there are serious omission or + errors in the published specification. When review is required, a + change request may be denied if it renders entities that were valid + under the previous definition invalid under the new definition. + + The owner of a content type may pass responsibility for the content + type to another person or agency by informing IANA and the ietf-types + list; this can be done without discussion or review. + + The IESG may reassign responsibility for a media type. The most + common case of this will be to enable changes to be made to types + where the author of the registration has died, moved out of contact + or is otherwise unable to make changes that are important to the + community. + + Media type registrations may not be deleted; media types which are no + longer believed appropriate for use can be declared OBSOLETE by a + change to their "intended use" field; such media types will be + clearly marked in the lists published by IANA. + + + + + + + + +Freed, et. al. Best Current Practice [Page 13] + +RFC 2048 MIME Registration Procedures November 1996 + + +2.8. Registration Template + + To: ietf-types@iana.org + Subject: Registration of MIME media type XXX/YYY + + MIME media type name: + + MIME subtype name: + + Required parameters: + + Optional parameters: + + Encoding considerations: + + Security considerations: + + Interoperability considerations: + + Published specification: + + Applications which use this media type: + + Additional information: + + Magic number(s): + File extension(s): + Macintosh File Type Code(s): + + Person & email address to contact for further information: + + Intended usage: + + (One of COMMON, LIMITED USE or OBSOLETE) + + Author/Change controller: + + (Any other information that the author deems interesting may be + added below this line.) + +3. External Body Access Types + + RFC 2046 defines the message/external-body media type, whereby a MIME + entity can act as pointer to the actual body data in lieu of + including the data directly in the entity body. Each + message/external-body reference specifies an access type, which + determines the mechanism used to retrieve the actual body data. RFC + 2046 defines an initial set of access types, but allows for the + + + +Freed, et. al. Best Current Practice [Page 14] + +RFC 2048 MIME Registration Procedures November 1996 + + + registration of additional access types to accommodate new retrieval + mechanisms. + +3.1. Registration Requirements + + New access type specifications must conform to a number of + requirements as described below. + +3.1.1. Naming Requirements + + Each access type must have a unique name. This name appears in the + access-type parameter in the message/external-body content-type + header field, and must conform to MIME content type parameter syntax. + +3.1.2. Mechanism Specification Requirements + + All of the protocols, transports, and procedures used by a given + access type must be described, either in the specification of the + access type itself or in some other publicly available specification, + in sufficient detail for the access type to be implemented by any + competent implementor. Use of secret and/or proprietary methods in + access types are expressly prohibited. The restrictions imposed by + RFC 1602 on the standardization of patented algorithms must be + respected as well. + +3.1.3. Publication Requirements + + All access types must be described by an RFC. The RFC may be + informational rather than standards-track, although standard-track + review and approval are encouraged for all access types. + +3.1.4. Security Requirements + + Any known security issues that arise from the use of the access type + must be completely and fully described. It is not required that the + access type be secure or that it be free from risks, but that the + known risks be identified. Publication of a new access type does not + require an exhaustive security review, and the security + considerations section is subject to continuing evaluation. + Additional security considerations should be addressed by publishing + revised versions of the access type specification. + +3.2. Registration Procedure + + Registration of a new access type starts with the construction of a + draft of an RFC. + + + + + +Freed, et. al. Best Current Practice [Page 15] + +RFC 2048 MIME Registration Procedures November 1996 + + +3.2.1. Present the Access Type to the Community + + Send a proposed access type specification to the "ietf- + types@iana.org" mailing list for a two week review period. This + mailing list has been established for the purpose of reviewing + proposed access and media types. Proposed access types are not + formally registered and must not be used. + + The intent of the public posting is to solicit comments and feedback + on the access type specification and a review of any security + considerations. + +3.2.2. Access Type Reviewer + + When the two week period has passed, the access type reviewer, who is + appointed by the IETF Applications Area Director, either forwards the + request to iana@isi.edu, or rejects it because of significant + objections raised on the list. + + Decisions made by the reviewer must be posted to the ietf-types + mailing list within 14 days. Decisions made by the reviewer may be + appealed to the IESG. + +3.2.3. IANA Registration + + Provided that the access type has either passed review or has been + successfully appealed to the IESG, the IANA will register the access + type and make the registration available to the community. The + specification of the access type must also be published as an RFC. + Informational RFCs are published by sending them to "rfc- + editor@isi.edu" (please follow the instructions to RFC authors [RFC- + 1543]). + +3.3. Location of Registered Access Type List + + Access type registrations will be posted in the anonymous FTP + directory "ftp://ftp.isi.edu/in-notes/iana/assignments/access-types/" + and all registered access types will be listed in the periodically + issued "Assigned Numbers" RFC [currently RFC-1700]. + +3.4. IANA Procedures for Registering Access Types + + The identity of the access type reviewer is communicated to the IANA + by the IESG. The IANA then only acts in response to access type + definitions that either are approved by the access type reviewer and + forwarded by the reviewer to the IANA for registration, or in + response to a communication from the IESG that an access type + definition appeal has overturned the access type reviewer's ruling. + + + +Freed, et. al. Best Current Practice [Page 16] + +RFC 2048 MIME Registration Procedures November 1996 + + +4. Transfer Encodings + + Transfer encodings are tranformations applied to MIME media types + after conversion to the media type's canonical form. Transfer + encodings are used for several purposes: + + (1) Many transports, especially message transports, can + only handle data consisting of relatively short lines + of text. There can also be severe restrictions on what + characters can be used in these lines of text -- some + transports are restricted to a small subset of US-ASCII + and others cannot handle certain character sequences. + Transfer encodings are used to transform binary data + into textual form that can survive such transports. + Examples of this sort of transfer encoding include the + base64 and quoted-printable transfer encodings defined + in RFC 2045. + + (2) Image, audio, video, and even application entities are + sometimes quite large. Compression algorithms are often + quite effective in reducing the size of large entities. + Transfer encodings can be used to apply general-purpose + non-lossy compression algorithms to MIME entities. + + (3) Transport encodings can be defined as a means of + representing existing encoding formats in a MIME + context. + + IMPORTANT: The standardization of a large numbers of different + transfer encodings is seen as a significant barrier to widespread + interoperability and is expressely discouraged. Nevertheless, the + following procedure has been defined to provide a means of defining + additional transfer encodings, should standardization actually be + justified. + +4.1. Transfer Encoding Requirements + + Transfer encoding specifications must conform to a number of + requirements as described below. + +4.1.1. Naming Requirements + + Each transfer encoding must have a unique name. This name appears in + the Content-Transfer-Encoding header field and must conform to the + syntax of that field. + + + + + + +Freed, et. al. Best Current Practice [Page 17] + +RFC 2048 MIME Registration Procedures November 1996 + + +4.1.2. Algorithm Specification Requirements + + All of the algorithms used in a transfer encoding (e.g. conversion + to printable form, compression) must be described in their entirety + in the transfer encoding specification. Use of secret and/or + proprietary algorithms in standardized transfer encodings are + expressly prohibited. The restrictions imposed by RFC 1602 on the + standardization of patented algorithms must be respected as well. + +4.1.3. Input Domain Requirements + + All transfer encodings must be applicable to an arbitrary sequence of + octets of any length. Dependence on particular input forms is not + allowed. + + It should be noted that the 7bit and 8bit encodings do not conform to + this requirement. Aside from the undesireability of having + specialized encodings, the intent here is to forbid the addition of + additional encodings along the lines of 7bit and 8bit. + +4.1.4. Output Range Requirements + + There is no requirement that a particular tranfer encoding produce a + particular form of encoded output. However, the output format for + each transfer encoding must be fully and completely documented. In + particular, each specification must clearly state whether the output + format always lies within the confines of 7bit data, 8bit data, or is + simply pure binary data. + +4.1.5. Data Integrity and Generality Requirements + + All transfer encodings must be fully invertible on any platform; it + must be possible for anyone to recover the original data by + performing the corresponding decoding operation. Note that this + requirement effectively excludes all forms of lossy compression as + well as all forms of encryption from use as a transfer encoding. + +4.1.6. New Functionality Requirements + + All transfer encodings must provide some sort of new functionality. + Some degree of functionality overlap with previously defined transfer + encodings is acceptable, but any new transfer encoding must also + offer something no other transfer encoding provides. + + + + + + + + +Freed, et. al. Best Current Practice [Page 18] + +RFC 2048 MIME Registration Procedures November 1996 + + +4.2. Transfer Encoding Definition Procedure + + Definition of a new transfer encoding starts with the construction of + a draft of a standards-track RFC. The RFC must define the transfer + encoding precisely and completely, and must also provide substantial + justification for defining and standardizing a new transfer encoding. + This specification must then be presented to the IESG for + consideration. The IESG can + + (1) reject the specification outright as being + inappropriate for standardization, + + (2) approve the formation of an IETF working group to work + on the specification in accordance with IETF + procedures, or, + + (3) accept the specification as-is and put it directly on + the standards track. + + Transfer encoding specifications on the standards track follow normal + IETF rules for standards track documents. A transfer encoding is + considered to be defined and available for use once it is on the + standards track. + +4.3. IANA Procedures for Transfer Encoding Registration + + There is no need for a special procedure for registering Transfer + Encodings with the IANA. All legitimate transfer encoding + registrations must appear as a standards-track RFC, so it is the + IESG's responsibility to notify the IANA when a new transfer encoding + has been approved. + +4.4. Location of Registered Transfer Encodings List + + Transfer encoding registrations will be posted in the anonymous FTP + directory "ftp://ftp.isi.edu/in-notes/iana/assignments/transfer- + encodings/" and all registered transfer encodings will be listed in + the periodically issued "Assigned Numbers" RFC [currently RFC-1700]. + + + + + + + + + + + + + +Freed, et. al. Best Current Practice [Page 19] + +RFC 2048 MIME Registration Procedures November 1996 + + +5. Authors' Addresses + + For more information, the authors of this document are best + contacted via Internet mail: + + Ned Freed + Innosoft International, Inc. + 1050 East Garvey Avenue South + West Covina, CA 91790 + USA + + Phone: +1 818 919 3600 + Fax: +1 818 919 3614 + EMail: ned@innosoft.com + + + John Klensin + MCI + 2100 Reston Parkway + Reston, VA 22091 + + Phone: +1 703 715-7361 + Fax: +1 703 715-7436 + EMail: klensin@mci.net + + + Jon Postel + USC/Information Sciences Institute + 4676 Admiralty Way + Marina del Rey, CA 90292 + USA + + + Phone: +1 310 822 1511 + Fax: +1 310 823 6714 + EMail: Postel@ISI.EDU + + + + + + + + + + + + + + + +Freed, et. al. Best Current Practice [Page 20] + +RFC 2048 MIME Registration Procedures November 1996 + + +Appendix A -- Grandfathered Media Types + + A number of media types, registered prior to 1996, would, if + registered under the guidelines in this document, be placed into + either the vendor or personal trees. Reregistration of those types + to reflect the appropriate trees is encouraged, but not required. + Ownership and change control principles outlined in this document + apply to those types as if they had been registered in the trees + described above. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Freed, et. al. Best Current Practice [Page 21] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2049.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2049.txt new file mode 100644 index 00000000..99f174b9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2049.txt @@ -0,0 +1,1347 @@ + + + + + + +Network Working Group N. Freed +Request for Comments: 2049 Innosoft +Obsoletes: 1521, 1522, 1590 N. Borenstein +Category: Standards Track First Virtual + November 1996 + + + Multipurpose Internet Mail Extensions + (MIME) Part Five: + Conformance Criteria and Examples + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + STD 11, RFC 822, defines a message representation protocol specifying + considerable detail about US-ASCII message headers, and leaves the + message content, or message body, as flat US-ASCII text. This set of + documents, collectively called the Multipurpose Internet Mail + Extensions, or MIME, redefines the format of messages to allow for + + (1) textual message bodies in character sets other than + US-ASCII, + + (2) an extensible set of different formats for non-textual + message bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than + US-ASCII. + + These documents are based on earlier work documented in RFC 934, STD + 11, and RFC 1049, but extends and revises them. Because RFC 822 said + so little about message bodies, these documents are largely + orthogonal to (rather than a revision of) RFC 822. + + The initial document in this set, RFC 2045, specifies the various + headers used to describe the structure of MIME messages. The second + document defines the general structure of the MIME media typing + system and defines an initial set of media types. The third + document, RFC 2047, describes extensions to RFC 822 to allow non-US- + + + +Freed & Borenstein Standards Track [Page 1] + +RFC 2049 MIME Conformance November 1996 + + + ASCII text data in Internet mail header fields. The fourth document, + RFC 2048, specifies various IANA registration procedures for MIME- + related facilities. This fifth and final document describes MIME + conformance criteria as well as providing some illustrative examples + of MIME message formats, acknowledgements, and the bibliography. + + These documents are revisions of RFCs 1521, 1522, and 1590, which + themselves were revisions of RFCs 1341 and 1342. Appendix B of this + document describes differences and changes from previous versions. + +Table of Contents + + 1. Introduction .......................................... 2 + 2. MIME Conformance ...................................... 2 + 3. Guidelines for Sending Email Data ..................... 6 + 4. Canonical Encoding Model .............................. 9 + 5. Summary ............................................... 12 + 6. Security Considerations ............................... 12 + 7. Authors' Addresses .................................... 12 + 8. Acknowledgements ...................................... 13 + A. A Complex Multipart Example ........................... 15 + B. Changes from RFC 1521, 1522, and 1590 ................. 16 + C. References ............................................ 20 + +1. Introduction + + The first and second documents in this set define MIME header fields + and the initial set of MIME media types. The third document + describes extensions to RFC822 formats to allow for character sets + other than US-ASCII. This document describes what portions of MIME + must be supported by a conformant MIME implementation. It also + describes various pitfalls of contemporary messaging systems as well + as the canonical encoding model MIME is based on. + +2. MIME Conformance + + The mechanisms described in these documents are open-ended. It is + definitely not expected that all implementations will support all + available media types, nor that they will all share the same + extensions. In order to promote interoperability, however, it is + useful to define the concept of "MIME-conformance" to define a + certain level of implementation that allows the useful interworking + of messages with content that differs from US-ASCII text. In this + section, we specify the requirements for such conformance. + + + + + + + +Freed & Borenstein Standards Track [Page 2] + +RFC 2049 MIME Conformance November 1996 + + + A mail user agent that is MIME-conformant MUST: + + (1) Always generate a "MIME-Version: 1.0" header field in + any message it creates. + + (2) Recognize the Content-Transfer-Encoding header field + and decode all received data encoded by either quoted- + printable or base64 implementations. The identity + transformations 7bit, 8bit, and binary must also be + recognized. + + Any non-7bit data that is sent without encoding must be + properly labelled with a content-transfer-encoding of + 8bit or binary, as appropriate. If the underlying + transport does not support 8bit or binary (as SMTP + [RFC-821] does not), the sender is required to both + encode and label data using an appropriate Content- + Transfer-Encoding such as quoted-printable or base64. + + (3) Must treat any unrecognized Content-Transfer-Encoding + as if it had a Content-Type of "application/octet- + stream", regardless of whether or not the actual + Content-Type is recognized. + + (4) Recognize and interpret the Content-Type header field, + and avoid showing users raw data with a Content-Type + field other than text. Implementations must be able + to send at least text/plain messages, with the + character set specified with the charset parameter if + it is not US-ASCII. + + (5) Ignore any content type parameters whose names they do + not recognize. + + (6) Explicitly handle the following media type values, to + at least the following extents: + + Text: + + -- Recognize and display "text" mail with the + character set "US-ASCII." + + -- Recognize other character sets at least to the + extent of being able to inform the user about what + character set the message uses. + + + + + + +Freed & Borenstein Standards Track [Page 3] + +RFC 2049 MIME Conformance November 1996 + + + -- Recognize the "ISO-8859-*" character sets to the + extent of being able to display those characters that + are common to ISO-8859-* and US-ASCII, namely all + characters represented by octet values 1-127. + + -- For unrecognized subtypes in a known character + set, show or offer to show the user the "raw" version + of the data after conversion of the content from + canonical form to local form. + + -- Treat material in an unknown character set as if + it were "application/octet-stream". + + Image, audio, and video: + + -- At a minumum provide facilities to treat any + unrecognized subtypes as if they were + "application/octet-stream". + + Application: + + -- Offer the ability to remove either of the quoted- + printable or base64 encodings defined in this + document if they were used and put the resulting + information in a user file. + + Multipart: + + -- Recognize the mixed subtype. Display all relevant + information on the message level and the body part + header level and then display or offer to display + each of the body parts individually. + + -- Recognize the "alternative" subtype, and avoid + showing the user redundant parts of + multipart/alternative mail. + + -- Recognize the "multipart/digest" subtype, + specifically using "message/rfc822" rather than + "text/plain" as the default media type for body parts + inside "multipart/digest" entities. + + -- Treat any unrecognized subtypes as if they were + "mixed". + + + + + + + +Freed & Borenstein Standards Track [Page 4] + +RFC 2049 MIME Conformance November 1996 + + + Message: + + -- Recognize and display at least the RFC822 message + encapsulation (message/rfc822) in such a way as to + preserve any recursive structure, that is, displaying + or offering to display the encapsulated data in + accordance with its media type. + + -- Treat any unrecognized subtypes as if they were + "application/octet-stream". + + (7) Upon encountering any unrecognized Content-Type field, + an implementation must treat it as if it had a media + type of "application/octet-stream" with no parameter + sub-arguments. How such data are handled is up to an + implementation, but likely options for handling such + unrecognized data include offering the user to write it + into a file (decoded from its mail transport format) or + offering the user to name a program to which the + decoded data should be passed as input. + + (8) Conformant user agents are required, if they provide + non-standard support for non-MIME messages employing + character sets other than US-ASCII, to do so on + received messages only. Conforming user agents must not + send non-MIME messages containing anything other than + US-ASCII text. + + In particular, the use of non-US-ASCII text in mail + messages without a MIME-Version field is strongly + discouraged as it impedes interoperability when sending + messages between regions with different localization + conventions. Conforming user agents MUST include proper + MIME labelling when sending anything other than plain + text in the US-ASCII character set. + + In addition, non-MIME user agents should be upgraded if + at all possible to include appropriate MIME header + information in the messages they send even if nothing + else in MIME is supported. This upgrade will have + little, if any, effect on non-MIME recipients and will + aid MIME in correctly displaying such messages. It + also provides a smooth transition path to eventual + adoption of other MIME capabilities. + + (9) Conforming user agents must ensure that any string of + non-white-space printable US-ASCII characters within a + "*text" or "*ctext" that begins with "=?" and ends with + + + +Freed & Borenstein Standards Track [Page 5] + +RFC 2049 MIME Conformance November 1996 + + + "?=" be a valid encoded-word. ("begins" means: At the + start of the field-body or immediately following + linear-white-space; "ends" means: At the end of the + field-body or immediately preceding linear-white- + space.) In addition, any "word" within a "phrase" that + begins with "=?" and ends with "?=" must be a valid + encoded-word. + + (10) Conforming user agents must be able to distinguish + encoded-words from "text", "ctext", or "word"s, + according to the rules in section 4, anytime they + appear in appropriate places in message headers. It + must support both the "B" and "Q" encodings for any + character set which it supports. The program must be + able to display the unencoded text if the character set + is "US-ASCII". For the ISO-8859-* character sets, the + mail reading program must at least be able to display + the characters which are also in the US-ASCII set. + + A user agent that meets the above conditions is said to be MIME- + conformant. The meaning of this phrase is that it is assumed to be + "safe" to send virtually any kind of properly-marked data to users of + such mail systems, because such systems will at least be able to + treat the data as undifferentiated binary, and will not simply splash + it onto the screen of unsuspecting users. + + There is another sense in which it is always "safe" to send data in a + format that is MIME-conformant, which is that such data will not + break or be broken by any known systems that are conformant with RFC + 821 and RFC 822. User agents that are MIME-conformant have the + additional guarantee that the user will not be shown data that were + never intended to be viewed as text. + +3. Guidelines for Sending Email Data + + Internet email is not a perfect, homogeneous system. Mail may become + corrupted at several stages in its travel to a final destination. + Specifically, email sent throughout the Internet may travel across + many networking technologies. Many networking and mail technologies + do not support the full functionality possible in the SMTP transport + environment. Mail traversing these systems is likely to be modified + in order that it can be transported. + + There exist many widely-deployed non-conformant MTAs in the Internet. + These MTAs, speaking the SMTP protocol, alter messages on the fly to + take advantage of the internal data structure of the hosts they are + implemented on, or are just plain broken. + + + + +Freed & Borenstein Standards Track [Page 6] + +RFC 2049 MIME Conformance November 1996 + + + The following guidelines may be useful to anyone devising a data + format (media type) that is supposed to survive the widest range of + networking technologies and known broken MTAs unscathed. Note that + anything encoded in the base64 encoding will satisfy these rules, but + that some well-known mechanisms, notably the UNIX uuencode facility, + will not. Note also that anything encoded in the Quoted-Printable + encoding will survive most gateways intact, but possibly not some + gateways to systems that use the EBCDIC character set. + + (1) Under some circumstances the encoding used for data may + change as part of normal gateway or user agent + operation. In particular, conversion from base64 to + quoted-printable and vice versa may be necessary. This + may result in the confusion of CRLF sequences with line + breaks in text bodies. As such, the persistence of + CRLF as something other than a line break must not be + relied on. + + (2) Many systems may elect to represent and store text data + using local newline conventions. Local newline + conventions may not match the RFC822 CRLF convention -- + systems are known that use plain CR, plain LF, CRLF, or + counted records. The result is that isolated CR and LF + characters are not well tolerated in general; they may + be lost or converted to delimiters on some systems, and + hence must not be relied on. + + (3) The transmission of NULs (US-ASCII value 0) is + problematic in Internet mail. (This is largely the + result of NULs being used as a termination character by + many of the standard runtime library routines in the C + programming language.) The practice of using NULs as + termination characters is so entrenched now that + messages should not rely on them being preserved. + + (4) TAB (HT) characters may be misinterpreted or may be + automatically converted to variable numbers of spaces. + This is unavoidable in some environments, notably those + not based on the US-ASCII character set. Such + conversion is STRONGLY DISCOURAGED, but it may occur, + and mail formats must not rely on the persistence of + TAB (HT) characters. + + (5) Lines longer than 76 characters may be wrapped or + truncated in some environments. Line wrapping or line + truncation imposed by mail transports is STRONGLY + DISCOURAGED, but unavoidable in some cases. + Applications which require long lines must somehow + + + +Freed & Borenstein Standards Track [Page 7] + +RFC 2049 MIME Conformance November 1996 + + + differentiate between soft and hard line breaks. (A + simple way to do this is to use the quoted-printable + encoding.) + + (6) Trailing "white space" characters (SPACE, TAB (HT)) on + a line may be discarded by some transport agents, while + other transport agents may pad lines with these + characters so that all lines in a mail file are of + equal length. The persistence of trailing white space, + therefore, must not be relied on. + + (7) Many mail domains use variations on the US-ASCII + character set, or use character sets such as EBCDIC + which contain most but not all of the US-ASCII + characters. The correct translation of characters not + in the "invariant" set cannot be depended on across + character converting gateways. For example, this + situation is a problem when sending uuencoded + information across BITNET, an EBCDIC system. Similar + problems can occur without crossing a gateway, since + many Internet hosts use character sets other than US- + ASCII internally. The definition of Printable Strings + in X.400 adds further restrictions in certain special + cases. In particular, the only characters that are + known to be consistent across all gateways are the 73 + characters that correspond to the upper and lower case + letters A-Z and a-z, the 10 digits 0-9, and the + following eleven special characters: + + "'" (US-ASCII decimal value 39) + "(" (US-ASCII decimal value 40) + ")" (US-ASCII decimal value 41) + "+" (US-ASCII decimal value 43) + "," (US-ASCII decimal value 44) + "-" (US-ASCII decimal value 45) + "." (US-ASCII decimal value 46) + "/" (US-ASCII decimal value 47) + ":" (US-ASCII decimal value 58) + "=" (US-ASCII decimal value 61) + "?" (US-ASCII decimal value 63) + + A maximally portable mail representation will confine + itself to relatively short lines of text in which the + only meaningful characters are taken from this set of + 73 characters. The base64 encoding follows this rule. + + (8) Some mail transport agents will corrupt data that + includes certain literal strings. In particular, a + + + +Freed & Borenstein Standards Track [Page 8] + +RFC 2049 MIME Conformance November 1996 + + + period (".") alone on a line is known to be corrupted + by some (incorrect) SMTP implementations, and a line + that starts with the five characters "From " (the fifth + character is a SPACE) are commonly corrupted as well. + A careful composition agent can prevent these + corruptions by encoding the data (e.g., in the quoted- + printable encoding using "=46rom " in place of "From " + at the start of a line, and "=2E" in place of "." alone + on a line). + + Please note that the above list is NOT a list of recommended + practices for MTAs. RFC 821 MTAs are prohibited from altering the + character of white space or wrapping long lines. These BAD and + invalid practices are known to occur on established networks, and + implementations should be robust in dealing with the bad effects they + can cause. + +4. Canonical Encoding Model + + There was some confusion, in earlier versions of these documents, + regarding the model for when email data was to be converted to + canonical form and encoded, and in particular how this process would + affect the treatment of CRLFs, given that the representation of + newlines varies greatly from system to system. For this reason, a + canonical model for encoding is presented below. + + The process of composing a MIME entity can be modeled as being done + in a number of steps. Note that these steps are roughly similar to + those steps used in PEM [RFC-1421] and are performed for each + "innermost level" body: + + (1) Creation of local form. + + The body to be transmitted is created in the system's + native format. The native character set is used and, + where appropriate, local end of line conventions are + used as well. The body may be a UNIX-style text file, + or a Sun raster image, or a VMS indexed file, or audio + data in a system-dependent format stored only in + memory, or anything else that corresponds to the local + model for the representation of some form of + information. Fundamentally, the data is created in the + "native" form that corresponds to the type specified by + the media type. + + + + + + + +Freed & Borenstein Standards Track [Page 9] + +RFC 2049 MIME Conformance November 1996 + + + (2) Conversion to canonical form. + + The entire body, including "out-of-band" information + such as record lengths and possibly file attribute + information, is converted to a universal canonical + form. The specific media type of the body as well as + its associated attributes dictate the nature of the + canonical form that is used. Conversion to the proper + canonical form may involve character set conversion, + transformation of audio data, compression, or various + other operations specific to the various media types. + If character set conversion is involved, however, care + must be taken to understand the semantics of the media + type, which may have strong implications for any + character set conversion, e.g. with regard to + syntactically meaningful characters in a text subtype + other than "plain". + + For example, in the case of text/plain data, the text + must be converted to a supported character set and + lines must be delimited with CRLF delimiters in + accordance with RFC 822. Note that the restriction on + line lengths implied by RFC 822 is eliminated if the + next step employs either quoted-printable or base64 + encoding. + + (3) Apply transfer encoding. + + A Content-Transfer-Encoding appropriate for this body + is applied. Note that there is no fixed relationship + between the media type and the transfer encoding. In + particular, it may be appropriate to base the choice of + base64 or quoted-printable on character frequency + counts which are specific to a given instance of a + body. + + (4) Insertion into entity. + + The encoded body is inserted into a MIME entity with + appropriate headers. The entity is then inserted into + the body of a higher-level entity (message or + multipart) as needed. + + Conversion from entity form to local form is accomplished by + reversing these steps. Note that reversal of these steps may produce + differing results since there is no guarantee that the original and + final local forms are the same. + + + + +Freed & Borenstein Standards Track [Page 10] + +RFC 2049 MIME Conformance November 1996 + + + It is vital to note that these steps are only a model; they are + specifically NOT a blueprint for how an actual system would be built. + In particular, the model fails to account for two common designs: + + (1) In many cases the conversion to a canonical form prior + to encoding will be subsumed into the encoder itself, + which understands local formats directly. For example, + the local newline convention for text bodies might be + carried through to the encoder itself along with + knowledge of what that format is. + + (2) The output of the encoders may have to pass through one + or more additional steps prior to being transmitted as + a message. As such, the output of the encoder may not + be conformant with the formats specified by RFC 822. + In particular, once again it may be appropriate for the + converter's output to be expressed using local newline + conventions rather than using the standard RFC 822 CRLF + delimiters. + + Other implementation variations are conceivable as well. The vital + aspect of this discussion is that, in spite of any optimizations, + collapsings of required steps, or insertion of additional processing, + the resulting messages must be consistent with those produced by the + model described here. For example, a message with the following + header fields: + + Content-type: text/foo; charset=bar + Content-Transfer-Encoding: base64 + + must be first represented in the text/foo form, then (if necessary) + represented in the "bar" character set, and finally transformed via + the base64 algorithm into a mail-safe form. + + NOTE: Some confusion has been caused by systems that represent + messages in a format which uses local newline conventions which + differ from the RFC822 CRLF convention. It is important to note that + these formats are not canonical RFC822/MIME. These formats are + instead *encodings* of RFC822, where CRLF sequences in the canonical + representation of the message are encoded as the local newline + convention. Note that formats which encode CRLF sequences as, for + example, LF are not capable of representing MIME messages containing + binary data which contains LF octets not part of CRLF line separation + sequences. + + + + + + + +Freed & Borenstein Standards Track [Page 11] + +RFC 2049 MIME Conformance November 1996 + + +5. Summary + + This document defines what is meant by MIME Conformance. It also + details various problems known to exist in the Internet email system + and how to use MIME to overcome them. Finally, it describes MIME's + canonical encoding model. + +6. Security Considerations + + Security issues are discussed in the second document in this set, RFC + 2046. + +7. Authors' Addresses + + For more information, the authors of this document are best contacted + via Internet mail: + + Ned Freed + Innosoft International, Inc. + 1050 East Garvey Avenue South + West Covina, CA 91790 + USA + + Phone: +1 818 919 3600 + Fax: +1 818 919 3614 + EMail: ned@innosoft.com + + Nathaniel S. Borenstein + First Virtual Holdings + 25 Washington Avenue + Morristown, NJ 07960 + USA + + Phone: +1 201 540 8967 + Fax: +1 201 993 3032 + EMail: nsb@nsb.fv.com + + MIME is a result of the work of the Internet Engineering Task Force + Working Group on RFC 822 Extensions. The chairman of that group, + Greg Vaudreuil, may be reached at: + + Gregory M. Vaudreuil + Octel Network Services + 17080 Dallas Parkway + Dallas, TX 75248-1905 + USA + + EMail: Greg.Vaudreuil@Octel.Com + + + +Freed & Borenstein Standards Track [Page 12] + +RFC 2049 MIME Conformance November 1996 + + +8. Acknowledgements + + This document is the result of the collective effort of a large + number of people, at several IETF meetings, on the IETF-SMTP and + IETF-822 mailing lists, and elsewhere. Although any enumeration + seems doomed to suffer from egregious omissions, the following are + among the many contributors to this effort: + + Harald Tveit Alvestrand Marc Andreessen + Randall Atkinson Bob Braden + Philippe Brandon Brian Capouch + Kevin Carosso Uhhyung Choi + Peter Clitherow Dave Collier-Brown + Cristian Constantinof John Coonrod + Mark Crispin Dave Crocker + Stephen Crocker Terry Crowley + Walt Daniels Jim Davis + Frank Dawson Axel Deininger + Hitoshi Doi Kevin Donnelly + Steve Dorner Keith Edwards + Chris Eich Dana S. Emery + Johnny Eriksson Craig Everhart + Patrik Faltstrom Erik E. Fair + Roger Fajman Alain Fontaine + Martin Forssen James M. Galvin + Stephen Gildea Philip Gladstone + Thomas Gordon Keld Simonsen + Terry Gray Phill Gross + James Hamilton David Herron + Mark Horton Bruce Howard + Bill Janssen Olle Jarnefors + Risto Kankkunen Phil Karn + Alan Katz Tim Kehres + Neil Katin Steve Kille + Kyuho Kim Anders Klemets + John Klensin Valdis Kletniek + Jim Knowles Stev Knowles + Bob Kummerfeld Pekka Kytolaakso + Stellan Lagerstrom Vincent Lau + Timo Lehtinen Donald Lindsay + Warner Losh Carlyn Lowery + Laurence Lundblade Charles Lynn + John R. MacMillan Larry Masinter + Rick McGowan Michael J. McInerny + Leo Mclaughlin Goli Montaser-Kohsari + Tom Moore John Gardiner Myers + Erik Naggum Mark Needleman + Chris Newman John Noerenberg + + + +Freed & Borenstein Standards Track [Page 13] + +RFC 2049 MIME Conformance November 1996 + + + Mats Ohrman Julian Onions + Michael Patton David J. Pepper + Erik van der Poel Blake C. Ramsdell + Christer Romson Luc Rooijakkers + Marshall T. Rose Jonathan Rosenberg + Guido van Rossum Jan Rynning + Harri Salminen Michael Sanderson + Yutaka Sato Markku Savela + Richard Alan Schafer Masahiro Sekiguchi + Mark Sherman Bob Smart + Peter Speck Henry Spencer + Einar Stefferud Michael Stein + Klaus Steinberger Peter Svanberg + James Thompson Steve Uhler + Stuart Vance Peter Vanderbilt + Greg Vaudreuil Ed Vielmetti + Larry W. Virden Ryan Waldron + Rhys Weatherly Jay Weber + Dave Wecker Wally Wedel + Sven-Ove Westberg Brian Wideen + John Wobus Glenn Wright + Rayan Zachariassen David Zimmerman + + The authors apologize for any omissions from this list, which are + certainly unintentional. + + + + + + + + + + + + + + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 14] + +RFC 2049 MIME Conformance November 1996 + + +Appendix A -- A Complex Multipart Example + + What follows is the outline of a complex multipart message. This + message contains five parts that are to be displayed serially: two + introductory plain text objects, an embedded multipart message, a + text/enriched object, and a closing encapsulated text message in a + non-ASCII character set. The embedded multipart message itself + contains two objects to be displayed in parallel, a picture and an + audio fragment. + + MIME-Version: 1.0 + From: Nathaniel Borenstein + To: Ned Freed + Date: Fri, 07 Oct 1994 16:15:05 -0700 (PDT) + Subject: A multipart example + Content-Type: multipart/mixed; + boundary=unique-boundary-1 + + This is the preamble area of a multipart message. + Mail readers that understand multipart format + should ignore this preamble. + + If you are reading this text, you might want to + consider changing to a mail reader that understands + how to properly display multipart messages. + + --unique-boundary-1 + + ... Some text appears here ... + + [Note that the blank between the boundary and the start + of the text in this part means no header fields were + given and this is text in the US-ASCII character set. + It could have been done with explicit typing as in the + next part.] + + --unique-boundary-1 + Content-type: text/plain; charset=US-ASCII + + This could have been part of the previous part, but + illustrates explicit versus implicit typing of body + parts. + + --unique-boundary-1 + Content-Type: multipart/parallel; boundary=unique-boundary-2 + + --unique-boundary-2 + Content-Type: audio/basic + + + +Freed & Borenstein Standards Track [Page 15] + +RFC 2049 MIME Conformance November 1996 + + + Content-Transfer-Encoding: base64 + + ... base64-encoded 8000 Hz single-channel + mu-law-format audio data goes here ... + + --unique-boundary-2 + Content-Type: image/jpeg + Content-Transfer-Encoding: base64 + + ... base64-encoded image data goes here ... + + --unique-boundary-2-- + + --unique-boundary-1 + Content-type: text/enriched + + This is enriched. + as defined in RFC 1896 + + Isn't it + cool? + + --unique-boundary-1 + Content-Type: message/rfc822 + + From: (mailbox in US-ASCII) + To: (address in US-ASCII) + Subject: (subject in US-ASCII) + Content-Type: Text/plain; charset=ISO-8859-1 + Content-Transfer-Encoding: Quoted-printable + + ... Additional text in ISO-8859-1 goes here ... + + --unique-boundary-1-- + +Appendix B -- Changes from RFC 1521, 1522, and 1590 + + These documents are a revision of RFC 1521, 1522, and 1590. For the + convenience of those familiar with the earlier documents, the changes + from those documents are summarized in this appendix. For further + history, note that Appendix H in RFC 1521 specified how that document + differed from its predecessor, RFC 1341. + + (1) This document has been completely reformatted and split + into multiple documents. This was done to improve the + quality of the plain text version of this document, + which is required to be the reference copy. + + + + +Freed & Borenstein Standards Track [Page 16] + +RFC 2049 MIME Conformance November 1996 + + + (2) BNF describing the overall structure of MIME object + headers has been added. This is a documentation change + only -- the underlying syntax has not changed in any + way. + + (3) The specific BNF for the seven media types in MIME has + been removed. This BNF was incorrect, incomplete, amd + inconsistent with the type-indendependent BNF. And + since the type-independent BNF already fully specifies + the syntax of the various MIME headers, the type- + specific BNF was, in the final analysis, completely + unnecessary and caused more problems than it solved. + + (4) The more specific "US-ASCII" character set name has + replaced the use of the informal term ASCII in many + parts of these documents. + + (5) The informal concept of a primary subtype has been + removed. + + (6) The term "object" was being used inconsistently. The + definition of this term has been clarified, along with + the related terms "body", "body part", and "entity", + and usage has been corrected where appropriate. + + (7) The BNF for the multipart media type has been + rearranged to make it clear that the CRLF preceeding + the boundary marker is actually part of the marker + itself rather than the preceeding body part. + + (8) The prose and BNF describing the multipart media type + have been changed to make it clear that the body parts + within a multipart object MUST NOT contain any lines + beginning with the boundary parameter string. + + (9) In the rules on reassembling "message/partial" MIME + entities, "Subject" is added to the list of headers to + take from the inner message, and the example is + modified to clarify this point. + + (10) "Message/partial" fragmenters are restricted to + splitting MIME objects only at line boundaries. + + (11) In the discussion of the application/postscript type, + an additional paragraph has been added warning about + possible interoperability problems caused by embedding + of binary data inside a PostScript MIME entity. + + + + +Freed & Borenstein Standards Track [Page 17] + +RFC 2049 MIME Conformance November 1996 + + + (12) Added a clarifying note to the basic syntax rules for + the Content-Type header field to make it clear that the + following two forms: + + Content-type: text/plain; charset=us-ascii (comment) + + Content-type: text/plain; charset="us-ascii" + + are completely equivalent. + + (13) The following sentence has been removed from the + discussion of the MIME-Version header: "However, + conformant software is encouraged to check the version + number and at least warn the user if an unrecognized + MIME-version is encountered." + + (14) A typo was fixed that said "application/external-body" + instead of "message/external-body". + + (15) The definition of a character set has been reorganized + to make the requirements clearer. + + (16) The definition of the "image/gif" media type has been + moved to a separate document. This change was made + because of potential conflicts with IETF rules + governing the standardization of patented technology. + + (17) The definitions of "7bit" and "8bit" have been + tightened so that use of bare CR, LF can only be used + as end-of-line sequences. The document also no longer + requires that NUL characters be preserved, which brings + MIME into alignment with real-world implementations. + + (18) The definition of canonical text in MIME has been + tightened so that line breaks must be represented by a + CRLF sequence. CR and LF characters are not allowed + outside of this usage. The definition of quoted- + printable encoding has been altered accordingly. + + (19) The definition of the quoted-printable encoding now + includes a number of suggestions for how quoted- + printable encoders might best handle improperly encoded + material. + + (20) Prose was added to clarify the use of the "7bit", + "8bit", and "binary" transfer-encodings on multipart or + message entities encapsulating "8bit" or "binary" data. + + + + +Freed & Borenstein Standards Track [Page 18] + +RFC 2049 MIME Conformance November 1996 + + + (21) In the section on MIME Conformance, "multipart/digest" + support was added to the list of requirements for + minimal MIME conformance. Also, the requirement for + "message/rfc822" support were strengthened to clarify + the importance of recognizing recursive structure. + + (22) The various restrictions on subtypes of "message" are + now specified entirely on a subtype by subtype basis. + + (23) The definition of "message/rfc822" was changed to + indicate that at least one of the "From", "Subject", or + "Date" headers must be present. + + (24) The required handling of unrecognized subtypes as + "application/octet-stream" has been made more explicit + in both the type definitions sections and the + conformance guidelines. + + (25) Examples using text/richtext were changed to + text/enriched. + + (26) The BNF definition of subtype has been changed to make + it clear that either an IANA registered subtype or a + nonstandard "X-" subtype must be used in a Content-Type + header field. + + (27) MIME media types that are simply registered for use and + those that are standardized by the IETF are now + distinguished in the MIME BNF. + + (28) All of the various MIME registration procedures have + been extensively revised. IANA registration procedures + for character sets have been moved to a separate + document that is no included in this set of documents. + + (29) The use of escape and shift mechanisms in the US-ASCII + and ISO-8859-X character sets these documents define + have been clarified: Such mechanisms should never be + used in conjunction with these character sets and their + effect if they are used is undefined. + + (30) The definition of the AFS access-type for + message/external-body has been removed. + + (31) The handling of the combination of + multipart/alternative and message/external-body is now + specifically addressed. + + + + +Freed & Borenstein Standards Track [Page 19] + +RFC 2049 MIME Conformance November 1996 + + + (32) Security issues specific to message/external-body are + now discussed in some detail. + +Appendix C -- References + + [ATK] + Borenstein, Nathaniel S., Multimedia Applications + Development with the Andrew Toolkit, Prentice-Hall, 1990. + + [ISO-2022] + International Standard -- Information Processing -- + Character Code Structure and Extension Techniques, + ISO/IEC 2022:1994, 4th ed. + + [ISO-8859] + International Standard -- Information Processing -- 8-bit + Single-Byte Coded Graphic Character Sets + - Part 1: Latin Alphabet No. 1, ISO 8859-1:1987, 1st ed. + - Part 2: Latin Alphabet No. 2, ISO 8859-2:1987, 1st ed. + - Part 3: Latin Alphabet No. 3, ISO 8859-3:1988, 1st ed. + - Part 4: Latin Alphabet No. 4, ISO 8859-4:1988, 1st ed. + - Part 5: Latin/Cyrillic Alphabet, ISO 8859-5:1988, 1st + ed. + - Part 6: Latin/Arabic Alphabet, ISO 8859-6:1987, 1st ed. + - Part 7: Latin/Greek Alphabet, ISO 8859-7:1987, 1st ed. + - Part 8: Latin/Hebrew Alphabet, ISO 8859-8:1988, 1st ed. + - Part 9: Latin Alphabet No. 5, ISO/IEC 8859-9:1989, 1st + ed. + International Standard -- Information Technology -- 8-bit + Single-Byte Coded Graphic Character Sets + - Part 10: Latin Alphabet No. 6, ISO/IEC 8859-10:1992, + 1st ed. + + [ISO-646] + International Standard -- Information Technology -- ISO + 7-bit Coded Character Set for Information Interchange, + ISO 646:1991, 3rd ed.. + + [JPEG] + JPEG Draft Standard ISO 10918-1 CD. + + [MPEG] + Video Coding Draft Standard ISO 11172 CD, ISO + IEC/JTC1/SC2/WG11 (Motion Picture Experts Group), May, + 1991. + + + + + + +Freed & Borenstein Standards Track [Page 20] + +RFC 2049 MIME Conformance November 1996 + + + [PCM] + CCITT, Fascicle III.4 - Recommendation G.711, "Pulse Code + Modulation (PCM) of Voice Frequencies", Geneva, 1972. + + [POSTSCRIPT] + Adobe Systems, Inc., PostScript Language Reference + Manual, Addison-Wesley, 1985. + + [POSTSCRIPT2] + Adobe Systems, Inc., PostScript Language Reference + Manual, Addison-Wesley, Second Ed., 1990. + + [RFC-783] + Sollins, K.R., "TFTP Protocol (revision 2)", RFC-783, + MIT, June 1981. + + [RFC-821] + Postel, J.B., "Simple Mail Transfer Protocol", STD 10, + RFC 821, USC/Information Sciences Institute, August 1982. + + [RFC-822] + Crocker, D., "Standard for the Format of ARPA Internet + Text Messages", STD 11, RFC 822, UDEL, August 1982. + + [RFC-934] + Rose, M. and E. Stefferud, "Proposed Standard for Message + Encapsulation", RFC 934, Delaware and NMA, January 1985. + + [RFC-959] + Postel, J. and J. Reynolds, "File Transfer Protocol", STD + 9, RFC 959, USC/Information Sciences Institute, October + 1985. + + [RFC-1049] + Sirbu, M., "Content-Type Header Field for Internet + Messages", RFC 1049, CMU, March 1988. + + [RFC-1154] + Robinson, D., and R. Ullmann, "Encoding Header Field for + Internet Messages", RFC 1154, Prime Computer, Inc., April + 1990. + + [RFC-1341] + Borenstein, N., and N. Freed, "MIME (Multipurpose + Internet Mail Extensions): Mechanisms for Specifying and + Describing the Format of Internet Message Bodies", RFC + 1341, Bellcore, Innosoft, June 1992. + + + + +Freed & Borenstein Standards Track [Page 21] + +RFC 2049 MIME Conformance November 1996 + + + [RFC-1342] + Moore, K., "Representation of Non-Ascii Text in Internet + Message Headers", RFC 1342, University of Tennessee, June + 1992. + + [RFC-1344] + Borenstein, N., "Implications of MIME for Internet Mail + Gateways", RFC 1344, Bellcore, June 1992. + + [RFC-1345] + Simonsen, K., "Character Mnemonics & Character Sets", RFC + 1345, Rationel Almen Planlaegning, June 1992. + + [RFC-1421] + Linn, J., "Privacy Enhancement for Internet Electronic + Mail: Part I -- Message Encryption and Authentication + Procedures", RFC 1421, IAB IRTF PSRG, IETF PEM WG, + February 1993. + + [RFC-1422] + Kent, S., "Privacy Enhancement for Internet Electronic + Mail: Part II -- Certificate-Based Key Management", RFC + 1422, IAB IRTF PSRG, IETF PEM WG, February 1993. + + [RFC-1423] + Balenson, D., "Privacy Enhancement for Internet + Electronic Mail: Part III -- Algorithms, Modes, and + Identifiers", IAB IRTF PSRG, IETF PEM WG, February 1993. + + [RFC-1424] + Kaliski, B., "Privacy Enhancement for Internet Electronic + Mail: Part IV -- Key Certification and Related + Services", IAB IRTF PSRG, IETF PEM WG, February 1993. + + [RFC-1521] + Borenstein, N., and Freed, N., "MIME (Multipurpose + Internet Mail Extensions): Mechanisms for Specifying and + Describing the Format of Internet Message Bodies", RFC + 1521, Bellcore, Innosoft, September, 1993. + + [RFC-1522] + Moore, K., "Representation of Non-ASCII Text in Internet + Message Headers", RFC 1522, University of Tennessee, + September 1993. + + + + + + + +Freed & Borenstein Standards Track [Page 22] + +RFC 2049 MIME Conformance November 1996 + + + [RFC-1524] + Borenstein, N., "A User Agent Configuration Mechanism for + Multimedia Mail Format Information", RFC 1524, Bellcore, + September 1993. + + [RFC-1543] + Postel, J., "Instructions to RFC Authors", RFC 1543, + USC/Information Sciences Institute, October 1993. + + [RFC-1556] + Nussbacher, H., "Handling of Bi-directional Texts in + MIME", RFC 1556, Israeli Inter-University Computer + Center, December 1993. + + [RFC-1590] + Postel, J., "Media Type Registration Procedure", RFC + 1590, USC/Information Sciences Institute, March 1994. + + [RFC-1602] + Internet Architecture Board, Internet Engineering + Steering Group, Huitema, C., Gross, P., "The Internet + Standards Process -- Revision 2", March 1994. + + [RFC-1652] + Klensin, J., (WG Chair), Freed, N., (Editor), Rose, M., + Stefferud, E., and Crocker, D., "SMTP Service Extension + for 8bit-MIME transport", RFC 1652, United Nations + University, Innosoft, Dover Beach Consulting, Inc., + Network Management Associates, Inc., The Branch Office, + March 1994. + + [RFC-1700] + Reynolds, J. and J. Postel, "Assigned Numbers", STD 2, + RFC 1700, USC/Information Sciences Institute, October + 1994. + + [RFC-1741] + Faltstrom, P., Crocker, D., and Fair, E., "MIME Content + Type for BinHex Encoded Files", December 1994. + + [RFC-1896] + Resnick, P., and A. Walker, "The text/enriched MIME + Content-type", RFC 1896, February, 1996. + + + + + + + + +Freed & Borenstein Standards Track [Page 23] + +RFC 2049 MIME Conformance November 1996 + + + [RFC-2045] + Freed, N., and and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message + Bodies", RFC 2045, Innosoft, First Virtual Holdings, + November 1996. + + [RFC-2046] + Freed, N., and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + Innosoft, First Virtual Holdings, November 1996. + + [RFC-2047] + Moore, K., "Multipurpose Internet Mail Extensions (MIME) + Part Three: Representation of Non-ASCII Text in Internet + Message Headers", RFC 2047, University of + Tennessee, November 1996. + + [RFC-2048] + Freed, N., Klensin, J., and J. Postel, "Multipurpose + Internet Mail Extensions (MIME) Part Four: MIME + Registration Procedures", RFC 2048, Innosoft, MCI, + ISI, November 1996. + + [RFC-2049] + Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Five: Conformance Criteria and + Examples", RFC 2049 (this document), Innosoft, First + Virtual Holdings, November 1996. + + [US-ASCII] + Coded Character Set -- 7-Bit American Standard Code for + Information Interchange, ANSI X3.4-1986. + + [X400] + Schicker, Pietro, "Message Handling Systems, X.400", + Message Handling Systems and Distributed Applications, E. + Stefferud, O-j. Jacobsen, and P. Schicker, eds., North- + Holland, 1989, pp. 3-41. + + + + + + + + + + + + + +Freed & Borenstein Standards Track [Page 24] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2183.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2183.txt new file mode 100644 index 00000000..f16f127e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2183.txt @@ -0,0 +1,675 @@ + + + + + + +Network Working Group R. Troost +Request for Comments: 2183 New Century Systems +Updates: 1806 S. Dorner +Category: Standards Track QUALCOMM Incorporated + K. Moore, Editor + University of Tennessee + August 1997 + + + Communicating Presentation Information in + Internet Messages: + The Content-Disposition Header Field + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + This memo provides a mechanism whereby messages conforming to the + MIME specifications [RFC 2045, RFC 2046, RFC 2047, RFC 2048, RFC + 2049] can convey presentational information. It specifies the + "Content-Disposition" header field, which is optional and valid for + any MIME entity ("message" or "body part"). Two values for this + header field are described in this memo; one for the ordinary linear + presentation of the body part, and another to facilitate the use of + mail to transfer files. It is expected that more values will be + defined in the future, and procedures are defined for extending this + set of values. + + This document is intended as an extension to MIME. As such, the + reader is assumed to be familiar with the MIME specifications, and + [RFC 822]. The information presented herein supplements but does not + replace that found in those documents. + + This document is a revision to the Experimental protocol defined in + RFC 1806. As compared to RFC 1806, this document contains minor + editorial updates, adds new parameters needed to support the File + Transfer Body Part, and references a separate specification for the + handling of non-ASCII and/or very long parameter values. + + + + + + + +Troost, et. al. Standards Track [Page 1] + +RFC 2183 Content-Disposition August 1997 + + +1. Introduction + + MIME specifies a standard format for encapsulating multiple pieces of + data into a single Internet message. That document does not address + the issue of presentation styles; it provides a framework for the + interchange of message content, but leaves presentation issues solely + in the hands of mail user agent (MUA) implementors. + + Two common ways of presenting multipart electronic messages are as a + main document with a list of separate attachments, and as a single + document with the various parts expanded (displayed) inline. The + display of an attachment is generally construed to require positive + action on the part of the recipient, while inline message components + are displayed automatically when the message is viewed. A mechanism + is needed to allow the sender to transmit this sort of presentational + information to the recipient; the Content-Disposition header provides + this mechanism, allowing each component of a message to be tagged + with an indication of its desired presentation semantics. + + Tagging messages in this manner will often be sufficient for basic + message formatting. However, in many cases a more powerful and + flexible approach will be necessary. The definition of such + approaches is beyond the scope of this memo; however, such approaches + can benefit from additional Content-Disposition values and + parameters, to be defined at a later date. + + In addition to allowing the sender to specify the presentational + disposition of a message component, it is desirable to allow her to + indicate a default archival disposition; a filename. The optional + "filename" parameter provides for this. Further, the creation-date, + modification-date, and read-date parameters allow preservation of + those file attributes when the file is transmitted over MIME email. + + NB: The keywords MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, + SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL, when they appear in this + document, are to be interpreted as described in [RFC 2119]. + +2. The Content-Disposition Header Field + + Content-Disposition is an optional header field. In its absence, the + MUA may use whatever presentation method it deems suitable. + + It is desirable to keep the set of possible disposition types small + and well defined, to avoid needless complexity. Even so, evolving + usage will likely require the definition of additional disposition + types or parameters, so the set of disposition values is extensible; + see below. + + + + +Troost, et. al. Standards Track [Page 2] + +RFC 2183 Content-Disposition August 1997 + + + In the extended BNF notation of [RFC 822], the Content-Disposition + header field is defined as follows: + + disposition := "Content-Disposition" ":" + disposition-type + *(";" disposition-parm) + + disposition-type := "inline" + / "attachment" + / extension-token + ; values are not case-sensitive + + disposition-parm := filename-parm + / creation-date-parm + / modification-date-parm + / read-date-parm + / size-parm + / parameter + + filename-parm := "filename" "=" value + + creation-date-parm := "creation-date" "=" quoted-date-time + + modification-date-parm := "modification-date" "=" quoted-date-time + + read-date-parm := "read-date" "=" quoted-date-time + + size-parm := "size" "=" 1*DIGIT + + quoted-date-time := quoted-string + ; contents MUST be an RFC 822 `date-time' + ; numeric timezones (+HHMM or -HHMM) MUST be used + + + + NOTE ON PARAMETER VALUE LENGHTS: A short (length <= 78 characters) + parameter value containing only non-`tspecials' characters SHOULD be + represented as a single `token'. A short parameter value containing + only ASCII characters, but including `tspecials' characters, SHOULD + be represented as `quoted-string'. Parameter values longer than 78 + characters, or which contain non-ASCII characters, MUST be encoded as + specified in [RFC 2184]. + + `Extension-token', `parameter', `tspecials' and `value' are defined + according to [RFC 2045] (which references [RFC 822] in the definition + of some of these tokens). `quoted-string' and `DIGIT' are defined in + [RFC 822]. + + + + +Troost, et. al. Standards Track [Page 3] + +RFC 2183 Content-Disposition August 1997 + + +2.1 The Inline Disposition Type + + A bodypart should be marked `inline' if it is intended to be + displayed automatically upon display of the message. Inline + bodyparts should be presented in the order in which they occur, + subject to the normal semantics of multipart messages. + +2.2 The Attachment Disposition Type + + Bodyparts can be designated `attachment' to indicate that they are + separate from the main body of the mail message, and that their + display should not be automatic, but contingent upon some further + action of the user. The MUA might instead present the user of a + bitmap terminal with an iconic representation of the attachments, or, + on character terminals, with a list of attachments from which the + user could select for viewing or storage. + +2.3 The Filename Parameter + + The sender may want to suggest a filename to be used if the entity is + detached and stored in a separate file. If the receiving MUA writes + the entity to a file, the suggested filename should be used as a + basis for the actual filename, where possible. + + It is important that the receiving MUA not blindly use the suggested + filename. The suggested filename SHOULD be checked (and possibly + changed) to see that it conforms to local filesystem conventions, + does not overwrite an existing file, and does not present a security + problem (see Security Considerations below). + + The receiving MUA SHOULD NOT respect any directory path information + that may seem to be present in the filename parameter. The filename + should be treated as a terminal component only. Portable + specification of directory paths might possibly be done in the future + via a separate Content-Disposition parameter, but no provision is + made for it in this draft. + + Current [RFC 2045] grammar restricts parameter values (and hence + Content-Disposition filenames) to US-ASCII. We recognize the great + desirability of allowing arbitrary character sets in filenames, but + it is beyond the scope of this document to define the necessary + mechanisms. We expect that the basic [RFC 1521] `value' + specification will someday be amended to allow use of non-US-ASCII + characters, at which time the same mechanism should be used in the + Content-Disposition filename parameter. + + + + + + +Troost, et. al. Standards Track [Page 4] + +RFC 2183 Content-Disposition August 1997 + + + Beyond the limitation to US-ASCII, the sending MUA may wish to bear + in mind the limitations of common filesystems. Many have severe + length and character set restrictions. Short alphanumeric filenames + are least likely to require modification by the receiving system. + + The presence of the filename parameter does not force an + implementation to write the entity to a separate file. It is + perfectly acceptable for implementations to leave the entity as part + of the normal mail stream unless the user requests otherwise. As a + consequence, the parameter may be used on any MIME entity, even + `inline' ones. These will not normally be written to files, but the + parameter could be used to provide a filename if the receiving user + should choose to write the part to a file. + +2.4 The Creation-Date parameter + + The creation-date parameter MAY be used to indicate the date at which + the file was created. If this parameter is included, the paramter + value MUST be a quoted-string which contains a representation of the + creation date of the file in [RFC 822] `date-time' format. + + UNIX and POSIX implementors are cautioned that the `st_ctime' file + attribute of the `stat' structure is not the creation time of the + file; it is thus not appropriate as a source for the creation-date + parameter value. + +2.5 The Modification-Date parameter + + The modification-date parameter MAY be used to indicate the date at + which the file was last modified. If the modification-date parameter + is included, the paramter value MUST be a quoted-string which + contains a representation of the last modification date of the file + in [RFC 822] `date-time' format. + +2.6 The Read-Date parameter + + The read-date parameter MAY be used to indicate the date at which the + file was last read. If the read-date parameter is included, the + parameter value MUST be a quoted-string which contains a + representation of the last-read date of the file in [RFC 822] `date- + time' format. + +2.7 The Size parameter + + The size parameter indicates an approximate size of the file in + octets. It can be used, for example, to pre-allocate space before + attempting to store the file, or to determine whether enough space + exists. + + + +Troost, et. al. Standards Track [Page 5] + +RFC 2183 Content-Disposition August 1997 + + +2.8 Future Extensions and Unrecognized Disposition Types + + In the likely event that new parameters or disposition types are + needed, they should be registered with the Internet Assigned Numbers + Authority (IANA), in the manner specified in Section 9 of this memo. + + Once new disposition types and parameters are defined, there is of + course the likelihood that implementations will see disposition types + and parameters they do not understand. Furthermore, since x-tokens + are allowed, implementations may also see entirely unregistered + disposition types and parameters. + + Unrecognized parameters should be ignored. Unrecognized disposition + types should be treated as `attachment'. The choice of `attachment' + for unrecognized types is made because a sender who goes to the + trouble of producing a Content-Disposition header with a new + disposition type is more likely aiming for something more elaborate + than inline presentation. + + Unless noted otherwise in the definition of a parameter, Content- + Disposition parameters are valid for all dispositions. (In contrast + to MIME content-type parameters, which are defined on a per-content- + type basis.) Thus, for example, the `filename' parameter still means + the name of the file to which the part should be written, even if the + disposition itself is unrecognized. + +2.9 Content-Disposition and Multipart + + If a Content-Disposition header is used on a multipart body part, it + applies to the multipart as a whole, not the individual subparts. + The disposition types of the subparts do not need to be consulted + until the multipart itself is presented. When the multipart is + displayed, then the dispositions of the subparts should be respected. + + If the `inline' disposition is used, the multipart should be + displayed as normal; however, an `attachment' subpart should require + action from the user to display. + + If the `attachment' disposition is used, presentation of the + multipart should not proceed without explicit user action. Once the + user has chosen to display the multipart, the individual subpart + dispositions should be consulted to determine how to present the + subparts. + + + + + + + + +Troost, et. al. Standards Track [Page 6] + +RFC 2183 Content-Disposition August 1997 + + +2.10 Content-Disposition and the Main Message + + It is permissible to use Content-Disposition on the main body of an + [RFC 822] message. + +3. Examples + + Here is a an example of a body part containing a JPEG image that is + intended to be viewed by the user immediately: + + Content-Type: image/jpeg + Content-Disposition: inline + Content-Description: just a small picture of me + + + + The following body part contains a JPEG image that should be + displayed to the user only if the user requests it. If the JPEG is + written to a file, the file should be named "genome.jpg". The + recipient's user might also choose to set the last-modified date of + the stored file to date in the modification-date parameter: + + Content-Type: image/jpeg + Content-Disposition: attachment; filename=genome.jpeg; + modification-date="Wed, 12 Feb 1997 16:29:51 -0500"; + Content-Description: a complete map of the human genome + + + + The following is an example of the use of the `attachment' + disposition with a multipart body part. The user should see text- + part-1 immediately, then take some action to view multipart-2. After + taking action to view multipart-2, the user will see text-part-2 + right away, and be required to take action to view jpeg-1. Subparts + are indented for clarity; they would not be so indented in a real + message. + + + + + + + + + + + + + + + +Troost, et. al. Standards Track [Page 7] + +RFC 2183 Content-Disposition August 1997 + + + Content-Type: multipart/mixed; boundary=outer + Content-Description: multipart-1 + + --outer + Content-Type: text/plain + Content-Disposition: inline + Content-Description: text-part-1 + + Some text goes here + + --outer + Content-Type: multipart/mixed; boundary=inner + Content-Disposition: attachment + Content-Description: multipart-2 + + --inner + Content-Type: text/plain + Content-Disposition: inline + Content-Description: text-part-2 + + Some more text here. + + --inner + Content-Type: image/jpeg + Content-Disposition: attachment + Content-Description: jpeg-1 + + + --inner-- + --outer-- + +4. Summary + + Content-Disposition takes one of two values, `inline' and + `attachment'. `Inline' indicates that the entity should be + immediately displayed to the user, whereas `attachment' means that + the user should take additional action to view the entity. + + The `filename' parameter can be used to suggest a filename for + storing the bodypart, if the user wishes to store it in an external + file. + + + + + + + + + + +Troost, et. al. Standards Track [Page 8] + +RFC 2183 Content-Disposition August 1997 + + +5. Security Considerations + + There are security issues involved any time users exchange data. + While these are not to be minimized, neither does this memo change + the status quo in that regard, except in one instance. + + Since this memo provides a way for the sender to suggest a filename, + a receiving MUA must take care that the sender's suggested filename + does not represent a hazard. Using UNIX as an example, some hazards + would be: + + + Creating startup files (e.g., ".login"). + + + Creating or overwriting system files (e.g., "/etc/passwd"). + + + Overwriting any existing file. + + + Placing executable files into any command search path + (e.g., "~/bin/more"). + + + Sending the file to a pipe (e.g., "| sh"). + + In general, the receiving MUA should not name or place the file such + that it will get interpreted or executed without the user explicitly + initiating the action. + + It is very important to note that this is not an exhaustive list; it + is intended as a small set of examples only. Implementors must be + alert to the potential hazards on their target systems. + +6. References + + [RFC 2119] + Bradner, S., "Key words for use in RFCs to Indicate Requirement + Levels", RFC 2119, March 1997. + + [RFC 2184] + Freed, N. and K. Moore, "MIME Parameter value and Encoded Words: + Character Sets, Lanaguage, and Continuations", RFC 2184, August + 1997. + + [RFC 2045] + Freed, N. and N. Borenstein, "MIME (Multipurpose Internet Mail + Extensions) Part One: Format of Internet Message Bodies", RFC + 2045, December 1996. + + + + + + +Troost, et. al. Standards Track [Page 9] + +RFC 2183 Content-Disposition August 1997 + + + [RFC 2046] + Freed, N. and N. Borenstein, "MIME (Multipurpose Internet Mail + Extensions) Part Two: Media Types", RFC 2046, December 1996. + + [RFC 2047] + Moore, K., "MIME (Multipurpose Internet Mail Extensions) Part + Three: Message Header Extensions for non-ASCII Text", RFC 2047, + December 1996. + + [RFC 2048] + Freed, N., Klensin, J. and J. Postel, "MIME (Multipurpose + Internet Mail Extensions) Part Four: Registration Procedures", + RFC 2048, December 1996. + + [RFC 2049] + Freed, N. and N. Borenstein, "MIME (Multipurpose Internet Mail + Extensions) Part Five: Conformance Criteria and Examples", RFC + 2049, December 1996. + + [RFC 822] + Crocker, D., "Standard for the Format of ARPA Internet Text + Messages", STD 11, RFC 822, UDEL, August 1982. + +7. Acknowledgements + + We gratefully acknowledge the help these people provided during the + preparation of this draft: + + Nathaniel Borenstein + Ned Freed + Keith Moore + Dave Crocker + Dan Pritchett + + + + + + + + + + + + + + + + + + +Troost, et. al. Standards Track [Page 10] + +RFC 2183 Content-Disposition August 1997 + + +8. Authors' Addresses + + You should blame the editor of this version of the document for any + changes since RFC 1806: + + Keith Moore + Department of Computer Science + University of Tennessee, Knoxville + 107 Ayres Hall + Knoxville TN 37996-1301 + USA + + Phone: +1 (423) 974-5067 + Fax: +1 (423) 974-8296 + Email: moore@cs.utk.edu + + + The authors of RFC 1806 are: + + Rens Troost + New Century Systems + 324 East 41st Street #804 + New York, NY, 10017 USA + + Phone: +1 (212) 557-2050 + Fax: +1 (212) 557-2049 + EMail: rens@century.com + + + Steve Dorner + QUALCOMM Incorporated + 6455 Lusk Boulevard + San Diego, CA 92121 + USA + + EMail: sdorner@qualcomm.com + + +9. Registration of New Content-Disposition Values and Parameters + + New Content-Disposition values (besides "inline" and "attachment") + may be defined only by Internet standards-track documents, or in + Experimental documents approved by the Internet Engineering Steering + Group. + + + + + + + +Troost, et. al. Standards Track [Page 11] + +RFC 2183 Content-Disposition August 1997 + + + New content-disposition parameters may be registered by supplying the + information in the following template and sending it via electronic + mail to IANA@IANA.ORG: + + To: IANA@IANA.ORG + Subject: Registration of new Content-Disposition parameter + + Content-Disposition parameter name: + + Allowable values for this parameter: + (If the parameter can only assume a small number of values, + list each of those values. Otherwise, describe the values + that the parameter can assume.) + Description: + (What is the purpose of this parameter and how is it used?) + +10. Changes since RFC 1806 + + The following changes have been made since the earlier version of + this document, published in RFC 1806 as an Experimental protocol: + + + Updated references to MIME documents. In some cases this + involved substituting a reference to one of the current MIME + RFCs for a reference to RFC 1521; in other cases, a reference to + RFC 1521 was simply replaced with the word "MIME". + + + Added a section on registration procedures, since none of the + procedures in RFC 2048 seemed to be appropriate. + + + Added new parameter types: creation-date, modification-date, + read-date, and size. + + + + Incorporated a reference to draft-freed-pvcsc-* for encoding + long or non-ASCII parameter values. + + + Added reference to RFC 2119 to define MUST, SHOULD, etc. + keywords. + + + + + + + + + + + + + +Troost, et. al. Standards Track [Page 12] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2222.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2222.txt new file mode 100644 index 00000000..2b0a2abc --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2222.txt @@ -0,0 +1,899 @@ + + + + + + +Network Working Group J. Myers +Request for Comments: 2222 Netscape Communications +Category: Standards Track October 1997 + + + Simple Authentication and Security Layer (SASL) + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1997). All Rights Reserved. + +Table of Contents + + 1. Abstract .............................................. 2 + 2. Organization of this Document ......................... 2 + 2.1. How to Read This Document ............................. 2 + 2.2. Conventions Used in this Document ..................... 2 + 2.3. Examples .............................................. 3 + 3. Introduction and Overview ............................. 3 + 4. Profiling requirements ................................ 4 + 5. Specific issues ....................................... 5 + 5.1. Client sends data first ............................... 5 + 5.2. Server returns success with additional data ........... 5 + 5.3. Multiple authentications .............................. 5 + 6. Registration procedures ............................... 6 + 6.1. Comments on SASL mechanism registrations .............. 6 + 6.2. Location of Registered SASL Mechanism List ............ 6 + 6.3. Change Control ........................................ 7 + 6.4. Registration Template ................................. 7 + 7. Mechanism definitions ................................. 8 + 7.1. Kerberos version 4 mechanism .......................... 8 + 7.2. GSSAPI mechanism ...................................... 9 + 7.2.1 Client side of authentication protocol exchange ....... 9 + 7.2.2 Server side of authentication protocol exchange ....... 10 + 7.2.3 Security layer ........................................ 11 + 7.3. S/Key mechanism ....................................... 11 + 7.4. External mechanism .................................... 12 + 8. References ............................................ 13 + 9. Security Considerations ............................... 13 + 10. Author's Address ...................................... 14 + + + +Myers Standards Track [Page 1] + +RFC 2222 SASL October 1997 + + + Appendix A. Relation of SASL to Transport Security .......... 15 + Full Copyright Statement .................................... 16 + +1. Abstract + + This document describes a method for adding authentication support to + connection-based protocols. To use this specification, a protocol + includes a command for identifying and authenticating a user to a + server and for optionally negotiating protection of subsequent + protocol interactions. If its use is negotiated, a security layer is + inserted between the protocol and the connection. This document + describes how a protocol specifies such a command, defines several + mechanisms for use by the command, and defines the protocol used for + carrying a negotiated security layer over the connection. + +2. Organization of this Document + +2.1. How to Read This Document + + This document is written to serve two different audiences, protocol + designers using this specification to support authentication in their + protocol, and implementors of clients or servers for those protocols + using this specification. + + The sections "Introduction and Overview", "Profiling requirements", + and "Security Considerations" cover issues that protocol designers + need to understand and address in profiling this specification for + use in a specific protocol. + + Implementors of a protocol using this specification need the + protocol-specific profiling information in addition to the + information in this document. + +2.2. Conventions Used in this Document + + In examples, "C:" and "S:" indicate lines sent by the client and + server respectively. + + The key words "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", and "MAY" + in this document are to be interpreted as defined in "Key words for + use in RFCs to Indicate Requirement Levels" [RFC 2119]. + + + + + + + + + + +Myers Standards Track [Page 2] + +RFC 2222 SASL October 1997 + + +2.3. Examples + + Examples in this document are for the IMAP profile [RFC 2060] of this + specification. The base64 encoding of challenges and responses, as + well as the "+ " preceding the responses are part of the IMAP4 + profile, not part of the SASL specification itself. + +3. Introduction and Overview + + The Simple Authentication and Security Layer (SASL) is a method for + adding authentication support to connection-based protocols. To use + this specification, a protocol includes a command for identifying and + authenticating a user to a server and for optionally negotiating a + security layer for subsequent protocol interactions. + + The command has a required argument identifying a SASL mechanism. + SASL mechanisms are named by strings, from 1 to 20 characters in + length, consisting of upper-case letters, digits, hyphens, and/or + underscores. SASL mechanism names must be registered with the IANA. + Procedures for registering new SASL mechanisms are given in the + section "Registration procedures" + + If a server supports the requested mechanism, it initiates an + authentication protocol exchange. This consists of a series of + server challenges and client responses that are specific to the + requested mechanism. The challenges and responses are defined by the + mechanisms as binary tokens of arbitrary length. The protocol's + profile then specifies how these binary tokens are then encoded for + transfer over the connection. + + After receiving the authentication command or any client response, a + server may issue a challenge, indicate failure, or indicate + completion. The protocol's profile specifies how the server + indicates which of the above it is doing. + + After receiving a challenge, a client may issue a response or abort + the exchange. The protocol's profile specifies how the client + indicates which of the above it is doing. + + During the authentication protocol exchange, the mechanism performs + authentication, transmits an authorization identity (frequently known + as a userid) from the client to server, and negotiates the use of a + mechanism-specific security layer. If the use of a security layer is + agreed upon, then the mechanism must also define or negotiate the + maximum cipher-text buffer size that each side is able to receive. + + + + + + +Myers Standards Track [Page 3] + +RFC 2222 SASL October 1997 + + + The transmitted authorization identity may be different than the + identity in the client's authentication credentials. This permits + agents such as proxy servers to authenticate using their own + credentials, yet request the access privileges of the identity for + which they are proxying. With any mechanism, transmitting an + authorization identity of the empty string directs the server to + derive an authorization identity from the client's authentication + credentials. + + If use of a security layer is negotiated, it is applied to all + subsequent data sent over the connection. The security layer takes + effect immediately following the last response of the authentication + exchange for data sent by the client and the completion indication + for data sent by the server. Once the security layer is in effect, + the protocol stream is processed by the security layer into buffers + of cipher-text. Each buffer is transferred over the connection as a + stream of octets prepended with a four octet field in network byte + order that represents the length of the following buffer. The length + of the cipher-text buffer must be no larger than the maximum size + that was defined or negotiated by the other side. + +4. Profiling requirements + + In order to use this specification, a protocol definition must supply + the following information: + + 1. A service name, to be selected from the IANA registry of "service" + elements for the GSSAPI host-based service name form [RFC 2078]. + + 2. A definition of the command to initiate the authentication + protocol exchange. This command must have as a parameter the + mechanism name being selected by the client. + + The command SHOULD have an optional parameter giving an initial + response. This optional parameter allows the client to avoid a + round trip when using a mechanism which is defined to have the + client send data first. When this initial response is sent by the + client and the selected mechanism is defined to have the server + start with an initial challenge, the command fails. See section + 5.1 of this document for further information. + + 3. A definition of the method by which the authentication protocol + exchange is carried out, including how the challenges and + responses are encoded, how the server indicates completion or + failure of the exchange, how the client aborts an exchange, and + how the exchange method interacts with any line length limits in + the protocol. + + + + +Myers Standards Track [Page 4] + +RFC 2222 SASL October 1997 + + + 4. Identification of the octet where any negotiated security layer + starts to take effect, in both directions. + + 5. A specification of how the authorization identity passed from the + client to the server is to be interpreted. + +5. Specific issues + +5.1. Client sends data first + + Some mechanisms specify that the first data sent in the + authentication protocol exchange is from the client to the server. + + If a protocol's profile permits the command which initiates an + authentication protocol exchange to contain an initial client + response, this parameter SHOULD be used with such mechanisms. + + If the initial client response parameter is not given, or if a + protocol's profile does not permit the command which initiates an + authentication protocol exchange to contain an initial client + response, then the server issues a challenge with no data. The + client's response to this challenge is then used as the initial + client response. (The server then proceeds to send the next + challenge, indicates completion, or indicates failure.) + +5.2. Server returns success with additional data + + Some mechanisms may specify that server challenge data be sent to the + client along with an indication of successful completion of the + exchange. This data would, for example, authenticate the server to + the client. + + If a protocol's profile does not permit this server challenge to be + returned with a success indication, then the server issues the server + challenge without an indication of successful completion. The client + then responds with no data. After receiving this empty response, the + server then indicates successful completion. + +5.3. Multiple authentications + + Unless otherwise stated by the protocol's profile, only one + successful SASL negotiation may occur in a protocol session. In this + case, once an authentication protocol exchange has successfully + completed, further attempts to initiate an authentication protocol + exchange fail. + + + + + + +Myers Standards Track [Page 5] + +RFC 2222 SASL October 1997 + + + In the case that a profile explicitly permits multiple successful + SASL negotiations to occur, then in no case may multiple security + layers be simultaneously in effect. If a security layer is in effect + and a subsequent SASL negotiation selects no security layer, the + original security layer remains in effect. If a security layer is in + effect and a subsequent SASL negotiation selects a second security + layer, then the second security layer replaces the first. + +6. Registration procedures + + Registration of a SASL mechanism is done by filling in the template + in section 6.4 and sending it in to iana@isi.edu. IANA has the right + to reject obviously bogus registrations, but will perform no review + of clams made in the registration form. + + There is no naming convention for SASL mechanisms; any name that + conforms to the syntax of a SASL mechanism name can be registered. + + While the registration procedures do not require it, authors of SASL + mechanisms are encouraged to seek community review and comment + whenever that is feasible. Authors may seek community review by + posting a specification of their proposed mechanism as an internet- + draft. SASL mechanisms intended for widespread use should be + standardized through the normal IETF process, when appropriate. + +6.1. Comments on SASL mechanism registrations + + Comments on registered SASL mechanisms should first be sent to the + "owner" of the mechanism. Submitters of comments may, after a + reasonable attempt to contact the owner, request IANA to attach their + comment to the SASL mechanism registration itself. If IANA approves + of this the comment will be made accessible in conjunction with the + SASL mechanism registration itself. + +6.2. Location of Registered SASL Mechanism List + + SASL mechanism registrations will be posted in the anonymous FTP + directory "ftp://ftp.isi.edu/in-notes/iana/assignments/sasl- + mechanisms/" and all registered SASL mechanisms will be listed in the + periodically issued "Assigned Numbers" RFC [currently STD 2, RFC + 1700]. The SASL mechanism description and other supporting material + may also be published as an Informational RFC by sending it to "rfc- + editor@isi.edu" (please follow the instructions to RFC authors [RFC + 2223]). + + + + + + + +Myers Standards Track [Page 6] + +RFC 2222 SASL October 1997 + + +6.3. Change Control + + Once a SASL mechanism registration has been published by IANA, the + author may request a change to its definition. The change request + follows the same procedure as the registration request. + + The owner of a SASL mechanism may pass responsibility for the SASL + mechanism to another person or agency by informing IANA; this can be + done without discussion or review. + + The IESG may reassign responsibility for a SASL mechanism. The most + common case of this will be to enable changes to be made to + mechanisms where the author of the registration has died, moved out + of contact or is otherwise unable to make changes that are important + to the community. + + SASL mechanism registrations may not be deleted; mechanisms which are + no longer believed appropriate for use can be declared OBSOLETE by a + change to their "intended use" field; such SASL mechanisms will be + clearly marked in the lists published by IANA. + + The IESG is considered to be the owner of all SASL mechanisms which + are on the IETF standards track. + +6.4. Registration Template + + To: iana@iana.org + Subject: Registration of SASL mechanism X + + SASL mechanism name: + + Security considerations: + + Published specification (optional, recommended): + + Person & email address to contact for further information: + + Intended usage: + + (One of COMMON, LIMITED USE or OBSOLETE) + + Author/Change controller: + + (Any other information that the author deems interesting may be + added below this line.) + + + + + + +Myers Standards Track [Page 7] + +RFC 2222 SASL October 1997 + + +7. Mechanism definitions + + The following mechanisms are hereby defined. + +7.1. Kerberos version 4 mechanism + + The mechanism name associated with Kerberos version 4 is + "KERBEROS_V4". + + The first challenge consists of a random 32-bit number in network + byte order. The client responds with a Kerberos ticket and an + authenticator for the principal "service.hostname@realm", where + "service" is the service name specified in the protocol's profile, + "hostname" is the first component of the host name of the server with + all letters in lower case, and where "realm" is the Kerberos realm of + the server. The encrypted checksum field included within the + Kerberos authenticator contains the server provided challenge in + network byte order. + + Upon decrypting and verifying the ticket and authenticator, the + server verifies that the contained checksum field equals the original + server provided random 32-bit number. Should the verification be + successful, the server must add one to the checksum and construct 8 + octets of data, with the first four octets containing the incremented + checksum in network byte order, the fifth octet containing a bit-mask + specifying the security layers supported by the server, and the sixth + through eighth octets containing, in network byte order, the maximum + cipher-text buffer size the server is able to receive. The server + must encrypt using DES ECB mode the 8 octets of data in the session + key and issue that encrypted data in a second challenge. The client + considers the server authenticated if the first four octets of the + un-encrypted data is equal to one plus the checksum it previously + sent. + + The client must construct data with the first four octets containing + the original server-issued checksum in network byte order, the fifth + octet containing the bit-mask specifying the selected security layer, + the sixth through eighth octets containing in network byte order the + maximum cipher-text buffer size the client is able to receive, and + the following octets containing the authorization identity. The + client must then append from one to eight zero-valued octets so that + the length of the data is a multiple of eight octets. The client must + then encrypt using DES PCBC mode the data with the session key and + respond with the encrypted data. The server decrypts the data and + verifies the contained checksum. The server must verify that the + principal identified in the Kerberos ticket is authorized to connect + as that authorization identity. After this verification, the + authentication process is complete. + + + +Myers Standards Track [Page 8] + +RFC 2222 SASL October 1997 + + + The security layers and their corresponding bit-masks are as follows: + + 1 No security layer + 2 Integrity (krb_mk_safe) protection + 4 Privacy (krb_mk_priv) protection + + Other bit-masks may be defined in the future; bits which are not + understood must be negotiated off. + + EXAMPLE: The following are two Kerberos version 4 login scenarios to + the IMAP4 protocol (note that the line breaks in the sample + authenticators are for editorial clarity and are not in real + authenticators) + + S: * OK IMAP4 Server + C: A001 AUTHENTICATE KERBEROS_V4 + S: + AmFYig== + C: BAcAQU5EUkVXLkNNVS5FRFUAOCAsho84kLN3/IJmrMG+25a4DT + +nZImJjnTNHJUtxAA+o0KPKfHEcAFs9a3CL5Oebe/ydHJUwYFd + WwuQ1MWiy6IesKvjL5rL9WjXUb9MwT9bpObYLGOKi1Qh + S: + or//EoAADZI= + C: DiAF5A4gA+oOIALuBkAAmw== + S: A001 OK Kerberos V4 authentication successful + + + S: * OK IMAP4 Server + C: A001 AUTHENTICATE KERBEROS_V4 + S: + gcfgCA== + C: BAcAQU5EUkVXLkNNVS5FRFUAOCAsho84kLN3/IJmrMG+25a4DT + +nZImJjnTNHJUtxAA+o0KPKfHEcAFs9a3CL5Oebe/ydHJUwYFd + WwuQ1MWiy6IesKvjL5rL9WjXUb9MwT9bpObYLGOKi1Qh + S: A001 NO Kerberos V4 authentication failed + +7.2. GSSAPI mechanism + + The mechanism name associated with all mechanisms employing the + GSSAPI [RFC 2078] is "GSSAPI". + +7.2.1 Client side of authentication protocol exchange + + The client calls GSS_Init_sec_context, passing in 0 for + input_context_handle (initially) and a targ_name equal to output_name + from GSS_Import_Name called with input_name_type of + GSS_C_NT_HOSTBASED_SERVICE and input_name_string of + "service@hostname" where "service" is the service name specified in + the protocol's profile, and "hostname" is the fully qualified host + name of the server. The client then responds with the resulting + output_token. If GSS_Init_sec_context returns GSS_S_CONTINUE_NEEDED, + + + +Myers Standards Track [Page 9] + +RFC 2222 SASL October 1997 + + + then the client should expect the server to issue a token in a + subsequent challenge. The client must pass the token to another call + to GSS_Init_sec_context, repeating the actions in this paragraph. + + When GSS_Init_sec_context returns GSS_S_COMPLETE, the client takes + the following actions: If the last call to GSS_Init_sec_context + returned an output_token, then the client responds with the + output_token, otherwise the client responds with no data. The client + should then expect the server to issue a token in a subsequent + challenge. The client passes this token to GSS_Unwrap and interprets + the first octet of resulting cleartext as a bit-mask specifying the + security layers supported by the server and the second through fourth + octets as the maximum size output_message to send to the server. The + client then constructs data, with the first octet containing the + bit-mask specifying the selected security layer, the second through + fourth octets containing in network byte order the maximum size + output_message the client is able to receive, and the remaining + octets containing the authorization identity. The client passes the + data to GSS_Wrap with conf_flag set to FALSE, and responds with the + generated output_message. The client can then consider the server + authenticated. + +7.2.2 Server side of authentication protocol exchange + + The server passes the initial client response to + GSS_Accept_sec_context as input_token, setting input_context_handle + to 0 (initially). If GSS_Accept_sec_context returns + GSS_S_CONTINUE_NEEDED, the server returns the generated output_token + to the client in challenge and passes the resulting response to + another call to GSS_Accept_sec_context, repeating the actions in this + paragraph. + + When GSS_Accept_sec_context returns GSS_S_COMPLETE, the client takes + the following actions: If the last call to GSS_Accept_sec_context + returned an output_token, the server returns it to the client in a + challenge and expects a reply from the client with no data. Whether + or not an output_token was returned (and after receipt of any + response from the client to such an output_token), the server then + constructs 4 octets of data, with the first octet containing a bit- + mask specifying the security layers supported by the server and the + second through fourth octets containing in network byte order the + maximum size output_token the server is able to receive. The server + must then pass the plaintext to GSS_Wrap with conf_flag set to FALSE + and issue the generated output_message to the client in a challenge. + The server must then pass the resulting response to GSS_Unwrap and + interpret the first octet of resulting cleartext as the bit-mask for + the selected security layer, the second through fourth octets as the + maximum size output_message to send to the client, and the remaining + + + +Myers Standards Track [Page 10] + +RFC 2222 SASL October 1997 + + + octets as the authorization identity. The server must verify that + the src_name is authorized to authenticate as the authorization + identity. After these verifications, the authentication process is + complete. + +7.2.3 Security layer + + The security layers and their corresponding bit-masks are as follows: + + 1 No security layer + 2 Integrity protection. + Sender calls GSS_Wrap with conf_flag set to FALSE + 4 Privacy protection. + Sender calls GSS_Wrap with conf_flag set to TRUE + + Other bit-masks may be defined in the future; bits which are not + understood must be negotiated off. + +7.3. S/Key mechanism + + The mechanism name associated with S/Key [RFC 1760] using the MD4 + digest algorithm is "SKEY". + + The client sends an initial response with the authorization identity. + + The server then issues a challenge which contains the decimal + sequence number followed by a single space and the seed string for + the indicated authorization identity. The client responds with the + one-time-password, as either a 64-bit value in network byte order or + encoded in the "six English words" format. + + The server must verify the one-time-password. After this + verification, the authentication process is complete. + + S/Key authentication does not provide for any security layers. + + EXAMPLE: The following are two S/Key login scenarios in the IMAP4 + protocol. + + S: * OK IMAP4 Server + C: A001 AUTHENTICATE SKEY + S: + + C: bW9yZ2Fu + S: + OTUgUWE1ODMwOA== + C: Rk9VUiBNQU5OIFNPT04gRklSIFZBUlkgTUFTSA== + S: A001 OK S/Key authentication successful + + + + + +Myers Standards Track [Page 11] + +RFC 2222 SASL October 1997 + + + S: * OK IMAP4 Server + C: A001 AUTHENTICATE SKEY + S: + + C: c21pdGg= + S: + OTUgUWE1ODMwOA== + C: BsAY3g4gBNo= + S: A001 NO S/Key authentication failed + + The following is an S/Key login scenario in an IMAP4-like protocol + which has an optional "initial response" argument to the AUTHENTICATE + command. + + S: * OK IMAP4-Like Server + C: A001 AUTHENTICATE SKEY bW9yZ2Fu + S: + OTUgUWE1ODMwOA== + C: Rk9VUiBNQU5OIFNPT04gRklSIFZBUlkgTUFTSA== + S: A001 OK S/Key authentication successful + +7.4. External mechanism + + The mechanism name associated with external authentication is + "EXTERNAL". + + The client sends an initial response with the authorization identity. + + The server uses information, external to SASL, to determine whether + the client is authorized to authenticate as the authorization + identity. If the client is so authorized, the server indicates + successful completion of the authentication exchange; otherwise the + server indicates failure. + + The system providing this external information may be, for example, + IPsec or TLS. + + If the client sends the empty string as the authorization identity + (thus requesting the authorization identity be derived from the + client's authentication credentials), the authorization identity is + to be derived from authentication credentials which exist in the + system which is providing the external authentication. + + + + + + + + + + + + +Myers Standards Track [Page 12] + +RFC 2222 SASL October 1997 + + +8. References + + [RFC 2060] Crispin, M., "Internet Message Access Protocol - Version + 4rev1", RFC 2060, December 1996. + + [RFC 2078] Linn, J., "Generic Security Service Application Program + Interface, Version 2", RFC 2078, January 1997. + + [RFC 2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", RFC 2119, March 1997. + + [RFC 2223] Postel, J., and J. Reynolds, "Instructions to RFC + Authors", RFC 2223, October 1997. + + [RFC 1760] Haller, N., "The S/Key One-Time Password System", RFC + 1760, February 1995. + + [RFC 1700] Reynolds, J., and J. Postel, "Assigned Numbers", STD 2, + RFC 1700, October 1994. + +9. Security Considerations + + Security issues are discussed throughout this memo. + + The mechanisms that support integrity protection are designed such + that the negotiation of the security layer and authorization identity + is integrity protected. When the client selects a security layer + with at least integrity protection, this protects against an active + attacker hijacking the connection and modifying the authentication + exchange to negotiate a plaintext connection. + + When a server or client supports multiple authentication mechanisms, + each of which has a different security strength, it is possible for + an active attacker to cause a party to use the least secure mechanism + supported. To protect against this sort of attack, a client or + server which supports mechanisms of different strengths should have a + configurable minimum strength that it will use. It is not sufficient + for this minimum strength check to only be on the server, since an + active attacker can change which mechanisms the client sees as being + supported, causing the client to send authentication credentials for + its weakest supported mechanism. + + + + + + + + + + +Myers Standards Track [Page 13] + +RFC 2222 SASL October 1997 + + + The client's selection of a SASL mechanism is done in the clear and + may be modified by an active attacker. It is important for any new + SASL mechanisms to be designed such that an active attacker cannot + obtain an authentication with weaker security properties by modifying + the SASL mechanism name and/or the challenges and responses. + + Any protocol interactions prior to authentication are performed in + the clear and may be modified by an active attacker. In the case + where a client selects integrity protection, it is important that any + security-sensitive protocol negotiations be performed after + authentication is complete. Protocols should be designed such that + negotiations performed prior to authentication should be either + ignored or revalidated once authentication is complete. + +10. Author's Address + + John G. Myers + Netscape Communications + 501 E. Middlefield Road + Mail Stop MV-029 + Mountain View, CA 94043-4042 + + EMail: jgmyers@netscape.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Myers Standards Track [Page 14] + +RFC 2222 SASL October 1997 + + +Appendix A. Relation of SASL to Transport Security + + Questions have been raised about the relationship between SASL and + various services (such as IPsec and TLS) which provide a secured + connection. + + Two of the key features of SASL are: + + 1. The separation of the authorization identity from the identity in + the client's credentials. This permits agents such as proxy + servers to authenticate using their own credentials, yet request + the access privileges of the identity for which they are proxying. + + 2. Upon successful completion of an authentication exchange, the + server knows the authorization identity the client wishes to use. + This allows servers to move to a "user is authenticated" state in + the protocol. + + These features are extremely important to some application protocols, + yet Transport Security services do not always provide them. To + define SASL mechanisms based on these services would be a very messy + task, as the framing of these services would be redundant with the + framing of SASL and some method of providing these important SASL + features would have to be devised. + + Sometimes it is desired to enable within an existing connection the + use of a security service which does not fit the SASL model. (TLS is + an example of such a service.) This can be done by adding a command, + for example "STARTTLS", to the protocol. Such a command is outside + the scope of SASL, and should be different from the command which + starts a SASL authentication protocol exchange. + + In certain situations, it is reasonable to use SASL underneath one of + these Transport Security services. The transport service would + secure the connection, either service would authenticate the client, + and SASL would negotiate the authorization identity. The SASL + negotiation would be what moves the protocol from "unauthenticated" + to "authenticated" state. The "EXTERNAL" SASL mechanism is + explicitly intended to handle the case where the transport service + secures the connection and authenticates the client and SASL + negotiates the authorization identity. + + When using SASL underneath a sufficiently strong Transport Security + service, a SASL security layer would most likely be redundant. The + client and server would thus probably want to negotiate off the use + of a SASL security layer. + + + + + +Myers Standards Track [Page 15] + +RFC 2222 SASL October 1997 + + +Full Copyright Statement + + Copyright (C) The Internet Society (1997). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implmentation may be prepared, copied, published + andand distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Myers Standards Track [Page 16] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2231.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2231.txt new file mode 100644 index 00000000..120f98f8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2231.txt @@ -0,0 +1,563 @@ + + + + + + +Network Working Group N. Freed +Request for Comments: 2231 Innosoft +Updates: 2045, 2047, 2183 K. Moore +Obsoletes: 2184 University of Tennessee +Category: Standards Track November 1997 + + + MIME Parameter Value and Encoded Word Extensions: + Character Sets, Languages, and Continuations + + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1997). All Rights Reserved. + +1. Abstract + + This memo defines extensions to the RFC 2045 media type and RFC 2183 + disposition parameter value mechanisms to provide + + (1) a means to specify parameter values in character sets + other than US-ASCII, + + (2) to specify the language to be used should the value be + displayed, and + + (3) a continuation mechanism for long parameter values to + avoid problems with header line wrapping. + + This memo also defines an extension to the encoded words defined in + RFC 2047 to allow the specification of the language to be used for + display as well as the character set. + +2. Introduction + + The Multipurpose Internet Mail Extensions, or MIME [RFC-2045, RFC- + 2046, RFC-2047, RFC-2048, RFC-2049], define a message format that + allows for: + + + + + +Freed & Moore Standards Track [Page 1] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + (1) textual message bodies in character sets other than + US-ASCII, + + (2) non-textual message bodies, + + (3) multi-part message bodies, and + + (4) textual header information in character sets other than + US-ASCII. + + MIME is now widely deployed and is used by a variety of Internet + protocols, including, of course, Internet email. However, MIME's + success has resulted in the need for additional mechanisms that were + not provided in the original protocol specification. + + In particular, existing MIME mechanisms provide for named media type + (content-type field) parameters as well as named disposition + (content-disposition field). A MIME media type may specify any + number of parameters associated with all of its subtypes, and any + specific subtype may specify additional parameters for its own use. A + MIME disposition value may specify any number of associated + parameters, the most important of which is probably the attachment + disposition's filename parameter. + + These parameter names and values end up appearing in the content-type + and content-disposition header fields in Internet email. This + inherently imposes three crucial limitations: + + (1) Lines in Internet email header fields are folded + according to RFC 822 folding rules. This makes long + parameter values problematic. + + (2) MIME headers, like the RFC 822 headers they often + appear in, are limited to 7bit US-ASCII, and the + encoded-word mechanisms of RFC 2047 are not available + to parameter values. This makes it impossible to have + parameter values in character sets other than US-ASCII + without specifying some sort of private per-parameter + encoding. + + (3) It has recently become clear that character set + information is not sufficient to properly display some + sorts of information -- language information is also + needed [RFC-2130]. For example, support for + handicapped users may require reading text string + + + + + + +Freed & Moore Standards Track [Page 2] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + aloud. The language the text is written in is needed + for this to be done correctly. Some parameter values + may need to be displayed, hence there is a need to + allow for the inclusion of language information. + + The last problem on this list is also an issue for the encoded words + defined by RFC 2047, as encoded words are intended primarily for + display purposes. + + This document defines extensions that address all of these + limitations. All of these extensions are implemented in a fashion + that is completely compatible at a syntactic level with existing MIME + implementations. In addition, the extensions are designed to have as + little impact as possible on existing uses of MIME. + + IMPORTANT NOTE: These mechanisms end up being somewhat gibbous when + they actually are used. As such, these mechanisms should not be used + lightly; they should be reserved for situations where a real need for + them exists. + +2.1. Requirements notation + + This document occasionally uses terms that appear in capital letters. + When the terms "MUST", "SHOULD", "MUST NOT", "SHOULD NOT", and "MAY" + appear capitalized, they are being used to indicate particular + requirements of this specification. A discussion of the meanings of + these terms appears in [RFC- 2119]. + +3. Parameter Value Continuations + + Long MIME media type or disposition parameter values do not interact + well with header line wrapping conventions. In particular, proper + header line wrapping depends on there being places where linear + whitespace (LWSP) is allowed, which may or may not be present in a + parameter value, and even if present may not be recognizable as such + since specific knowledge of parameter value syntax may not be + available to the agent doing the line wrapping. The result is that + long parameter values may end up getting truncated or otherwise + damaged by incorrect line wrapping implementations. + + A mechanism is therefore needed to break up parameter values into + smaller units that are amenable to line wrapping. Any such mechanism + MUST be compatible with existing MIME processors. This means that + + (1) the mechanism MUST NOT change the syntax of MIME media + type and disposition lines, and + + + + + +Freed & Moore Standards Track [Page 3] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + (2) the mechanism MUST NOT depend on parameter ordering + since MIME states that parameters are not order + sensitive. Note that while MIME does prohibit + modification of MIME headers during transport, it is + still possible that parameters will be reordered when + user agent level processing is done. + + The obvious solution, then, is to use multiple parameters to contain + a single parameter value and to use some kind of distinguished name + to indicate when this is being done. And this obvious solution is + exactly what is specified here: The asterisk character ("*") followed + by a decimal count is employed to indicate that multiple parameters + are being used to encapsulate a single parameter value. The count + starts at 0 and increments by 1 for each subsequent section of the + parameter value. Decimal values are used and neither leading zeroes + nor gaps in the sequence are allowed. + + The original parameter value is recovered by concatenating the + various sections of the parameter, in order. For example, the + content-type field + + Content-Type: message/external-body; access-type=URL; + URL*0="ftp://"; + URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar" + + is semantically identical to + + Content-Type: message/external-body; access-type=URL; + URL="ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar" + + Note that quotes around parameter values are part of the value + syntax; they are NOT part of the value itself. Furthermore, it is + explicitly permitted to have a mixture of quoted and unquoted + continuation fields. + +4. Parameter Value Character Set and Language Information + + Some parameter values may need to be qualified with character set or + language information. It is clear that a distinguished parameter + name is needed to identify when this information is present along + with a specific syntax for the information in the value itself. In + addition, a lightweight encoding mechanism is needed to accommodate 8 + bit information in parameter values. + + + + + + + + +Freed & Moore Standards Track [Page 4] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + Asterisks ("*") are reused to provide the indicator that language and + character set information is present and encoding is being used. A + single quote ("'") is used to delimit the character set and language + information at the beginning of the parameter value. Percent signs + ("%") are used as the encoding flag, which agrees with RFC 2047. + + Specifically, an asterisk at the end of a parameter name acts as an + indicator that character set and language information may appear at + the beginning of the parameter value. A single quote is used to + separate the character set, language, and actual value information in + the parameter value string, and an percent sign is used to flag + octets encoded in hexadecimal. For example: + + Content-Type: application/x-stuff; + title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A + + Note that it is perfectly permissible to leave either the character + set or language field blank. Note also that the single quote + delimiters MUST be present even when one of the field values is + omitted. This is done when either character set, language, or both + are not relevant to the parameter value at hand. This MUST NOT be + done in order to indicate a default character set or language -- + parameter field definitions MUST NOT assign a default character set + or language. + +4.1. Combining Character Set, Language, and Parameter Continuations + + Character set and language information may be combined with the + parameter continuation mechanism. For example: + + Content-Type: application/x-stuff + title*0*=us-ascii'en'This%20is%20even%20more%20 + title*1*=%2A%2A%2Afun%2A%2A%2A%20 + title*2="isn't it!" + + Note that: + + (1) Language and character set information only appear at + the beginning of a given parameter value. + + (2) Continuations do not provide a facility for using more + than one character set or language in the same + parameter value. + + (3) A value presented using multiple continuations may + contain a mixture of encoded and unencoded segments. + + + + + +Freed & Moore Standards Track [Page 5] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + (4) The first segment of a continuation MUST be encoded if + language and character set information are given. + + (5) If the first segment of a continued parameter value is + encoded the language and character set field delimiters + MUST be present even when the fields are left blank. + +5. Language specification in Encoded Words + + RFC 2047 provides support for non-US-ASCII character sets in RFC 822 + message header comments, phrases, and any unstructured text field. + This is done by defining an encoded word construct which can appear + in any of these places. Given that these are fields intended for + display, it is sometimes necessary to associate language information + with encoded words as well as just the character set. This + specification extends the definition of an encoded word to allow the + inclusion of such information. This is simply done by suffixing the + character set specification with an asterisk followed by the language + tag. For example: + + From: =?US-ASCII*EN?Q?Keith_Moore?= + +6. IMAP4 Handling of Parameter Values + + IMAP4 [RFC-2060] servers SHOULD decode parameter value continuations + when generating the BODY and BODYSTRUCTURE fetch attributes. + +7. Modifications to MIME ABNF + + The ABNF for MIME parameter values given in RFC 2045 is: + + parameter := attribute "=" value + + attribute := token + ; Matching of attributes + ; is ALWAYS case-insensitive. + + This specification changes this ABNF to: + + parameter := regular-parameter / extended-parameter + + regular-parameter := regular-parameter-name "=" value + + regular-parameter-name := attribute [section] + + attribute := 1*attribute-char + + + + + +Freed & Moore Standards Track [Page 6] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + attribute-char := + + section := initial-section / other-sections + + initial-section := "*0" + + other-sections := "*" ("1" / "2" / "3" / "4" / "5" / + "6" / "7" / "8" / "9") *DIGIT) + + extended-parameter := (extended-initial-name "=" + extended-value) / + (extended-other-names "=" + extended-other-values) + + extended-initial-name := attribute [initial-section] "*" + + extended-other-names := attribute other-sections "*" + + extended-initial-value := [charset] "'" [language] "'" + extended-other-values + + extended-other-values := *(ext-octet / attribute-char) + + ext-octet := "%" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F") + + charset := + + language := + + The ABNF given in RFC 2047 for encoded-words is: + + encoded-word := "=?" charset "?" encoding "?" encoded-text "?=" + + This specification changes this ABNF to: + + encoded-word := "=?" charset ["*" language] "?" encoded-text "?=" + +8. Character sets which allow specification of language + + In the future it is likely that some character sets will provide + facilities for inline language labeling. Such facilities are + inherently more flexible than those defined here as they allow for + language switching in the middle of a string. + + + + + + + +Freed & Moore Standards Track [Page 7] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + If and when such facilities are developed they SHOULD be used in + preference to the language labeling facilities specified here. Note + that all the mechanisms defined here allow for the omission of + language labels so as to be able to accommodate this possible future + usage. + +9. Security Considerations + + This RFC does not discuss security issues and is not believed to + raise any security issues not already endemic in electronic mail and + present in fully conforming implementations of MIME. + +10. References + + [RFC-822] + Crocker, D., "Standard for the Format of ARPA Internet + Text Messages", STD 11, RFC 822 August 1982. + + [RFC-1766] + Alvestrand, H., "Tags for the Identification of + Languages", RFC 1766, March 1995. + + [RFC-2045] + Freed, N., and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message + Bodies", RFC 2045, December 1996. + + [RFC-2046] + Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + December 1996. + + [RFC-2047] + Moore, K., "Multipurpose Internet Mail Extensions (MIME) + Part Three: Representation of Non-ASCII Text in Internet + Message Headers", RFC 2047, December 1996. + + [RFC-2048] + Freed, N., Klensin, J. and J. Postel, "Multipurpose + Internet Mail Extensions (MIME) Part Four: MIME + Registration Procedures", RFC 2048, December 1996. + + [RFC-2049] + Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Five: Conformance Criteria and + Examples", RFC 2049, December 1996. + + + + + +Freed & Moore Standards Track [Page 8] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + + [RFC-2060] + Crispin, M., "Internet Message Access Protocol - Version + 4rev1", RFC 2060, December 1996. + + [RFC-2119] + Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", RFC 2119, March 1997. + + [RFC-2130] + Weider, C., Preston, C., Simonsen, K., Alvestrand, H., + Atkinson, R., Crispin, M., and P. Svanberg, "Report from the + IAB Character Set Workshop", RFC 2130, April 1997. + + [RFC-2183] + Troost, R., Dorner, S. and K. Moore, "Communicating + Presentation Information in Internet Messages: The + Content-Disposition Header", RFC 2183, August 1997. + +11. Authors' Addresses + + Ned Freed + Innosoft International, Inc. + 1050 Lakes Drive + West Covina, CA 91790 + USA + + Phone: +1 626 919 3600 + Fax: +1 626 919 3614 + EMail: ned.freed@innosoft.com + + + Keith Moore + Computer Science Dept. + University of Tennessee + 107 Ayres Hall + Knoxville, TN 37996-1301 + USA + + EMail: moore@cs.utk.edu + + + + + + + + + + + + +Freed & Moore Standards Track [Page 9] + +RFC 2231 MIME Value and Encoded Word Extensions November 1997 + + +12. Full Copyright Statement + + Copyright (C) The Internet Society (1997). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Freed & Moore Standards Track [Page 10] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2234.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2234.txt new file mode 100644 index 00000000..edea302f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2234.txt @@ -0,0 +1,787 @@ + + + + + + +Network Working Group D. Crocker, Ed. +Request for Comments: 2234 Internet Mail Consortium +Category: Standards Track P. Overell + Demon Internet Ltd. + November 1997 + + + Augmented BNF for Syntax Specifications: ABNF + + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1997). All Rights Reserved. + +TABLE OF CONTENTS + + 1. INTRODUCTION .................................................. 2 + + 2. RULE DEFINITION ............................................... 2 + 2.1 RULE NAMING .................................................. 2 + 2.2 RULE FORM .................................................... 3 + 2.3 TERMINAL VALUES .............................................. 3 + 2.4 EXTERNAL ENCODINGS ........................................... 5 + + 3. OPERATORS ..................................................... 5 + 3.1 CONCATENATION RULE1 RULE2 ............................. 5 + 3.2 ALTERNATIVES RULE1 / RULE2 ................................... 6 + 3.3 INCREMENTAL ALTERNATIVES RULE1 =/ RULE2 .................... 6 + 3.4 VALUE RANGE ALTERNATIVES %C##-## ........................... 7 + 3.5 SEQUENCE GROUP (RULE1 RULE2) ................................. 7 + 3.6 VARIABLE REPETITION *RULE .................................... 8 + 3.7 SPECIFIC REPETITION NRULE .................................... 8 + 3.8 OPTIONAL SEQUENCE [RULE] ..................................... 8 + 3.9 ; COMMENT .................................................... 8 + 3.10 OPERATOR PRECEDENCE ......................................... 9 + + 4. ABNF DEFINITION OF ABNF ....................................... 9 + + 5. SECURITY CONSIDERATIONS ....................................... 10 + + + + +Crocker & Overell Standards Track [Page 1] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + 6. APPENDIX A - CORE ............................................. 11 + 6.1 CORE RULES ................................................... 11 + 6.2 COMMON ENCODING .............................................. 12 + + 7. ACKNOWLEDGMENTS ............................................... 12 + + 8. REFERENCES .................................................... 13 + + 9. CONTACT ....................................................... 13 + + 10. FULL COPYRIGHT STATEMENT ..................................... 14 + +1. INTRODUCTION + + Internet technical specifications often need to define a format + syntax and are free to employ whatever notation their authors deem + useful. Over the years, a modified version of Backus-Naur Form + (BNF), called Augmented BNF (ABNF), has been popular among many + Internet specifications. It balances compactness and simplicity, + with reasonable representational power. In the early days of the + Arpanet, each specification contained its own definition of ABNF. + This included the email specifications, RFC733 and then RFC822 which + have come to be the common citations for defining ABNF. The current + document separates out that definition, to permit selective + reference. Predictably, it also provides some modifications and + enhancements. + + The differences between standard BNF and ABNF involve naming rules, + repetition, alternatives, order-independence, and value ranges. + Appendix A (Core) supplies rule definitions and encoding for a core + lexical analyzer of the type common to several Internet + specifications. It is provided as a convenience and is otherwise + separate from the meta language defined in the body of this document, + and separate from its formal status. + +2. RULE DEFINITION + +2.1 Rule Naming + + The name of a rule is simply the name itself; that is, a sequence of + characters, beginning with an alphabetic character, and followed by + a combination of alphabetics, digits and hyphens (dashes). + + NOTE: Rule names are case-insensitive + + The names , , and all refer + to the same rule. + + + + +Crocker & Overell Standards Track [Page 2] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + Unlike original BNF, angle brackets ("<", ">") are not required. + However, angle brackets may be used around a rule name whenever their + presence will facilitate discerning the use of a rule name. This is + typically restricted to rule name references in free-form prose, or + to distinguish partial rules that combine into a string not separated + by white space, such as shown in the discussion about repetition, + below. + +2.2 Rule Form + + A rule is defined by the following sequence: + + name = elements crlf + + where is the name of the rule, is one or more rule + names or terminal specifications and is the end-of- line + indicator, carriage return followed by line feed. The equal sign + separates the name from the definition of the rule. The elements + form a sequence of one or more rule names and/or value definitions, + combined according to the various operators, defined in this + document, such as alternative and repetition. + + For visual ease, rule definitions are left aligned. When a rule + requires multiple lines, the continuation lines are indented. The + left alignment and indentation are relative to the first lines of the + ABNF rules and need not match the left margin of the document. + +2.3 Terminal Values + + Rules resolve into a string of terminal values, sometimes called + characters. In ABNF a character is merely a non-negative integer. + In certain contexts a specific mapping (encoding) of values into a + character set (such as ASCII) will be specified. + + Terminals are specified by one or more numeric characters with the + base interpretation of those characters indicated explicitly. The + following bases are currently defined: + + b = binary + + d = decimal + + x = hexadecimal + + + + + + + + +Crocker & Overell Standards Track [Page 3] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + Hence: + + CR = %d13 + + CR = %x0D + + respectively specify the decimal and hexadecimal representation of + [US-ASCII] for carriage return. + + A concatenated string of such values is specified compactly, using a + period (".") to indicate separation of characters within that value. + Hence: + + CRLF = %d13.10 + + ABNF permits specifying literal text string directly, enclosed in + quotation-marks. Hence: + + command = "command string" + + Literal text strings are interpreted as a concatenated set of + printable characters. + + NOTE: ABNF strings are case-insensitive and + the character set for these strings is us-ascii. + + Hence: + + rulename = "abc" + + and: + + rulename = "aBc" + + will match "abc", "Abc", "aBc", "abC", "ABc", "aBC", "AbC" and "ABC". + + To specify a rule which IS case SENSITIVE, + specify the characters individually. + + For example: + + rulename = %d97 %d98 %d99 + + or + + rulename = %d97.98.99 + + + + + +Crocker & Overell Standards Track [Page 4] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + will match only the string which comprises only lowercased + characters, abc. + +2.4 External Encodings + + External representations of terminal value characters will vary + according to constraints in the storage or transmission environment. + Hence, the same ABNF-based grammar may have multiple external + encodings, such as one for a 7-bit US-ASCII environment, another for + a binary octet environment and still a different one when 16-bit + Unicode is used. Encoding details are beyond the scope of ABNF, + although Appendix A (Core) provides definitions for a 7-bit US-ASCII + environment as has been common to much of the Internet. + + By separating external encoding from the syntax, it is intended that + alternate encoding environments can be used for the same syntax. + +3. OPERATORS + +3.1 Concatenation Rule1 Rule2 + + A rule can define a simple, ordered string of values -- i.e., a + concatenation of contiguous characters -- by listing a sequence of + rule names. For example: + + foo = %x61 ; a + + bar = %x62 ; b + + mumble = foo bar foo + + So that the rule matches the lowercase string "aba". + + LINEAR WHITE SPACE: Concatenation is at the core of the ABNF + parsing model. A string of contiguous characters (values) is + parsed according to the rules defined in ABNF. For Internet + specifications, there is some history of permitting linear white + space (space and horizontal tab) to be freelyPand + implicitlyPinterspersed around major constructs, such as + delimiting special characters or atomic strings. + + NOTE: This specification for ABNF does not + provide for implicit specification of linear white + space. + + Any grammar which wishes to permit linear white space around + delimiters or string segments must specify it explicitly. It is + often useful to provide for such white space in "core" rules that are + + + +Crocker & Overell Standards Track [Page 5] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + then used variously among higher-level rules. The "core" rules might + be formed into a lexical analyzer or simply be part of the main + ruleset. + +3.2 Alternatives Rule1 / Rule2 + + Elements separated by forward slash ("/") are alternatives. + Therefore, + + foo / bar + + will accept or . + + NOTE: A quoted string containing alphabetic + characters is special form for specifying alternative + characters and is interpreted as a non-terminal + representing the set of combinatorial strings with the + contained characters, in the specified order but with + any mixture of upper and lower case.. + +3.3 Incremental Alternatives Rule1 =/ Rule2 + + It is sometimes convenient to specify a list of alternatives in + fragments. That is, an initial rule may match one or more + alternatives, with later rule definitions adding to the set of + alternatives. This is particularly useful for otherwise- independent + specifications which derive from the same parent rule set, such as + often occurs with parameter lists. ABNF permits this incremental + definition through the construct: + + oldrule =/ additional-alternatives + + So that the rule set + + ruleset = alt1 / alt2 + + ruleset =/ alt3 + + ruleset =/ alt4 / alt5 + + is the same as specifying + + ruleset = alt1 / alt2 / alt3 / alt4 / alt5 + + + + + + + + +Crocker & Overell Standards Track [Page 6] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +3.4 Value Range Alternatives %c##-## + + A range of alternative numeric values can be specified compactly, + using dash ("-") to indicate the range of alternative values. Hence: + + DIGIT = %x30-39 + + is equivalent to: + + DIGIT = "0" / "1" / "2" / "3" / "4" / "5" / "6" / + + "7" / "8" / "9" + + Concatenated numeric values and numeric value ranges can not be + specified in the same string. A numeric value may use the dotted + notation for concatenation or it may use the dash notation to specify + one value range. Hence, to specify one printable character, between + end of line sequences, the specification could be: + + char-line = %x0D.0A %x20-7E %x0D.0A + +3.5 Sequence Group (Rule1 Rule2) + + Elements enclosed in parentheses are treated as a single element, + whose contents are STRICTLY ORDERED. Thus, + + elem (foo / bar) blat + + which matches (elem foo blat) or (elem bar blat). + + elem foo / bar blat + + matches (elem foo) or (bar blat). + + NOTE: It is strongly advised to use grouping + notation, rather than to rely on proper reading of + "bare" alternations, when alternatives consist of + multiple rule names or literals. + + Hence it is recommended that instead of the above form, the form: + + (elem foo) / (bar blat) + + be used. It will avoid misinterpretation by casual readers. + + The sequence group notation is also used within free text to set off + an element sequence from the prose. + + + + +Crocker & Overell Standards Track [Page 7] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +3.6 Variable Repetition *Rule + + The operator "*" preceding an element indicates repetition. The full + form is: + + *element + + where and are optional decimal values, indicating at least + and at most occurrences of element. + + Default values are 0 and infinity so that * allows any + number, including zero; 1* requires at least one; + 3*3 allows exactly 3 and 1*2 allows one or two. + +3.7 Specific Repetition nRule + + A rule of the form: + + element + + is equivalent to + + *element + + That is, exactly occurrences of . Thus 2DIGIT is a + 2-digit number, and 3ALPHA is a string of three alphabetic + characters. + +3.8 Optional Sequence [RULE] + + Square brackets enclose an optional element sequence: + + [foo bar] + + is equivalent to + + *1(foo bar). + +3.9 ; Comment + + A semi-colon starts a comment that continues to the end of line. + This is a simple way of including useful notes in parallel with the + specifications. + + + + + + + + +Crocker & Overell Standards Track [Page 8] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +3.10 Operator Precedence + + The various mechanisms described above have the following precedence, + from highest (binding tightest) at the top, to lowest and loosest at + the bottom: + + Strings, Names formation + Comment + Value range + Repetition + Grouping, Optional + Concatenation + Alternative + + Use of the alternative operator, freely mixed with concatenations can + be confusing. + + Again, it is recommended that the grouping operator be used to + make explicit concatenation groups. + +4. ABNF DEFINITION OF ABNF + + This syntax uses the rules provided in Appendix A (Core). + + rulelist = 1*( rule / (*c-wsp c-nl) ) + + rule = rulename defined-as elements c-nl + ; continues if next line starts + ; with white space + + rulename = ALPHA *(ALPHA / DIGIT / "-") + + defined-as = *c-wsp ("=" / "=/") *c-wsp + ; basic rules definition and + ; incremental alternatives + + elements = alternation *c-wsp + + c-wsp = WSP / (c-nl WSP) + + c-nl = comment / CRLF + ; comment or newline + + comment = ";" *(WSP / VCHAR) CRLF + + alternation = concatenation + *(*c-wsp "/" *c-wsp concatenation) + + + + +Crocker & Overell Standards Track [Page 9] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + concatenation = repetition *(1*c-wsp repetition) + + repetition = [repeat] element + + repeat = 1*DIGIT / (*DIGIT "*" *DIGIT) + + element = rulename / group / option / + char-val / num-val / prose-val + + group = "(" *c-wsp alternation *c-wsp ")" + + option = "[" *c-wsp alternation *c-wsp "]" + + char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE + ; quoted string of SP and VCHAR + without DQUOTE + + num-val = "%" (bin-val / dec-val / hex-val) + + bin-val = "b" 1*BIT + [ 1*("." 1*BIT) / ("-" 1*BIT) ] + ; series of concatenated bit values + ; or single ONEOF range + + dec-val = "d" 1*DIGIT + [ 1*("." 1*DIGIT) / ("-" 1*DIGIT) ] + + hex-val = "x" 1*HEXDIG + [ 1*("." 1*HEXDIG) / ("-" 1*HEXDIG) ] + + prose-val = "<" *(%x20-3D / %x3F-7E) ">" + ; bracketed string of SP and VCHAR + without angles + ; prose description, to be used as + last resort + + +5. SECURITY CONSIDERATIONS + + Security is truly believed to be irrelevant to this document. + + + + + + + + + + + +Crocker & Overell Standards Track [Page 10] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +6. APPENDIX A - CORE + + This Appendix is provided as a convenient core for specific grammars. + The definitions may be used as a core set of rules. + +6.1 Core Rules + + Certain basic rules are in uppercase, such as SP, HTAB, CRLF, + DIGIT, ALPHA, etc. + + ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + + BIT = "0" / "1" + + CHAR = %x01-7F + ; any 7-bit US-ASCII character, + excluding NUL + + CR = %x0D + ; carriage return + + CRLF = CR LF + ; Internet standard newline + + CTL = %x00-1F / %x7F + ; controls + + DIGIT = %x30-39 + ; 0-9 + + DQUOTE = %x22 + ; " (Double Quote) + + HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F" + + HTAB = %x09 + ; horizontal tab + + LF = %x0A + ; linefeed + + LWSP = *(WSP / CRLF WSP) + ; linear white space (past newline) + + OCTET = %x00-FF + ; 8 bits of data + + SP = %x20 + + + +Crocker & Overell Standards Track [Page 11] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + + ; space + + VCHAR = %x21-7E + ; visible (printing) characters + + WSP = SP / HTAB + ; white space + +6.2 Common Encoding + + Externally, data are represented as "network virtual ASCII", namely + 7-bit US-ASCII in an 8-bit field, with the high (8th) bit set to + zero. A string of values is in "network byte order" with the + higher-valued bytes represented on the left-hand side and being sent + over the network first. + +7. ACKNOWLEDGMENTS + + The syntax for ABNF was originally specified in RFC 733. Ken L. + Harrenstien, of SRI International, was responsible for re-coding the + BNF into an augmented BNF that makes the representation smaller and + easier to understand. + + This recent project began as a simple effort to cull out the portion + of RFC 822 which has been repeatedly cited by non-email specification + writers, namely the description of augmented BNF. Rather than simply + and blindly converting the existing text into a separate document, + the working group chose to give careful consideration to the + deficiencies, as well as benefits, of the existing specification and + related specifications available over the last 15 years and therefore + to pursue enhancement. This turned the project into something rather + more ambitious than first intended. Interestingly the result is not + massively different from that original, although decisions such as + removing the list notation came as a surprise. + + The current round of specification was part of the DRUMS working + group, with significant contributions from Jerome Abela , Harald + Alvestrand, Robert Elz, Roger Fajman, Aviva Garrett, Tom Harsch, Dan + Kohn, Bill McQuillan, Keith Moore, Chris Newman , Pete Resnick and + Henning Schulzrinne. + + + + + + + + + + + +Crocker & Overell Standards Track [Page 12] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +8. REFERENCES + + [US-ASCII] Coded Character Set--7-Bit American Standard Code for + Information Interchange, ANSI X3.4-1986. + + [RFC733] Crocker, D., Vittal, J., Pogran, K., and D. Henderson, + "Standard for the Format of ARPA Network Text Message," RFC 733, + November 1977. + + [RFC822] Crocker, D., "Standard for the Format of ARPA Internet Text + Messages", STD 11, RFC 822, August 1982. + +9. CONTACT + + David H. Crocker Paul Overell + + Internet Mail Consortium Demon Internet Ltd + 675 Spruce Dr. Dorking Business Park + Sunnyvale, CA 94086 USA Dorking + Surrey, RH4 1HN + UK + + Phone: +1 408 246 8253 + Fax: +1 408 249 6205 + EMail: dcrocker@imc.org paulo@turnpike.com + + + + + + + + + + + + + + + + + + + + + + + + + + +Crocker & Overell Standards Track [Page 13] + +RFC 2234 ABNF for Syntax Specifications November 1997 + + +10. Full Copyright Statement + + Copyright (C) The Internet Society (1997). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Crocker & Overell Standards Track [Page 14] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2440.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2440.txt new file mode 100644 index 00000000..902ecee4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2440.txt @@ -0,0 +1,3642 @@ + + + + + +Network Working Group J. Callas +Request for Comments: 2440 Network Associates +Category: Standards Track L. Donnerhacke + IN-Root-CA Individual Network e.V. + H. Finney + Network Associates + R. Thayer + EIS Corporation + November 1998 + + + OpenPGP Message Format + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1998). All Rights Reserved. + +IESG Note + + This document defines many tag values, yet it doesn't describe a + mechanism for adding new tags (for new features). Traditionally the + Internet Assigned Numbers Authority (IANA) handles the allocation of + new values for future expansion and RFCs usually define the procedure + to be used by the IANA. However, there are subtle (and not so + subtle) interactions that may occur in this protocol between new + features and existing features which result in a significant + reduction in over all security. Therefore, this document does not + define an extension procedure. Instead requests to define new tag + values (say for new encryption algorithms for example) should be + forwarded to the IESG Security Area Directors for consideration or + forwarding to the appropriate IETF Working Group for consideration. + +Abstract + + This document is maintained in order to publish all necessary + information needed to develop interoperable applications based on the + OpenPGP format. It is not a step-by-step cookbook for writing an + application. It describes only the format and methods needed to read, + check, generate, and write conforming packets crossing any network. + It does not deal with storage and implementation questions. It does, + + + +Callas, et. al. Standards Track [Page 1] + +RFC 2440 OpenPGP Message Format November 1998 + + + however, discuss implementation issues necessary to avoid security + flaws. + + Open-PGP software uses a combination of strong public-key and + symmetric cryptography to provide security services for electronic + communications and data storage. These services include + confidentiality, key management, authentication, and digital + signatures. This document specifies the message formats used in + OpenPGP. + +Table of Contents + + Status of this Memo 1 + IESG Note 1 + Abstract 1 + Table of Contents 2 + 1. Introduction 4 + 1.1. Terms 5 + 2. General functions 5 + 2.1. Confidentiality via Encryption 5 + 2.2. Authentication via Digital signature 6 + 2.3. Compression 7 + 2.4. Conversion to Radix-64 7 + 2.5. Signature-Only Applications 7 + 3. Data Element Formats 7 + 3.1. Scalar numbers 8 + 3.2. Multi-Precision Integers 8 + 3.3. Key IDs 8 + 3.4. Text 8 + 3.5. Time fields 9 + 3.6. String-to-key (S2K) specifiers 9 + 3.6.1. String-to-key (S2k) specifier types 9 + 3.6.1.1. Simple S2K 9 + 3.6.1.2. Salted S2K 10 + 3.6.1.3. Iterated and Salted S2K 10 + 3.6.2. String-to-key usage 11 + 3.6.2.1. Secret key encryption 11 + 3.6.2.2. Symmetric-key message encryption 11 + 4. Packet Syntax 12 + 4.1. Overview 12 + 4.2. Packet Headers 12 + 4.2.1. Old-Format Packet Lengths 13 + 4.2.2. New-Format Packet Lengths 13 + 4.2.2.1. One-Octet Lengths 14 + 4.2.2.2. Two-Octet Lengths 14 + 4.2.2.3. Five-Octet Lengths 14 + 4.2.2.4. Partial Body Lengths 14 + 4.2.3. Packet Length Examples 14 + + + +Callas, et. al. Standards Track [Page 2] + +RFC 2440 OpenPGP Message Format November 1998 + + + 4.3. Packet Tags 15 + 5. Packet Types 16 + 5.1. Public-Key Encrypted Session Key Packets (Tag 1) 16 + 5.2. Signature Packet (Tag 2) 17 + 5.2.1. Signature Types 17 + 5.2.2. Version 3 Signature Packet Format 19 + 5.2.3. Version 4 Signature Packet Format 21 + 5.2.3.1. Signature Subpacket Specification 22 + 5.2.3.2. Signature Subpacket Types 24 + 5.2.3.3. Signature creation time 25 + 5.2.3.4. Issuer 25 + 5.2.3.5. Key expiration time 25 + 5.2.3.6. Preferred symmetric algorithms 25 + 5.2.3.7. Preferred hash algorithms 25 + 5.2.3.8. Preferred compression algorithms 26 + 5.2.3.9. Signature expiration time 26 + 5.2.3.10.Exportable Certification 26 + 5.2.3.11.Revocable 27 + 5.2.3.12.Trust signature 27 + 5.2.3.13.Regular expression 27 + 5.2.3.14.Revocation key 27 + 5.2.3.15.Notation Data 28 + 5.2.3.16.Key server preferences 28 + 5.2.3.17.Preferred key server 29 + 5.2.3.18.Primary user id 29 + 5.2.3.19.Policy URL 29 + 5.2.3.20.Key Flags 29 + 5.2.3.21.Signer's User ID 30 + 5.2.3.22.Reason for Revocation 30 + 5.2.4. Computing Signatures 31 + 5.2.4.1. Subpacket Hints 32 + 5.3. Symmetric-Key Encrypted Session-Key Packets (Tag 3) 32 + 5.4. One-Pass Signature Packets (Tag 4) 33 + 5.5. Key Material Packet 34 + 5.5.1. Key Packet Variants 34 + 5.5.1.1. Public Key Packet (Tag 6) 34 + 5.5.1.2. Public Subkey Packet (Tag 14) 34 + 5.5.1.3. Secret Key Packet (Tag 5) 35 + 5.5.1.4. Secret Subkey Packet (Tag 7) 35 + 5.5.2. Public Key Packet Formats 35 + 5.5.3. Secret Key Packet Formats 37 + 5.6. Compressed Data Packet (Tag 8) 38 + 5.7. Symmetrically Encrypted Data Packet (Tag 9) 39 + 5.8. Marker Packet (Obsolete Literal Packet) (Tag 10) 39 + 5.9. Literal Data Packet (Tag 11) 40 + 5.10. Trust Packet (Tag 12) 40 + 5.11. User ID Packet (Tag 13) 41 + 6. Radix-64 Conversions 41 + + + +Callas, et. al. Standards Track [Page 3] + +RFC 2440 OpenPGP Message Format November 1998 + + + 6.1. An Implementation of the CRC-24 in "C" 42 + 6.2. Forming ASCII Armor 42 + 6.3. Encoding Binary in Radix-64 44 + 6.4. Decoding Radix-64 46 + 6.5. Examples of Radix-64 46 + 6.6. Example of an ASCII Armored Message 47 + 7. Cleartext signature framework 47 + 7.1. Dash-Escaped Text 47 + 8. Regular Expressions 48 + 9. Constants 49 + 9.1. Public Key Algorithms 49 + 9.2. Symmetric Key Algorithms 49 + 9.3. Compression Algorithms 50 + 9.4. Hash Algorithms 50 + 10. Packet Composition 50 + 10.1. Transferable Public Keys 50 + 10.2. OpenPGP Messages 52 + 10.3. Detached Signatures 52 + 11. Enhanced Key Formats 52 + 11.1. Key Structures 52 + 11.2. Key IDs and Fingerprints 53 + 12. Notes on Algorithms 54 + 12.1. Symmetric Algorithm Preferences 54 + 12.2. Other Algorithm Preferences 55 + 12.2.1. Compression Preferences 56 + 12.2.2. Hash Algorithm Preferences 56 + 12.3. Plaintext 56 + 12.4. RSA 56 + 12.5. Elgamal 57 + 12.6. DSA 58 + 12.7. Reserved Algorithm Numbers 58 + 12.8. OpenPGP CFB mode 58 + 13. Security Considerations 59 + 14. Implementation Nits 60 + 15. Authors and Working Group Chair 62 + 16. References 63 + 17. Full Copyright Statement 65 + +1. Introduction + + This document provides information on the message-exchange packet + formats used by OpenPGP to provide encryption, decryption, signing, + and key management functions. It builds on the foundation provided in + RFC 1991 "PGP Message Exchange Formats." + + + + + + + +Callas, et. al. Standards Track [Page 4] + +RFC 2440 OpenPGP Message Format November 1998 + + +1.1. Terms + + * OpenPGP - This is a definition for security software that uses + PGP 5.x as a basis. + + * PGP - Pretty Good Privacy. PGP is a family of software systems + developed by Philip R. Zimmermann from which OpenPGP is based. + + * PGP 2.6.x - This version of PGP has many variants, hence the term + PGP 2.6.x. It used only RSA, MD5, and IDEA for its cryptographic + transforms. An informational RFC, RFC 1991, was written + describing this version of PGP. + + * PGP 5.x - This version of PGP is formerly known as "PGP 3" in the + community and also in the predecessor of this document, RFC 1991. + It has new formats and corrects a number of problems in the PGP + 2.6.x design. It is referred to here as PGP 5.x because that + software was the first release of the "PGP 3" code base. + + "PGP", "Pretty Good", and "Pretty Good Privacy" are trademarks of + Network Associates, Inc. and are used with permission. + + This document uses the terms "MUST", "SHOULD", and "MAY" as defined + in RFC 2119, along with the negated forms of those terms. + +2. General functions + + OpenPGP provides data integrity services for messages and data files + by using these core technologies: + + - digital signatures + + - encryption + + - compression + + - radix-64 conversion + + In addition, OpenPGP provides key management and certificate + services, but many of these are beyond the scope of this document. + +2.1. Confidentiality via Encryption + + OpenPGP uses two encryption methods to provide confidentiality: + symmetric-key encryption and public key encryption. With public-key + encryption, the object is encrypted using a symmetric encryption + algorithm. Each symmetric key is used only once. A new "session key" + is generated as a random number for each message. Since it is used + + + +Callas, et. al. Standards Track [Page 5] + +RFC 2440 OpenPGP Message Format November 1998 + + + only once, the session key is bound to the message and transmitted + with it. To protect the key, it is encrypted with the receiver's + public key. The sequence is as follows: + + 1. The sender creates a message. + + 2. The sending OpenPGP generates a random number to be used as a + session key for this message only. + + 3. The session key is encrypted using each recipient's public key. + These "encrypted session keys" start the message. + + 4. The sending OpenPGP encrypts the message using the session key, + which forms the remainder of the message. Note that the message + is also usually compressed. + + 5. The receiving OpenPGP decrypts the session key using the + recipient's private key. + + 6. The receiving OpenPGP decrypts the message using the session key. + If the message was compressed, it will be decompressed. + + With symmetric-key encryption, an object may be encrypted with a + symmetric key derived from a passphrase (or other shared secret), or + a two-stage mechanism similar to the public-key method described + above in which a session key is itself encrypted with a symmetric + algorithm keyed from a shared secret. + + Both digital signature and confidentiality services may be applied to + the same message. First, a signature is generated for the message and + attached to the message. Then, the message plus signature is + encrypted using a symmetric session key. Finally, the session key is + encrypted using public-key encryption and prefixed to the encrypted + block. + +2.2. Authentication via Digital signature + + The digital signature uses a hash code or message digest algorithm, + and a public-key signature algorithm. The sequence is as follows: + + 1. The sender creates a message. + + 2. The sending software generates a hash code of the message. + + 3. The sending software generates a signature from the hash code + using the sender's private key. + + 4. The binary signature is attached to the message. + + + +Callas, et. al. Standards Track [Page 6] + +RFC 2440 OpenPGP Message Format November 1998 + + + 5. The receiving software keeps a copy of the message signature. + + 6. The receiving software generates a new hash code for the + received message and verifies it using the message's signature. + If the verification is successful, the message is accepted as + authentic. + +2.3. Compression + + OpenPGP implementations MAY compress the message after applying the + signature but before encryption. + +2.4. Conversion to Radix-64 + + OpenPGP's underlying native representation for encrypted messages, + signature certificates, and keys is a stream of arbitrary octets. + Some systems only permit the use of blocks consisting of seven-bit, + printable text. For transporting OpenPGP's native raw binary octets + through channels that are not safe to raw binary data, a printable + encoding of these binary octets is needed. OpenPGP provides the + service of converting the raw 8-bit binary octet stream to a stream + of printable ASCII characters, called Radix-64 encoding or ASCII + Armor. + + Implementations SHOULD provide Radix-64 conversions. + + Note that many applications, particularly messaging applications, + will want more advanced features as described in the OpenPGP-MIME + document, RFC 2015. An application that implements OpenPGP for + messaging SHOULD implement OpenPGP-MIME. + +2.5. Signature-Only Applications + + OpenPGP is designed for applications that use both encryption and + signatures, but there are a number of problems that are solved by a + signature-only implementation. Although this specification requires + both encryption and signatures, it is reasonable for there to be + subset implementations that are non-comformant only in that they omit + encryption. + +3. Data Element Formats + + This section describes the data elements used by OpenPGP. + + + + + + + + +Callas, et. al. Standards Track [Page 7] + +RFC 2440 OpenPGP Message Format November 1998 + + +3.1. Scalar numbers + + Scalar numbers are unsigned, and are always stored in big-endian + format. Using n[k] to refer to the kth octet being interpreted, the + value of a two-octet scalar is ((n[0] << 8) + n[1]). The value of a + four-octet scalar is ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + + n[3]). + +3.2. Multi-Precision Integers + + Multi-Precision Integers (also called MPIs) are unsigned integers + used to hold large integers such as the ones used in cryptographic + calculations. + + An MPI consists of two pieces: a two-octet scalar that is the length + of the MPI in bits followed by a string of octets that contain the + actual integer. + + These octets form a big-endian number; a big-endian number can be + made into an MPI by prefixing it with the appropriate length. + + Examples: + + (all numbers are in hexadecimal) + + The string of octets [00 01 01] forms an MPI with the value 1. The + string [00 09 01 FF] forms an MPI with the value of 511. + + Additional rules: + + The size of an MPI is ((MPI.length + 7) / 8) + 2 octets. + + The length field of an MPI describes the length starting from its + most significant non-zero bit. Thus, the MPI [00 02 01] is not formed + correctly. It should be [00 01 01]. + +3.3. Key IDs + + A Key ID is an eight-octet scalar that identifies a key. + Implementations SHOULD NOT assume that Key IDs are unique. The + section, "Enhanced Key Formats" below describes how Key IDs are + formed. + +3.4. Text + + The default character set for text is the UTF-8 [RFC2279] encoding of + Unicode [ISO10646]. + + + + +Callas, et. al. Standards Track [Page 8] + +RFC 2440 OpenPGP Message Format November 1998 + + +3.5. Time fields + + A time field is an unsigned four-octet number containing the number + of seconds elapsed since midnight, 1 January 1970 UTC. + +3.6. String-to-key (S2K) specifiers + + String-to-key (S2K) specifiers are used to convert passphrase strings + into symmetric-key encryption/decryption keys. They are used in two + places, currently: to encrypt the secret part of private keys in the + private keyring, and to convert passphrases to encryption keys for + symmetrically encrypted messages. + +3.6.1. String-to-key (S2k) specifier types + + There are three types of S2K specifiers currently supported, as + follows: + +3.6.1.1. Simple S2K + + This directly hashes the string to produce the key data. See below + for how this hashing is done. + + Octet 0: 0x00 + Octet 1: hash algorithm + + Simple S2K hashes the passphrase to produce the session key. The + manner in which this is done depends on the size of the session key + (which will depend on the cipher used) and the size of the hash + algorithm's output. If the hash size is greater than or equal to the + session key size, the high-order (leftmost) octets of the hash are + used as the key. + + If the hash size is less than the key size, multiple instances of the + hash context are created -- enough to produce the required key data. + These instances are preloaded with 0, 1, 2, ... octets of zeros (that + is to say, the first instance has no preloading, the second gets + preloaded with 1 octet of zero, the third is preloaded with two + octets of zeros, and so forth). + + As the data is hashed, it is given independently to each hash + context. Since the contexts have been initialized differently, they + will each produce different hash output. Once the passphrase is + hashed, the output data from the multiple hashes is concatenated, + first hash leftmost, to produce the key data, with any excess octets + on the right discarded. + + + + + +Callas, et. al. Standards Track [Page 9] + +RFC 2440 OpenPGP Message Format November 1998 + + +3.6.1.2. Salted S2K + + This includes a "salt" value in the S2K specifier -- some arbitrary + data -- that gets hashed along with the passphrase string, to help + prevent dictionary attacks. + + Octet 0: 0x01 + Octet 1: hash algorithm + Octets 2-9: 8-octet salt value + + Salted S2K is exactly like Simple S2K, except that the input to the + hash function(s) consists of the 8 octets of salt from the S2K + specifier, followed by the passphrase. + +3.6.1.3. Iterated and Salted S2K + + This includes both a salt and an octet count. The salt is combined + with the passphrase and the resulting value is hashed repeatedly. + This further increases the amount of work an attacker must do to try + dictionary attacks. + + Octet 0: 0x03 + Octet 1: hash algorithm + Octets 2-9: 8-octet salt value + Octet 10: count, a one-octet, coded value + + The count is coded into a one-octet number using the following + formula: + + #define EXPBIAS 6 + count = ((Int32)16 + (c & 15)) << ((c >> 4) + EXPBIAS); + + The above formula is in C, where "Int32" is a type for a 32-bit + integer, and the variable "c" is the coded count, Octet 10. + + Iterated-Salted S2K hashes the passphrase and salt data multiple + times. The total number of octets to be hashed is specified in the + encoded count in the S2K specifier. Note that the resulting count + value is an octet count of how many octets will be hashed, not an + iteration count. + + Initially, one or more hash contexts are set up as with the other S2K + algorithms, depending on how many octets of key data are needed. + Then the salt, followed by the passphrase data is repeatedly hashed + until the number of octets specified by the octet count has been + hashed. The one exception is that if the octet count is less than + the size of the salt plus passphrase, the full salt plus passphrase + will be hashed even though that is greater than the octet count. + + + +Callas, et. al. Standards Track [Page 10] + +RFC 2440 OpenPGP Message Format November 1998 + + + After the hashing is done the data is unloaded from the hash + context(s) as with the other S2K algorithms. + +3.6.2. String-to-key usage + + Implementations SHOULD use salted or iterated-and-salted S2K + specifiers, as simple S2K specifiers are more vulnerable to + dictionary attacks. + +3.6.2.1. Secret key encryption + + An S2K specifier can be stored in the secret keyring to specify how + to convert the passphrase to a key that unlocks the secret data. + Older versions of PGP just stored a cipher algorithm octet preceding + the secret data or a zero to indicate that the secret data was + unencrypted. The MD5 hash function was always used to convert the + passphrase to a key for the specified cipher algorithm. + + For compatibility, when an S2K specifier is used, the special value + 255 is stored in the position where the hash algorithm octet would + have been in the old data structure. This is then followed + immediately by a one-octet algorithm identifier, and then by the S2K + specifier as encoded above. + + Therefore, preceding the secret data there will be one of these + possibilities: + + 0: secret data is unencrypted (no pass phrase) + 255: followed by algorithm octet and S2K specifier + Cipher alg: use Simple S2K algorithm using MD5 hash + + This last possibility, the cipher algorithm number with an implicit + use of MD5 and IDEA, is provided for backward compatibility; it MAY + be understood, but SHOULD NOT be generated, and is deprecated. + + These are followed by an 8-octet Initial Vector for the decryption of + the secret values, if they are encrypted, and then the secret key + values themselves. + +3.6.2.2. Symmetric-key message encryption + + OpenPGP can create a Symmetric-key Encrypted Session Key (ESK) packet + at the front of a message. This is used to allow S2K specifiers to + be used for the passphrase conversion or to create messages with a + mix of symmetric-key ESKs and public-key ESKs. This allows a message + to be decrypted either with a passphrase or a public key. + + + + + +Callas, et. al. Standards Track [Page 11] + +RFC 2440 OpenPGP Message Format November 1998 + + + PGP 2.X always used IDEA with Simple string-to-key conversion when + encrypting a message with a symmetric algorithm. This is deprecated, + but MAY be used for backward-compatibility. + +4. Packet Syntax + + This section describes the packets used by OpenPGP. + +4.1. Overview + + An OpenPGP message is constructed from a number of records that are + traditionally called packets. A packet is a chunk of data that has a + tag specifying its meaning. An OpenPGP message, keyring, certificate, + and so forth consists of a number of packets. Some of those packets + may contain other OpenPGP packets (for example, a compressed data + packet, when uncompressed, contains OpenPGP packets). + + Each packet consists of a packet header, followed by the packet body. + The packet header is of variable length. + +4.2. Packet Headers + + The first octet of the packet header is called the "Packet Tag." It + determines the format of the header and denotes the packet contents. + The remainder of the packet header is the length of the packet. + + Note that the most significant bit is the left-most bit, called bit + 7. A mask for this bit is 0x80 in hexadecimal. + + +---------------+ + PTag |7 6 5 4 3 2 1 0| + +---------------+ + Bit 7 -- Always one + Bit 6 -- New packet format if set + + PGP 2.6.x only uses old format packets. Thus, software that + interoperates with those versions of PGP must only use old format + packets. If interoperability is not an issue, either format may be + used. Note that old format packets have four bits of content tags, + and new format packets have six; some features cannot be used and + still be backward-compatible. + + Old format packets contain: + + Bits 5-2 -- content tag + Bits 1-0 - length-type + + + + + +Callas, et. al. Standards Track [Page 12] + +RFC 2440 OpenPGP Message Format November 1998 + + + New format packets contain: + + Bits 5-0 -- content tag + +4.2.1. Old-Format Packet Lengths + + The meaning of the length-type in old-format packets is: + + 0 - The packet has a one-octet length. The header is 2 octets long. + + 1 - The packet has a two-octet length. The header is 3 octets long. + + 2 - The packet has a four-octet length. The header is 5 octets long. + + 3 - The packet is of indeterminate length. The header is 1 octet + long, and the implementation must determine how long the packet + is. If the packet is in a file, this means that the packet + extends until the end of the file. In general, an implementation + SHOULD NOT use indeterminate length packets except where the end + of the data will be clear from the context, and even then it is + better to use a definite length, or a new-format header. The + new-format headers described below have a mechanism for precisely + encoding data of indeterminate length. + +4.2.2. New-Format Packet Lengths + + New format packets have four possible ways of encoding length: + + 1. A one-octet Body Length header encodes packet lengths of up to + 191 octets. + + 2. A two-octet Body Length header encodes packet lengths of 192 to + 8383 octets. + + 3. A five-octet Body Length header encodes packet lengths of up to + 4,294,967,295 (0xFFFFFFFF) octets in length. (This actually + encodes a four-octet scalar number.) + + 4. When the length of the packet body is not known in advance by the + issuer, Partial Body Length headers encode a packet of + indeterminate length, effectively making it a stream. + + + + + + + + + + +Callas, et. al. Standards Track [Page 13] + +RFC 2440 OpenPGP Message Format November 1998 + + +4.2.2.1. One-Octet Lengths + + A one-octet Body Length header encodes a length of from 0 to 191 + octets. This type of length header is recognized because the one + octet value is less than 192. The body length is equal to: + + bodyLen = 1st_octet; + +4.2.2.2. Two-Octet Lengths + + A two-octet Body Length header encodes a length of from 192 to 8383 + octets. It is recognized because its first octet is in the range 192 + to 223. The body length is equal to: + + bodyLen = ((1st_octet - 192) << 8) + (2nd_octet) + 192 + +4.2.2.3. Five-Octet Lengths + + A five-octet Body Length header consists of a single octet holding + the value 255, followed by a four-octet scalar. The body length is + equal to: + + bodyLen = (2nd_octet << 24) | (3rd_octet << 16) | + (4th_octet << 8) | 5th_octet + +4.2.2.4. Partial Body Lengths + + A Partial Body Length header is one octet long and encodes the length + of only part of the data packet. This length is a power of 2, from 1 + to 1,073,741,824 (2 to the 30th power). It is recognized by its one + octet value that is greater than or equal to 224, and less than 255. + The partial body length is equal to: + + partialBodyLen = 1 << (1st_octet & 0x1f); + + Each Partial Body Length header is followed by a portion of the + packet body data. The Partial Body Length header specifies this + portion's length. Another length header (of one of the three types -- + one octet, two-octet, or partial) follows that portion. The last + length header in the packet MUST NOT be a partial Body Length header. + Partial Body Length headers may only be used for the non-final parts + of the packet. + +4.2.3. Packet Length Examples + + These examples show ways that new-format packets might encode the + packet lengths. + + + + +Callas, et. al. Standards Track [Page 14] + +RFC 2440 OpenPGP Message Format November 1998 + + + A packet with length 100 may have its length encoded in one octet: + 0x64. This is followed by 100 octets of data. + + A packet with length 1723 may have its length coded in two octets: + 0xC5, 0xFB. This header is followed by the 1723 octets of data. + + A packet with length 100000 may have its length encoded in five + octets: 0xFF, 0x00, 0x01, 0x86, 0xA0. + + It might also be encoded in the following octet stream: 0xEF, first + 32768 octets of data; 0xE1, next two octets of data; 0xE0, next one + octet of data; 0xF0, next 65536 octets of data; 0xC5, 0xDD, last 1693 + octets of data. This is just one possible encoding, and many + variations are possible on the size of the Partial Body Length + headers, as long as a regular Body Length header encodes the last + portion of the data. Note also that the last Body Length header can + be a zero-length header. + + An implementation MAY use Partial Body Lengths for data packets, be + they literal, compressed, or encrypted. The first partial length MUST + be at least 512 octets long. Partial Body Lengths MUST NOT be used + for any other packet types. + + Please note that in all of these explanations, the total length of + the packet is the length of the header(s) plus the length of the + body. + +4.3. Packet Tags + + The packet tag denotes what type of packet the body holds. Note that + old format headers can only have tags less than 16, whereas new + format headers can have tags as great as 63. The defined tags (in + decimal) are: + + 0 -- Reserved - a packet tag must not have this value + 1 -- Public-Key Encrypted Session Key Packet + 2 -- Signature Packet + 3 -- Symmetric-Key Encrypted Session Key Packet + 4 -- One-Pass Signature Packet + 5 -- Secret Key Packet + 6 -- Public Key Packet + 7 -- Secret Subkey Packet + 8 -- Compressed Data Packet + 9 -- Symmetrically Encrypted Data Packet + 10 -- Marker Packet + 11 -- Literal Data Packet + 12 -- Trust Packet + + + + +Callas, et. al. Standards Track [Page 15] + +RFC 2440 OpenPGP Message Format November 1998 + + + 13 -- User ID Packet + 14 -- Public Subkey Packet + 60 to 63 -- Private or Experimental Values + +5. Packet Types + +5.1. Public-Key Encrypted Session Key Packets (Tag 1) + + A Public-Key Encrypted Session Key packet holds the session key used + to encrypt a message. Zero or more Encrypted Session Key packets + (either Public-Key or Symmetric-Key) may precede a Symmetrically + Encrypted Data Packet, which holds an encrypted message. The message + is encrypted with the session key, and the session key is itself + encrypted and stored in the Encrypted Session Key packet(s). The + Symmetrically Encrypted Data Packet is preceded by one Public-Key + Encrypted Session Key packet for each OpenPGP key to which the + message is encrypted. The recipient of the message finds a session + key that is encrypted to their public key, decrypts the session key, + and then uses the session key to decrypt the message. + + The body of this packet consists of: + + - A one-octet number giving the version number of the packet type. + The currently defined value for packet version is 3. An + implementation should accept, but not generate a version of 2, + which is equivalent to V3 in all other respects. + + - An eight-octet number that gives the key ID of the public key + that the session key is encrypted to. + + - A one-octet number giving the public key algorithm used. + + - A string of octets that is the encrypted session key. This string + takes up the remainder of the packet, and its contents are + dependent on the public key algorithm used. + + Algorithm Specific Fields for RSA encryption + + - multiprecision integer (MPI) of RSA encrypted value m**e mod n. + + Algorithm Specific Fields for Elgamal encryption: + + - MPI of Elgamal (Diffie-Hellman) value g**k mod p. + + - MPI of Elgamal (Diffie-Hellman) value m * y**k mod p. + + + + + + +Callas, et. al. Standards Track [Page 16] + +RFC 2440 OpenPGP Message Format November 1998 + + + The value "m" in the above formulas is derived from the session key + as follows. First the session key is prefixed with a one-octet + algorithm identifier that specifies the symmetric encryption + algorithm used to encrypt the following Symmetrically Encrypted Data + Packet. Then a two-octet checksum is appended which is equal to the + sum of the preceding session key octets, not including the algorithm + identifier, modulo 65536. This value is then padded as described in + PKCS-1 block type 02 [RFC2313] to form the "m" value used in the + formulas above. + + Note that when an implementation forms several PKESKs with one + session key, forming a message that can be decrypted by several keys, + the implementation MUST make new PKCS-1 padding for each key. + + An implementation MAY accept or use a Key ID of zero as a "wild card" + or "speculative" Key ID. In this case, the receiving implementation + would try all available private keys, checking for a valid decrypted + session key. This format helps reduce traffic analysis of messages. + +5.2. Signature Packet (Tag 2) + + A signature packet describes a binding between some public key and + some data. The most common signatures are a signature of a file or a + block of text, and a signature that is a certification of a user ID. + + Two versions of signature packets are defined. Version 3 provides + basic signature information, while version 4 provides an expandable + format with subpackets that can specify more information about the + signature. PGP 2.6.x only accepts version 3 signatures. + + Implementations MUST accept V3 signatures. Implementations SHOULD + generate V4 signatures. Implementations MAY generate a V3 signature + that can be verified by PGP 2.6.x. + + Note that if an implementation is creating an encrypted and signed + message that is encrypted to a V3 key, it is reasonable to create a + V3 signature. + +5.2.1. Signature Types + + There are a number of possible meanings for a signature, which are + specified in a signature type octet in any given signature. These + meanings are: + + 0x00: Signature of a binary document. + Typically, this means the signer owns it, created it, or + certifies that it has not been modified. + + + + +Callas, et. al. Standards Track [Page 17] + +RFC 2440 OpenPGP Message Format November 1998 + + + 0x01: Signature of a canonical text document. + Typically, this means the signer owns it, created it, or + certifies that it has not been modified. The signature is + calculated over the text data with its line endings converted + to and trailing blanks removed. + + 0x02: Standalone signature. + This signature is a signature of only its own subpacket + contents. It is calculated identically to a signature over a + zero-length binary document. Note that it doesn't make sense to + have a V3 standalone signature. + + 0x10: Generic certification of a User ID and Public Key packet. + The issuer of this certification does not make any particular + assertion as to how well the certifier has checked that the + owner of the key is in fact the person described by the user + ID. Note that all PGP "key signatures" are this type of + certification. + + 0x11: Persona certification of a User ID and Public Key packet. + The issuer of this certification has not done any verification + of the claim that the owner of this key is the user ID + specified. + + 0x12: Casual certification of a User ID and Public Key packet. + The issuer of this certification has done some casual + verification of the claim of identity. + + 0x13: Positive certification of a User ID and Public Key packet. + The issuer of this certification has done substantial + verification of the claim of identity. + + Please note that the vagueness of these certification claims is + not a flaw, but a feature of the system. Because PGP places + final authority for validity upon the receiver of a + certification, it may be that one authority's casual + certification might be more rigorous than some other + authority's positive certification. These classifications allow + a certification authority to issue fine-grained claims. + + 0x18: Subkey Binding Signature + This signature is a statement by the top-level signing key + indicates that it owns the subkey. This signature is calculated + directly on the subkey itself, not on any User ID or other + packets. + + + + + + +Callas, et. al. Standards Track [Page 18] + +RFC 2440 OpenPGP Message Format November 1998 + + + 0x1F: Signature directly on a key + This signature is calculated directly on a key. It binds the + information in the signature subpackets to the key, and is + appropriate to be used for subpackets that provide information + about the key, such as the revocation key subpacket. It is also + appropriate for statements that non-self certifiers want to + make about the key itself, rather than the binding between a + key and a name. + + 0x20: Key revocation signature + The signature is calculated directly on the key being revoked. + A revoked key is not to be used. Only revocation signatures by + the key being revoked, or by an authorized revocation key, + should be considered valid revocation signatures. + + 0x28: Subkey revocation signature + The signature is calculated directly on the subkey being + revoked. A revoked subkey is not to be used. Only revocation + signatures by the top-level signature key that is bound to this + subkey, or by an authorized revocation key, should be + considered valid revocation signatures. + + 0x30: Certification revocation signature + This signature revokes an earlier user ID certification + signature (signature class 0x10 through 0x13). It should be + issued by the same key that issued the revoked signature or an + authorized revocation key The signature should have a later + creation date than the signature it revokes. + + 0x40: Timestamp signature. + This signature is only meaningful for the timestamp contained + in it. + +5.2.2. Version 3 Signature Packet Format + + The body of a version 3 Signature Packet contains: + + - One-octet version number (3). + + - One-octet length of following hashed material. MUST be 5. + + - One-octet signature type. + + - Four-octet creation time. + + - Eight-octet key ID of signer. + + - One-octet public key algorithm. + + + +Callas, et. al. Standards Track [Page 19] + +RFC 2440 OpenPGP Message Format November 1998 + + + - One-octet hash algorithm. + + - Two-octet field holding left 16 bits of signed hash value. + + - One or more multi-precision integers comprising the signature. + This portion is algorithm specific, as described below. + + The data being signed is hashed, and then the signature type and + creation time from the signature packet are hashed (5 additional + octets). The resulting hash value is used in the signature + algorithm. The high 16 bits (first two octets) of the hash are + included in the signature packet to provide a quick test to reject + some invalid signatures. + + Algorithm Specific Fields for RSA signatures: + + - multiprecision integer (MPI) of RSA signature value m**d. + + Algorithm Specific Fields for DSA signatures: + + - MPI of DSA value r. + + - MPI of DSA value s. + + The signature calculation is based on a hash of the signed data, as + described above. The details of the calculation are different for + DSA signature than for RSA signatures. + + With RSA signatures, the hash value is encoded as described in PKCS-1 + section 10.1.2, "Data encoding", producing an ASN.1 value of type + DigestInfo, and then padded using PKCS-1 block type 01 [RFC2313]. + This requires inserting the hash value as an octet string into an + ASN.1 structure. The object identifier for the type of hash being + used is included in the structure. The hexadecimal representations + for the currently defined hash algorithms are: + + - MD2: 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x02 + + - MD5: 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 + + - RIPEMD-160: 0x2B, 0x24, 0x03, 0x02, 0x01 + + - SHA-1: 0x2B, 0x0E, 0x03, 0x02, 0x1A + + + + + + + + +Callas, et. al. Standards Track [Page 20] + +RFC 2440 OpenPGP Message Format November 1998 + + + The ASN.1 OIDs are: + + - MD2: 1.2.840.113549.2.2 + + - MD5: 1.2.840.113549.2.5 + + - RIPEMD-160: 1.3.36.3.2.1 + + - SHA-1: 1.3.14.3.2.26 + + The full hash prefixes for these are: + + MD2: 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x02, 0x05, 0x00, + 0x04, 0x10 + + MD5: 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, + 0x04, 0x10 + + RIPEMD-160: 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, + 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 + + SHA-1: 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0E, + 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14 + + DSA signatures MUST use hashes with a size of 160 bits, to match q, + the size of the group generated by the DSA key's generator value. + The hash function result is treated as a 160 bit number and used + directly in the DSA signature algorithm. + +5.2.3. Version 4 Signature Packet Format + + The body of a version 4 Signature Packet contains: + + - One-octet version number (4). + + - One-octet signature type. + + - One-octet public key algorithm. + + - One-octet hash algorithm. + + - Two-octet scalar octet count for following hashed subpacket + data. Note that this is the length in octets of all of the hashed + subpackets; a pointer incremented by this number will skip over + the hashed subpackets. + + + + +Callas, et. al. Standards Track [Page 21] + +RFC 2440 OpenPGP Message Format November 1998 + + + - Hashed subpacket data. (zero or more subpackets) + + - Two-octet scalar octet count for following unhashed subpacket + data. Note that this is the length in octets of all of the + unhashed subpackets; a pointer incremented by this number will + skip over the unhashed subpackets. + + - Unhashed subpacket data. (zero or more subpackets) + + - Two-octet field holding left 16 bits of signed hash value. + + - One or more multi-precision integers comprising the signature. + This portion is algorithm specific, as described above. + + The data being signed is hashed, and then the signature data from the + version number through the hashed subpacket data (inclusive) is + hashed. The resulting hash value is what is signed. The left 16 bits + of the hash are included in the signature packet to provide a quick + test to reject some invalid signatures. + + There are two fields consisting of signature subpackets. The first + field is hashed with the rest of the signature data, while the second + is unhashed. The second set of subpackets is not cryptographically + protected by the signature and should include only advisory + information. + + The algorithms for converting the hash function result to a signature + are described in a section below. + +5.2.3.1. Signature Subpacket Specification + + The subpacket fields consist of zero or more signature subpackets. + Each set of subpackets is preceded by a two-octet scalar count of the + length of the set of subpackets. + + Each subpacket consists of a subpacket header and a body. The header + consists of: + + - the subpacket length (1, 2, or 5 octets) + + - the subpacket type (1 octet) + + and is followed by the subpacket specific data. + + The length includes the type octet but not this length. Its format is + similar to the "new" format packet header lengths, but cannot have + partial body lengths. That is: + + + + +Callas, et. al. Standards Track [Page 22] + +RFC 2440 OpenPGP Message Format November 1998 + + + if the 1st octet < 192, then + lengthOfLength = 1 + subpacketLen = 1st_octet + + if the 1st octet >= 192 and < 255, then + lengthOfLength = 2 + subpacketLen = ((1st_octet - 192) << 8) + (2nd_octet) + 192 + + if the 1st octet = 255, then + lengthOfLength = 5 + subpacket length = [four-octet scalar starting at 2nd_octet] + + The value of the subpacket type octet may be: + + 2 = signature creation time + 3 = signature expiration time + 4 = exportable certification + 5 = trust signature + 6 = regular expression + 7 = revocable + 9 = key expiration time + 10 = placeholder for backward compatibility + 11 = preferred symmetric algorithms + 12 = revocation key + 16 = issuer key ID + 20 = notation data + 21 = preferred hash algorithms + 22 = preferred compression algorithms + 23 = key server preferences + 24 = preferred key server + 25 = primary user id + 26 = policy URL + 27 = key flags + 28 = signer's user id + 29 = reason for revocation + 100 to 110 = internal or user-defined + + An implementation SHOULD ignore any subpacket of a type that it does + not recognize. + + Bit 7 of the subpacket type is the "critical" bit. If set, it + denotes that the subpacket is one that is critical for the evaluator + of the signature to recognize. If a subpacket is encountered that is + marked critical but is unknown to the evaluating software, the + evaluator SHOULD consider the signature to be in error. + + + + + + +Callas, et. al. Standards Track [Page 23] + +RFC 2440 OpenPGP Message Format November 1998 + + + An evaluator may "recognize" a subpacket, but not implement it. The + purpose of the critical bit is to allow the signer to tell an + evaluator that it would prefer a new, unknown feature to generate an + error than be ignored. + + Implementations SHOULD implement "preferences". + +5.2.3.2. Signature Subpacket Types + + A number of subpackets are currently defined. Some subpackets apply + to the signature itself and some are attributes of the key. + Subpackets that are found on a self-signature are placed on a user id + certification made by the key itself. Note that a key may have more + than one user id, and thus may have more than one self-signature, and + differing subpackets. + + A self-signature is a binding signature made by the key the signature + refers to. There are three types of self-signatures, the + certification signatures (types 0x10-0x13), the direct-key signature + (type 0x1f), and the subkey binding signature (type 0x18). For + certification self-signatures, each user ID may have a self- + signature, and thus different subpackets in those self-signatures. + For subkey binding signatures, each subkey in fact has a self- + signature. Subpackets that appear in a certification self-signature + apply to the username, and subpackets that appear in the subkey + self-signature apply to the subkey. Lastly, subpackets on the direct + key signature apply to the entire key. + + Implementing software should interpret a self-signature's preference + subpackets as narrowly as possible. For example, suppose a key has + two usernames, Alice and Bob. Suppose that Alice prefers the + symmetric algorithm CAST5, and Bob prefers IDEA or Triple-DES. If the + software locates this key via Alice's name, then the preferred + algorithm is CAST5, if software locates the key via Bob's name, then + the preferred algorithm is IDEA. If the key is located by key id, + then algorithm of the default user id of the key provides the default + symmetric algorithm. + + A subpacket may be found either in the hashed or unhashed subpacket + sections of a signature. If a subpacket is not hashed, then the + information in it cannot be considered definitive because it is not + part of the signature proper. + + + + + + + + + +Callas, et. al. Standards Track [Page 24] + +RFC 2440 OpenPGP Message Format November 1998 + + +5.2.3.3. Signature creation time + + (4 octet time field) + + The time the signature was made. + + MUST be present in the hashed area. + +5.2.3.4. Issuer + + (8 octet key ID) + + The OpenPGP key ID of the key issuing the signature. + +5.2.3.5. Key expiration time + + (4 octet time field) + + The validity period of the key. This is the number of seconds after + the key creation time that the key expires. If this is not present + or has a value of zero, the key never expires. This is found only on + a self-signature. + +5.2.3.6. Preferred symmetric algorithms + + (sequence of one-octet values) + + Symmetric algorithm numbers that indicate which algorithms the key + holder prefers to use. The subpacket body is an ordered list of + octets with the most preferred listed first. It is assumed that only + algorithms listed are supported by the recipient's software. + Algorithm numbers in section 9. This is only found on a self- + signature. + +5.2.3.7. Preferred hash algorithms + + (array of one-octet values) + + Message digest algorithm numbers that indicate which algorithms the + key holder prefers to receive. Like the preferred symmetric + algorithms, the list is ordered. Algorithm numbers are in section 6. + This is only found on a self-signature. + + + + + + + + + +Callas, et. al. Standards Track [Page 25] + +RFC 2440 OpenPGP Message Format November 1998 + + +5.2.3.8. Preferred compression algorithms + + (array of one-octet values) + + Compression algorithm numbers that indicate which algorithms the key + holder prefers to use. Like the preferred symmetric algorithms, the + list is ordered. Algorithm numbers are in section 6. If this + subpacket is not included, ZIP is preferred. A zero denotes that + uncompressed data is preferred; the key holder's software might have + no compression software in that implementation. This is only found on + a self-signature. + +5.2.3.9. Signature expiration time + + (4 octet time field) + + The validity period of the signature. This is the number of seconds + after the signature creation time that the signature expires. If this + is not present or has a value of zero, it never expires. + +5.2.3.10. Exportable Certification + + (1 octet of exportability, 0 for not, 1 for exportable) + + This subpacket denotes whether a certification signature is + "exportable", to be used by other users than the signature's issuer. + The packet body contains a boolean flag indicating whether the + signature is exportable. If this packet is not present, the + certification is exportable; it is equivalent to a flag containing a + 1. + + Non-exportable, or "local", certifications are signatures made by a + user to mark a key as valid within that user's implementation only. + Thus, when an implementation prepares a user's copy of a key for + transport to another user (this is the process of "exporting" the + key), any local certification signatures are deleted from the key. + + The receiver of a transported key "imports" it, and likewise trims + any local certifications. In normal operation, there won't be any, + assuming the import is performed on an exported key. However, there + are instances where this can reasonably happen. For example, if an + implementation allows keys to be imported from a key database in + addition to an exported key, then this situation can arise. + + Some implementations do not represent the interest of a single user + (for example, a key server). Such implementations always trim local + certifications from any key they handle. + + + + +Callas, et. al. Standards Track [Page 26] + +RFC 2440 OpenPGP Message Format November 1998 + + +5.2.3.11. Revocable + + (1 octet of revocability, 0 for not, 1 for revocable) + + Signature's revocability status. Packet body contains a boolean flag + indicating whether the signature is revocable. Signatures that are + not revocable have any later revocation signatures ignored. They + represent a commitment by the signer that he cannot revoke his + signature for the life of his key. If this packet is not present, + the signature is revocable. + +5.2.3.12. Trust signature + + (1 octet "level" (depth), 1 octet of trust amount) + + Signer asserts that the key is not only valid, but also trustworthy, + at the specified level. Level 0 has the same meaning as an ordinary + validity signature. Level 1 means that the signed key is asserted to + be a valid trusted introducer, with the 2nd octet of the body + specifying the degree of trust. Level 2 means that the signed key is + asserted to be trusted to issue level 1 trust signatures, i.e. that + it is a "meta introducer". Generally, a level n trust signature + asserts that a key is trusted to issue level n-1 trust signatures. + The trust amount is in a range from 0-255, interpreted such that + values less than 120 indicate partial trust and values of 120 or + greater indicate complete trust. Implementations SHOULD emit values + of 60 for partial trust and 120 for complete trust. + +5.2.3.13. Regular expression + + (null-terminated regular expression) + + Used in conjunction with trust signature packets (of level > 0) to + limit the scope of trust that is extended. Only signatures by the + target key on user IDs that match the regular expression in the body + of this packet have trust extended by the trust signature subpacket. + The regular expression uses the same syntax as the Henry Spencer's + "almost public domain" regular expression package. A description of + the syntax is found in a section below. + +5.2.3.14. Revocation key + + (1 octet of class, 1 octet of algid, 20 octets of fingerprint) + + Authorizes the specified key to issue revocation signatures for this + key. Class octet must have bit 0x80 set. If the bit 0x40 is set, + then this means that the revocation information is sensitive. Other + bits are for future expansion to other kinds of authorizations. This + + + +Callas, et. al. Standards Track [Page 27] + +RFC 2440 OpenPGP Message Format November 1998 + + + is found on a self-signature. + + If the "sensitive" flag is set, the keyholder feels this subpacket + contains private trust information that describes a real-world + sensitive relationship. If this flag is set, implementations SHOULD + NOT export this signature to other users except in cases where the + data needs to be available: when the signature is being sent to the + designated revoker, or when it is accompanied by a revocation + signature from that revoker. Note that it may be appropriate to + isolate this subpacket within a separate signature so that it is not + combined with other subpackets that need to be exported. + +5.2.3.15. Notation Data + + (4 octets of flags, 2 octets of name length (M), + 2 octets of value length (N), + M octets of name data, + N octets of value data) + + This subpacket describes a "notation" on the signature that the + issuer wishes to make. The notation has a name and a value, each of + which are strings of octets. There may be more than one notation in a + signature. Notations can be used for any extension the issuer of the + signature cares to make. The "flags" field holds four octets of + flags. + + All undefined flags MUST be zero. Defined flags are: + + First octet: 0x80 = human-readable. This note is text, a note + from one person to another, and has no + meaning to software. + Other octets: none. + +5.2.3.16. Key server preferences + + (N octets of flags) + + This is a list of flags that indicate preferences that the key holder + has about how the key is handled on a key server. All undefined flags + MUST be zero. + + First octet: 0x80 = No-modify + the key holder requests that this key only be modified or updated + by the key holder or an administrator of the key server. + + This is found only on a self-signature. + + + + + +Callas, et. al. Standards Track [Page 28] + +RFC 2440 OpenPGP Message Format November 1998 + + +5.2.3.17. Preferred key server + + (String) + + This is a URL of a key server that the key holder prefers be used for + updates. Note that keys with multiple user ids can have a preferred + key server for each user id. Note also that since this is a URL, the + key server can actually be a copy of the key retrieved by ftp, http, + finger, etc. + +5.2.3.18. Primary user id + + (1 octet, boolean) + + This is a flag in a user id's self signature that states whether this + user id is the main user id for this key. It is reasonable for an + implementation to resolve ambiguities in preferences, etc. by + referring to the primary user id. If this flag is absent, its value + is zero. If more than one user id in a key is marked as primary, the + implementation may resolve the ambiguity in any way it sees fit. + +5.2.3.19. Policy URL + + (String) + + This subpacket contains a URL of a document that describes the policy + that the signature was issued under. + +5.2.3.20. Key Flags + + (Octet string) + + This subpacket contains a list of binary flags that hold information + about a key. It is a string of octets, and an implementation MUST NOT + assume a fixed size. This is so it can grow over time. If a list is + shorter than an implementation expects, the unstated flags are + considered to be zero. The defined flags are: + + First octet: + + 0x01 - This key may be used to certify other keys. + + 0x02 - This key may be used to sign data. + + 0x04 - This key may be used to encrypt communications. + + 0x08 - This key may be used to encrypt storage. + + + + +Callas, et. al. Standards Track [Page 29] + +RFC 2440 OpenPGP Message Format November 1998 + + + 0x10 - The private component of this key may have been split by a + secret-sharing mechanism. + + 0x80 - The private component of this key may be in the possession + of more than one person. + + Usage notes: + + The flags in this packet may appear in self-signatures or in + certification signatures. They mean different things depending on who + is making the statement -- for example, a certification signature + that has the "sign data" flag is stating that the certification is + for that use. On the other hand, the "communications encryption" flag + in a self-signature is stating a preference that a given key be used + for communications. Note however, that it is a thorny issue to + determine what is "communications" and what is "storage." This + decision is left wholly up to the implementation; the authors of this + document do not claim any special wisdom on the issue, and realize + that accepted opinion may change. + + The "split key" (0x10) and "group key" (0x80) flags are placed on a + self-signature only; they are meaningless on a certification + signature. They SHOULD be placed only on a direct-key signature (type + 0x1f) or a subkey signature (type 0x18), one that refers to the key + the flag applies to. + +5.2.3.21. Signer's User ID + + This subpacket allows a keyholder to state which user id is + responsible for the signing. Many keyholders use a single key for + different purposes, such as business communications as well as + personal communications. This subpacket allows such a keyholder to + state which of their roles is making a signature. + +5.2.3.22. Reason for Revocation + + (1 octet of revocation code, N octets of reason string) + + This subpacket is used only in key revocation and certification + revocation signatures. It describes the reason why the key or + certificate was revoked. + + The first octet contains a machine-readable code that denotes the + reason for the revocation: + + + + + + + +Callas, et. al. Standards Track [Page 30] + +RFC 2440 OpenPGP Message Format November 1998 + + + 0x00 - No reason specified (key revocations or cert revocations) + 0x01 - Key is superceded (key revocations) + 0x02 - Key material has been compromised (key revocations) + 0x03 - Key is no longer used (key revocations) + 0x20 - User id information is no longer valid (cert revocations) + + Following the revocation code is a string of octets which gives + information about the reason for revocation in human-readable form + (UTF-8). The string may be null, that is, of zero length. The length + of the subpacket is the length of the reason string plus one. + +5.2.4. Computing Signatures + + All signatures are formed by producing a hash over the signature + data, and then using the resulting hash in the signature algorithm. + + The signature data is simple to compute for document signatures + (types 0x00 and 0x01), for which the document itself is the data. + For standalone signatures, this is a null string. + + When a signature is made over a key, the hash data starts with the + octet 0x99, followed by a two-octet length of the key, and then body + of the key packet. (Note that this is an old-style packet header for + a key packet with two-octet length.) A subkey signature (type 0x18) + then hashes the subkey, using the same format as the main key. Key + revocation signatures (types 0x20 and 0x28) hash only the key being + revoked. + + A certification signature (type 0x10 through 0x13) hashes the user id + being bound to the key into the hash context after the above data. A + V3 certification hashes the contents of the name packet, without any + header. A V4 certification hashes the constant 0xb4 (which is an + old-style packet header with the length-of-length set to zero), a + four-octet number giving the length of the username, and then the + username data. + + Once the data body is hashed, then a trailer is hashed. A V3 + signature hashes five octets of the packet body, starting from the + signature type field. This data is the signature type, followed by + the four-octet signature time. A V4 signature hashes the packet body + starting from its first field, the version number, through the end of + the hashed subpacket data. Thus, the fields hashed are the signature + version, the signature type, the public key algorithm, the hash + algorithm, the hashed subpacket length, and the hashed subpacket + body. + + + + + + +Callas, et. al. Standards Track [Page 31] + +RFC 2440 OpenPGP Message Format November 1998 + + + V4 signatures also hash in a final trailer of six octets: the version + of the signature packet, i.e. 0x04; 0xFF; a four-octet, big-endian + number that is the length of the hashed data from the signature + packet (note that this number does not include these final six + octets. + + After all this has been hashed, the resulting hash field is used in + the signature algorithm, and placed at the end of the signature + packet. + +5.2.4.1. Subpacket Hints + + An implementation SHOULD put the two mandatory subpackets, creation + time and issuer, as the first subpackets in the subpacket list, + simply to make it easier for the implementer to find them. + + It is certainly possible for a signature to contain conflicting + information in subpackets. For example, a signature may contain + multiple copies of a preference or multiple expiration times. In most + cases, an implementation SHOULD use the last subpacket in the + signature, but MAY use any conflict resolution scheme that makes more + sense. Please note that we are intentionally leaving conflict + resolution to the implementer; most conflicts are simply syntax + errors, and the wishy-washy language here allows a receiver to be + generous in what they accept, while putting pressure on a creator to + be stingy in what they generate. + + Some apparent conflicts may actually make sense -- for example, + suppose a keyholder has an V3 key and a V4 key that share the same + RSA key material. Either of these keys can verify a signature created + by the other, and it may be reasonable for a signature to contain an + issuer subpacket for each key, as a way of explicitly tying those + keys to the signature. + +5.3. Symmetric-Key Encrypted Session-Key Packets (Tag 3) + + The Symmetric-Key Encrypted Session Key packet holds the symmetric- + key encryption of a session key used to encrypt a message. Zero or + more Encrypted Session Key packets and/or Symmetric-Key Encrypted + Session Key packets may precede a Symmetrically Encrypted Data Packet + that holds an encrypted message. The message is encrypted with a + session key, and the session key is itself encrypted and stored in + the Encrypted Session Key packet or the Symmetric-Key Encrypted + Session Key packet. + + If the Symmetrically Encrypted Data Packet is preceded by one or more + Symmetric-Key Encrypted Session Key packets, each specifies a + passphrase that may be used to decrypt the message. This allows a + + + +Callas, et. al. Standards Track [Page 32] + +RFC 2440 OpenPGP Message Format November 1998 + + + message to be encrypted to a number of public keys, and also to one + or more pass phrases. This packet type is new, and is not generated + by PGP 2.x or PGP 5.0. + + The body of this packet consists of: + + - A one-octet version number. The only currently defined version + is 4. + + - A one-octet number describing the symmetric algorithm used. + + - A string-to-key (S2K) specifier, length as defined above. + + - Optionally, the encrypted session key itself, which is decrypted + with the string-to-key object. + + If the encrypted session key is not present (which can be detected on + the basis of packet length and S2K specifier size), then the S2K + algorithm applied to the passphrase produces the session key for + decrypting the file, using the symmetric cipher algorithm from the + Symmetric-Key Encrypted Session Key packet. + + If the encrypted session key is present, the result of applying the + S2K algorithm to the passphrase is used to decrypt just that + encrypted session key field, using CFB mode with an IV of all zeros. + The decryption result consists of a one-octet algorithm identifier + that specifies the symmetric-key encryption algorithm used to encrypt + the following Symmetrically Encrypted Data Packet, followed by the + session key octets themselves. + + Note: because an all-zero IV is used for this decryption, the S2K + specifier MUST use a salt value, either a Salted S2K or an Iterated- + Salted S2K. The salt value will insure that the decryption key is + not repeated even if the passphrase is reused. + +5.4. One-Pass Signature Packets (Tag 4) + + The One-Pass Signature packet precedes the signed data and contains + enough information to allow the receiver to begin calculating any + hashes needed to verify the signature. It allows the Signature + Packet to be placed at the end of the message, so that the signer can + compute the entire signed message in one pass. + + A One-Pass Signature does not interoperate with PGP 2.6.x or earlier. + + The body of this packet consists of: + + + + + +Callas, et. al. Standards Track [Page 33] + +RFC 2440 OpenPGP Message Format November 1998 + + + - A one-octet version number. The current version is 3. + + - A one-octet signature type. Signature types are described in + section 5.2.1. + + - A one-octet number describing the hash algorithm used. + + - A one-octet number describing the public key algorithm used. + + - An eight-octet number holding the key ID of the signing key. + + - A one-octet number holding a flag showing whether the signature + is nested. A zero value indicates that the next packet is + another One-Pass Signature packet that describes another + signature to be applied to the same message data. + + Note that if a message contains more than one one-pass signature, + then the signature packets bracket the message; that is, the first + signature packet after the message corresponds to the last one-pass + packet and the final signature packet corresponds to the first one- + pass packet. + +5.5. Key Material Packet + + A key material packet contains all the information about a public or + private key. There are four variants of this packet type, and two + major versions. Consequently, this section is complex. + +5.5.1. Key Packet Variants + +5.5.1.1. Public Key Packet (Tag 6) + + A Public Key packet starts a series of packets that forms an OpenPGP + key (sometimes called an OpenPGP certificate). + +5.5.1.2. Public Subkey Packet (Tag 14) + + A Public Subkey packet (tag 14) has exactly the same format as a + Public Key packet, but denotes a subkey. One or more subkeys may be + associated with a top-level key. By convention, the top-level key + provides signature services, and the subkeys provide encryption + services. + + Note: in PGP 2.6.x, tag 14 was intended to indicate a comment packet. + This tag was selected for reuse because no previous version of PGP + ever emitted comment packets but they did properly ignore them. + Public Subkey packets are ignored by PGP 2.6.x and do not cause it to + fail, providing a limited degree of backward compatibility. + + + +Callas, et. al. Standards Track [Page 34] + +RFC 2440 OpenPGP Message Format November 1998 + + +5.5.1.3. Secret Key Packet (Tag 5) + + A Secret Key packet contains all the information that is found in a + Public Key packet, including the public key material, but also + includes the secret key material after all the public key fields. + +5.5.1.4. Secret Subkey Packet (Tag 7) + + A Secret Subkey packet (tag 7) is the subkey analog of the Secret Key + packet, and has exactly the same format. + +5.5.2. Public Key Packet Formats + + There are two versions of key-material packets. Version 3 packets + were first generated by PGP 2.6. Version 2 packets are identical in + format to Version 3 packets, but are generated by PGP 2.5 or before. + V2 packets are deprecated and they MUST NOT be generated. PGP 5.0 + introduced version 4 packets, with new fields and semantics. PGP + 2.6.x will not accept key-material packets with versions greater than + 3. + + OpenPGP implementations SHOULD create keys with version 4 format. An + implementation MAY generate a V3 key to ensure interoperability with + old software; note, however, that V4 keys correct some security + deficiencies in V3 keys. These deficiencies are described below. An + implementation MUST NOT create a V3 key with a public key algorithm + other than RSA. + + A version 3 public key or public subkey packet contains: + + - A one-octet version number (3). + + - A four-octet number denoting the time that the key was created. + + - A two-octet number denoting the time in days that this key is + valid. If this number is zero, then it does not expire. + + - A one-octet number denoting the public key algorithm of this key + + - A series of multi-precision integers comprising the key + material: + + - a multiprecision integer (MPI) of RSA public modulus n; + + - an MPI of RSA public encryption exponent e. + + + + + + +Callas, et. al. Standards Track [Page 35] + +RFC 2440 OpenPGP Message Format November 1998 + + + V3 keys SHOULD only be used for backward compatibility because of + three weaknesses in them. First, it is relatively easy to construct a + V3 key that has the same key ID as any other key because the key ID + is simply the low 64 bits of the public modulus. Secondly, because + the fingerprint of a V3 key hashes the key material, but not its + length, which increases the opportunity for fingerprint collisions. + Third, there are minor weaknesses in the MD5 hash algorithm that make + developers prefer other algorithms. See below for a fuller discussion + of key IDs and fingerprints. + + The version 4 format is similar to the version 3 format except for + the absence of a validity period. This has been moved to the + signature packet. In addition, fingerprints of version 4 keys are + calculated differently from version 3 keys, as described in section + "Enhanced Key Formats." + + A version 4 packet contains: + + - A one-octet version number (4). + + - A four-octet number denoting the time that the key was created. + + - A one-octet number denoting the public key algorithm of this key + + - A series of multi-precision integers comprising the key + material. This algorithm-specific portion is: + + Algorithm Specific Fields for RSA public keys: + + - multiprecision integer (MPI) of RSA public modulus n; + + - MPI of RSA public encryption exponent e. + + Algorithm Specific Fields for DSA public keys: + + - MPI of DSA prime p; + + - MPI of DSA group order q (q is a prime divisor of p-1); + + - MPI of DSA group generator g; + + - MPI of DSA public key value y (= g**x where x is secret). + + Algorithm Specific Fields for Elgamal public keys: + + - MPI of Elgamal prime p; + + - MPI of Elgamal group generator g; + + + +Callas, et. al. Standards Track [Page 36] + +RFC 2440 OpenPGP Message Format November 1998 + + + - MPI of Elgamal public key value y (= g**x where x is + secret). + +5.5.3. Secret Key Packet Formats + + The Secret Key and Secret Subkey packets contain all the data of the + Public Key and Public Subkey packets, with additional algorithm- + specific secret key data appended, in encrypted form. + + The packet contains: + + - A Public Key or Public Subkey packet, as described above + + - One octet indicating string-to-key usage conventions. 0 + indicates that the secret key data is not encrypted. 255 + indicates that a string-to-key specifier is being given. Any + other value is a symmetric-key encryption algorithm specifier. + + - [Optional] If string-to-key usage octet was 255, a one-octet + symmetric encryption algorithm. + + - [Optional] If string-to-key usage octet was 255, a string-to-key + specifier. The length of the string-to-key specifier is implied + by its type, as described above. + + - [Optional] If secret data is encrypted, eight-octet Initial + Vector (IV). + + - Encrypted multi-precision integers comprising the secret key + data. These algorithm-specific fields are as described below. + + - Two-octet checksum of the plaintext of the algorithm-specific + portion (sum of all octets, mod 65536). + + Algorithm Specific Fields for RSA secret keys: + + - multiprecision integer (MPI) of RSA secret exponent d. + + - MPI of RSA secret prime value p. + + - MPI of RSA secret prime value q (p < q). + + - MPI of u, the multiplicative inverse of p, mod q. + + Algorithm Specific Fields for DSA secret keys: + + - MPI of DSA secret exponent x. + + + + +Callas, et. al. Standards Track [Page 37] + +RFC 2440 OpenPGP Message Format November 1998 + + + Algorithm Specific Fields for Elgamal secret keys: + + - MPI of Elgamal secret exponent x. + + Secret MPI values can be encrypted using a passphrase. If a string- + to-key specifier is given, that describes the algorithm for + converting the passphrase to a key, else a simple MD5 hash of the + passphrase is used. Implementations SHOULD use a string-to-key + specifier; the simple hash is for backward compatibility. The cipher + for encrypting the MPIs is specified in the secret key packet. + + Encryption/decryption of the secret data is done in CFB mode using + the key created from the passphrase and the Initial Vector from the + packet. A different mode is used with V3 keys (which are only RSA) + than with other key formats. With V3 keys, the MPI bit count prefix + (i.e., the first two octets) is not encrypted. Only the MPI non- + prefix data is encrypted. Furthermore, the CFB state is + resynchronized at the beginning of each new MPI value, so that the + CFB block boundary is aligned with the start of the MPI data. + + With V4 keys, a simpler method is used. All secret MPI values are + encrypted in CFB mode, including the MPI bitcount prefix. + + The 16-bit checksum that follows the algorithm-specific portion is + the algebraic sum, mod 65536, of the plaintext of all the algorithm- + specific octets (including MPI prefix and data). With V3 keys, the + checksum is stored in the clear. With V4 keys, the checksum is + encrypted like the algorithm-specific data. This value is used to + check that the passphrase was correct. + +5.6. Compressed Data Packet (Tag 8) + + The Compressed Data packet contains compressed data. Typically, this + packet is found as the contents of an encrypted packet, or following + a Signature or One-Pass Signature packet, and contains literal data + packets. + + The body of this packet consists of: + + - One octet that gives the algorithm used to compress the packet. + + - The remainder of the packet is compressed data. + + A Compressed Data Packet's body contains an block that compresses + some set of packets. See section "Packet Composition" for details on + how messages are formed. + + + + + +Callas, et. al. Standards Track [Page 38] + +RFC 2440 OpenPGP Message Format November 1998 + + + ZIP-compressed packets are compressed with raw RFC 1951 DEFLATE + blocks. Note that PGP V2.6 uses 13 bits of compression. If an + implementation uses more bits of compression, PGP V2.6 cannot + decompress it. + + ZLIB-compressed packets are compressed with RFC 1950 ZLIB-style + blocks. + +5.7. Symmetrically Encrypted Data Packet (Tag 9) + + The Symmetrically Encrypted Data packet contains data encrypted with + a symmetric-key algorithm. When it has been decrypted, it will + typically contain other packets (often literal data packets or + compressed data packets). + + The body of this packet consists of: + + - Encrypted data, the output of the selected symmetric-key cipher + operating in PGP's variant of Cipher Feedback (CFB) mode. + + The symmetric cipher used may be specified in an Public-Key or + Symmetric-Key Encrypted Session Key packet that precedes the + Symmetrically Encrypted Data Packet. In that case, the cipher + algorithm octet is prefixed to the session key before it is + encrypted. If no packets of these types precede the encrypted data, + the IDEA algorithm is used with the session key calculated as the MD5 + hash of the passphrase. + + The data is encrypted in CFB mode, with a CFB shift size equal to the + cipher's block size. The Initial Vector (IV) is specified as all + zeros. Instead of using an IV, OpenPGP prefixes a 10-octet string to + the data before it is encrypted. The first eight octets are random, + and the 9th and 10th octets are copies of the 7th and 8th octets, + respectively. After encrypting the first 10 octets, the CFB state is + resynchronized if the cipher block size is 8 octets or less. The + last 8 octets of ciphertext are passed through the cipher and the + block boundary is reset. + + The repetition of 16 bits in the 80 bits of random data prefixed to + the message allows the receiver to immediately check whether the + session key is incorrect. + +5.8. Marker Packet (Obsolete Literal Packet) (Tag 10) + + An experimental version of PGP used this packet as the Literal + packet, but no released version of PGP generated Literal packets with + this tag. With PGP 5.x, this packet has been re-assigned and is + reserved for use as the Marker packet. + + + +Callas, et. al. Standards Track [Page 39] + +RFC 2440 OpenPGP Message Format November 1998 + + + The body of this packet consists of: + + - The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + + Such a packet MUST be ignored when received. It may be placed at the + beginning of a message that uses features not available in PGP 2.6.x + in order to cause that version to report that newer software is + necessary to process the message. + +5.9. Literal Data Packet (Tag 11) + + A Literal Data packet contains the body of a message; data that is + not to be further interpreted. + + The body of this packet consists of: + + - A one-octet field that describes how the data is formatted. + + If it is a 'b' (0x62), then the literal packet contains binary data. + If it is a 't' (0x74), then it contains text data, and thus may need + line ends converted to local form, or other text-mode changes. RFC + 1991 also defined a value of 'l' as a 'local' mode for machine-local + conversions. This use is now deprecated. + + - File name as a string (one-octet length, followed by file name), + if the encrypted data should be saved as a file. + + If the special name "_CONSOLE" is used, the message is considered to + be "for your eyes only". This advises that the message data is + unusually sensitive, and the receiving program should process it more + carefully, perhaps avoiding storing the received data to disk, for + example. + + - A four-octet number that indicates the modification date of the + file, or the creation time of the packet, or a zero that + indicates the present time. + + - The remainder of the packet is literal data. + + Text data is stored with text endings (i.e. network-normal + line endings). These should be converted to native line endings by + the receiving software. + +5.10. Trust Packet (Tag 12) + + The Trust packet is used only within keyrings and is not normally + exported. Trust packets contain data that record the user's + specifications of which key holders are trustworthy introducers, + + + +Callas, et. al. Standards Track [Page 40] + +RFC 2440 OpenPGP Message Format November 1998 + + + along with other information that implementing software uses for + trust information. + + Trust packets SHOULD NOT be emitted to output streams that are + transferred to other users, and they SHOULD be ignored on any input + other than local keyring files. + +5.11. User ID Packet (Tag 13) + + A User ID packet consists of data that is intended to represent the + name and email address of the key holder. By convention, it includes + an RFC 822 mail name, but there are no restrictions on its content. + The packet length in the header specifies the length of the user id. + If it is text, it is encoded in UTF-8. + +6. Radix-64 Conversions + + As stated in the introduction, OpenPGP's underlying native + representation for objects is a stream of arbitrary octets, and some + systems desire these objects to be immune to damage caused by + character set translation, data conversions, etc. + + In principle, any printable encoding scheme that met the requirements + of the unsafe channel would suffice, since it would not change the + underlying binary bit streams of the native OpenPGP data structures. + The OpenPGP standard specifies one such printable encoding scheme to + ensure interoperability. + + OpenPGP's Radix-64 encoding is composed of two parts: a base64 + encoding of the binary data, and a checksum. The base64 encoding is + identical to the MIME base64 content-transfer-encoding [RFC2231, + Section 6.8]. An OpenPGP implementation MAY use ASCII Armor to + protect the raw binary data. + + The checksum is a 24-bit CRC converted to four characters of radix-64 + encoding by the same MIME base64 transformation, preceded by an + equals sign (=). The CRC is computed by using the generator 0x864CFB + and an initialization of 0xB704CE. The accumulation is done on the + data before it is converted to radix-64, rather than on the converted + data. A sample implementation of this algorithm is in the next + section. + + The checksum with its leading equal sign MAY appear on the first line + after the Base64 encoded data. + + Rationale for CRC-24: The size of 24 bits fits evenly into printable + base64. The nonzero initialization can detect more errors than a + zero initialization. + + + +Callas, et. al. Standards Track [Page 41] + +RFC 2440 OpenPGP Message Format November 1998 + + +6.1. An Implementation of the CRC-24 in "C" + + #define CRC24_INIT 0xb704ceL + #define CRC24_POLY 0x1864cfbL + + typedef long crc24; + crc24 crc_octets(unsigned char *octets, size_t len) + { + crc24 crc = CRC24_INIT; + int i; + + while (len--) { + crc ^= (*octets++) << 16; + for (i = 0; i < 8; i++) { + crc <<= 1; + if (crc & 0x1000000) + crc ^= CRC24_POLY; + } + } + return crc & 0xffffffL; + } + +6.2. Forming ASCII Armor + + When OpenPGP encodes data into ASCII Armor, it puts specific headers + around the data, so OpenPGP can reconstruct the data later. OpenPGP + informs the user what kind of data is encoded in the ASCII armor + through the use of the headers. + + Concatenating the following data creates ASCII Armor: + + - An Armor Header Line, appropriate for the type of data + + - Armor Headers + + - A blank (zero-length, or containing only whitespace) line + + - The ASCII-Armored data + + - An Armor Checksum + + - The Armor Tail, which depends on the Armor Header Line. + + An Armor Header Line consists of the appropriate header line text + surrounded by five (5) dashes ('-', 0x2D) on either side of the + header line text. The header line text is chosen based upon the type + of data that is being encoded in Armor, and how it is being encoded. + Header line texts include the following strings: + + + +Callas, et. al. Standards Track [Page 42] + +RFC 2440 OpenPGP Message Format November 1998 + + + BEGIN PGP MESSAGE + Used for signed, encrypted, or compressed files. + + BEGIN PGP PUBLIC KEY BLOCK + Used for armoring public keys + + BEGIN PGP PRIVATE KEY BLOCK + Used for armoring private keys + + BEGIN PGP MESSAGE, PART X/Y + Used for multi-part messages, where the armor is split amongst Y + parts, and this is the Xth part out of Y. + + BEGIN PGP MESSAGE, PART X + Used for multi-part messages, where this is the Xth part of an + unspecified number of parts. Requires the MESSAGE-ID Armor Header + to be used. + + BEGIN PGP SIGNATURE + Used for detached signatures, OpenPGP/MIME signatures, and + natures following clearsigned messages. Note that PGP 2.x s BEGIN + PGP MESSAGE for detached signatures. + + The Armor Headers are pairs of strings that can give the user or the + receiving OpenPGP implementation some information about how to decode + or use the message. The Armor Headers are a part of the armor, not a + part of the message, and hence are not protected by any signatures + applied to the message. + + The format of an Armor Header is that of a key-value pair. A colon + (':' 0x38) and a single space (0x20) separate the key and value. + OpenPGP should consider improperly formatted Armor Headers to be + corruption of the ASCII Armor. Unknown keys should be reported to + the user, but OpenPGP should continue to process the message. + + Currently defined Armor Header Keys are: + + - "Version", that states the OpenPGP Version used to encode the + message. + + - "Comment", a user-defined comment. + + - "MessageID", a 32-character string of printable characters. The + string must be the same for all parts of a multi-part message + that uses the "PART X" Armor Header. MessageID strings should be + + + + + + +Callas, et. al. Standards Track [Page 43] + +RFC 2440 OpenPGP Message Format November 1998 + + + unique enough that the recipient of the mail can associate all + the parts of a message with each other. A good checksum or + cryptographic hash function is sufficient. + + - "Hash", a comma-separated list of hash algorithms used in this + message. This is used only in clear-signed messages. + + - "Charset", a description of the character set that the plaintext + is in. Please note that OpenPGP defines text to be in UTF-8 by + default. An implementation will get best results by translating + into and out of UTF-8. However, there are many instances where + this is easier said than done. Also, there are communities of + users who have no need for UTF-8 because they are all happy with + a character set like ISO Latin-5 or a Japanese character set. In + such instances, an implementation MAY override the UTF-8 default + by using this header key. An implementation MAY implement this + key and any translations it cares to; an implementation MAY + ignore it and assume all text is UTF-8. + + The MessageID SHOULD NOT appear unless it is in a multi-part + message. If it appears at all, it MUST be computed from the + finished (encrypted, signed, etc.) message in a deterministic + fashion, rather than contain a purely random value. This is to + allow the legitimate recipient to determine that the MessageID + cannot serve as a covert means of leaking cryptographic key + information. + + The Armor Tail Line is composed in the same manner as the Armor + Header Line, except the string "BEGIN" is replaced by the string + "END." + +6.3. Encoding Binary in Radix-64 + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating three 8-bit input + groups. These 24 bits are then treated as four concatenated 6-bit + groups, each of which is translated into a single digit in the + Radix-64 alphabet. When encoding a bit stream with the Radix-64 + encoding, the bit stream must be presumed to be ordered with the + most-significant-bit first. That is, the first bit in the stream will + be the high-order bit in the first 8-bit octet, and the eighth bit + will be the low-order bit in the first 8-bit octet, and so on. + + + + + + + + +Callas, et. al. Standards Track [Page 44] + +RFC 2440 OpenPGP Message Format November 1998 + + + +--first octet--+-second octet--+--third octet--+ + |7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0| + +-----------+---+-------+-------+---+-----------+ + |5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0| + +--1.index--+--2.index--+--3.index--+--4.index--+ + + Each 6-bit group is used as an index into an array of 64 printable + characters from the table below. The character referenced by the + index is placed in the output string. + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + The encoded output stream must be represented in lines of no more + than 76 characters each. + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. There are three possibilities: + + 1. The last data group has 24 bits (3 octets). No special + processing is needed. + + 2. The last data group has 16 bits (2 octets). The first two 6-bit + groups are processed as above. The third (incomplete) data group + has two zero-value bits added to it, and is processed as above. + A pad character (=) is added to the output. + + 3. The last data group has 8 bits (1 octet). The first 6-bit group + is processed as above. The second (incomplete) data group has + four zero-value bits added to it, and is processed as above. Two + pad characters (=) are added to the output. + + + + +Callas, et. al. Standards Track [Page 45] + +RFC 2440 OpenPGP Message Format November 1998 + + +6.4. Decoding Radix-64 + + Any characters outside of the base64 alphabet are ignored in Radix-64 + data. Decoding software must ignore all line breaks or other + characters not found in the table above. + + In Radix-64 data, characters other than those in the table, line + breaks, and other white space probably indicate a transmission error, + about which a warning message or even a message rejection might be + appropriate under some circumstances. + + Because it is used only for padding at the end of the data, the + occurrence of any "=" characters may be taken as evidence that the + end of the data has been reached (without truncation in transit). No + such assurance is possible, however, when the number of octets + transmitted was a multiple of three and no "=" characters are + present. + +6.5. Examples of Radix-64 + + Input data: 0x14fb9c03d97e + Hex: 1 4 f b 9 c | 0 3 d 9 7 e + 8-bit: 00010100 11111011 10011100 | 00000011 11011001 + 11111110 + 6-bit: 000101 001111 101110 011100 | 000000 111101 100111 + 111110 + Decimal: 5 15 46 28 0 61 37 62 + Output: F P u c A 9 l + + + Input data: 0x14fb9c03d9 + Hex: 1 4 f b 9 c | 0 3 d 9 + 8-bit: 00010100 11111011 10011100 | 00000011 11011001 + pad with 00 + 6-bit: 000101 001111 101110 011100 | 000000 111101 100100 + Decimal: 5 15 46 28 0 61 36 + pad with = + Output: F P u c A 9 k = + + Input data: 0x14fb9c03 + Hex: 1 4 f b 9 c | 0 3 + 8-bit: 00010100 11111011 10011100 | 00000011 + pad with 0000 + 6-bit: 000101 001111 101110 011100 | 000000 110000 + Decimal: 5 15 46 28 0 48 + pad with = = + Output: F P u c A w = = + + + + + +Callas, et. al. Standards Track [Page 46] + +RFC 2440 OpenPGP Message Format November 1998 + + +6.6. Example of an ASCII Armored Message + + + -----BEGIN PGP MESSAGE----- + Version: OpenPrivacy 0.99 + + yDgBO22WxBHv7O8X7O/jygAEzol56iUKiXmV+XmpCtmpqQUKiQrFqclFqUDBovzS + vBSFjNSiVHsuAA== + =njUN + -----END PGP MESSAGE----- + + Note that this example is indented by two spaces. + +7. Cleartext signature framework + + It is desirable to sign a textual octet stream without ASCII armoring + the stream itself, so the signed text is still readable without + special software. In order to bind a signature to such a cleartext, + this framework is used. (Note that RFC 2015 defines another way to + clear sign messages for environments that support MIME.) + + The cleartext signed message consists of: + + - The cleartext header '-----BEGIN PGP SIGNED MESSAGE-----' on a + single line, + + - One or more "Hash" Armor Headers, + + - Exactly one empty line not included into the message digest, + + - The dash-escaped cleartext that is included into the message + digest, + + - The ASCII armored signature(s) including the '-----BEGIN PGP + SIGNATURE-----' Armor Header and Armor Tail Lines. + + If the "Hash" armor header is given, the specified message digest + algorithm is used for the signature. If there are no such headers, + MD5 is used, an implementation MAY omit them for V2.x compatibility. + If more than one message digest is used in the signature, the "Hash" + armor header contains a comma-delimited list of used message digests. + + Current message digest names are described below with the algorithm + IDs. + +7.1. Dash-Escaped Text + + The cleartext content of the message must also be dash-escaped. + + + +Callas, et. al. Standards Track [Page 47] + +RFC 2440 OpenPGP Message Format November 1998 + + + Dash escaped cleartext is the ordinary cleartext where every line + starting with a dash '-' (0x2D) is prefixed by the sequence dash '-' + (0x2D) and space ' ' (0x20). This prevents the parser from + recognizing armor headers of the cleartext itself. The message digest + is computed using the cleartext itself, not the dash escaped form. + + As with binary signatures on text documents, a cleartext signature is + calculated on the text using canonical line endings. The + line ending (i.e. the ) before the '-----BEGIN PGP + SIGNATURE-----' line that terminates the signed text is not + considered part of the signed text. + + Also, any trailing whitespace (spaces, and tabs, 0x09) at the end of + any line is ignored when the cleartext signature is calculated. + +8. Regular Expressions + + A regular expression is zero or more branches, separated by '|'. It + matches anything that matches one of the branches. + + A branch is zero or more pieces, concatenated. It matches a match for + the first, followed by a match for the second, etc. + + A piece is an atom possibly followed by '*', '+', or '?'. An atom + followed by '*' matches a sequence of 0 or more matches of the atom. + An atom followed by '+' matches a sequence of 1 or more matches of + the atom. An atom followed by '?' matches a match of the atom, or the + null string. + + An atom is a regular expression in parentheses (matching a match for + the regular expression), a range (see below), '.' (matching any + single character), '^' (matching the null string at the beginning of + the input string), '$' (matching the null string at the end of the + input string), a '\' followed by a single character (matching that + character), or a single character with no other significance + (matching that character). + + A range is a sequence of characters enclosed in '[]'. It normally + matches any single character from the sequence. If the sequence + begins with '^', it matches any single character not from the rest of + the sequence. If two characters in the sequence are separated by '-', + this is shorthand for the full list of ASCII characters between them + (e.g. '[0-9]' matches any decimal digit). To include a literal ']' in + the sequence, make it the first character (following a possible '^'). + To include a literal '-', make it the first or last character. + + + + + + +Callas, et. al. Standards Track [Page 48] + +RFC 2440 OpenPGP Message Format November 1998 + + +9. Constants + + This section describes the constants used in OpenPGP. + + Note that these tables are not exhaustive lists; an implementation + MAY implement an algorithm not on these lists. + + See the section "Notes on Algorithms" below for more discussion of + the algorithms. + +9.1. Public Key Algorithms + + ID Algorithm + -- --------- + 1 - RSA (Encrypt or Sign) + 2 - RSA Encrypt-Only + 3 - RSA Sign-Only + 16 - Elgamal (Encrypt-Only), see [ELGAMAL] + 17 - DSA (Digital Signature Standard) + 18 - Reserved for Elliptic Curve + 19 - Reserved for ECDSA + 20 - Elgamal (Encrypt or Sign) + + + + + + 21 - Reserved for Diffie-Hellman (X9.42, + as defined for IETF-S/MIME) + 100 to 110 - Private/Experimental algorithm. + + Implementations MUST implement DSA for signatures, and Elgamal for + encryption. Implementations SHOULD implement RSA keys. + Implementations MAY implement any other algorithm. + +9.2. Symmetric Key Algorithms + + ID Algorithm + -- --------- + 0 - Plaintext or unencrypted data + 1 - IDEA [IDEA] + 2 - Triple-DES (DES-EDE, as per spec - + 168 bit key derived from 192) + 3 - CAST5 (128 bit key, as per RFC 2144) + 4 - Blowfish (128 bit key, 16 rounds) [BLOWFISH] + 5 - SAFER-SK128 (13 rounds) [SAFER] + 6 - Reserved for DES/SK + 7 - Reserved for AES with 128-bit key + + + +Callas, et. al. Standards Track [Page 49] + +RFC 2440 OpenPGP Message Format November 1998 + + + 8 - Reserved for AES with 192-bit key + 9 - Reserved for AES with 256-bit key + 100 to 110 - Private/Experimental algorithm. + + Implementations MUST implement Triple-DES. Implementations SHOULD + implement IDEA and CAST5.Implementations MAY implement any other + algorithm. + +9.3. Compression Algorithms + + ID Algorithm + -- --------- + 0 - Uncompressed + 1 - ZIP (RFC 1951) + 2 - ZLIB (RFC 1950) + 100 to 110 - Private/Experimental algorithm. + + Implementations MUST implement uncompressed data. Implementations + SHOULD implement ZIP. Implementations MAY implement ZLIB. + +9.4. Hash Algorithms + + ID Algorithm Text Name + -- --------- ---- ---- + 1 - MD5 "MD5" + 2 - SHA-1 "SHA1" + 3 - RIPE-MD/160 "RIPEMD160" + 4 - Reserved for double-width SHA (experimental) + 5 - MD2 "MD2" + 6 - Reserved for TIGER/192 "TIGER192" + 7 - Reserved for HAVAL (5 pass, 160-bit) + "HAVAL-5-160" + 100 to 110 - Private/Experimental algorithm. + + Implementations MUST implement SHA-1. Implementations SHOULD + implement MD5. + +10. Packet Composition + + OpenPGP packets are assembled into sequences in order to create + messages and to transfer keys. Not all possible packet sequences are + meaningful and correct. This describes the rules for how packets + should be placed into sequences. + +10.1. Transferable Public Keys + + OpenPGP users may transfer public keys. The essential elements of a + transferable public key are: + + + +Callas, et. al. Standards Track [Page 50] + +RFC 2440 OpenPGP Message Format November 1998 + + + - One Public Key packet + + - Zero or more revocation signatures + + - One or more User ID packets + + - After each User ID packet, zero or more signature packets + (certifications) + + - Zero or more Subkey packets + + - After each Subkey packet, one signature packet, optionally a + revocation. + + The Public Key packet occurs first. Each of the following User ID + packets provides the identity of the owner of this public key. If + there are multiple User ID packets, this corresponds to multiple + means of identifying the same unique individual user; for example, a + user may have more than one email address, and construct a User ID + for each one. + + Immediately following each User ID packet, there are zero or more + signature packets. Each signature packet is calculated on the + immediately preceding User ID packet and the initial Public Key + packet. The signature serves to certify the corresponding public key + and user ID. In effect, the signer is testifying to his or her + belief that this public key belongs to the user identified by this + user ID. + + After the User ID packets there may be one or more Subkey packets. + In general, subkeys are provided in cases where the top-level public + key is a signature-only key. However, any V4 key may have subkeys, + and the subkeys may be encryption-only keys, signature-only keys, or + general-purpose keys. + + Each Subkey packet must be followed by one Signature packet, which + should be a subkey binding signature issued by the top level key. + + Subkey and Key packets may each be followed by a revocation Signature + packet to indicate that the key is revoked. Revocation signatures + are only accepted if they are issued by the key itself, or by a key + that is authorized to issue revocations via a revocation key + subpacket in a self-signature by the top level key. + + Transferable public key packet sequences may be concatenated to allow + transferring multiple public keys in one operation. + + + + + +Callas, et. al. Standards Track [Page 51] + +RFC 2440 OpenPGP Message Format November 1998 + + +10.2. OpenPGP Messages + + An OpenPGP message is a packet or sequence of packets that + corresponds to the following grammatical rules (comma represents + sequential composition, and vertical bar separates alternatives): + + OpenPGP Message :- Encrypted Message | Signed Message | + Compressed Message | Literal Message. + + Compressed Message :- Compressed Data Packet. + + Literal Message :- Literal Data Packet. + + ESK :- Public Key Encrypted Session Key Packet | + Symmetric-Key Encrypted Session Key Packet. + + ESK Sequence :- ESK | ESK Sequence, ESK. + + Encrypted Message :- Symmetrically Encrypted Data Packet | + ESK Sequence, Symmetrically Encrypted Data Packet. + + One-Pass Signed Message :- One-Pass Signature Packet, + OpenPGP Message, Corresponding Signature Packet. + + Signed Message :- Signature Packet, OpenPGP Message | + One-Pass Signed Message. + + In addition, decrypting a Symmetrically Encrypted Data packet and + + decompressing a Compressed Data packet must yield a valid OpenPGP + Message. + +10.3. Detached Signatures + + Some OpenPGP applications use so-called "detached signatures." For + example, a program bundle may contain a file, and with it a second + file that is a detached signature of the first file. These detached + signatures are simply a signature packet stored separately from the + data that they are a signature of. + +11. Enhanced Key Formats + +11.1. Key Structures + + The format of an OpenPGP V3 key is as follows. Entries in square + brackets are optional and ellipses indicate repetition. + + + + + +Callas, et. al. Standards Track [Page 52] + +RFC 2440 OpenPGP Message Format November 1998 + + + RSA Public Key + [Revocation Self Signature] + User ID [Signature ...] + [User ID [Signature ...] ...] + + Each signature certifies the RSA public key and the preceding user + ID. The RSA public key can have many user IDs and each user ID can + have many signatures. + + The format of an OpenPGP V4 key that uses two public keys is similar + except that the other keys are added to the end as 'subkeys' of the + primary key. + + Primary-Key + [Revocation Self Signature] + [Direct Key Self Signature...] + User ID [Signature ...] + [User ID [Signature ...] ...] + [[Subkey [Binding-Signature-Revocation] + Primary-Key-Binding-Signature] ...] + + A subkey always has a single signature after it that is issued using + the primary key to tie the two keys together. This binding signature + may be in either V3 or V4 format, but V4 is preferred, of course. + + In the above diagram, if the binding signature of a subkey has been + revoked, the revoked binding signature may be removed, leaving only + one signature. + + In a key that has a main key and subkeys, the primary key MUST be a + key capable of signing. The subkeys may be keys of any other type. + There may be other constructions of V4 keys, too. For example, there + may be a single-key RSA key in V4 format, a DSA primary key with an + RSA encryption key, or RSA primary key with an Elgamal subkey, etc. + + It is also possible to have a signature-only subkey. This permits a + primary key that collects certifications (key signatures) but is used + only used for certifying subkeys that are used for encryption and + signatures. + +11.2. Key IDs and Fingerprints + + For a V3 key, the eight-octet key ID consists of the low 64 bits of + the public modulus of the RSA key. + + The fingerprint of a V3 key is formed by hashing the body (but not + the two-octet length) of the MPIs that form the key material (public + modulus n, followed by exponent e) with MD5. + + + +Callas, et. al. Standards Track [Page 53] + +RFC 2440 OpenPGP Message Format November 1998 + + + A V4 fingerprint is the 160-bit SHA-1 hash of the one-octet Packet + Tag, followed by the two-octet packet length, followed by the entire + Public Key packet starting with the version field. The key ID is the + low order 64 bits of the fingerprint. Here are the fields of the + hash material, with the example of a DSA key: + + a.1) 0x99 (1 octet) + + a.2) high order length octet of (b)-(f) (1 octet) + + a.3) low order length octet of (b)-(f) (1 octet) + + b) version number = 4 (1 octet); + + c) time stamp of key creation (4 octets); + + d) algorithm (1 octet): 17 = DSA (example); + + e) Algorithm specific fields. + + Algorithm Specific Fields for DSA keys (example): + + e.1) MPI of DSA prime p; + + e.2) MPI of DSA group order q (q is a prime divisor of p-1); + + e.3) MPI of DSA group generator g; + + e.4) MPI of DSA public key value y (= g**x where x is secret). + + Note that it is possible for there to be collisions of key IDs -- two + different keys with the same key ID. Note that there is a much + smaller, but still non-zero probability that two different keys have + the same fingerprint. + + Also note that if V3 and V4 format keys share the same RSA key + material, they will have different key ids as well as different + fingerprints. + +12. Notes on Algorithms + +12.1. Symmetric Algorithm Preferences + + The symmetric algorithm preference is an ordered list of algorithms + that the keyholder accepts. Since it is found on a self-signature, it + is possible that a keyholder may have different preferences. For + example, Alice may have TripleDES only specified for "alice@work.com" + but CAST5, Blowfish, and TripleDES specified for "alice@home.org". + + + +Callas, et. al. Standards Track [Page 54] + +RFC 2440 OpenPGP Message Format November 1998 + + + Note that it is also possible for preferences to be in a subkey's + binding signature. + + Since TripleDES is the MUST-implement algorithm, if it is not + explicitly in the list, it is tacitly at the end. However, it is good + form to place it there explicitly. Note also that if an + implementation does not implement the preference, then it is + implicitly a TripleDES-only implementation. + + An implementation MUST not use a symmetric algorithm that is not in + the recipient's preference list. When encrypting to more than one + recipient, the implementation finds a suitable algorithm by taking + the intersection of the preferences of the recipients. Note that the + MUST-implement algorithm, TripleDES, ensures that the intersection is + not null. The implementation may use any mechanism to pick an + algorithm in the intersection. + + If an implementation can decrypt a message that a keyholder doesn't + have in their preferences, the implementation SHOULD decrypt the + message anyway, but MUST warn the keyholder than protocol has been + violated. (For example, suppose that Alice, above, has software that + implements all algorithms in this specification. Nonetheless, she + prefers subsets for work or home. If she is sent a message encrypted + with IDEA, which is not in her preferences, the software warns her + that someone sent her an IDEA-encrypted message, but it would ideally + decrypt it anyway.) + + An implementation that is striving for backward compatibility MAY + consider a V3 key with a V3 self-signature to be an implicit + preference for IDEA, and no ability to do TripleDES. This is + technically non-compliant, but an implementation MAY violate the + above rule in this case only and use IDEA to encrypt the message, + provided that the message creator is warned. Ideally, though, the + implementation would follow the rule by actually generating two + messages, because it is possible that the OpenPGP user's + implementation does not have IDEA, and thus could not read the + message. Consequently, an implementation MAY, but SHOULD NOT use IDEA + in an algorithm conflict with a V3 key. + +12.2. Other Algorithm Preferences + + Other algorithm preferences work similarly to the symmetric algorithm + preference, in that they specify which algorithms the keyholder + accepts. There are two interesting cases that other comments need to + be made about, though, the compression preferences and the hash + preferences. + + + + + +Callas, et. al. Standards Track [Page 55] + +RFC 2440 OpenPGP Message Format November 1998 + + +12.2.1. Compression Preferences + + Compression has been an integral part of PGP since its first days. + OpenPGP and all previous versions of PGP have offered compression. + And in this specification, the default is for messages to be + compressed, although an implementation is not required to do so. + Consequently, the compression preference gives a way for a keyholder + to request that messages not be compressed, presumably because they + are using a minimal implementation that does not include compression. + Additionally, this gives a keyholder a way to state that it can + support alternate algorithms. + + Like the algorithm preferences, an implementation MUST NOT use an + algorithm that is not in the preference vector. If the preferences + are not present, then they are assumed to be [ZIP(1), + UNCOMPRESSED(0)]. + +12.2.2. Hash Algorithm Preferences + + Typically, the choice of a hash algorithm is something the signer + does, rather than the verifier, because a signer does not typically + know who is going to be verifying the signature. This preference, + though, allows a protocol based upon digital signatures ease in + negotiation. + + Thus, if Alice is authenticating herself to Bob with a signature, it + makes sense for her to use a hash algorithm that Bob's software uses. + This preference allows Bob to state in his key which algorithms Alice + may use. + +12.3. Plaintext + + Algorithm 0, "plaintext", may only be used to denote secret keys that + are stored in the clear. Implementations must not use plaintext in + Symmetrically Encrypted Data Packets; they must use Literal Data + Packets to encode unencrypted or literal data. + +12.4. RSA + + There are algorithm types for RSA-signature-only, and RSA-encrypt- + only keys. These types are deprecated. The "key flags" subpacket in a + signature is a much better way to express the same idea, and + generalizes it to all algorithms. An implementation SHOULD NOT create + such a key, but MAY interpret it. + + An implementation SHOULD NOT implement RSA keys of size less than 768 + bits. + + + + +Callas, et. al. Standards Track [Page 56] + +RFC 2440 OpenPGP Message Format November 1998 + + + It is permissible for an implementation to support RSA merely for + backward compatibility; for example, such an implementation would + support V3 keys with IDEA symmetric cryptography. Note that this is + an exception to the other MUST-implement rules. An implementation + that supports RSA in V4 keys MUST implement the MUST-implement + features. + +12.5. Elgamal + + If an Elgamal key is to be used for both signing and encryption, + extra care must be taken in creating the key. + + An ElGamal key consists of a generator g, a prime modulus p, a secret + exponent x, and a public value y = g^x mod p. + + The generator and prime must be chosen so that solving the discrete + log problem is intractable. The group g should generate the + multiplicative group mod p-1 or a large subgroup of it, and the order + of g should have at least one large prime factor. A good choice is + to use a "strong" Sophie-Germain prime in choosing p, so that both p + and (p-1)/2 are primes. In fact, this choice is so good that + implementors SHOULD do it, as it avoids a small subgroup attack. + + In addition, a result of Bleichenbacher [BLEICHENBACHER] shows that + if the generator g has only small prime factors, and if g divides the + order of the group it generates, then signatures can be forged. In + particular, choosing g=2 is a bad choice if the group order may be + even. On the other hand, a generator of 2 is a fine choice for an + encryption-only key, as this will make the encryption faster. + + While verifying Elgamal signatures, note that it is important to test + that r and s are less than p. If this test is not done then + signatures can be trivially forged by using large r values of + approximately twice the length of p. This attack is also discussed + in the Bleichenbacher paper. + + Details on safe use of Elgamal signatures may be found in [MENEZES], + which discusses all the weaknesses described above. + + If an implementation allows Elgamal signatures, then it MUST use the + algorithm identifier 20 for an Elgamal public key that can sign. + + An implementation SHOULD NOT implement Elgamal keys of size less than + 768 bits. For long-term security, Elgamal keys should be 1024 bits or + longer. + + + + + + +Callas, et. al. Standards Track [Page 57] + +RFC 2440 OpenPGP Message Format November 1998 + + +12.6. DSA + + An implementation SHOULD NOT implement DSA keys of size less than 768 + bits. Note that present DSA is limited to a maximum of 1024 bit keys, + which are recommended for long-term use. + +12.7. Reserved Algorithm Numbers + + A number of algorithm IDs have been reserved for algorithms that + would be useful to use in an OpenPGP implementation, yet there are + issues that prevent an implementor from actually implementing the + algorithm. These are marked in the Public Algorithms section as + "(reserved for)". + + The reserved public key algorithms, Elliptic Curve (18), ECDSA (19), + and X9.42 (21) do not have the necessary parameters, parameter order, + or semantics defined. + + The reserved symmetric key algorithm, DES/SK (6), does not have + semantics defined. + + The reserved hash algorithms, TIGER192 (6), and HAVAL-5-160 (7), do + not have OIDs. The reserved algorithm number 4, reserved for a + double-width variant of SHA1, is not presently defined. + + We have reserver three algorithm IDs for the US NIST's Advanced + Encryption Standard. This algorithm will work with (at least) 128, + 192, and 256-bit keys. We expect that this algorithm will be selected + from the candidate algorithms in the year 2000. + +12.8. OpenPGP CFB mode + + OpenPGP does symmetric encryption using a variant of Cipher Feedback + Mode (CFB mode). This section describes the procedure it uses in + detail. This mode is what is used for Symmetrically Encrypted Data + Packets; the mechanism used for encrypting secret key material is + similar, but described in those sections above. + + OpenPGP CFB mode uses an initialization vector (IV) of all zeros, and + prefixes the plaintext with ten octets of random data, such that + octets 9 and 10 match octets 7 and 8. It does a CFB "resync" after + encrypting those ten octets. + + Note that for an algorithm that has a larger block size than 64 bits, + the equivalent function will be done with that entire block. For + example, a 16-octet block algorithm would operate on 16 octets, and + then produce two octets of check, and then work on 16-octet blocks. + + + + +Callas, et. al. Standards Track [Page 58] + +RFC 2440 OpenPGP Message Format November 1998 + + + Step by step, here is the procedure: + + 1. The feedback register (FR) is set to the IV, which is all zeros. + + 2. FR is encrypted to produce FRE (FR Encrypted). This is the + encryption of an all-zero value. + + 3. FRE is xored with the first 8 octets of random data prefixed to + the plaintext to produce C1-C8, the first 8 octets of ciphertext. + + 4. FR is loaded with C1-C8. + + 5. FR is encrypted to produce FRE, the encryption of the first 8 + octets of ciphertext. + + 6. The left two octets of FRE get xored with the next two octets of + data that were prefixed to the plaintext. This produces C9-C10, + the next two octets of ciphertext. + + 7. (The resync step) FR is loaded with C3-C10. + + 8. FR is encrypted to produce FRE. + + 9. FRE is xored with the first 8 octets of the given plaintext, now + that we have finished encrypting the 10 octets of prefixed data. + This produces C11-C18, the next 8 octets of ciphertext. + + 10. FR is loaded with C11-C18 + + 11. FR is encrypted to produce FRE. + + 12. FRE is xored with the next 8 octets of plaintext, to produce the + next 8 octets of ciphertext. These are loaded into FR and the + process is repeated until the plaintext is used up. + +13. Security Considerations + + As with any technology involving cryptography, you should check the + current literature to determine if any algorithms used here have been + found to be vulnerable to attack. + + This specification uses Public Key Cryptography technologies. + Possession of the private key portion of a public-private key pair is + assumed to be controlled by the proper party or parties. + + Certain operations in this specification involve the use of random + numbers. An appropriate entropy source should be used to generate + these numbers. See RFC 1750. + + + +Callas, et. al. Standards Track [Page 59] + +RFC 2440 OpenPGP Message Format November 1998 + + + The MD5 hash algorithm has been found to have weaknesses (pseudo- + collisions in the compress function) that make some people deprecate + its use. They consider the SHA-1 algorithm better. + + Many security protocol designers think that it is a bad idea to use a + single key for both privacy (encryption) and integrity (signatures). + In fact, this was one of the motivating forces behind the V4 key + format with separate signature and encryption keys. If you as an + implementor promote dual-use keys, you should at least be aware of + this controversy. + + The DSA algorithm will work with any 160-bit hash, but it is + sensitive to the quality of the hash algorithm, if the hash algorithm + is broken, it can leak the secret key. The Digital Signature Standard + (DSS) specifies that DSA be used with SHA-1. RIPEMD-160 is + considered by many cryptographers to be as strong. An implementation + should take care which hash algorithms are used with DSA, as a weak + hash can not only allow a signature to be forged, but could leak the + secret key. These same considerations about the quality of the hash + algorithm apply to Elgamal signatures. + + If you are building an authentication system, the recipient may + specify a preferred signing algorithm. However, the signer would be + foolish to use a weak algorithm simply because the recipient requests + it. + + Some of the encryption algorithms mentioned in this document have + been analyzed less than others. For example, although CAST5 is + presently considered strong, it has been analyzed less than Triple- + DES. Other algorithms may have other controversies surrounding them. + + Some technologies mentioned here may be subject to government control + in some countries. + +14. Implementation Nits + + This section is a collection of comments to help an implementer, + particularly with an eye to backward compatibility. Previous + implementations of PGP are not OpenPGP-compliant. Often the + differences are small, but small differences are frequently more + vexing than large differences. Thus, this list of potential problems + and gotchas for a developer who is trying to be backward-compatible. + + * PGP 5.x does not accept V4 signatures for anything other than + key material. + + * PGP 5.x does not recognize the "five-octet" lengths in new-format + headers or in signature subpacket lengths. + + + +Callas, et. al. Standards Track [Page 60] + +RFC 2440 OpenPGP Message Format November 1998 + + + * PGP 5.0 rejects an encrypted session key if the keylength differs + from the S2K symmetric algorithm. This is a bug in its validation + function. + + * PGP 5.0 does not handle multiple one-pass signature headers and + trailers. Signing one will compress the one-pass signed literal + and prefix a V3 signature instead of doing a nested one-pass + signature. + + * When exporting a private key, PGP 2.x generates the header "BEGIN + PGP SECRET KEY BLOCK" instead of "BEGIN PGP PRIVATE KEY BLOCK". + All previous versions ignore the implied data type, and look + directly at the packet data type. + + * In a clear-signed signature, PGP 5.0 will figure out the correct + hash algorithm if there is no "Hash:" header, but it will reject + a mismatch between the header and the actual algorithm used. The + "standard" (i.e. Zimmermann/Finney/et al.) version of PGP 2.x + rejects the "Hash:" header and assumes MD5. There are a number of + enhanced variants of PGP 2.6.x that have been modified for SHA-1 + signatures. + + * PGP 5.0 can read an RSA key in V4 format, but can only recognize + it with a V3 keyid, and can properly use only a V3 format RSA + key. + + * Neither PGP 5.x nor PGP 6.0 recognize Elgamal Encrypt and Sign + keys. They only handle Elgamal Encrypt-only keys. + + * There are many ways possible for two keys to have the same key + material, but different fingerprints (and thus key ids). Perhaps + the most interesting is an RSA key that has been "upgraded" to V4 + format, but since a V4 fingerprint is constructed by hashing the + key creation time along with other things, two V4 keys created at + different times, yet with the same key material will have + different fingerprints. + + * If an implementation is using zlib to interoperate with PGP 2.x, + then the "windowBits" parameter should be set to -13. + + + + + + + + + + + + +Callas, et. al. Standards Track [Page 61] + +RFC 2440 OpenPGP Message Format November 1998 + + +15. Authors and Working Group Chair + + The working group can be contacted via the current chair: + + John W. Noerenberg, II + Qualcomm, Inc + 6455 Lusk Blvd + San Diego, CA 92131 USA + + Phone: +1 619-658-3510 + EMail: jwn2@qualcomm.com + + + The principal authors of this memo are: + + Jon Callas + Network Associates, Inc. + 3965 Freedom Circle + Santa Clara, CA 95054, USA + + Phone: +1 408-346-5860 + EMail: jon@pgp.com, jcallas@nai.com + + + Lutz Donnerhacke + IKS GmbH + Wildenbruchstr. 15 + 07745 Jena, Germany + + Phone: +49-3641-675642 + EMail: lutz@iks-jena.de + + + Hal Finney + Network Associates, Inc. + 3965 Freedom Circle + Santa Clara, CA 95054, USA + + EMail: hal@pgp.com + + + Rodney Thayer + EIS Corporation + Clearwater, FL 33767, USA + + EMail: rodney@unitran.com + + + + + +Callas, et. al. Standards Track [Page 62] + +RFC 2440 OpenPGP Message Format November 1998 + + + This memo also draws on much previous work from a number of other + authors who include: Derek Atkins, Charles Breed, Dave Del Torto, + Marc Dyksterhouse, Gail Haspert, Gene Hoffman, Paul Hoffman, Raph + Levien, Colin Plumb, Will Price, William Stallings, Mark Weaver, and + Philip R. Zimmermann. + +16. References + + [BLEICHENBACHER] Bleichenbacher, Daniel, "Generating ElGamal + signatures without knowing the secret key," + Eurocrypt 96. Note that the version in the + proceedings has an error. A revised version is + available at the time of writing from + + + [BLOWFISH] Schneier, B. "Description of a New Variable-Length + Key, 64-Bit Block Cipher (Blowfish)" Fast Software + Encryption, Cambridge Security Workshop Proceedings + (December 1993), Springer-Verlag, 1994, pp191-204 + + + + [DONNERHACKE] Donnerhacke, L., et. al, "PGP263in - an improved + international version of PGP", ftp://ftp.iks- + jena.de/mitarb/lutz/crypt/software/pgp/ + + [ELGAMAL] T. ElGamal, "A Public-Key Cryptosystem and a + Signature Scheme Based on Discrete Logarithms," IEEE + Transactions on Information Theory, v. IT-31, n. 4, + 1985, pp. 469-472. + + [IDEA] Lai, X, "On the design and security of block + ciphers", ETH Series in Information Processing, J.L. + Massey (editor), Vol. 1, Hartung-Gorre Verlag + Knostanz, Technische Hochschule (Zurich), 1992 + + [ISO-10646] ISO/IEC 10646-1:1993. International Standard -- + Information technology -- Universal Multiple-Octet + Coded Character Set (UCS) -- Part 1: Architecture + and Basic Multilingual Plane. UTF-8 is described in + Annex R, adopted but not yet published. UTF-16 is + described in Annex Q, adopted but not yet published. + + [MENEZES] Alfred Menezes, Paul van Oorschot, and Scott + Vanstone, "Handbook of Applied Cryptography," CRC + Press, 1996. + + + + +Callas, et. al. Standards Track [Page 63] + +RFC 2440 OpenPGP Message Format November 1998 + + + [RFC822] Crocker, D., "Standard for the format of ARPA + Internet text messages", STD 11, RFC 822, August + 1982. + + [RFC1423] Balenson, D., "Privacy Enhancement for Internet + Electronic Mail: Part III: Algorithms, Modes, and + Identifiers", RFC 1423, October 1993. + + [RFC1641] Goldsmith, D. and M. Davis, "Using Unicode with + MIME", RFC 1641, July 1994. + + [RFC1750] Eastlake, D., Crocker, S. and J. Schiller, + "Randomness Recommendations for Security", RFC 1750, + December 1994. + + [RFC1951] Deutsch, P., "DEFLATE Compressed Data Format + Specification version 1.3.", RFC 1951, May 1996. + + [RFC1983] Malkin, G., "Internet Users' Glossary", FYI 18, RFC + 1983, August 1996. + + [RFC1991] Atkins, D., Stallings, W. and P. Zimmermann, "PGP + Message Exchange Formats", RFC 1991, August 1996. + + [RFC2015] Elkins, M., "MIME Security with Pretty Good Privacy + (PGP)", RFC 2015, October 1996. + + [RFC2231] Borenstein, N. and N. Freed, "Multipurpose Internet + Mail Extensions (MIME) Part One: Format of Internet + Message Bodies.", RFC 2231, November 1996. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Level", BCP 14, RFC 2119, March 1997. + + [RFC2144] Adams, C., "The CAST-128 Encryption Algorithm", RFC + 2144, May 1997. + + [RFC2279] Yergeau., F., "UTF-8, a transformation format of + Unicode and ISO 10646", RFC 2279, January 1998. + + [RFC2313] Kaliski, B., "PKCS #1: RSA Encryption Standard + version 1.5", RFC 2313, March 1998. + + [SAFER] Massey, J.L. "SAFER K-64: One Year Later", B. + Preneel, editor, Fast Software Encryption, Second + International Workshop (LNCS 1008) pp212-241, + Springer-Verlag 1995 + + + + +Callas, et. al. Standards Track [Page 64] + +RFC 2440 OpenPGP Message Format November 1998 + + +17. Full Copyright Statement + + Copyright (C) The Internet Society (1998). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Callas, et. al. Standards Track [Page 65] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2487.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2487.txt new file mode 100644 index 00000000..fb1305f0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2487.txt @@ -0,0 +1,451 @@ + + + + + + +Network Working Group P. Hoffman +Request for Comments: 2487 Internet Mail Consortium +Category: Standards Track January 1999 + + + SMTP Service Extension for Secure SMTP over TLS + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1999). All Rights Reserved. + +1. Abstract + + This document describes an extension to the SMTP service that allows + an SMTP server and client to use transport-layer security to provide + private, authenticated communication over the Internet. This gives + SMTP agents the ability to protect some or all of their + communications from eavesdroppers and attackers. + +2. Introduction + + SMTP [RFC-821] servers and clients normally communicate in the clear + over the Internet. In many cases, this communication goes through one + or more router that is not controlled or trusted by either entity. + Such an untrusted router might allow a third party to monitor or + alter the communications between the server and client. + + Further, there is often a desire for two SMTP agents to be able to + authenticate each others' identities. For example, a secure SMTP + server might only allow communications from other SMTP agents it + knows, or it might act differently for messages received from an + agent it knows than from one it doesn't know. + + TLS [TLS], more commonly known as SSL, is a popular mechanism for + enhancing TCP communications with privacy and authentication. TLS is + in wide use with the HTTP protocol, and is also being used for adding + security to many other common protocols that run over TCP. + + + + + + +Hoffman Standards Track [Page 1] + +RFC 2487 SMTP Service Extension January 1999 + + +2.1 Terminology + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [RFC-2119]. + +3. STARTTLS Extension + + The STARTTLS extension to SMTP is laid out as follows: + + (1) the name of the SMTP service defined here is STARTTLS; + + (2) the EHLO keyword value associated with the extension is STARTTLS; + + (3) the STARTTLS keyword has no parameters; + + (4) a new SMTP verb, "STARTTLS", is defined; + + (5) no additional parameters are added to any SMTP command. + +4. The STARTTLS Keyword + + The STARTTLS keyword is used to tell the SMTP client that the SMTP + server allows use of TLS. It takes no parameters. + +5. The STARTTLS Command + + The format for the STARTTLS command is: + + STARTTLS + + with no parameters. + + After the client gives the STARTTLS command, the server responds with + one of the following reply codes: + + 220 Ready to start TLS + 501 Syntax error (no parameters allowed) + 454 TLS not available due to temporary reason + + A publicly-referenced SMTP server MUST NOT require use of the + STARTTLS extension in order to deliver mail locally. This rule + prevents the STARTTLS extension from damaging the interoperability of + the Internet's SMTP infrastructure. A publicly-referenced SMTP server + is an SMTP server which runs on port 25 of an Internet host listed in + the MX record (or A record if an MX record is not present) for the + domain name on the right hand side of an Internet mail address. + + + + +Hoffman Standards Track [Page 2] + +RFC 2487 SMTP Service Extension January 1999 + + + Any SMTP server may refuse to accept messages for relay based on + authentication supplied during the TLS negotiation. An SMTP server + that is not publicly referenced may refuse to accept any messages for + relay or local delivery based on authentication supplied during the + TLS negotiation. + + A SMTP server that is not publicly referenced may choose to require + that the client perform a TLS negotiation before accepting any + commands. In this case, the server SHOULD return the reply code: + + 530 Must issue a STARTTLS command first + + to every command other than NOOP, EHLO, STARTTLS, or QUIT. If the + client and server are using the ENHANCEDSTATUSCODES ESMTP extension + [RFC-2034], the status code to be returned SHOULD be 5.7.0. + + After receiving a 220 response to a STARTTLS command, the client + SHOULD start the TLS negotiation before giving any other SMTP + commands. + + If the SMTP client is using pipelining as defined in RFC 1854, the + STARTTLS command must be the last command in a group. + +5.1 Processing After the STARTTLS Command + + After the TLS handshake has been completed, both parties MUST + immediately decide whether or not to continue based on the + authentication and privacy achieved. The SMTP client and server may + decide to move ahead even if the TLS negotiation ended with no + authentication and/or no privacy because most SMTP services are + performed with no authentication and no privacy, but some SMTP + clients or servers may want to continue only if a particular level of + authentication and/or privacy was achieved. + + If the SMTP client decides that the level of authentication or + privacy is not high enough for it to continue, it SHOULD issue an + SMTP QUIT command immediately after the TLS negotiation is complete. + If the SMTP server decides that the level of authentication or + privacy is not high enough for it to continue, it SHOULD reply to + every SMTP command from the client (other than a QUIT command) with + the 554 reply code (with a possible text string such as "Command + refused due to lack of security"). + + The decision of whether or not to believe the authenticity of the + other party in a TLS negotiation is a local matter. However, some + general rules for the decisions are: + + + + + +Hoffman Standards Track [Page 3] + +RFC 2487 SMTP Service Extension January 1999 + + + - A SMTP client would probably only want to authenticate an SMTP + server whose server certificate has a domain name that is the + domain name that the client thought it was connecting to. + - A publicly-referenced SMTP server would probably want to accept + any certificate from an SMTP client, and would possibly want to + put distinguishing information about the certificate in the + Received header of messages that were relayed or submitted from + the client. + +5.2 Result of the STARTTLS Command + + Upon completion of the TLS handshake, the SMTP protocol is reset to + the initial state (the state in SMTP after a server issues a 220 + service ready greeting). The server MUST discard any knowledge + obtained from the client, such as the argument to the EHLO command, + which was not obtained from the TLS negotiation itself. The client + MUST discard any knowledge obtained from the server, such as the list + of SMTP service extensions, which was not obtained from the TLS + negotiation itself. The client SHOULD send an EHLO command as the + first command after a successful TLS negotiation. + + The list of SMTP service extensions returned in response to an EHLO + command received after the TLS handshake MAY be different than the + list returned before the TLS handshake. For example, an SMTP server + might not want to advertise support for a particular SASL mechanism + [SASL] unless a client has sent an appropriate client certificate + during a TLS handshake. + + Both the client and the server MUST know if there is a TLS session + active. A client MUST NOT attempt to start a TLS session if a TLS + session is already active. A server MUST NOT return the TLS extension + in response to an EHLO command received after a TLS handshake has + completed. + +6. Usage Example + + The following dialog illustrates how a client and server can start a + TLS session: + + S: + C: + S: 220 mail.imc.org SMTP service ready + C: EHLO mail.ietf.org + S: 250-mail.imc.org offers a warm hug of welcome + S: 250 STARTTLS + C: STARTTLS + S: 220 Go ahead + C: + + + +Hoffman Standards Track [Page 4] + +RFC 2487 SMTP Service Extension January 1999 + + + C & S: + C & S: + C: + . . . + +7. Security Considerations + + It should be noted that SMTP is not an end-to-end mechanism. Thus, if + an SMTP client/server pair decide to add TLS privacy, they are not + securing the transport from the originating mail user agent to the + recipient. Further, because delivery of a single piece of mail may + go between more than two SMTP servers, adding TLS privacy to one pair + of servers does not mean that the entire SMTP chain has been made + private. Further, just because an SMTP server can authenticate an + SMTP client, it does not mean that the mail from the SMTP client was + authenticated by the SMTP client when the client received it. + + Both the STMP client and server must check the result of the TLS + negotiation to see whether acceptable authentication or privacy was + achieved. Ignoring this step completely invalidates using TLS for + security. The decision about whether acceptable authentication or + privacy was achieved is made locally, is implementation-dependant, + and is beyond the scope of this document. + + The SMTP client and server should note carefully the result of the + TLS negotiation. If the negotiation results in no privacy, or if it + results in privacy using algorithms or key lengths that are deemed + not strong enough, or if the authentication is not good enough for + either party, the client may choose to end the SMTP session with an + immediate QUIT command, or the server may choose to not accept any + more SMTP commands. + + A server announcing in an EHLO response that it uses a particular TLS + protocol should not pose any security issues, since any use of TLS + will be at least as secure as no use of TLS. + + A man-in-the-middle attack can be launched by deleting the "250 + STARTTLS" response from the server. This would cause the client not + to try to start a TLS session. An SMTP client can protect against + this attack by recording the fact that a particular SMTP server + offers TLS during one session and generating an alarm if it does not + appear in the EHLO response for a later session. The lack of TLS + during a session SHOULD NOT result in the bouncing of email, although + it could result in delayed processing. + + + + + + + +Hoffman Standards Track [Page 5] + +RFC 2487 SMTP Service Extension January 1999 + + + Before the TLS handshake has begun, any protocol interactions are + performed in the clear and may be modified by an active attacker. For + this reason, clients and servers MUST discard any knowledge obtained + prior to the start of the TLS handshake upon completion of the TLS + handshake. + + The STARTTLS extension is not suitable for authenticating the author + of an email message unless every hop in the delivery chain, including + the submission to the first SMTP server, is authenticated. Another + proposal [SMTP-AUTH] can be used to authenticate delivery and MIME + security multiparts [MIME-SEC] can be used to authenticate the author + of an email message. In addition, the [SMTP-AUTH] proposal offers + simpler and more flexible options to authenticate an SMTP client and + the SASL EXTERNAL mechanism [SASL] MAY be used in conjunction with + the STARTTLS command to provide an authorization identity. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Hoffman Standards Track [Page 6] + +RFC 2487 SMTP Service Extension January 1999 + + +A. References + + [RFC-821] Postel, J., "Simple Mail Transfer Protocol", RFC 821, + August 1982. + + [RFC-1869] Klensin, J., Freed, N, Rose, M, Stefferud, E. and D. + Crocker, "SMTP Service Extensions", STD 10, RFC 1869, + November 1995. + + [RFC-2034] Freed, N., "SMTP Service Extension for Returning Enhanced + Error Codes", RFC 2034, October 1996. + + [RFC-2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [SASL] Myers, J., "Simple Authentication and Security Layer + (SASL)", RFC 2222, October 1997. + + [SMTP-AUTH] "SMTP Service Extension for Authentication", Work in + Progress. + + [TLS] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", + RFC 2246, January 1999. + +B. Author's Address + + Paul Hoffman + Internet Mail Consortium + 127 Segre Place + Santa Cruz, CA 95060 + + Phone: (831) 426-9827 + EMail: phoffman@imc.org + + + + + + + + + + + + + + + + + + +Hoffman Standards Track [Page 7] + +RFC 2487 SMTP Service Extension January 1999 + + +C. Full Copyright Statement + + Copyright (C) The Internet Society (1999). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Hoffman Standards Track [Page 8] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2554.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2554.txt new file mode 100644 index 00000000..2922deae --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2554.txt @@ -0,0 +1,619 @@ + + + + + + +Network Working Group J. Myers +Request for Comments: 2554 Netscape Communications +Category: Standards Track March 1999 + + + SMTP Service Extension + for Authentication + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (1999). All Rights Reserved. + + +1. Introduction + + This document defines an SMTP service extension [ESMTP] whereby an + SMTP client may indicate an authentication mechanism to the server, + perform an authentication protocol exchange, and optionally negotiate + a security layer for subsequent protocol interactions. This + extension is a profile of the Simple Authentication and Security + Layer [SASL]. + + +2. Conventions Used in this Document + + In examples, "C:" and "S:" indicate lines sent by the client and + server respectively. + + The key words "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", and "MAY" + in this document are to be interpreted as defined in "Key words for + use in RFCs to Indicate Requirement Levels" [KEYWORDS]. + + +3. The Authentication service extension + + + (1) the name of the SMTP service extension is "Authentication" + + (2) the EHLO keyword value associated with this extension is "AUTH" + + + + +Myers Standards Track [Page 1] + +RFC 2554 SMTP Authentication March 1999 + + + (3) The AUTH EHLO keyword contains as a parameter a space separated + list of the names of supported SASL mechanisms. + + (4) a new SMTP verb "AUTH" is defined + + (5) an optional parameter using the keyword "AUTH" is added to the + MAIL FROM command, and extends the maximum line length of the + MAIL FROM command by 500 characters. + + (6) this extension is appropriate for the submission protocol + [SUBMIT]. + + +4. The AUTH command + + AUTH mechanism [initial-response] + + Arguments: + a string identifying a SASL authentication mechanism. + an optional base64-encoded response + + Restrictions: + After an AUTH command has successfully completed, no more AUTH + commands may be issued in the same session. After a successful + AUTH command completes, a server MUST reject any further AUTH + commands with a 503 reply. + + The AUTH command is not permitted during a mail transaction. + + Discussion: + The AUTH command indicates an authentication mechanism to the + server. If the server supports the requested authentication + mechanism, it performs an authentication protocol exchange to + authenticate and identify the user. Optionally, it also + negotiates a security layer for subsequent protocol + interactions. If the requested authentication mechanism is not + supported, the server rejects the AUTH command with a 504 + reply. + + The authentication protocol exchange consists of a series of + server challenges and client answers that are specific to the + authentication mechanism. A server challenge, otherwise known + as a ready response, is a 334 reply with the text part + containing a BASE64 encoded string. The client answer consists + of a line containing a BASE64 encoded string. If the client + wishes to cancel an authentication exchange, it issues a line + with a single "*". If the server receives such an answer, it + MUST reject the AUTH command by sending a 501 reply. + + + +Myers Standards Track [Page 2] + +RFC 2554 SMTP Authentication March 1999 + + + The optional initial-response argument to the AUTH command is + used to save a round trip when using authentication mechanisms + that are defined to send no data in the initial challenge. + When the initial-response argument is used with such a + mechanism, the initial empty challenge is not sent to the + client and the server uses the data in the initial-response + argument as if it were sent in response to the empty challenge. + Unlike a zero-length client answer to a 334 reply, a zero- + length initial response is sent as a single equals sign ("="). + If the client uses an initial-response argument to the AUTH + command with a mechanism that sends data in the initial + challenge, the server rejects the AUTH command with a 535 + reply. + + If the server cannot BASE64 decode the argument, it rejects the + AUTH command with a 501 reply. If the server rejects the + authentication data, it SHOULD reject the AUTH command with a + 535 reply unless a more specific error code, such as one listed + in section 6, is appropriate. Should the client successfully + complete the authentication exchange, the SMTP server issues a + 235 reply. + + The service name specified by this protocol's profile of SASL + is "smtp". + + If a security layer is negotiated through the SASL + authentication exchange, it takes effect immediately following + the CRLF that concludes the authentication exchange for the + client, and the CRLF of the success reply for the server. Upon + a security layer's taking effect, the SMTP protocol is reset to + the initial state (the state in SMTP after a server issues a + 220 service ready greeting). The server MUST discard any + knowledge obtained from the client, such as the argument to the + EHLO command, which was not obtained from the SASL negotiation + itself. The client MUST discard any knowledge obtained from + the server, such as the list of SMTP service extensions, which + was not obtained from the SASL negotiation itself (with the + exception that a client MAY compare the list of advertised SASL + mechanisms before and after authentication in order to detect + an active down-negotiation attack). The client SHOULD send an + EHLO command as the first command after a successful SASL + negotiation which results in the enabling of a security layer. + + The server is not required to support any particular + authentication mechanism, nor are authentication mechanisms + required to support any security layers. If an AUTH command + fails, the client may try another authentication mechanism by + issuing another AUTH command. + + + +Myers Standards Track [Page 3] + +RFC 2554 SMTP Authentication March 1999 + + + If an AUTH command fails, the server MUST behave the same as if + the client had not issued the AUTH command. + + The BASE64 string may in general be arbitrarily long. Clients + and servers MUST be able to support challenges and responses + that are as long as are generated by the authentication + mechanisms they support, independent of any line length + limitations the client or server may have in other parts of its + protocol implementation. + + Examples: + S: 220 smtp.example.com ESMTP server ready + C: EHLO jgm.example.com + S: 250-smtp.example.com + S: 250 AUTH CRAM-MD5 DIGEST-MD5 + C: AUTH FOOBAR + S: 504 Unrecognized authentication type. + C: AUTH CRAM-MD5 + S: 334 + PENCeUxFREJoU0NnbmhNWitOMjNGNndAZWx3b29kLmlubm9zb2Z0LmNvbT4= + C: ZnJlZCA5ZTk1YWVlMDljNDBhZjJiODRhMGMyYjNiYmFlNzg2ZQ== + S: 235 Authentication successful. + + + +5. The AUTH parameter to the MAIL FROM command + + AUTH=addr-spec + + Arguments: + An addr-spec containing the identity which submitted the message + to the delivery system, or the two character sequence "<>" + indicating such an identity is unknown or insufficiently + authenticated. To comply with the restrictions imposed on ESMTP + parameters, the addr-spec is encoded inside an xtext. The syntax + of an xtext is described in section 5 of [ESMTP-DSN]. + + Discussion: + The optional AUTH parameter to the MAIL FROM command allows + cooperating agents in a trusted environment to communicate the + authentication of individual messages. + + If the server trusts the authenticated identity of the client to + assert that the message was originally submitted by the supplied + addr-spec, then the server SHOULD supply the same addr-spec in an + AUTH parameter when relaying the message to any server which + supports the AUTH extension. + + + + +Myers Standards Track [Page 4] + +RFC 2554 SMTP Authentication March 1999 + + + A MAIL FROM parameter of AUTH=<> indicates that the original + submitter of the message is not known. The server MUST NOT treat + the message as having been originally submitted by the client. + + If the AUTH parameter to the MAIL FROM is not supplied, the + client has authenticated, and the server believes the message is + an original submission by the client, the server MAY supply the + client's identity in the addr-spec in an AUTH parameter when + relaying the message to any server which supports the AUTH + extension. + + If the server does not sufficiently trust the authenticated + identity of the client, or if the client is not authenticated, + then the server MUST behave as if the AUTH=<> parameter was + supplied. The server MAY, however, write the value of the AUTH + parameter to a log file. + + If an AUTH=<> parameter was supplied, either explicitly or due to + the requirement in the previous paragraph, then the server MUST + supply the AUTH=<> parameter when relaying the message to any + server which it has authenticated to using the AUTH extension. + + A server MAY treat expansion of a mailing list as a new + submission, setting the AUTH parameter to the mailing list + address or mailing list administration address when relaying the + message to list subscribers. + + It is conforming for an implementation to be hard-coded to treat + all clients as being insufficiently trusted. In that case, the + implementation does nothing more than parse and discard + syntactically valid AUTH parameters to the MAIL FROM command and + supply AUTH=<> parameters to any servers to which it + authenticates using the AUTH extension. + + Examples: + C: MAIL FROM: AUTH=e+3Dmc2@example.com + S: 250 OK + + + + + + + + + + + + + + +Myers Standards Track [Page 5] + +RFC 2554 SMTP Authentication March 1999 + + +6. Error Codes + + The following error codes may be used to indicate various conditions + as described. + + 432 A password transition is needed + + This response to the AUTH command indicates that the user needs to + transition to the selected authentication mechanism. This typically + done by authenticating once using the PLAIN authentication mechanism. + + 534 Authentication mechanism is too weak + + This response to the AUTH command indicates that the selected + authentication mechanism is weaker than server policy permits for + that user. + + 538 Encryption required for requested authentication mechanism + + This response to the AUTH command indicates that the selected + authentication mechanism may only be used when the underlying SMTP + connection is encrypted. + + 454 Temporary authentication failure + + This response to the AUTH command indicates that the authentication + failed due to a temporary server failure. + + 530 Authentication required + + This response may be returned by any command other than AUTH, EHLO, + HELO, NOOP, RSET, or QUIT. It indicates that server policy requires + authentication in order to perform the requested action. + + + + + + + + + + + + + + + + + + +Myers Standards Track [Page 6] + +RFC 2554 SMTP Authentication March 1999 + + +7. Formal Syntax + + The following syntax specification uses the augmented Backus-Naur + Form (BNF) notation as specified in [ABNF]. + + Except as noted otherwise, all alphabetic characters are case- + insensitive. The use of upper or lower case characters to define + token strings is for editorial clarity only. Implementations MUST + accept these strings in a case-insensitive fashion. + + UPALPHA = %x41-5A ;; Uppercase: A-Z + + LOALPHA = %x61-7A ;; Lowercase: a-z + + ALPHA = UPALPHA / LOALPHA ;; case insensitive + + DIGIT = %x30-39 ;; Digits 0-9 + + HEXDIGIT = %x41-46 / DIGIT ;; hexidecimal digit (uppercase) + + hexchar = "+" HEXDIGIT HEXDIGIT + + xchar = %x21-2A / %x2C-3C / %x3E-7E + ;; US-ASCII except for "+", "=", SPACE and CTL + + xtext = *(xchar / hexchar) + + AUTH_CHAR = ALPHA / DIGIT / "-" / "_" + + auth_type = 1*20AUTH_CHAR + + auth_command = "AUTH" SPACE auth_type [SPACE (base64 / "=")] + *(CRLF [base64]) CRLF + + auth_param = "AUTH=" xtext + ;; The decoded form of the xtext MUST be either + ;; an addr-spec or the two characters "<>" + + base64 = base64_terminal / + ( 1*(4base64_CHAR) [base64_terminal] ) + + base64_char = UPALPHA / LOALPHA / DIGIT / "+" / "/" + ;; Case-sensitive + + base64_terminal = (2base64_char "==") / (3base64_char "=") + + continue_req = "334" SPACE [base64] CRLF + + + + +Myers Standards Track [Page 7] + +RFC 2554 SMTP Authentication March 1999 + + + CR = %x0C ;; ASCII CR, carriage return + + CRLF = CR LF + + CTL = %x00-1F / %x7F ;; any ASCII control character and DEL + + LF = %x0A ;; ASCII LF, line feed + + SPACE = %x20 ;; ASCII SP, space + + + + +8. References + + [ABNF] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", RFC 2234, November 1997. + + [CRAM-MD5] Klensin, J., Catoe, R. and P. Krumviede, "IMAP/POP + AUTHorize Extension for Simple Challenge/Response", RFC + 2195, September 1997. + + [ESMTP] Klensin, J., Freed, N., Rose, M., Stefferud, E. and D. + Crocker, "SMTP Service Extensions", RFC 1869, November + 1995. + + [ESMTP-DSN] Moore, K, "SMTP Service Extension for Delivery Status + Notifications", RFC 1891, January 1996. + + [KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [SASL] Myers, J., "Simple Authentication and Security Layer + (SASL)", RFC 2222, October 1997. + + [SUBMIT] Gellens, R. and J. Klensin, "Message Submission", RFC + 2476, December 1998. + + [RFC821] Postel, J., "Simple Mail Transfer Protocol", STD 10, RFC + 821, August 1982. + + [RFC822] Crocker, D., "Standard for the Format of ARPA Internet + Text Messages", STD 11, RFC 822, August 1982. + + + + + + + + +Myers Standards Track [Page 8] + +RFC 2554 SMTP Authentication March 1999 + + +9. Security Considerations + + Security issues are discussed throughout this memo. + + If a client uses this extension to get an encrypted tunnel through an + insecure network to a cooperating server, it needs to be configured + to never send mail to that server when the connection is not mutually + authenticated and encrypted. Otherwise, an attacker could steal the + client's mail by hijacking the SMTP connection and either pretending + the server does not support the Authentication extension or causing + all AUTH commands to fail. + + Before the SASL negotiation has begun, any protocol interactions are + performed in the clear and may be modified by an active attacker. + For this reason, clients and servers MUST discard any knowledge + obtained prior to the start of the SASL negotiation upon completion + of a SASL negotiation which results in a security layer. + + This mechanism does not protect the TCP port, so an active attacker + may redirect a relay connection attempt to the submission port + [SUBMIT]. The AUTH=<> parameter prevents such an attack from causing + an relayed message without an envelope authentication to pick up the + authentication of the relay client. + + A message submission client may require the user to authenticate + whenever a suitable SASL mechanism is advertised. Therefore, it may + not be desirable for a submission server [SUBMIT] to advertise a SASL + mechanism when use of that mechanism grants the client no benefits + over anonymous submission. + + This extension is not intended to replace or be used instead of end- + to-end message signature and encryption systems such as S/MIME or + PGP. This extension addresses a different problem than end-to-end + systems; it has the following key differences: + + (1) it is generally useful only within a trusted enclave + + (2) it protects the entire envelope of a message, not just the + message's body. + + (3) it authenticates the message submission, not authorship of the + message content + + (4) it can give the sender some assurance the message was + delivered to the next hop in the case where the sender + mutually authenticates with the next hop and negotiates an + appropriate security layer. + + + + +Myers Standards Track [Page 9] + +RFC 2554 SMTP Authentication March 1999 + + + Additional security considerations are mentioned in the SASL + specification [SASL]. + + + +10. Author's Address + + John Gardiner Myers + Netscape Communications + 501 East Middlefield Road + Mail Stop MV-029 + Mountain View, CA 94043 + + EMail: jgmyers@netscape.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Myers Standards Track [Page 10] + +RFC 2554 SMTP Authentication March 1999 + + +11. Full Copyright Statement + + Copyright (C) The Internet Society (1999). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + + + + + + + + + + + + + + + + + + + + + + + + +Myers Standards Track [Page 11] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2821.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2821.txt new file mode 100644 index 00000000..0eac9118 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2821.txt @@ -0,0 +1,4427 @@ + + + + + + +Network Working Group J. Klensin, Editor +Request for Comments: 2821 AT&T Laboratories +Obsoletes: 821, 974, 1869 April 2001 +Updates: 1123 +Category: Standards Track + + + Simple Mail Transfer Protocol + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2001). All Rights Reserved. + +Abstract + + This document is a self-contained specification of the basic protocol + for the Internet electronic mail transport. It consolidates, updates + and clarifies, but doesn't add new or change existing functionality + of the following: + + - the original SMTP (Simple Mail Transfer Protocol) specification of + RFC 821 [30], + + - domain name system requirements and implications for mail + transport from RFC 1035 [22] and RFC 974 [27], + + - the clarifications and applicability statements in RFC 1123 [2], + and + + - material drawn from the SMTP Extension mechanisms [19]. + + It obsoletes RFC 821, RFC 974, and updates RFC 1123 (replaces the + mail transport materials of RFC 1123). However, RFC 821 specifies + some features that were not in significant use in the Internet by the + mid-1990s and (in appendices) some additional transport models. + Those sections are omitted here in the interest of clarity and + brevity; readers needing them should refer to RFC 821. + + + + + + +Klensin Standards Track [Page 1] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + It also includes some additional material from RFC 1123 that required + amplification. This material has been identified in multiple ways, + mostly by tracking flaming on various lists and newsgroups and + problems of unusual readings or interpretations that have appeared as + the SMTP extensions have been deployed. Where this specification + moves beyond consolidation and actually differs from earlier + documents, it supersedes them technically as well as textually. + + Although SMTP was designed as a mail transport and delivery protocol, + this specification also contains information that is important to its + use as a 'mail submission' protocol, as recommended for POP [3, 26] + and IMAP [6]. Additional submission issues are discussed in RFC 2476 + [15]. + + Section 2.3 provides definitions of terms specific to this document. + Except when the historical terminology is necessary for clarity, this + document uses the current 'client' and 'server' terminology to + identify the sending and receiving SMTP processes, respectively. + + A companion document [32] discusses message headers, message bodies + and formats and structures for them, and their relationship. + +Table of Contents + + 1. Introduction .................................................. 4 + 2. The SMTP Model ................................................ 5 + 2.1 Basic Structure .............................................. 5 + 2.2 The Extension Model .......................................... 7 + 2.2.1 Background ................................................. 7 + 2.2.2 Definition and Registration of Extensions .................. 8 + 2.3 Terminology .................................................. 9 + 2.3.1 Mail Objects ............................................... 10 + 2.3.2 Senders and Receivers ...................................... 10 + 2.3.3 Mail Agents and Message Stores ............................. 10 + 2.3.4 Host ....................................................... 11 + 2.3.5 Domain ..................................................... 11 + 2.3.6 Buffer and State Table ..................................... 11 + 2.3.7 Lines ...................................................... 12 + 2.3.8 Originator, Delivery, Relay, and Gateway Systems ........... 12 + 2.3.9 Message Content and Mail Data .............................. 13 + 2.3.10 Mailbox and Address ....................................... 13 + 2.3.11 Reply ..................................................... 13 + 2.4 General Syntax Principles and Transaction Model .............. 13 + 3. The SMTP Procedures: An Overview .............................. 15 + 3.1 Session Initiation ........................................... 15 + 3.2 Client Initiation ............................................ 16 + 3.3 Mail Transactions ............................................ 16 + 3.4 Forwarding for Address Correction or Updating ................ 19 + + + +Klensin Standards Track [Page 2] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + 3.5 Commands for Debugging Addresses ............................. 20 + 3.5.1 Overview ................................................... 20 + 3.5.2 VRFY Normal Response ....................................... 22 + 3.5.3 Meaning of VRFY or EXPN Success Response ................... 22 + 3.5.4 Semantics and Applications of EXPN ......................... 23 + 3.6 Domains ...................................................... 23 + 3.7 Relaying ..................................................... 24 + 3.8 Mail Gatewaying .............................................. 25 + 3.8.1 Header Fields in Gatewaying ................................ 26 + 3.8.2 Received Lines in Gatewaying ............................... 26 + 3.8.3 Addresses in Gatewaying .................................... 26 + 3.8.4 Other Header Fields in Gatewaying .......................... 27 + 3.8.5 Envelopes in Gatewaying .................................... 27 + 3.9 Terminating Sessions and Connections ......................... 27 + 3.10 Mailing Lists and Aliases ................................... 28 + 3.10.1 Alias ..................................................... 28 + 3.10.2 List ...................................................... 28 + 4. The SMTP Specifications ....................................... 29 + 4.1 SMTP Commands ................................................ 29 + 4.1.1 Command Semantics and Syntax ............................... 29 + 4.1.1.1 Extended HELLO (EHLO) or HELLO (HELO) ................... 29 + 4.1.1.2 MAIL (MAIL) .............................................. 31 + 4.1.1.3 RECIPIENT (RCPT) ......................................... 31 + 4.1.1.4 DATA (DATA) .............................................. 33 + 4.1.1.5 RESET (RSET) ............................................. 34 + 4.1.1.6 VERIFY (VRFY) ............................................ 35 + 4.1.1.7 EXPAND (EXPN) ............................................ 35 + 4.1.1.8 HELP (HELP) .............................................. 35 + 4.1.1.9 NOOP (NOOP) .............................................. 35 + 4.1.1.10 QUIT (QUIT) ............................................. 36 + 4.1.2 Command Argument Syntax .................................... 36 + 4.1.3 Address Literals ........................................... 38 + 4.1.4 Order of Commands .......................................... 39 + 4.1.5 Private-use Commands ....................................... 40 + 4.2 SMTP Replies ................................................ 40 + 4.2.1 Reply Code Severities and Theory ........................... 42 + 4.2.2 Reply Codes by Function Groups ............................. 44 + 4.2.3 Reply Codes in Numeric Order .............................. 45 + 4.2.4 Reply Code 502 ............................................. 46 + 4.2.5 Reply Codes After DATA and the Subsequent . .... 46 + 4.3 Sequencing of Commands and Replies ........................... 47 + 4.3.1 Sequencing Overview ........................................ 47 + 4.3.2 Command-Reply Sequences .................................... 48 + 4.4 Trace Information ............................................ 49 + 4.5 Additional Implementation Issues ............................. 53 + 4.5.1 Minimum Implementation ..................................... 53 + 4.5.2 Transparency ............................................... 53 + 4.5.3 Sizes and Timeouts ......................................... 54 + + + +Klensin Standards Track [Page 3] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + 4.5.3.1 Size limits and minimums ................................. 54 + 4.5.3.2 Timeouts ................................................. 56 + 4.5.4 Retry Strategies ........................................... 57 + 4.5.4.1 Sending Strategy ......................................... 58 + 4.5.4.2 Receiving Strategy ....................................... 59 + 4.5.5 Messages with a null reverse-path .......................... 59 + 5. Address Resolution and Mail Handling .......................... 60 + 6. Problem Detection and Handling ................................ 62 + 6.1 Reliable Delivery and Replies by Email ....................... 62 + 6.2 Loop Detection ............................................... 63 + 6.3 Compensating for Irregularities .............................. 63 + 7. Security Considerations ....................................... 64 + 7.1 Mail Security and Spoofing ................................... 64 + 7.2 "Blind" Copies ............................................... 65 + 7.3 VRFY, EXPN, and Security ..................................... 65 + 7.4 Information Disclosure in Announcements ...................... 66 + 7.5 Information Disclosure in Trace Fields ....................... 66 + 7.6 Information Disclosure in Message Forwarding ................. 67 + 7.7 Scope of Operation of SMTP Servers ........................... 67 + 8. IANA Considerations ........................................... 67 + 9. References .................................................... 68 + 10. Editor's Address ............................................. 70 + 11. Acknowledgments .............................................. 70 + Appendices ....................................................... 71 + A. TCP Transport Service ......................................... 71 + B. Generating SMTP Commands from RFC 822 Headers ................. 71 + C. Source Routes ................................................. 72 + D. Scenarios ..................................................... 73 + E. Other Gateway Issues .......................................... 76 + F. Deprecated Features of RFC 821 ................................ 76 + Full Copyright Statement ......................................... 79 + +1. Introduction + + The objective of the Simple Mail Transfer Protocol (SMTP) is to + transfer mail reliably and efficiently. + + SMTP is independent of the particular transmission subsystem and + requires only a reliable ordered data stream channel. While this + document specifically discusses transport over TCP, other transports + are possible. Appendices to RFC 821 describe some of them. + + An important feature of SMTP is its capability to transport mail + across networks, usually referred to as "SMTP mail relaying" (see + section 3.8). A network consists of the mutually-TCP-accessible + hosts on the public Internet, the mutually-TCP-accessible hosts on a + firewall-isolated TCP/IP Intranet, or hosts in some other LAN or WAN + environment utilizing a non-TCP transport-level protocol. Using + + + +Klensin Standards Track [Page 4] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + SMTP, a process can transfer mail to another process on the same + network or to some other network via a relay or gateway process + accessible to both networks. + + In this way, a mail message may pass through a number of intermediate + relay or gateway hosts on its path from sender to ultimate recipient. + The Mail eXchanger mechanisms of the domain name system [22, 27] (and + section 5 of this document) are used to identify the appropriate + next-hop destination for a message being transported. + +2. The SMTP Model + +2.1 Basic Structure + + The SMTP design can be pictured as: + + +----------+ +----------+ + +------+ | | | | + | User |<-->| | SMTP | | + +------+ | Client- |Commands/Replies| Server- | + +------+ | SMTP |<-------------->| SMTP | +------+ + | File |<-->| | and Mail | |<-->| File | + |System| | | | | |System| + +------+ +----------+ +----------+ +------+ + SMTP client SMTP server + + When an SMTP client has a message to transmit, it establishes a two- + way transmission channel to an SMTP server. The responsibility of an + SMTP client is to transfer mail messages to one or more SMTP servers, + or report its failure to do so. + + The means by which a mail message is presented to an SMTP client, and + how that client determines the domain name(s) to which mail messages + are to be transferred is a local matter, and is not addressed by this + document. In some cases, the domain name(s) transferred to, or + determined by, an SMTP client will identify the final destination(s) + of the mail message. In other cases, common with SMTP clients + associated with implementations of the POP [3, 26] or IMAP [6] + protocols, or when the SMTP client is inside an isolated transport + service environment, the domain name determined will identify an + intermediate destination through which all mail messages are to be + relayed. SMTP clients that transfer all traffic, regardless of the + target domain names associated with the individual messages, or that + do not maintain queues for retrying message transmissions that + initially cannot be completed, may otherwise conform to this + specification but are not considered fully-capable. Fully-capable + SMTP implementations, including the relays used by these less capable + + + + +Klensin Standards Track [Page 5] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + ones, and their destinations, are expected to support all of the + queuing, retrying, and alternate address functions discussed in this + specification. + + The means by which an SMTP client, once it has determined a target + domain name, determines the identity of an SMTP server to which a + copy of a message is to be transferred, and then performs that + transfer, is covered by this document. To effect a mail transfer to + an SMTP server, an SMTP client establishes a two-way transmission + channel to that SMTP server. An SMTP client determines the address + of an appropriate host running an SMTP server by resolving a + destination domain name to either an intermediate Mail eXchanger host + or a final target host. + + An SMTP server may be either the ultimate destination or an + intermediate "relay" (that is, it may assume the role of an SMTP + client after receiving the message) or "gateway" (that is, it may + transport the message further using some protocol other than SMTP). + SMTP commands are generated by the SMTP client and sent to the SMTP + server. SMTP replies are sent from the SMTP server to the SMTP + client in response to the commands. + + In other words, message transfer can occur in a single connection + between the original SMTP-sender and the final SMTP-recipient, or can + occur in a series of hops through intermediary systems. In either + case, a formal handoff of responsibility for the message occurs: the + protocol requires that a server accept responsibility for either + delivering a message or properly reporting the failure to do so. + + Once the transmission channel is established and initial handshaking + completed, the SMTP client normally initiates a mail transaction. + Such a transaction consists of a series of commands to specify the + originator and destination of the mail and transmission of the + message content (including any headers or other structure) itself. + When the same message is sent to multiple recipients, this protocol + encourages the transmission of only one copy of the data for all + recipients at the same destination (or intermediate relay) host. + + The server responds to each command with a reply; replies may + indicate that the command was accepted, that additional commands are + expected, or that a temporary or permanent error condition exists. + Commands specifying the sender or recipients may include server- + permitted SMTP service extension requests as discussed in section + 2.2. The dialog is purposely lock-step, one-at-a-time, although this + can be modified by mutually-agreed extension requests such as command + pipelining [13]. + + + + + +Klensin Standards Track [Page 6] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + Once a given mail message has been transmitted, the client may either + request that the connection be shut down or may initiate other mail + transactions. In addition, an SMTP client may use a connection to an + SMTP server for ancillary services such as verification of email + addresses or retrieval of mailing list subscriber addresses. + + As suggested above, this protocol provides mechanisms for the + transmission of mail. This transmission normally occurs directly + from the sending user's host to the receiving user's host when the + two hosts are connected to the same transport service. When they are + not connected to the same transport service, transmission occurs via + one or more relay SMTP servers. An intermediate host that acts as + either an SMTP relay or as a gateway into some other transmission + environment is usually selected through the use of the domain name + service (DNS) Mail eXchanger mechanism. + + Usually, intermediate hosts are determined via the DNS MX record, not + by explicit "source" routing (see section 5 and appendices C and + F.2). + +2.2 The Extension Model + +2.2.1 Background + + In an effort that started in 1990, approximately a decade after RFC + 821 was completed, the protocol was modified with a "service + extensions" model that permits the client and server to agree to + utilize shared functionality beyond the original SMTP requirements. + The SMTP extension mechanism defines a means whereby an extended SMTP + client and server may recognize each other, and the server can inform + the client as to the service extensions that it supports. + + Contemporary SMTP implementations MUST support the basic extension + mechanisms. For instance, servers MUST support the EHLO command even + if they do not implement any specific extensions and clients SHOULD + preferentially utilize EHLO rather than HELO. (However, for + compatibility with older conforming implementations, SMTP clients and + servers MUST support the original HELO mechanisms as a fallback.) + Unless the different characteristics of HELO must be identified for + interoperability purposes, this document discusses only EHLO. + + SMTP is widely deployed and high-quality implementations have proven + to be very robust. However, the Internet community now considers + some services to be important that were not anticipated when the + protocol was first designed. If support for those services is to be + added, it must be done in a way that permits older implementations to + continue working acceptably. The extension framework consists of: + + + + +Klensin Standards Track [Page 7] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + - The SMTP command EHLO, superseding the earlier HELO, + + - a registry of SMTP service extensions, + + - additional parameters to the SMTP MAIL and RCPT commands, and + + - optional replacements for commands defined in this protocol, such + as for DATA in non-ASCII transmissions [33]. + + SMTP's strength comes primarily from its simplicity. Experience with + many protocols has shown that protocols with few options tend towards + ubiquity, whereas protocols with many options tend towards obscurity. + + Each and every extension, regardless of its benefits, must be + carefully scrutinized with respect to its implementation, deployment, + and interoperability costs. In many cases, the cost of extending the + SMTP service will likely outweigh the benefit. + +2.2.2 Definition and Registration of Extensions + + The IANA maintains a registry of SMTP service extensions. A + corresponding EHLO keyword value is associated with each extension. + Each service extension registered with the IANA must be defined in a + formal standards-track or IESG-approved experimental protocol + document. The definition must include: + + - the textual name of the SMTP service extension; + + - the EHLO keyword value associated with the extension; + + - the syntax and possible values of parameters associated with the + EHLO keyword value; + + - any additional SMTP verbs associated with the extension + (additional verbs will usually be, but are not required to be, the + same as the EHLO keyword value); + + - any new parameters the extension associates with the MAIL or RCPT + verbs; + + - a description of how support for the extension affects the + behavior of a server and client SMTP; and, + + - the increment by which the extension is increasing the maximum + length of the commands MAIL and/or RCPT, over that specified in + this standard. + + + + + +Klensin Standards Track [Page 8] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + In addition, any EHLO keyword value starting with an upper or lower + case "X" refers to a local SMTP service extension used exclusively + through bilateral agreement. Keywords beginning with "X" MUST NOT be + used in a registered service extension. Conversely, keyword values + presented in the EHLO response that do not begin with "X" MUST + correspond to a standard, standards-track, or IESG-approved + experimental SMTP service extension registered with IANA. A + conforming server MUST NOT offer non-"X"-prefixed keyword values that + are not described in a registered extension. + + Additional verbs and parameter names are bound by the same rules as + EHLO keywords; specifically, verbs beginning with "X" are local + extensions that may not be registered or standardized. Conversely, + verbs not beginning with "X" must always be registered. + +2.3 Terminology + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described below. + + 1. MUST This word, or the terms "REQUIRED" or "SHALL", mean that + the definition is an absolute requirement of the specification. + + 2. MUST NOT This phrase, or the phrase "SHALL NOT", mean that the + definition is an absolute prohibition of the specification. + + 3. SHOULD This word, or the adjective "RECOMMENDED", mean that + there may exist valid reasons in particular circumstances to + ignore a particular item, but the full implications must be + understood and carefully weighed before choosing a different + course. + + 4. SHOULD NOT This phrase, or the phrase "NOT RECOMMENDED" mean + that there may exist valid reasons in particular circumstances + when the particular behavior is acceptable or even useful, but the + full implications should be understood and the case carefully + weighed before implementing any behavior described with this + label. + + 5. MAY This word, or the adjective "OPTIONAL", mean that an item is + truly optional. One vendor may choose to include the item because + a particular marketplace requires it or because the vendor feels + that it enhances the product while another vendor may omit the + same item. An implementation which does not include a particular + option MUST be prepared to interoperate with another + implementation which does include the option, though perhaps with + reduced functionality. In the same vein an implementation which + + + +Klensin Standards Track [Page 9] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + does include a particular option MUST be prepared to interoperate + with another implementation which does not include the option + (except, of course, for the feature the option provides.) + +2.3.1 Mail Objects + + SMTP transports a mail object. A mail object contains an envelope + and content. + + The SMTP envelope is sent as a series of SMTP protocol units + (described in section 3). It consists of an originator address (to + which error reports should be directed); one or more recipient + addresses; and optional protocol extension material. Historically, + variations on the recipient address specification command (RCPT TO) + could be used to specify alternate delivery modes, such as immediate + display; those variations have now been deprecated (see appendix F, + section F.6). + + The SMTP content is sent in the SMTP DATA protocol unit and has two + parts: the headers and the body. If the content conforms to other + contemporary standards, the headers form a collection of field/value + pairs structured as in the message format specification [32]; the + body, if structured, is defined according to MIME [12]. The content + is textual in nature, expressed using the US-ASCII repertoire [1]. + Although SMTP extensions (such as "8BITMIME" [20]) may relax this + restriction for the content body, the content headers are always + encoded using the US-ASCII repertoire. A MIME extension [23] defines + an algorithm for representing header values outside the US-ASCII + repertoire, while still encoding them using the US-ASCII repertoire. + +2.3.2 Senders and Receivers + + In RFC 821, the two hosts participating in an SMTP transaction were + described as the "SMTP-sender" and "SMTP-receiver". This document + has been changed to reflect current industry terminology and hence + refers to them as the "SMTP client" (or sometimes just "the client") + and "SMTP server" (or just "the server"), respectively. Since a + given host may act both as server and client in a relay situation, + "receiver" and "sender" terminology is still used where needed for + clarity. + +2.3.3 Mail Agents and Message Stores + + Additional mail system terminology became common after RFC 821 was + published and, where convenient, is used in this specification. In + particular, SMTP servers and clients provide a mail transport service + and therefore act as "Mail Transfer Agents" (MTAs). "Mail User + Agents" (MUAs or UAs) are normally thought of as the sources and + + + +Klensin Standards Track [Page 10] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + targets of mail. At the source, an MUA might collect mail to be + transmitted from a user and hand it off to an MTA; the final + ("delivery") MTA would be thought of as handing the mail off to an + MUA (or at least transferring responsibility to it, e.g., by + depositing the message in a "message store"). However, while these + terms are used with at least the appearance of great precision in + other environments, the implied boundaries between MUAs and MTAs + often do not accurately match common, and conforming, practices with + Internet mail. Hence, the reader should be cautious about inferring + the strong relationships and responsibilities that might be implied + if these terms were used elsewhere. + +2.3.4 Host + + For the purposes of this specification, a host is a computer system + attached to the Internet (or, in some cases, to a private TCP/IP + network) and supporting the SMTP protocol. Hosts are known by names + (see "domain"); identifying them by numerical address is discouraged. + +2.3.5 Domain + + A domain (or domain name) consists of one or more dot-separated + components. These components ("labels" in DNS terminology [22]) are + restricted for SMTP purposes to consist of a sequence of letters, + digits, and hyphens drawn from the ASCII character set [1]. Domain + names are used as names of hosts and of other entities in the domain + name hierarchy. For example, a domain may refer to an alias (label + of a CNAME RR) or the label of Mail eXchanger records to be used to + deliver mail instead of representing a host name. See [22] and + section 5 of this specification. + + The domain name, as described in this document and in [22], is the + entire, fully-qualified name (often referred to as an "FQDN"). A + domain name that is not in FQDN form is no more than a local alias. + Local aliases MUST NOT appear in any SMTP transaction. + +2.3.6 Buffer and State Table + + SMTP sessions are stateful, with both parties carefully maintaining a + common view of the current state. In this document we model this + state by a virtual "buffer" and a "state table" on the server which + may be used by the client to, for example, "clear the buffer" or + "reset the state table," causing the information in the buffer to be + discarded and the state to be returned to some previous state. + + + + + + + +Klensin Standards Track [Page 11] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +2.3.7 Lines + + SMTP commands and, unless altered by a service extension, message + data, are transmitted in "lines". Lines consist of zero or more data + characters terminated by the sequence ASCII character "CR" (hex value + 0D) followed immediately by ASCII character "LF" (hex value 0A). + This termination sequence is denoted as in this document. + Conforming implementations MUST NOT recognize or generate any other + character or character sequence as a line terminator. Limits MAY be + imposed on line lengths by servers (see section 4.5.3). + + In addition, the appearance of "bare" "CR" or "LF" characters in text + (i.e., either without the other) has a long history of causing + problems in mail implementations and applications that use the mail + system as a tool. SMTP client implementations MUST NOT transmit + these characters except when they are intended as line terminators + and then MUST, as indicated above, transmit them only as a + sequence. + +2.3.8 Originator, Delivery, Relay, and Gateway Systems + + This specification makes a distinction among four types of SMTP + systems, based on the role those systems play in transmitting + electronic mail. An "originating" system (sometimes called an SMTP + originator) introduces mail into the Internet or, more generally, + into a transport service environment. A "delivery" SMTP system is + one that receives mail from a transport service environment and + passes it to a mail user agent or deposits it in a message store + which a mail user agent is expected to subsequently access. A + "relay" SMTP system (usually referred to just as a "relay") receives + mail from an SMTP client and transmits it, without modification to + the message data other than adding trace information, to another SMTP + server for further relaying or for delivery. + + A "gateway" SMTP system (usually referred to just as a "gateway") + receives mail from a client system in one transport environment and + transmits it to a server system in another transport environment. + Differences in protocols or message semantics between the transport + environments on either side of a gateway may require that the gateway + system perform transformations to the message that are not permitted + to SMTP relay systems. For the purposes of this specification, + firewalls that rewrite addresses should be considered as gateways, + even if SMTP is used on both sides of them (see [11]). + + + + + + + + +Klensin Standards Track [Page 12] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +2.3.9 Message Content and Mail Data + + The terms "message content" and "mail data" are used interchangeably + in this document to describe the material transmitted after the DATA + command is accepted and before the end of data indication is + transmitted. Message content includes message headers and the + possibly-structured message body. The MIME specification [12] + provides the standard mechanisms for structured message bodies. + +2.3.10 Mailbox and Address + + As used in this specification, an "address" is a character string + that identifies a user to whom mail will be sent or a location into + which mail will be deposited. The term "mailbox" refers to that + depository. The two terms are typically used interchangeably unless + the distinction between the location in which mail is placed (the + mailbox) and a reference to it (the address) is important. An + address normally consists of user and domain specifications. The + standard mailbox naming convention is defined to be "local- + part@domain": contemporary usage permits a much broader set of + applications than simple "user names". Consequently, and due to a + long history of problems when intermediate hosts have attempted to + optimize transport by modifying them, the local-part MUST be + interpreted and assigned semantics only by the host specified in the + domain part of the address. + +2.3.11 Reply + + An SMTP reply is an acknowledgment (positive or negative) sent from + receiver to sender via the transmission channel in response to a + command. The general form of a reply is a numeric completion code + (indicating failure or success) usually followed by a text string. + The codes are for use by programs and the text is usually intended + for human users. Recent work [34] has specified further structuring + of the reply strings, including the use of supplemental and more + specific completion codes. + +2.4 General Syntax Principles and Transaction Model + + SMTP commands and replies have a rigid syntax. All commands begin + with a command verb. All Replies begin with a three digit numeric + code. In some commands and replies, arguments MUST follow the verb + or reply code. Some commands do not accept arguments (after the + verb), and some reply codes are followed, sometimes optionally, by + free form text. In both cases, where text appears, it is separated + from the verb or reply code by a space character. Complete + definitions of commands and replies appear in section 4. + + + + +Klensin Standards Track [Page 13] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + Verbs and argument values (e.g., "TO:" or "to:" in the RCPT command + and extension name keywords) are not case sensitive, with the sole + exception in this specification of a mailbox local-part (SMTP + Extensions may explicitly specify case-sensitive elements). That is, + a command verb, an argument value other than a mailbox local-part, + and free form text MAY be encoded in upper case, lower case, or any + mixture of upper and lower case with no impact on its meaning. This + is NOT true of a mailbox local-part. The local-part of a mailbox + MUST BE treated as case sensitive. Therefore, SMTP implementations + MUST take care to preserve the case of mailbox local-parts. Mailbox + domains are not case sensitive. In particular, for some hosts the + user "smith" is different from the user "Smith". However, exploiting + the case sensitivity of mailbox local-parts impedes interoperability + and is discouraged. + + A few SMTP servers, in violation of this specification (and RFC 821) + require that command verbs be encoded by clients in upper case. + Implementations MAY wish to employ this encoding to accommodate those + servers. + + The argument field consists of a variable length character string + ending with the end of the line, i.e., with the character sequence + . The receiver will take no action until this sequence is + received. + + The syntax for each command is shown with the discussion of that + command. Common elements and parameters are shown in section 4.1.2. + + Commands and replies are composed of characters from the ASCII + character set [1]. When the transport service provides an 8-bit byte + (octet) transmission channel, each 7-bit character is transmitted + right justified in an octet with the high order bit cleared to zero. + More specifically, the unextended SMTP service provides seven bit + transport only. An originating SMTP client which has not + successfully negotiated an appropriate extension with a particular + server MUST NOT transmit messages with information in the high-order + bit of octets. If such messages are transmitted in violation of this + rule, receiving SMTP servers MAY clear the high-order bit or reject + the message as invalid. In general, a relay SMTP SHOULD assume that + the message content it has received is valid and, assuming that the + envelope permits doing so, relay it without inspecting that content. + Of course, if the content is mislabeled and the data path cannot + accept the actual content, this may result in ultimate delivery of a + severely garbled message to the recipient. Delivery SMTP systems MAY + reject ("bounce") such messages rather than deliver them. No sending + SMTP system is permitted to send envelope commands in any character + + + + + +Klensin Standards Track [Page 14] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + set other than US-ASCII; receiving systems SHOULD reject such + commands, normally using "500 syntax error - invalid character" + replies. + + Eight-bit message content transmission MAY be requested of the server + by a client using extended SMTP facilities, notably the "8BITMIME" + extension [20]. 8BITMIME SHOULD be supported by SMTP servers. + However, it MUST not be construed as authorization to transmit + unrestricted eight bit material. 8BITMIME MUST NOT be requested by + senders for material with the high bit on that is not in MIME format + with an appropriate content-transfer encoding; servers MAY reject + such messages. + + The metalinguistic notation used in this document corresponds to the + "Augmented BNF" used in other Internet mail system documents. The + reader who is not familiar with that syntax should consult the ABNF + specification [8]. Metalanguage terms used in running text are + surrounded by pointed brackets (e.g., ) for clarity. + +3. The SMTP Procedures: An Overview + + This section contains descriptions of the procedures used in SMTP: + session initiation, the mail transaction, forwarding mail, verifying + mailbox names and expanding mailing lists, and the opening and + closing exchanges. Comments on relaying, a note on mail domains, and + a discussion of changing roles are included at the end of this + section. Several complete scenarios are presented in appendix D. + +3.1 Session Initiation + + An SMTP session is initiated when a client opens a connection to a + server and the server responds with an opening message. + + SMTP server implementations MAY include identification of their + software and version information in the connection greeting reply + after the 220 code, a practice that permits more efficient isolation + and repair of any problems. Implementations MAY make provision for + SMTP servers to disable the software and version announcement where + it causes security concerns. While some systems also identify their + contact point for mail problems, this is not a substitute for + maintaining the required "postmaster" address (see section 4.5.1). + + The SMTP protocol allows a server to formally reject a transaction + while still allowing the initial connection as follows: a 554 + response MAY be given in the initial connection opening message + instead of the 220. A server taking this approach MUST still wait + for the client to send a QUIT (see section 4.1.1.10) before closing + the connection and SHOULD respond to any intervening commands with + + + +Klensin Standards Track [Page 15] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + "503 bad sequence of commands". Since an attempt to make an SMTP + connection to such a system is probably in error, a server returning + a 554 response on connection opening SHOULD provide enough + information in the reply text to facilitate debugging of the sending + system. + +3.2 Client Initiation + + Once the server has sent the welcoming message and the client has + received it, the client normally sends the EHLO command to the + server, indicating the client's identity. In addition to opening the + session, use of EHLO indicates that the client is able to process + service extensions and requests that the server provide a list of the + extensions it supports. Older SMTP systems which are unable to + support service extensions and contemporary clients which do not + require service extensions in the mail session being initiated, MAY + use HELO instead of EHLO. Servers MUST NOT return the extended + EHLO-style response to a HELO command. For a particular connection + attempt, if the server returns a "command not recognized" response to + EHLO, the client SHOULD be able to fall back and send HELO. + + In the EHLO command the host sending the command identifies itself; + the command may be interpreted as saying "Hello, I am " (and, + in the case of EHLO, "and I support service extension requests"). + +3.3 Mail Transactions + + There are three steps to SMTP mail transactions. The transaction + starts with a MAIL command which gives the sender identification. + (In general, the MAIL command may be sent only when no mail + transaction is in progress; see section 4.1.4.) A series of one or + more RCPT commands follows giving the receiver information. Then a + DATA command initiates transfer of the mail data and is terminated by + the "end of mail" data indicator, which also confirms the + transaction. + + The first step in the procedure is the MAIL command. + + MAIL FROM: [SP ] + + This command tells the SMTP-receiver that a new mail transaction is + starting and to reset all its state tables and buffers, including any + recipients or mail data. The portion of the first or + only argument contains the source mailbox (between "<" and ">" + brackets), which can be used to report errors (see section 4.2 for a + discussion of error reporting). If accepted, the SMTP server returns + a 250 OK reply. If the mailbox specification is not acceptable for + some reason, the server MUST return a reply indicating whether the + + + +Klensin Standards Track [Page 16] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + failure is permanent (i.e., will occur again if the client tries to + send the same address again) or temporary (i.e., the address might be + accepted if the client tries again later). Despite the apparent + scope of this requirement, there are circumstances in which the + acceptability of the reverse-path may not be determined until one or + more forward-paths (in RCPT commands) can be examined. In those + cases, the server MAY reasonably accept the reverse-path (with a 250 + reply) and then report problems after the forward-paths are received + and examined. Normally, failures produce 550 or 553 replies. + + Historically, the can contain more than just a + mailbox, however, contemporary systems SHOULD NOT use source routing + (see appendix C). + + The optional are associated with negotiated SMTP + service extensions (see section 2.2). + + The second step in the procedure is the RCPT command. + + RCPT TO: [ SP ] + + The first or only argument to this command includes a forward-path + (normally a mailbox and domain, always surrounded by "<" and ">" + brackets) identifying one recipient. If accepted, the SMTP server + returns a 250 OK reply and stores the forward-path. If the recipient + is known not to be a deliverable address, the SMTP server returns a + 550 reply, typically with a string such as "no such user - " and the + mailbox name (other circumstances and reply codes are possible). + This step of the procedure can be repeated any number of times. + + The can contain more than just a mailbox. + Historically, the can be a source routing list of + hosts and the destination mailbox, however, contemporary SMTP clients + SHOULD NOT utilize source routes (see appendix C). Servers MUST be + prepared to encounter a list of source routes in the forward path, + but SHOULD ignore the routes or MAY decline to support the relaying + they imply. Similarly, servers MAY decline to accept mail that is + destined for other hosts or systems. These restrictions make a + server useless as a relay for clients that do not support full SMTP + functionality. Consequently, restricted-capability clients MUST NOT + assume that any SMTP server on the Internet can be used as their mail + processing (relaying) site. If a RCPT command appears without a + previous MAIL command, the server MUST return a 503 "Bad sequence of + commands" response. The optional are associated + with negotiated SMTP service extensions (see section 2.2). + + The third step in the procedure is the DATA command (or some + alternative specified in a service extension). + + + +Klensin Standards Track [Page 17] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + DATA + + If accepted, the SMTP server returns a 354 Intermediate reply and + considers all succeeding lines up to but not including the end of + mail data indicator to be the message text. When the end of text is + successfully received and stored the SMTP-receiver sends a 250 OK + reply. + + Since the mail data is sent on the transmission channel, the end of + mail data must be indicated so that the command and reply dialog can + be resumed. SMTP indicates the end of the mail data by sending a + line containing only a "." (period or full stop). A transparency + procedure is used to prevent this from interfering with the user's + text (see section 4.5.2). + + The end of mail data indicator also confirms the mail transaction and + tells the SMTP server to now process the stored recipients and mail + data. If accepted, the SMTP server returns a 250 OK reply. The DATA + command can fail at only two points in the protocol exchange: + + - If there was no MAIL, or no RCPT, command, or all such commands + were rejected, the server MAY return a "command out of sequence" + (503) or "no valid recipients" (554) reply in response to the DATA + command. If one of those replies (or any other 5yz reply) is + received, the client MUST NOT send the message data; more + generally, message data MUST NOT be sent unless a 354 reply is + received. + + - If the verb is initially accepted and the 354 reply issued, the + DATA command should fail only if the mail transaction was + incomplete (for example, no recipients), or if resources were + unavailable (including, of course, the server unexpectedly + becoming unavailable), or if the server determines that the + message should be rejected for policy or other reasons. + + However, in practice, some servers do not perform recipient + verification until after the message text is received. These servers + SHOULD treat a failure for one or more recipients as a "subsequent + failure" and return a mail message as discussed in section 6. Using + a "550 mailbox not found" (or equivalent) reply code after the data + are accepted makes it difficult or impossible for the client to + determine which recipients failed. + + When RFC 822 format [7, 32] is being used, the mail data include the + memo header items such as Date, Subject, To, Cc, From. Server SMTP + systems SHOULD NOT reject messages based on perceived defects in the + RFC 822 or MIME [12] message header or message body. In particular, + + + + +Klensin Standards Track [Page 18] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + they MUST NOT reject messages in which the numbers of Resent-fields + do not match or Resent-to appears without Resent-from and/or Resent- + date. + + Mail transaction commands MUST be used in the order discussed above. + +3.4 Forwarding for Address Correction or Updating + + Forwarding support is most often required to consolidate and simplify + addresses within, or relative to, some enterprise and less frequently + to establish addresses to link a person's prior address with current + one. Silent forwarding of messages (without server notification to + the sender), for security or non-disclosure purposes, is common in + the contemporary Internet. + + In both the enterprise and the "new address" cases, information + hiding (and sometimes security) considerations argue against exposure + of the "final" address through the SMTP protocol as a side-effect of + the forwarding activity. This may be especially important when the + final address may not even be reachable by the sender. Consequently, + the "forwarding" mechanisms described in section 3.2 of RFC 821, and + especially the 251 (corrected destination) and 551 reply codes from + RCPT must be evaluated carefully by implementers and, when they are + available, by those configuring systems. + + In particular: + + * Servers MAY forward messages when they are aware of an address + change. When they do so, they MAY either provide address-updating + information with a 251 code, or may forward "silently" and return + a 250 code. But, if a 251 code is used, they MUST NOT assume that + the client will actually update address information or even return + that information to the user. + + Alternately, + + * Servers MAY reject or bounce messages when they are not + deliverable when addressed. When they do so, they MAY either + provide address-updating information with a 551 code, or may + reject the message as undeliverable with a 550 code and no + address-specific information. But, if a 551 code is used, they + MUST NOT assume that the client will actually update address + information or even return that information to the user. + + SMTP server implementations that support the 251 and/or 551 reply + codes are strongly encouraged to provide configuration mechanisms so + that sites which conclude that they would undesirably disclose + information can disable or restrict their use. + + + +Klensin Standards Track [Page 19] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +3.5 Commands for Debugging Addresses + +3.5.1 Overview + + SMTP provides commands to verify a user name or obtain the content of + a mailing list. This is done with the VRFY and EXPN commands, which + have character string arguments. Implementations SHOULD support VRFY + and EXPN (however, see section 3.5.2 and 7.3). + + For the VRFY command, the string is a user name or a user name and + domain (see below). If a normal (i.e., 250) response is returned, + the response MAY include the full name of the user and MUST include + the mailbox of the user. It MUST be in either of the following + forms: + + User Name + local-part@domain + + When a name that is the argument to VRFY could identify more than one + mailbox, the server MAY either note the ambiguity or identify the + alternatives. In other words, any of the following are legitimate + response to VRFY: + + 553 User ambiguous + + or + + 553- Ambiguous; Possibilities are + 553-Joe Smith + 553-Harry Smith + 553 Melvin Smith + + or + + 553-Ambiguous; Possibilities + 553- + 553- + 553 + + Under normal circumstances, a client receiving a 553 reply would be + expected to expose the result to the user. Use of exactly the forms + given, and the "user ambiguous" or "ambiguous" keywords, possibly + supplemented by extended reply codes such as those described in [34], + will facilitate automated translation into other languages as needed. + Of course, a client that was highly automated or that was operating + in another language than English, might choose to try to translate + the response, to return some other indication to the user than the + + + + +Klensin Standards Track [Page 20] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + literal text of the reply, or to take some automated action such as + consulting a directory service for additional information before + reporting to the user. + + For the EXPN command, the string identifies a mailing list, and the + successful (i.e., 250) multiline response MAY include the full name + of the users and MUST give the mailboxes on the mailing list. + + In some hosts the distinction between a mailing list and an alias for + a single mailbox is a bit fuzzy, since a common data structure may + hold both types of entries, and it is possible to have mailing lists + containing only one mailbox. If a request is made to apply VRFY to a + mailing list, a positive response MAY be given if a message so + addressed would be delivered to everyone on the list, otherwise an + error SHOULD be reported (e.g., "550 That is a mailing list, not a + user" or "252 Unable to verify members of mailing list"). If a + request is made to expand a user name, the server MAY return a + positive response consisting of a list containing one name, or an + error MAY be reported (e.g., "550 That is a user name, not a mailing + list"). + + In the case of a successful multiline reply (normal for EXPN) exactly + one mailbox is to be specified on each line of the reply. The case + of an ambiguous request is discussed above. + + "User name" is a fuzzy term and has been used deliberately. An + implementation of the VRFY or EXPN commands MUST include at least + recognition of local mailboxes as "user names". However, since + current Internet practice often results in a single host handling + mail for multiple domains, hosts, especially hosts that provide this + functionality, SHOULD accept the "local-part@domain" form as a "user + name"; hosts MAY also choose to recognize other strings as "user + names". + + The case of expanding a mailbox list requires a multiline reply, such + as: + + C: EXPN Example-People + S: 250-Jon Postel + S: 250-Fred Fonebone + S: 250 Sam Q. Smith + + or + + C: EXPN Executive-Washroom-List + S: 550 Access Denied to You. + + + + + +Klensin Standards Track [Page 21] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + The character string arguments of the VRFY and EXPN commands cannot + be further restricted due to the variety of implementations of the + user name and mailbox list concepts. On some systems it may be + appropriate for the argument of the EXPN command to be a file name + for a file containing a mailing list, but again there are a variety + of file naming conventions in the Internet. Similarly, historical + variations in what is returned by these commands are such that the + response SHOULD be interpreted very carefully, if at all, and SHOULD + generally only be used for diagnostic purposes. + +3.5.2 VRFY Normal Response + + When normal (2yz or 551) responses are returned from a VRFY or EXPN + request, the reply normally includes the mailbox name, i.e., + "", where "domain" is a fully qualified domain + name, MUST appear in the syntax. In circumstances exceptional enough + to justify violating the intent of this specification, free-form text + MAY be returned. In order to facilitate parsing by both computers + and people, addresses SHOULD appear in pointed brackets. When + addresses, rather than free-form debugging information, are returned, + EXPN and VRFY MUST return only valid domain addresses that are usable + in SMTP RCPT commands. Consequently, if an address implies delivery + to a program or other system, the mailbox name used to reach that + target MUST be given. Paths (explicit source routes) MUST NOT be + returned by VRFY or EXPN. + + Server implementations SHOULD support both VRFY and EXPN. For + security reasons, implementations MAY provide local installations a + way to disable either or both of these commands through configuration + options or the equivalent. When these commands are supported, they + are not required to work across relays when relaying is supported. + Since they were both optional in RFC 821, they MUST be listed as + service extensions in an EHLO response, if they are supported. + +3.5.3 Meaning of VRFY or EXPN Success Response + + A server MUST NOT return a 250 code in response to a VRFY or EXPN + command unless it has actually verified the address. In particular, + a server MUST NOT return 250 if all it has done is to verify that the + syntax given is valid. In that case, 502 (Command not implemented) + or 500 (Syntax error, command unrecognized) SHOULD be returned. As + stated elsewhere, implementation (in the sense of actually validating + addresses and returning information) of VRFY and EXPN are strongly + recommended. Hence, implementations that return 500 or 502 for VRFY + are not in full compliance with this specification. + + + + + + +Klensin Standards Track [Page 22] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + There may be circumstances where an address appears to be valid but + cannot reasonably be verified in real time, particularly when a + server is acting as a mail exchanger for another server or domain. + "Apparent validity" in this case would normally involve at least + syntax checking and might involve verification that any domains + specified were ones to which the host expected to be able to relay + mail. In these situations, reply code 252 SHOULD be returned. These + cases parallel the discussion of RCPT verification discussed in + section 2.1. Similarly, the discussion in section 3.4 applies to the + use of reply codes 251 and 551 with VRFY (and EXPN) to indicate + addresses that are recognized but that would be forwarded or bounced + were mail received for them. Implementations generally SHOULD be + more aggressive about address verification in the case of VRFY than + in the case of RCPT, even if it takes a little longer to do so. + +3.5.4 Semantics and Applications of EXPN + + EXPN is often very useful in debugging and understanding problems + with mailing lists and multiple-target-address aliases. Some systems + have attempted to use source expansion of mailing lists as a means of + eliminating duplicates. The propagation of aliasing systems with + mail on the Internet, for hosts (typically with MX and CNAME DNS + records), for mailboxes (various types of local host aliases), and in + various proxying arrangements, has made it nearly impossible for + these strategies to work consistently, and mail systems SHOULD NOT + attempt them. + +3.6 Domains + + Only resolvable, fully-qualified, domain names (FQDNs) are permitted + when domain names are used in SMTP. In other words, names that can + be resolved to MX RRs or A RRs (as discussed in section 5) are + permitted, as are CNAME RRs whose targets can be resolved, in turn, + to MX or A RRs. Local nicknames or unqualified names MUST NOT be + used. There are two exceptions to the rule requiring FQDNs: + + - The domain name given in the EHLO command MUST BE either a primary + host name (a domain name that resolves to an A RR) or, if the host + has no name, an address literal as described in section 4.1.1.1. + + - The reserved mailbox name "postmaster" may be used in a RCPT + command without domain qualification (see section 4.1.1.3) and + MUST be accepted if so used. + + + + + + + + +Klensin Standards Track [Page 23] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +3.7 Relaying + + In general, the availability of Mail eXchanger records in the domain + name system [22, 27] makes the use of explicit source routes in the + Internet mail system unnecessary. Many historical problems with + their interpretation have made their use undesirable. SMTP clients + SHOULD NOT generate explicit source routes except under unusual + circumstances. SMTP servers MAY decline to act as mail relays or to + accept addresses that specify source routes. When route information + is encountered, SMTP servers are also permitted to ignore the route + information and simply send to the final destination specified as the + last element in the route and SHOULD do so. There has been an + invalid practice of using names that do not appear in the DNS as + destination names, with the senders counting on the intermediate + hosts specified in source routing to resolve any problems. If source + routes are stripped, this practice will cause failures. This is one + of several reasons why SMTP clients MUST NOT generate invalid source + routes or depend on serial resolution of names. + + When source routes are not used, the process described in RFC 821 for + constructing a reverse-path from the forward-path is not applicable + and the reverse-path at the time of delivery will simply be the + address that appeared in the MAIL command. + + A relay SMTP server is usually the target of a DNS MX record that + designates it, rather than the final delivery system. The relay + server may accept or reject the task of relaying the mail in the same + way it accepts or rejects mail for a local user. If it accepts the + task, it then becomes an SMTP client, establishes a transmission + channel to the next SMTP server specified in the DNS (according to + the rules in section 5), and sends it the mail. If it declines to + relay mail to a particular address for policy reasons, a 550 response + SHOULD be returned. + + Many mail-sending clients exist, especially in conjunction with + facilities that receive mail via POP3 or IMAP, that have limited + capability to support some of the requirements of this specification, + such as the ability to queue messages for subsequent delivery + attempts. For these clients, it is common practice to make private + arrangements to send all messages to a single server for processing + and subsequent distribution. SMTP, as specified here, is not ideally + suited for this role, and work is underway on standardized mail + submission protocols that might eventually supercede the current + practices. In any event, because these arrangements are private and + fall outside the scope of this specification, they are not described + here. + + + + + +Klensin Standards Track [Page 24] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + It is important to note that MX records can point to SMTP servers + which act as gateways into other environments, not just SMTP relays + and final delivery systems; see sections 3.8 and 5. + + If an SMTP server has accepted the task of relaying the mail and + later finds that the destination is incorrect or that the mail cannot + be delivered for some other reason, then it MUST construct an + "undeliverable mail" notification message and send it to the + originator of the undeliverable mail (as indicated by the reverse- + path). Formats specified for non-delivery reports by other standards + (see, for example, [24, 25]) SHOULD be used if possible. + + This notification message must be from the SMTP server at the relay + host or the host that first determines that delivery cannot be + accomplished. Of course, SMTP servers MUST NOT send notification + messages about problems transporting notification messages. One way + to prevent loops in error reporting is to specify a null reverse-path + in the MAIL command of a notification message. When such a message + is transmitted the reverse-path MUST be set to null (see section + 4.5.5 for additional discussion). A MAIL command with a null + reverse-path appears as follows: + + MAIL FROM:<> + + As discussed in section 2.4.1, a relay SMTP has no need to inspect or + act upon the headers or body of the message data and MUST NOT do so + except to add its own "Received:" header (section 4.4) and, + optionally, to attempt to detect looping in the mail system (see + section 6.2). + +3.8 Mail Gatewaying + + While the relay function discussed above operates within the Internet + SMTP transport service environment, MX records or various forms of + explicit routing may require that an intermediate SMTP server perform + a translation function between one transport service and another. As + discussed in section 2.3.8, when such a system is at the boundary + between two transport service environments, we refer to it as a + "gateway" or "gateway SMTP". + + Gatewaying mail between different mail environments, such as + different mail formats and protocols, is complex and does not easily + yield to standardization. However, some general requirements may be + given for a gateway between the Internet and another mail + environment. + + + + + + +Klensin Standards Track [Page 25] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +3.8.1 Header Fields in Gatewaying + + Header fields MAY be rewritten when necessary as messages are + gatewayed across mail environment boundaries. This may involve + inspecting the message body or interpreting the local-part of the + destination address in spite of the prohibitions in section 2.4.1. + + Other mail systems gatewayed to the Internet often use a subset of + RFC 822 headers or provide similar functionality with a different + syntax, but some of these mail systems do not have an equivalent to + the SMTP envelope. Therefore, when a message leaves the Internet + environment, it may be necessary to fold the SMTP envelope + information into the message header. A possible solution would be to + create new header fields to carry the envelope information (e.g., + "X-SMTP-MAIL:" and "X-SMTP-RCPT:"); however, this would require + changes in mail programs in foreign environments and might risk + disclosure of private information (see section 7.2). + +3.8.2 Received Lines in Gatewaying + + When forwarding a message into or out of the Internet environment, a + gateway MUST prepend a Received: line, but it MUST NOT alter in any + way a Received: line that is already in the header. + + "Received:" fields of messages originating from other environments + may not conform exactly to this specification. However, the most + important use of Received: lines is for debugging mail faults, and + this debugging can be severely hampered by well-meaning gateways that + try to "fix" a Received: line. As another consequence of trace + fields arising in non-SMTP environments, receiving systems MUST NOT + reject mail based on the format of a trace field and SHOULD be + extremely robust in the light of unexpected information or formats in + those fields. + + The gateway SHOULD indicate the environment and protocol in the "via" + clauses of Received field(s) that it supplies. + +3.8.3 Addresses in Gatewaying + + From the Internet side, the gateway SHOULD accept all valid address + formats in SMTP commands and in RFC 822 headers, and all valid RFC + 822 messages. Addresses and headers generated by gateways MUST + conform to applicable Internet standards (including this one and RFC + 822). Gateways are, of course, subject to the same rules for + handling source routes as those described for other SMTP systems in + section 3.3. + + + + + +Klensin Standards Track [Page 26] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +3.8.4 Other Header Fields in Gatewaying + + The gateway MUST ensure that all header fields of a message that it + forwards into the Internet mail environment meet the requirements for + Internet mail. In particular, all addresses in "From:", "To:", + "Cc:", etc., fields MUST be transformed (if necessary) to satisfy RFC + 822 syntax, MUST reference only fully-qualified domain names, and + MUST be effective and useful for sending replies. The translation + algorithm used to convert mail from the Internet protocols to another + environment's protocol SHOULD ensure that error messages from the + foreign mail environment are delivered to the return path from the + SMTP envelope, not to the sender listed in the "From:" field (or + other fields) of the RFC 822 message. + +3.8.5 Envelopes in Gatewaying + + Similarly, when forwarding a message from another environment into + the Internet, the gateway SHOULD set the envelope return path in + accordance with an error message return address, if supplied by the + foreign environment. If the foreign environment has no equivalent + concept, the gateway must select and use a best approximation, with + the message originator's address as the default of last resort. + +3.9 Terminating Sessions and Connections + + An SMTP connection is terminated when the client sends a QUIT + command. The server responds with a positive reply code, after which + it closes the connection. + + An SMTP server MUST NOT intentionally close the connection except: + + - After receiving a QUIT command and responding with a 221 reply. + + - After detecting the need to shut down the SMTP service and + returning a 421 response code. This response code can be issued + after the server receives any command or, if necessary, + asynchronously from command receipt (on the assumption that the + client will receive it after the next command is issued). + + In particular, a server that closes connections in response to + commands that are not understood is in violation of this + specification. Servers are expected to be tolerant of unknown + commands, issuing a 500 reply and awaiting further instructions from + the client. + + + + + + + +Klensin Standards Track [Page 27] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + An SMTP server which is forcibly shut down via external means SHOULD + attempt to send a line containing a 421 response code to the SMTP + client before exiting. The SMTP client will normally read the 421 + response code after sending its next command. + + SMTP clients that experience a connection close, reset, or other + communications failure due to circumstances not under their control + (in violation of the intent of this specification but sometimes + unavoidable) SHOULD, to maintain the robustness of the mail system, + treat the mail transaction as if a 451 response had been received and + act accordingly. + +3.10 Mailing Lists and Aliases + + An SMTP-capable host SHOULD support both the alias and the list + models of address expansion for multiple delivery. When a message is + delivered or forwarded to each address of an expanded list form, the + return address in the envelope ("MAIL FROM:") MUST be changed to be + the address of a person or other entity who administers the list. + However, in this case, the message header [32] MUST be left + unchanged; in particular, the "From" field of the message header is + unaffected. + + An important mail facility is a mechanism for multi-destination + delivery of a single message, by transforming (or "expanding" or + "exploding") a pseudo-mailbox address into a list of destination + mailbox addresses. When a message is sent to such a pseudo-mailbox + (sometimes called an "exploder"), copies are forwarded or + redistributed to each mailbox in the expanded list. Servers SHOULD + simply utilize the addresses on the list; application of heuristics + or other matching rules to eliminate some addresses, such as that of + the originator, is strongly discouraged. We classify such a pseudo- + mailbox as an "alias" or a "list", depending upon the expansion + rules. + +3.10.1 Alias + + To expand an alias, the recipient mailer simply replaces the pseudo- + mailbox address in the envelope with each of the expanded addresses + in turn; the rest of the envelope and the message body are left + unchanged. The message is then delivered or forwarded to each + expanded address. + +3.10.2 List + + A mailing list may be said to operate by "redistribution" rather than + by "forwarding". To expand a list, the recipient mailer replaces the + pseudo-mailbox address in the envelope with all of the expanded + + + +Klensin Standards Track [Page 28] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + addresses. The return address in the envelope is changed so that all + error messages generated by the final deliveries will be returned to + a list administrator, not to the message originator, who generally + has no control over the contents of the list and will typically find + error messages annoying. + +4. The SMTP Specifications + +4.1 SMTP Commands + +4.1.1 Command Semantics and Syntax + + The SMTP commands define the mail transfer or the mail system + function requested by the user. SMTP commands are character strings + terminated by . The commands themselves are alphabetic + characters terminated by if parameters follow and + otherwise. (In the interest of improved interoperability, SMTP + receivers are encouraged to tolerate trailing white space before the + terminating .) The syntax of the local part of a mailbox must + conform to receiver site conventions and the syntax specified in + section 4.1.2. The SMTP commands are discussed below. The SMTP + replies are discussed in section 4.2. + + A mail transaction involves several data objects which are + communicated as arguments to different commands. The reverse-path is + the argument of the MAIL command, the forward-path is the argument of + the RCPT command, and the mail data is the argument of the DATA + command. These arguments or data objects must be transmitted and + held pending the confirmation communicated by the end of mail data + indication which finalizes the transaction. The model for this is + that distinct buffers are provided to hold the types of data objects, + that is, there is a reverse-path buffer, a forward-path buffer, and a + mail data buffer. Specific commands cause information to be appended + to a specific buffer, or cause one or more buffers to be cleared. + + Several commands (RSET, DATA, QUIT) are specified as not permitting + parameters. In the absence of specific extensions offered by the + server and accepted by the client, clients MUST NOT send such + parameters and servers SHOULD reject commands containing them as + having invalid syntax. + +4.1.1.1 Extended HELLO (EHLO) or HELLO (HELO) + + These commands are used to identify the SMTP client to the SMTP + server. The argument field contains the fully-qualified domain name + of the SMTP client if one is available. In situations in which the + SMTP client system does not have a meaningful domain name (e.g., when + its address is dynamically allocated and no reverse mapping record is + + + +Klensin Standards Track [Page 29] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + available), the client SHOULD send an address literal (see section + 4.1.3), optionally followed by information that will help to identify + the client system. y The SMTP server identifies itself to the SMTP + client in the connection greeting reply and in the response to this + command. + + A client SMTP SHOULD start an SMTP session by issuing the EHLO + command. If the SMTP server supports the SMTP service extensions it + will give a successful response, a failure response, or an error + response. If the SMTP server, in violation of this specification, + does not support any SMTP service extensions it will generate an + error response. Older client SMTP systems MAY, as discussed above, + use HELO (as specified in RFC 821) instead of EHLO, and servers MUST + support the HELO command and reply properly to it. In any event, a + client MUST issue HELO or EHLO before starting a mail transaction. + + These commands, and a "250 OK" reply to one of them, confirm that + both the SMTP client and the SMTP server are in the initial state, + that is, there is no transaction in progress and all state tables and + buffers are cleared. + + Syntax: + + ehlo = "EHLO" SP Domain CRLF + helo = "HELO" SP Domain CRLF + + Normally, the response to EHLO will be a multiline reply. Each line + of the response contains a keyword and, optionally, one or more + parameters. Following the normal syntax for multiline replies, these + keyworks follow the code (250) and a hyphen for all but the last + line, and the code and a space for the last line. The syntax for a + positive response, using the ABNF notation and terminal symbols of + [8], is: + + ehlo-ok-rsp = ( "250" domain [ SP ehlo-greet ] CRLF ) + / ( "250-" domain [ SP ehlo-greet ] CRLF + *( "250-" ehlo-line CRLF ) + "250" SP ehlo-line CRLF ) + + ehlo-greet = 1*(%d0-9 / %d11-12 / %d14-127) + ; string of any characters other than CR or LF + + ehlo-line = ehlo-keyword *( SP ehlo-param ) + + ehlo-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") + ; additional syntax of ehlo-params depends on + ; ehlo-keyword + + + + +Klensin Standards Track [Page 30] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + ehlo-param = 1*(%d33-127) + ; any CHAR excluding and all + ; control characters (US-ASCII 0-31 inclusive) + + Although EHLO keywords may be specified in upper, lower, or mixed + case, they MUST always be recognized and processed in a case- + insensitive manner. This is simply an extension of practices + specified in RFC 821 and section 2.4.1. + +4.1.1.2 MAIL (MAIL) + + This command is used to initiate a mail transaction in which the mail + data is delivered to an SMTP server which may, in turn, deliver it to + one or more mailboxes or pass it on to another system (possibly using + SMTP). The argument field contains a reverse-path and may contain + optional parameters. In general, the MAIL command may be sent only + when no mail transaction is in progress, see section 4.1.4. + + The reverse-path consists of the sender mailbox. Historically, that + mailbox might optionally have been preceded by a list of hosts, but + that behavior is now deprecated (see appendix C). In some types of + reporting messages for which a reply is likely to cause a mail loop + (for example, mail delivery and nondelivery notifications), the + reverse-path may be null (see section 3.7). + + This command clears the reverse-path buffer, the forward-path buffer, + and the mail data buffer; and inserts the reverse-path information + from this command into the reverse-path buffer. + + If service extensions were negotiated, the MAIL command may also + carry parameters associated with a particular service extension. + + Syntax: + + "MAIL FROM:" ("<>" / Reverse-Path) + [SP Mail-parameters] CRLF + +4.1.1.3 RECIPIENT (RCPT) + + This command is used to identify an individual recipient of the mail + data; multiple recipients are specified by multiple use of this + command. The argument field contains a forward-path and may contain + optional parameters. + + The forward-path normally consists of the required destination + mailbox. Sending systems SHOULD not generate the optional list of + hosts known as a source route. Receiving systems MUST recognize + + + + +Klensin Standards Track [Page 31] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + source route syntax but SHOULD strip off the source route + specification and utilize the domain name associated with the mailbox + as if the source route had not been provided. + + Similarly, relay hosts SHOULD strip or ignore source routes, and + names MUST NOT be copied into the reverse-path. When mail reaches + its ultimate destination (the forward-path contains only a + destination mailbox), the SMTP server inserts it into the destination + mailbox in accordance with its host mail conventions. + + For example, mail received at relay host xyz.com with envelope + commands + + MAIL FROM: + RCPT TO:<@hosta.int,@jkl.org:userc@d.bar.org> + + will normally be sent directly on to host d.bar.org with envelope + commands + + MAIL FROM: + RCPT TO: + + As provided in appendix C, xyz.com MAY also choose to relay the + message to hosta.int, using the envelope commands + + MAIL FROM: + RCPT TO:<@hosta.int,@jkl.org:userc@d.bar.org> + + or to jkl.org, using the envelope commands + + MAIL FROM: + RCPT TO:<@jkl.org:userc@d.bar.org> + + Of course, since hosts are not required to relay mail at all, xyz.com + may also reject the message entirely when the RCPT command is + received, using a 550 code (since this is a "policy reason"). + + If service extensions were negotiated, the RCPT command may also + carry parameters associated with a particular service extension + offered by the server. The client MUST NOT transmit parameters other + than those associated with a service extension offered by the server + in its EHLO response. + +Syntax: + "RCPT TO:" ("" / "" / Forward-Path) + [SP Rcpt-parameters] CRLF + + + + + +Klensin Standards Track [Page 32] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +4.1.1.4 DATA (DATA) + + The receiver normally sends a 354 response to DATA, and then treats + the lines (strings ending in sequences, as described in + section 2.3.7) following the command as mail data from the sender. + This command causes the mail data to be appended to the mail data + buffer. The mail data may contain any of the 128 ASCII character + codes, although experience has indicated that use of control + characters other than SP, HT, CR, and LF may cause problems and + SHOULD be avoided when possible. + + The mail data is terminated by a line containing only a period, that + is, the character sequence "." (see section 4.5.2). This + is the end of mail data indication. Note that the first of + this terminating sequence is also the that ends the final line + of the data (message text) or, if there was no data, ends the DATA + command itself. An extra MUST NOT be added, as that would + cause an empty line to be added to the message. The only exception + to this rule would arise if the message body were passed to the + originating SMTP-sender with a final "line" that did not end in + ; in that case, the originating SMTP system MUST either reject + the message as invalid or add in order to have the receiving + SMTP server recognize the "end of data" condition. + + The custom of accepting lines ending only in , as a concession to + non-conforming behavior on the part of some UNIX systems, has proven + to cause more interoperability problems than it solves, and SMTP + server systems MUST NOT do this, even in the name of improved + robustness. In particular, the sequence "." (bare line + feeds, without carriage returns) MUST NOT be treated as equivalent to + . as the end of mail data indication. + + Receipt of the end of mail data indication requires the server to + process the stored mail transaction information. This processing + consumes the information in the reverse-path buffer, the forward-path + buffer, and the mail data buffer, and on the completion of this + command these buffers are cleared. If the processing is successful, + the receiver MUST send an OK reply. If the processing fails the + receiver MUST send a failure reply. The SMTP model does not allow + for partial failures at this point: either the message is accepted by + the server for delivery and a positive response is returned or it is + not accepted and a failure reply is returned. In sending a positive + completion reply to the end of data indication, the receiver takes + full responsibility for the message (see section 6.1). Errors that + are diagnosed subsequently MUST be reported in a mail message, as + discussed in section 4.4. + + + + + +Klensin Standards Track [Page 33] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + When the SMTP server accepts a message either for relaying or for + final delivery, it inserts a trace record (also referred to + interchangeably as a "time stamp line" or "Received" line) at the top + of the mail data. This trace record indicates the identity of the + host that sent the message, the identity of the host that received + the message (and is inserting this time stamp), and the date and time + the message was received. Relayed messages will have multiple time + stamp lines. Details for formation of these lines, including their + syntax, is specified in section 4.4. + + Additional discussion about the operation of the DATA command appears + in section 3.3. + + Syntax: + "DATA" CRLF + +4.1.1.5 RESET (RSET) + + This command specifies that the current mail transaction will be + aborted. Any stored sender, recipients, and mail data MUST be + discarded, and all buffers and state tables cleared. The receiver + MUST send a "250 OK" reply to a RSET command with no arguments. A + reset command may be issued by the client at any time. It is + effectively equivalent to a NOOP (i.e., if has no effect) if issued + immediately after EHLO, before EHLO is issued in the session, after + an end-of-data indicator has been sent and acknowledged, or + immediately before a QUIT. An SMTP server MUST NOT close the + connection as the result of receiving a RSET; that action is reserved + for QUIT (see section 4.1.1.10). + + Since EHLO implies some additional processing and response by the + server, RSET will normally be more efficient than reissuing that + command, even though the formal semantics are the same. + + There are circumstances, contrary to the intent of this + specification, in which an SMTP server may receive an indication that + the underlying TCP connection has been closed or reset. To preserve + the robustness of the mail system, SMTP servers SHOULD be prepared + for this condition and SHOULD treat it as if a QUIT had been received + before the connection disappeared. + + Syntax: + "RSET" CRLF + + + + + + + + +Klensin Standards Track [Page 34] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +4.1.1.6 VERIFY (VRFY) + + This command asks the receiver to confirm that the argument + identifies a user or mailbox. If it is a user name, information is + returned as specified in section 3.5. + + This command has no effect on the reverse-path buffer, the forward- + path buffer, or the mail data buffer. + + Syntax: + "VRFY" SP String CRLF + +4.1.1.7 EXPAND (EXPN) + + This command asks the receiver to confirm that the argument + identifies a mailing list, and if so, to return the membership of + that list. If the command is successful, a reply is returned + containing information as described in section 3.5. This reply will + have multiple lines except in the trivial case of a one-member list. + + This command has no effect on the reverse-path buffer, the forward- + path buffer, or the mail data buffer and may be issued at any time. + + Syntax: + "EXPN" SP String CRLF + +4.1.1.8 HELP (HELP) + + This command causes the server to send helpful information to the + client. The command MAY take an argument (e.g., any command name) + and return more specific information as a response. + + This command has no effect on the reverse-path buffer, the forward- + path buffer, or the mail data buffer and may be issued at any time. + + SMTP servers SHOULD support HELP without arguments and MAY support it + with arguments. + + Syntax: + "HELP" [ SP String ] CRLF + +4.1.1.9 NOOP (NOOP) + + This command does not affect any parameters or previously entered + commands. It specifies no action other than that the receiver send + an OK reply. + + + + + +Klensin Standards Track [Page 35] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + This command has no effect on the reverse-path buffer, the forward- + path buffer, or the mail data buffer and may be issued at any time. + If a parameter string is specified, servers SHOULD ignore it. + + Syntax: + "NOOP" [ SP String ] CRLF + +4.1.1.10 QUIT (QUIT) + + This command specifies that the receiver MUST send an OK reply, and + then close the transmission channel. + + The receiver MUST NOT intentionally close the transmission channel + until it receives and replies to a QUIT command (even if there was an + error). The sender MUST NOT intentionally close the transmission + channel until it sends a QUIT command and SHOULD wait until it + receives the reply (even if there was an error response to a previous + command). If the connection is closed prematurely due to violations + of the above or system or network failure, the server MUST cancel any + pending transaction, but not undo any previously completed + transaction, and generally MUST act as if the command or transaction + in progress had received a temporary error (i.e., a 4yz response). + + The QUIT command may be issued at any time. + + Syntax: + "QUIT" CRLF + +4.1.2 Command Argument Syntax + + The syntax of the argument fields of the above commands (using the + syntax specified in [8] where applicable) is given below. Some of + the productions given below are used only in conjunction with source + routes as described in appendix C. Terminals not defined in this + document, such as ALPHA, DIGIT, SP, CR, LF, CRLF, are as defined in + the "core" syntax [8 (section 6)] or in the message format syntax + [32]. + + Reverse-path = Path + Forward-path = Path + Path = "<" [ A-d-l ":" ] Mailbox ">" + A-d-l = At-domain *( "," A-d-l ) + ; Note that this form, the so-called "source route", + ; MUST BE accepted, SHOULD NOT be generated, and SHOULD be + ; ignored. + At-domain = "@" domain + Mail-parameters = esmtp-param *(SP esmtp-param) + Rcpt-parameters = esmtp-param *(SP esmtp-param) + + + +Klensin Standards Track [Page 36] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + esmtp-param = esmtp-keyword ["=" esmtp-value] + esmtp-keyword = (ALPHA / DIGIT) *(ALPHA / DIGIT / "-") + esmtp-value = 1*(%d33-60 / %d62-127) + ; any CHAR excluding "=", SP, and control characters + Keyword = Ldh-str + Argument = Atom + Domain = (sub-domain 1*("." sub-domain)) / address-literal + sub-domain = Let-dig [Ldh-str] + + address-literal = "[" IPv4-address-literal / + IPv6-address-literal / + General-address-literal "]" + ; See section 4.1.3 + + Mailbox = Local-part "@" Domain + + Local-part = Dot-string / Quoted-string + ; MAY be case-sensitive + + Dot-string = Atom *("." Atom) + + Atom = 1*atext + + Quoted-string = DQUOTE *qcontent DQUOTE + + String = Atom / Quoted-string + + While the above definition for Local-part is relatively permissive, + for maximum interoperability, a host that expects to receive mail + SHOULD avoid defining mailboxes where the Local-part requires (or + uses) the Quoted-string form or where the Local-part is case- + sensitive. For any purposes that require generating or comparing + Local-parts (e.g., to specific mailbox names), all quoted forms MUST + be treated as equivalent and the sending system SHOULD transmit the + form that uses the minimum quoting possible. + + Systems MUST NOT define mailboxes in such a way as to require the use + in SMTP of non-ASCII characters (octets with the high order bit set + to one) or ASCII "control characters" (decimal value 0-31 and 127). + These characters MUST NOT be used in MAIL or RCPT commands or other + commands that require mailbox names. + + Note that the backslash, "\", is a quote character, which is used to + indicate that the next character is to be used literally (instead of + its normal interpretation). For example, "Joe\,Smith" indicates a + single nine character user field with the comma being the fourth + character of the field. + + + + +Klensin Standards Track [Page 37] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + To promote interoperability and consistent with long-standing + guidance about conservative use of the DNS in naming and applications + (e.g., see section 2.3.1 of the base DNS document, RFC1035 [22]), + characters outside the set of alphas, digits, and hyphen MUST NOT + appear in domain name labels for SMTP clients or servers. In + particular, the underscore character is not permitted. SMTP servers + that receive a command in which invalid character codes have been + employed, and for which there are no other reasons for rejection, + MUST reject that command with a 501 response. + +4.1.3 Address Literals + + Sometimes a host is not known to the domain name system and + communication (and, in particular, communication to report and repair + the error) is blocked. To bypass this barrier a special literal form + of the address is allowed as an alternative to a domain name. For + IPv4 addresses, this form uses four small decimal integers separated + by dots and enclosed by brackets such as [123.255.37.2], which + indicates an (IPv4) Internet Address in sequence-of-octets form. For + IPv6 and other forms of addressing that might eventually be + standardized, the form consists of a standardized "tag" that + identifies the address syntax, a colon, and the address itself, in a + format specified as part of the IPv6 standards [17]. + + Specifically: + + IPv4-address-literal = Snum 3("." Snum) + IPv6-address-literal = "IPv6:" IPv6-addr + General-address-literal = Standardized-tag ":" 1*dcontent + Standardized-tag = Ldh-str + ; MUST be specified in a standards-track RFC + ; and registered with IANA + + Snum = 1*3DIGIT ; representing a decimal integer + ; value in the range 0 through 255 + Let-dig = ALPHA / DIGIT + Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig + + IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp + IPv6-hex = 1*4HEXDIG + IPv6-full = IPv6-hex 7(":" IPv6-hex) + IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::" [IPv6-hex *5(":" + IPv6-hex)] + ; The "::" represents at least 2 16-bit groups of zeros + ; No more than 6 groups in addition to the "::" may be + ; present + IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal + IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::" + + + +Klensin Standards Track [Page 38] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + [IPv6-hex *3(":" IPv6-hex) ":"] IPv4-address-literal + ; The "::" represents at least 2 16-bit groups of zeros + ; No more than 4 groups in addition to the "::" and + ; IPv4-address-literal may be present + +4.1.4 Order of Commands + + There are restrictions on the order in which these commands may be + used. + + A session that will contain mail transactions MUST first be + initialized by the use of the EHLO command. An SMTP server SHOULD + accept commands for non-mail transactions (e.g., VRFY or EXPN) + without this initialization. + + An EHLO command MAY be issued by a client later in the session. If + it is issued after the session begins, the SMTP server MUST clear all + buffers and reset the state exactly as if a RSET command had been + issued. In other words, the sequence of RSET followed immediately by + EHLO is redundant, but not harmful other than in the performance cost + of executing unnecessary commands. + + If the EHLO command is not acceptable to the SMTP server, 501, 500, + or 502 failure replies MUST be returned as appropriate. The SMTP + server MUST stay in the same state after transmitting these replies + that it was in before the EHLO was received. + + The SMTP client MUST, if possible, ensure that the domain parameter + to the EHLO command is a valid principal host name (not a CNAME or MX + name) for its host. If this is not possible (e.g., when the client's + address is dynamically assigned and the client does not have an + obvious name), an address literal SHOULD be substituted for the + domain name and supplemental information provided that will assist in + identifying the client. + + An SMTP server MAY verify that the domain name parameter in the EHLO + command actually corresponds to the IP address of the client. + However, the server MUST NOT refuse to accept a message for this + reason if the verification fails: the information about verification + failure is for logging and tracing only. + + The NOOP, HELP, EXPN, VRFY, and RSET commands can be used at any time + during a session, or without previously initializing a session. SMTP + servers SHOULD process these normally (that is, not return a 503 + code) even if no EHLO command has yet been received; clients SHOULD + open a session with EHLO before sending these commands. + + + + + +Klensin Standards Track [Page 39] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + If these rules are followed, the example in RFC 821 that shows "550 + access denied to you" in response to an EXPN command is incorrect + unless an EHLO command precedes the EXPN or the denial of access is + based on the client's IP address or other authentication or + authorization-determining mechanisms. + + The MAIL command (or the obsolete SEND, SOML, or SAML commands) + begins a mail transaction. Once started, a mail transaction consists + of a transaction beginning command, one or more RCPT commands, and a + DATA command, in that order. A mail transaction may be aborted by + the RSET (or a new EHLO) command. There may be zero or more + transactions in a session. MAIL (or SEND, SOML, or SAML) MUST NOT be + sent if a mail transaction is already open, i.e., it should be sent + only if no mail transaction had been started in the session, or it + the previous one successfully concluded with a successful DATA + command, or if the previous one was aborted with a RSET. + + If the transaction beginning command argument is not acceptable, a + 501 failure reply MUST be returned and the SMTP server MUST stay in + the same state. If the commands in a transaction are out of order to + the degree that they cannot be processed by the server, a 503 failure + reply MUST be returned and the SMTP server MUST stay in the same + state. + + The last command in a session MUST be the QUIT command. The QUIT + command cannot be used at any other time in a session, but SHOULD be + used by the client SMTP to request connection closure, even when no + session opening command was sent and accepted. + +4.1.5 Private-use Commands + + As specified in section 2.2.2, commands starting in "X" may be used + by bilateral agreement between the client (sending) and server + (receiving) SMTP agents. An SMTP server that does not recognize such + a command is expected to reply with "500 Command not recognized". An + extended SMTP server MAY list the feature names associated with these + private commands in the response to the EHLO command. + + Commands sent or accepted by SMTP systems that do not start with "X" + MUST conform to the requirements of section 2.2.2. + +4.2 SMTP Replies + + Replies to SMTP commands serve to ensure the synchronization of + requests and actions in the process of mail transfer and to guarantee + that the SMTP client always knows the state of the SMTP server. + Every command MUST generate exactly one reply. + + + + +Klensin Standards Track [Page 40] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + The details of the command-reply sequence are described in section + 4.3. + + An SMTP reply consists of a three digit number (transmitted as three + numeric characters) followed by some text unless specified otherwise + in this document. The number is for use by automata to determine + what state to enter next; the text is for the human user. The three + digits contain enough encoded information that the SMTP client need + not examine the text and may either discard it or pass it on to the + user, as appropriate. Exceptions are as noted elsewhere in this + document. In particular, the 220, 221, 251, 421, and 551 reply codes + are associated with message text that must be parsed and interpreted + by machines. In the general case, the text may be receiver dependent + and context dependent, so there are likely to be varying texts for + each reply code. A discussion of the theory of reply codes is given + in section 4.2.1. Formally, a reply is defined to be the sequence: a + three-digit code, , one line of text, and , or a multiline + reply (as defined in section 4.2.1). Since, in violation of this + specification, the text is sometimes not sent, clients which do not + receive it SHOULD be prepared to process the code alone (with or + without a trailing space character). Only the EHLO, EXPN, and HELP + commands are expected to result in multiline replies in normal + circumstances, however, multiline replies are allowed for any + command. + + In ABNF, server responses are: + + Greeting = "220 " Domain [ SP text ] CRLF + Reply-line = Reply-code [ SP text ] CRLF + + where "Greeting" appears only in the 220 response that announces that + the server is opening its part of the connection. + + An SMTP server SHOULD send only the reply codes listed in this + document. An SMTP server SHOULD use the text shown in the examples + whenever appropriate. + + An SMTP client MUST determine its actions only by the reply code, not + by the text (except for the "change of address" 251 and 551 and, if + necessary, 220, 221, and 421 replies); in the general case, any text, + including no text at all (although senders SHOULD NOT send bare + codes), MUST be acceptable. The space (blank) following the reply + code is considered part of the text. Whenever possible, a receiver- + SMTP SHOULD test the first digit (severity indication) of the reply + code. + + + + + + +Klensin Standards Track [Page 41] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + The list of codes that appears below MUST NOT be construed as + permanent. While the addition of new codes should be a rare and + significant activity, with supplemental information in the textual + part of the response being preferred, new codes may be added as the + result of new Standards or Standards-track specifications. + Consequently, a sender-SMTP MUST be prepared to handle codes not + specified in this document and MUST do so by interpreting the first + digit only. + +4.2.1 Reply Code Severities and Theory + + The three digits of the reply each have a special significance. The + first digit denotes whether the response is good, bad or incomplete. + An unsophisticated SMTP client, or one that receives an unexpected + code, will be able to determine its next action (proceed as planned, + redo, retrench, etc.) by examining this first digit. An SMTP client + that wants to know approximately what kind of error occurred (e.g., + mail system error, command syntax error) may examine the second + digit. The third digit and any supplemental information that may be + present is reserved for the finest gradation of information. + + There are five values for the first digit of the reply code: + + 1yz Positive Preliminary reply + The command has been accepted, but the requested action is being + held in abeyance, pending confirmation of the information in this + reply. The SMTP client should send another command specifying + whether to continue or abort the action. Note: unextended SMTP + does not have any commands that allow this type of reply, and so + does not have continue or abort commands. + + 2yz Positive Completion reply + The requested action has been successfully completed. A new + request may be initiated. + + 3yz Positive Intermediate reply + The command has been accepted, but the requested action is being + held in abeyance, pending receipt of further information. The + SMTP client should send another command specifying this + information. This reply is used in command sequence groups (i.e., + in DATA). + + 4yz Transient Negative Completion reply + The command was not accepted, and the requested action did not + occur. However, the error condition is temporary and the action + may be requested again. The sender should return to the beginning + of the command sequence (if any). It is difficult to assign a + meaning to "transient" when two different sites (receiver- and + + + +Klensin Standards Track [Page 42] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + sender-SMTP agents) must agree on the interpretation. Each reply + in this category might have a different time value, but the SMTP + client is encouraged to try again. A rule of thumb to determine + whether a reply fits into the 4yz or the 5yz category (see below) + is that replies are 4yz if they can be successful if repeated + without any change in command form or in properties of the sender + or receiver (that is, the command is repeated identically and the + receiver does not put up a new implementation.) + + 5yz Permanent Negative Completion reply + The command was not accepted and the requested action did not + occur. The SMTP client is discouraged from repeating the exact + request (in the same sequence). Even some "permanent" error + conditions can be corrected, so the human user may want to direct + the SMTP client to reinitiate the command sequence by direct + action at some point in the future (e.g., after the spelling has + been changed, or the user has altered the account status). + + The second digit encodes responses in specific categories: + + x0z Syntax: These replies refer to syntax errors, syntactically + correct commands that do not fit any functional category, and + unimplemented or superfluous commands. + + x1z Information: These are replies to requests for information, + such as status or help. + + x2z Connections: These are replies referring to the transmission + channel. + + x3z Unspecified. + + x4z Unspecified. + + x5z Mail system: These replies indicate the status of the receiver + mail system vis-a-vis the requested transfer or other mail system + action. + + The third digit gives a finer gradation of meaning in each category + specified by the second digit. The list of replies illustrates this. + Each reply text is recommended rather than mandatory, and may even + change according to the command with which it is associated. On the + other hand, the reply codes must strictly follow the specifications + in this section. Receiver implementations should not invent new + codes for slightly different situations from the ones described here, + but rather adapt codes already defined. + + + + + +Klensin Standards Track [Page 43] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + For example, a command such as NOOP, whose successful execution does + not offer the SMTP client any new information, will return a 250 + reply. The reply is 502 when the command requests an unimplemented + non-site-specific action. A refinement of that is the 504 reply for + a command that is implemented, but that requests an unimplemented + parameter. + + The reply text may be longer than a single line; in these cases the + complete text must be marked so the SMTP client knows when it can + stop reading the reply. This requires a special format to indicate a + multiple line reply. + + The format for multiline replies requires that every line, except the + last, begin with the reply code, followed immediately by a hyphen, + "-" (also known as minus), followed by text. The last line will + begin with the reply code, followed immediately by , optionally + some text, and . As noted above, servers SHOULD send the + if subsequent text is not sent, but clients MUST be prepared for it + to be omitted. + + For example: + + 123-First line + 123-Second line + 123-234 text beginning with numbers + 123 The last line + + In many cases the SMTP client then simply needs to search for a line + beginning with the reply code followed by or and ignore + all preceding lines. In a few cases, there is important data for the + client in the reply "text". The client will be able to identify + these cases from the current context. + +4.2.2 Reply Codes by Function Groups + + 500 Syntax error, command unrecognized + (This may include errors such as command line too long) + 501 Syntax error in parameters or arguments + 502 Command not implemented (see section 4.2.4) + 503 Bad sequence of commands + 504 Command parameter not implemented + + 211 System status, or system help reply + 214 Help message + (Information on how to use the receiver or the meaning of a + particular non-standard command; this reply is useful only + to the human user) + + + + +Klensin Standards Track [Page 44] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + 220 Service ready + 221 Service closing transmission channel + 421 Service not available, closing transmission channel + (This may be a reply to any command if the service knows it + must shut down) + + 250 Requested mail action okay, completed + 251 User not local; will forward to + (See section 3.4) + 252 Cannot VRFY user, but will accept message and attempt + delivery + (See section 3.5.3) + 450 Requested mail action not taken: mailbox unavailable + (e.g., mailbox busy) + 550 Requested action not taken: mailbox unavailable + (e.g., mailbox not found, no access, or command rejected + for policy reasons) + 451 Requested action aborted: error in processing + 551 User not local; please try + (See section 3.4) + 452 Requested action not taken: insufficient system storage + 552 Requested mail action aborted: exceeded storage allocation + 553 Requested action not taken: mailbox name not allowed + (e.g., mailbox syntax incorrect) + 354 Start mail input; end with . + 554 Transaction failed (Or, in the case of a connection-opening + response, "No SMTP service here") + +4.2.3 Reply Codes in Numeric Order + + 211 System status, or system help reply + 214 Help message + (Information on how to use the receiver or the meaning of a + particular non-standard command; this reply is useful only + to the human user) + 220 Service ready + 221 Service closing transmission channel + 250 Requested mail action okay, completed + 251 User not local; will forward to + (See section 3.4) + 252 Cannot VRFY user, but will accept message and attempt + delivery + (See section 3.5.3) + + 354 Start mail input; end with . + + + + + + +Klensin Standards Track [Page 45] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + 421 Service not available, closing transmission channel + (This may be a reply to any command if the service knows it + must shut down) + 450 Requested mail action not taken: mailbox unavailable + (e.g., mailbox busy) + 451 Requested action aborted: local error in processing + 452 Requested action not taken: insufficient system storage + 500 Syntax error, command unrecognized + (This may include errors such as command line too long) + 501 Syntax error in parameters or arguments + 502 Command not implemented (see section 4.2.4) + 503 Bad sequence of commands + 504 Command parameter not implemented + 550 Requested action not taken: mailbox unavailable + (e.g., mailbox not found, no access, or command rejected + for policy reasons) + 551 User not local; please try + (See section 3.4) + 552 Requested mail action aborted: exceeded storage allocation + 553 Requested action not taken: mailbox name not allowed + (e.g., mailbox syntax incorrect) + 554 Transaction failed (Or, in the case of a connection-opening + response, "No SMTP service here") + +4.2.4 Reply Code 502 + + Questions have been raised as to when reply code 502 (Command not + implemented) SHOULD be returned in preference to other codes. 502 + SHOULD be used when the command is actually recognized by the SMTP + server, but not implemented. If the command is not recognized, code + 500 SHOULD be returned. Extended SMTP systems MUST NOT list + capabilities in response to EHLO for which they will return 502 (or + 500) replies. + +4.2.5 Reply Codes After DATA and the Subsequent . + + When an SMTP server returns a positive completion status (2yz code) + after the DATA command is completed with ., it accepts + responsibility for: + + - delivering the message (if the recipient mailbox exists), or + + - if attempts to deliver the message fail due to transient + conditions, retrying delivery some reasonable number of times at + intervals as specified in section 4.5.4. + + + + + + +Klensin Standards Track [Page 46] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + - if attempts to deliver the message fail due to permanent + conditions, or if repeated attempts to deliver the message fail + due to transient conditions, returning appropriate notification to + the sender of the original message (using the address in the SMTP + MAIL command). + + When an SMTP server returns a permanent error status (5yz) code after + the DATA command is completed with ., it MUST NOT make + any subsequent attempt to deliver that message. The SMTP client + retains responsibility for delivery of that message and may either + return it to the user or requeue it for a subsequent attempt (see + section 4.5.4.1). + + The user who originated the message SHOULD be able to interpret the + return of a transient failure status (by mail message or otherwise) + as a non-delivery indication, just as a permanent failure would be + interpreted. I.e., if the client SMTP successfully handles these + conditions, the user will not receive such a reply. + + When an SMTP server returns a permanent error status (5yz) code after + the DATA command is completely with ., it MUST NOT make + any subsequent attempt to deliver the message. As with temporary + error status codes, the SMTP client retains responsibility for the + message, but SHOULD not again attempt delivery to the same server + without user review and intervention of the message. + +4.3 Sequencing of Commands and Replies + +4.3.1 Sequencing Overview + + The communication between the sender and receiver is an alternating + dialogue, controlled by the sender. As such, the sender issues a + command and the receiver responds with a reply. Unless other + arrangements are negotiated through service extensions, the sender + MUST wait for this response before sending further commands. + + One important reply is the connection greeting. Normally, a receiver + will send a 220 "Service ready" reply when the connection is + completed. The sender SHOULD wait for this greeting message before + sending any commands. + + Note: all the greeting-type replies have the official name (the + fully-qualified primary domain name) of the server host as the first + word following the reply code. Sometimes the host will have no + meaningful name. See 4.1.3 for a discussion of alternatives in these + situations. + + + + + +Klensin Standards Track [Page 47] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + For example, + + 220 ISIF.USC.EDU Service ready + or + 220 mail.foo.com SuperSMTP v 6.1.2 Service ready + or + 220 [10.0.0.1] Clueless host service ready + + The table below lists alternative success and failure replies for + each command. These SHOULD be strictly adhered to: a receiver may + substitute text in the replies, but the meaning and action implied by + the code numbers and by the specific command reply sequence cannot be + altered. + +4.3.2 Command-Reply Sequences + + Each command is listed with its usual possible replies. The prefixes + used before the possible replies are "I" for intermediate, "S" for + success, and "E" for error. Since some servers may generate other + replies under special circumstances, and to allow for future + extension, SMTP clients SHOULD, when possible, interpret only the + first digit of the reply and MUST be prepared to deal with + unrecognized reply codes by interpreting the first digit only. + Unless extended using the mechanisms described in section 2.2, SMTP + servers MUST NOT transmit reply codes to an SMTP client that are + other than three digits or that do not start in a digit between 2 and + 5 inclusive. + + These sequencing rules and, in principle, the codes themselves, can + be extended or modified by SMTP extensions offered by the server and + accepted (requested) by the client. + + In addition to the codes listed below, any SMTP command can return + any of the following codes if the corresponding unusual circumstances + are encountered: + + 500 For the "command line too long" case or if the command name was + not recognized. Note that producing a "command not recognized" + error in response to the required subset of these commands is a + violation of this specification. + + 501 Syntax error in command or arguments. In order to provide for + future extensions, commands that are specified in this document as + not accepting arguments (DATA, RSET, QUIT) SHOULD return a 501 + message if arguments are supplied in the absence of EHLO- + advertised extensions. + + 421 Service shutting down and closing transmission channel + + + +Klensin Standards Track [Page 48] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + Specific sequences are: + + CONNECTION ESTABLISHMENT + S: 220 + E: 554 + EHLO or HELO + S: 250 + E: 504, 550 + MAIL + S: 250 + E: 552, 451, 452, 550, 553, 503 + RCPT + S: 250, 251 (but see section 3.4 for discussion of 251 and 551) + E: 550, 551, 552, 553, 450, 451, 452, 503, 550 + DATA + I: 354 -> data -> S: 250 + E: 552, 554, 451, 452 + E: 451, 554, 503 + RSET + S: 250 + VRFY + S: 250, 251, 252 + E: 550, 551, 553, 502, 504 + EXPN + S: 250, 252 + E: 550, 500, 502, 504 + HELP + S: 211, 214 + E: 502, 504 + NOOP + S: 250 + QUIT + S: 221 + +4.4 Trace Information + + When an SMTP server receives a message for delivery or further + processing, it MUST insert trace ("time stamp" or "Received") + information at the beginning of the message content, as discussed in + section 4.1.1.4. + + This line MUST be structured as follows: + + - The FROM field, which MUST be supplied in an SMTP environment, + SHOULD contain both (1) the name of the source host as presented + in the EHLO command and (2) an address literal containing the IP + address of the source, determined from the TCP connection. + + + + +Klensin Standards Track [Page 49] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + - The ID field MAY contain an "@" as suggested in RFC 822, but this + is not required. + + - The FOR field MAY contain a list of entries when multiple + RCPT commands have been given. This may raise some security + issues and is usually not desirable; see section 7.2. + + An Internet mail program MUST NOT change a Received: line that was + previously added to the message header. SMTP servers MUST prepend + Received lines to messages; they MUST NOT change the order of + existing lines or insert Received lines in any other location. + + As the Internet grows, comparability of Received fields is important + for detecting problems, especially slow relays. SMTP servers that + create Received fields SHOULD use explicit offsets in the dates + (e.g., -0800), rather than time zone names of any type. Local time + (with an offset) is preferred to UT when feasible. This formulation + allows slightly more information about local circumstances to be + specified. If UT is needed, the receiver need merely do some simple + arithmetic to convert the values. Use of UT loses information about + the time zone-location of the server. If it is desired to supply a + time zone name, it SHOULD be included in a comment. + + When the delivery SMTP server makes the "final delivery" of a + message, it inserts a return-path line at the beginning of the mail + data. This use of return-path is required; mail systems MUST support + it. The return-path line preserves the information in the from the MAIL command. Here, final delivery means the message + has left the SMTP environment. Normally, this would mean it had been + delivered to the destination user or an associated mail drop, but in + some cases it may be further processed and transmitted by another + mail system. + + It is possible for the mailbox in the return path to be different + from the actual sender's mailbox, for example, if error responses are + to be delivered to a special error handling mailbox rather than to + the message sender. When mailing lists are involved, this + arrangement is common and useful as a means of directing errors to + the list maintainer rather than the message originator. + + The text above implies that the final mail data will begin with a + return path line, followed by one or more time stamp lines. These + lines will be followed by the mail data headers and body [32]. + + It is sometimes difficult for an SMTP server to determine whether or + not it is making final delivery since forwarding or other operations + may occur after the message is accepted for delivery. Consequently, + + + + +Klensin Standards Track [Page 50] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + any further (forwarding, gateway, or relay) systems MAY remove the + return path and rebuild the MAIL command as needed to ensure that + exactly one such line appears in a delivered message. + + A message-originating SMTP system SHOULD NOT send a message that + already contains a Return-path header. SMTP servers performing a + relay function MUST NOT inspect the message data, and especially not + to the extent needed to determine if Return-path headers are present. + SMTP servers making final delivery MAY remove Return-path headers + before adding their own. + + The primary purpose of the Return-path is to designate the address to + which messages indicating non-delivery or other mail system failures + are to be sent. For this to be unambiguous, exactly one return path + SHOULD be present when the message is delivered. Systems using RFC + 822 syntax with non-SMTP transports SHOULD designate an unambiguous + address, associated with the transport envelope, to which error + reports (e.g., non-delivery messages) should be sent. + + Historical note: Text in RFC 822 that appears to contradict the use + of the Return-path header (or the envelope reverse path address from + the MAIL command) as the destination for error messages is not + applicable on the Internet. The reverse path address (as copied into + the Return-path) MUST be used as the target of any mail containing + delivery error messages. + + In particular: + + - a gateway from SMTP->elsewhere SHOULD insert a return-path header, + unless it is known that the "elsewhere" transport also uses + Internet domain addresses and maintains the envelope sender + address separately. + + - a gateway from elsewhere->SMTP SHOULD delete any return-path + header present in the message, and either copy that information to + the SMTP envelope or combine it with information present in the + envelope of the other transport system to construct the reverse + path argument to the MAIL command in the SMTP envelope. + + The server must give special treatment to cases in which the + processing following the end of mail data indication is only + partially successful. This could happen if, after accepting several + recipients and the mail data, the SMTP server finds that the mail + data could be successfully delivered to some, but not all, of the + recipients. In such cases, the response to the DATA command MUST be + an OK reply. However, the SMTP server MUST compose and send an + "undeliverable mail" notification message to the originator of the + message. + + + +Klensin Standards Track [Page 51] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + A single notification listing all of the failed recipients or + separate notification messages MUST be sent for each failed + recipient. For economy of processing by the sender, the former is + preferred when possible. All undeliverable mail notification + messages are sent using the MAIL command (even if they result from + processing the obsolete SEND, SOML, or SAML commands) and use a null + return path as discussed in section 3.7. + + The time stamp line and the return path line are formally defined as + follows: + +Return-path-line = "Return-Path:" FWS Reverse-path + +Time-stamp-line = "Received:" FWS Stamp + +Stamp = From-domain By-domain Opt-info ";" FWS date-time + + ; where "date-time" is as defined in [32] + ; but the "obs-" forms, especially two-digit + ; years, are prohibited in SMTP and MUST NOT be used. + +From-domain = "FROM" FWS Extended-Domain CFWS + +By-domain = "BY" FWS Extended-Domain CFWS + +Extended-Domain = Domain / + ( Domain FWS "(" TCP-info ")" ) / + ( Address-literal FWS "(" TCP-info ")" ) + +TCP-info = Address-literal / ( Domain FWS Address-literal ) + ; Information derived by server from TCP connection + ; not client EHLO. + +Opt-info = [Via] [With] [ID] [For] + +Via = "VIA" FWS Link CFWS + +With = "WITH" FWS Protocol CFWS + +ID = "ID" FWS String / msg-id CFWS + +For = "FOR" FWS 1*( Path / Mailbox ) CFWS + +Link = "TCP" / Addtl-Link +Addtl-Link = Atom + ; Additional standard names for links are registered with the + ; Internet Assigned Numbers Authority (IANA). "Via" is + ; primarily of value with non-Internet transports. SMTP + + + +Klensin Standards Track [Page 52] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + ; servers SHOULD NOT use unregistered names. +Protocol = "ESMTP" / "SMTP" / Attdl-Protocol +Attdl-Protocol = Atom + ; Additional standard names for protocols are registered with the + ; Internet Assigned Numbers Authority (IANA). SMTP servers + ; SHOULD NOT use unregistered names. + +4.5 Additional Implementation Issues + +4.5.1 Minimum Implementation + + In order to make SMTP workable, the following minimum implementation + is required for all receivers. The following commands MUST be + supported to conform to this specification: + + EHLO + HELO + MAIL + RCPT + DATA + RSET + NOOP + QUIT + VRFY + + Any system that includes an SMTP server supporting mail relaying or + delivery MUST support the reserved mailbox "postmaster" as a case- + insensitive local name. This postmaster address is not strictly + necessary if the server always returns 554 on connection opening (as + described in section 3.1). The requirement to accept mail for + postmaster implies that RCPT commands which specify a mailbox for + postmaster at any of the domains for which the SMTP server provides + mail service, as well as the special case of "RCPT TO:" + (with no domain specification), MUST be supported. + + SMTP systems are expected to make every reasonable effort to accept + mail directed to Postmaster from any other system on the Internet. + In extreme cases --such as to contain a denial of service attack or + other breach of security-- an SMTP server may block mail directed to + Postmaster. However, such arrangements SHOULD be narrowly tailored + so as to avoid blocking messages which are not part of such attacks. + +4.5.2 Transparency + + Without some provision for data transparency, the character sequence + "." ends the mail text and cannot be sent by the user. + In general, users are not aware of such "forbidden" sequences. To + + + + +Klensin Standards Track [Page 53] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + allow all user composed text to be transmitted transparently, the + following procedures are used: + + - Before sending a line of mail text, the SMTP client checks the + first character of the line. If it is a period, one additional + period is inserted at the beginning of the line. + + - When a line of mail text is received by the SMTP server, it checks + the line. If the line is composed of a single period, it is + treated as the end of mail indicator. If the first character is a + period and there are other characters on the line, the first + character is deleted. + + The mail data may contain any of the 128 ASCII characters. All + characters are to be delivered to the recipient's mailbox, including + spaces, vertical and horizontal tabs, and other control characters. + If the transmission channel provides an 8-bit byte (octet) data + stream, the 7-bit ASCII codes are transmitted right justified in the + octets, with the high order bits cleared to zero. See 3.7 for + special treatment of these conditions in SMTP systems serving a relay + function. + + In some systems it may be necessary to transform the data as it is + received and stored. This may be necessary for hosts that use a + different character set than ASCII as their local character set, that + store data in records rather than strings, or which use special + character sequences as delimiters inside mailboxes. If such + transformations are necessary, they MUST be reversible, especially if + they are applied to mail being relayed. + +4.5.3 Sizes and Timeouts + +4.5.3.1 Size limits and minimums + + There are several objects that have required minimum/maximum sizes. + Every implementation MUST be able to receive objects of at least + these sizes. Objects larger than these sizes SHOULD be avoided when + possible. However, some Internet mail constructs such as encoded + X.400 addresses [16] will often require larger objects: clients MAY + attempt to transmit these, but MUST be prepared for a server to + reject them if they cannot be handled by it. To the maximum extent + possible, implementation techniques which impose no limits on the + length of these objects should be used. + + local-part + The maximum total length of a user name or other local-part is 64 + characters. + + + + +Klensin Standards Track [Page 54] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + domain + The maximum total length of a domain name or number is 255 + characters. + + path + The maximum total length of a reverse-path or forward-path is 256 + characters (including the punctuation and element separators). + + command line + The maximum total length of a command line including the command + word and the is 512 characters. SMTP extensions may be + used to increase this limit. + + reply line + The maximum total length of a reply line including the reply code + and the is 512 characters. More information may be + conveyed through multiple-line replies. + + text line + The maximum total length of a text line including the is + 1000 characters (not counting the leading dot duplicated for + transparency). This number may be increased by the use of SMTP + Service Extensions. + + message content + The maximum total length of a message content (including any + message headers as well as the message body) MUST BE at least 64K + octets. Since the introduction of Internet standards for + multimedia mail [12], message lengths on the Internet have grown + dramatically, and message size restrictions should be avoided if + at all possible. SMTP server systems that must impose + restrictions SHOULD implement the "SIZE" service extension [18], + and SMTP client systems that will send large messages SHOULD + utilize it when possible. + + recipients buffer + The minimum total number of recipients that must be buffered is + 100 recipients. Rejection of messages (for excessive recipients) + with fewer than 100 RCPT commands is a violation of this + specification. The general principle that relaying SMTP servers + MUST NOT, and delivery SMTP servers SHOULD NOT, perform validation + tests on message headers suggests that rejecting a message based + on the total number of recipients shown in header fields is to be + discouraged. A server which imposes a limit on the number of + recipients MUST behave in an orderly fashion, such as to reject + additional addresses over its limit rather than silently + discarding addresses previously accepted. A client that needs to + + + + +Klensin Standards Track [Page 55] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + deliver a message containing over 100 RCPT commands SHOULD be + prepared to transmit in 100-recipient "chunks" if the server + declines to accept more than 100 recipients in a single message. + + Errors due to exceeding these limits may be reported by using the + reply codes. Some examples of reply codes are: + + 500 Line too long. + or + 501 Path too long + or + 452 Too many recipients (see below) + or + 552 Too much mail data. + + RFC 821 [30] incorrectly listed the error where an SMTP server + exhausts its implementation limit on the number of RCPT commands + ("too many recipients") as having reply code 552. The correct reply + code for this condition is 452. Clients SHOULD treat a 552 code in + this case as a temporary, rather than permanent, failure so the logic + below works. + + When a conforming SMTP server encounters this condition, it has at + least 100 successful RCPT commands in its recipients buffer. If the + server is able to accept the message, then at least these 100 + addresses will be removed from the SMTP client's queue. When the + client attempts retransmission of those addresses which received 452 + responses, at least 100 of these will be able to fit in the SMTP + server's recipients buffer. Each retransmission attempt which is + able to deliver anything will be able to dispose of at least 100 of + these recipients. + + If an SMTP server has an implementation limit on the number of RCPT + commands and this limit is exhausted, it MUST use a response code of + 452 (but the client SHOULD also be prepared for a 552, as noted + above). If the server has a configured site-policy limitation on the + number of RCPT commands, it MAY instead use a 5XX response code. + This would be most appropriate if the policy limitation was intended + to apply if the total recipient count for a particular message body + were enforced even if that message body was sent in multiple mail + transactions. + +4.5.3.2 Timeouts + + An SMTP client MUST provide a timeout mechanism. It MUST use per- + command timeouts rather than somehow trying to time the entire mail + transaction. Timeouts SHOULD be easily reconfigurable, preferably + without recompiling the SMTP code. To implement this, a timer is set + + + +Klensin Standards Track [Page 56] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + for each SMTP command and for each buffer of the data transfer. The + latter means that the overall timeout is inherently proportional to + the size of the message. + + Based on extensive experience with busy mail-relay hosts, the minimum + per-command timeout values SHOULD be as follows: + + Initial 220 Message: 5 minutes + An SMTP client process needs to distinguish between a failed TCP + connection and a delay in receiving the initial 220 greeting + message. Many SMTP servers accept a TCP connection but delay + delivery of the 220 message until their system load permits more + mail to be processed. + + MAIL Command: 5 minutes + + RCPT Command: 5 minutes + A longer timeout is required if processing of mailing lists and + aliases is not deferred until after the message was accepted. + + DATA Initiation: 2 minutes + This is while awaiting the "354 Start Input" reply to a DATA + command. + + Data Block: 3 minutes + This is while awaiting the completion of each TCP SEND call + transmitting a chunk of data. + + DATA Termination: 10 minutes. + This is while awaiting the "250 OK" reply. When the receiver gets + the final period terminating the message data, it typically + performs processing to deliver the message to a user mailbox. A + spurious timeout at this point would be very wasteful and would + typically result in delivery of multiple copies of the message, + since it has been successfully sent and the server has accepted + responsibility for delivery. See section 6.1 for additional + discussion. + + An SMTP server SHOULD have a timeout of at least 5 minutes while it + is awaiting the next command from the sender. + +4.5.4 Retry Strategies + + The common structure of a host SMTP implementation includes user + mailboxes, one or more areas for queuing messages in transit, and one + or more daemon processes for sending and receiving mail. The exact + structure will vary depending on the needs of the users on the host + + + + +Klensin Standards Track [Page 57] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + and the number and size of mailing lists supported by the host. We + describe several optimizations that have proved helpful, particularly + for mailers supporting high traffic levels. + + Any queuing strategy MUST include timeouts on all activities on a + per-command basis. A queuing strategy MUST NOT send error messages + in response to error messages under any circumstances. + +4.5.4.1 Sending Strategy + + The general model for an SMTP client is one or more processes that + periodically attempt to transmit outgoing mail. In a typical system, + the program that composes a message has some method for requesting + immediate attention for a new piece of outgoing mail, while mail that + cannot be transmitted immediately MUST be queued and periodically + retried by the sender. A mail queue entry will include not only the + message itself but also the envelope information. + + The sender MUST delay retrying a particular destination after one + attempt has failed. In general, the retry interval SHOULD be at + least 30 minutes; however, more sophisticated and variable strategies + will be beneficial when the SMTP client can determine the reason for + non-delivery. + + Retries continue until the message is transmitted or the sender gives + up; the give-up time generally needs to be at least 4-5 days. The + parameters to the retry algorithm MUST be configurable. + + A client SHOULD keep a list of hosts it cannot reach and + corresponding connection timeouts, rather than just retrying queued + mail items. + + Experience suggests that failures are typically transient (the target + system or its connection has crashed), favoring a policy of two + connection attempts in the first hour the message is in the queue, + and then backing off to one every two or three hours. + + The SMTP client can shorten the queuing delay in cooperation with the + SMTP server. For example, if mail is received from a particular + address, it is likely that mail queued for that host can now be sent. + Application of this principle may, in many cases, eliminate the + requirement for an explicit "send queues now" function such as ETRN + [9]. + + The strategy may be further modified as a result of multiple + addresses per host (see below) to optimize delivery time vs. resource + usage. + + + + +Klensin Standards Track [Page 58] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + An SMTP client may have a large queue of messages for each + unavailable destination host. If all of these messages were retried + in every retry cycle, there would be excessive Internet overhead and + the sending system would be blocked for a long period. Note that an + SMTP client can generally determine that a delivery attempt has + failed only after a timeout of several minutes and even a one-minute + timeout per connection will result in a very large delay if retries + are repeated for dozens, or even hundreds, of queued messages to the + same host. + + At the same time, SMTP clients SHOULD use great care in caching + negative responses from servers. In an extreme case, if EHLO is + issued multiple times during the same SMTP connection, different + answers may be returned by the server. More significantly, 5yz + responses to the MAIL command MUST NOT be cached. + + When a mail message is to be delivered to multiple recipients, and + the SMTP server to which a copy of the message is to be sent is the + same for multiple recipients, then only one copy of the message + SHOULD be transmitted. That is, the SMTP client SHOULD use the + command sequence: MAIL, RCPT, RCPT,... RCPT, DATA instead of the + sequence: MAIL, RCPT, DATA, ..., MAIL, RCPT, DATA. However, if there + are very many addresses, a limit on the number of RCPT commands per + MAIL command MAY be imposed. Implementation of this efficiency + feature is strongly encouraged. + + Similarly, to achieve timely delivery, the SMTP client MAY support + multiple concurrent outgoing mail transactions. However, some limit + may be appropriate to protect the host from devoting all its + resources to mail. + +4.5.4.2 Receiving Strategy + + The SMTP server SHOULD attempt to keep a pending listen on the SMTP + port at all times. This requires the support of multiple incoming + TCP connections for SMTP. Some limit MAY be imposed but servers that + cannot handle more than one SMTP transaction at a time are not in + conformance with the intent of this specification. + + As discussed above, when the SMTP server receives mail from a + particular host address, it could activate its own SMTP queuing + mechanisms to retry any mail pending for that host address. + +4.5.5 Messages with a null reverse-path + + There are several types of notification messages which are required + by existing and proposed standards to be sent with a null reverse + path, namely non-delivery notifications as discussed in section 3.7, + + + +Klensin Standards Track [Page 59] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + other kinds of Delivery Status Notifications (DSNs) [24], and also + Message Disposition Notifications (MDNs) [10]. All of these kinds of + messages are notifications about a previous message, and they are + sent to the reverse-path of the previous mail message. (If the + delivery of such a notification message fails, that usually indicates + a problem with the mail system of the host to which the notification + message is addressed. For this reason, at some hosts the MTA is set + up to forward such failed notification messages to someone who is + able to fix problems with the mail system, e.g., via the postmaster + alias.) + + All other types of messages (i.e., any message which is not required + by a standards-track RFC to have a null reverse-path) SHOULD be sent + with with a valid, non-null reverse-path. + + Implementors of automated email processors should be careful to make + sure that the various kinds of messages with null reverse-path are + handled correctly, in particular such systems SHOULD NOT reply to + messages with null reverse-path. + +5. Address Resolution and Mail Handling + + Once an SMTP client lexically identifies a domain to which mail will + be delivered for processing (as described in sections 3.6 and 3.7), a + DNS lookup MUST be performed to resolve the domain name [22]. The + names are expected to be fully-qualified domain names (FQDNs): + mechanisms for inferring FQDNs from partial names or local aliases + are outside of this specification and, due to a history of problems, + are generally discouraged. The lookup first attempts to locate an MX + record associated with the name. If a CNAME record is found instead, + the resulting name is processed as if it were the initial name. If + no MX records are found, but an A RR is found, the A RR is treated as + if it was associated with an implicit MX RR, with a preference of 0, + pointing to that host. If one or more MX RRs are found for a given + name, SMTP systems MUST NOT utilize any A RRs associated with that + name unless they are located using the MX RRs; the "implicit MX" rule + above applies only if there are no MX records present. If MX records + are present, but none of them are usable, this situation MUST be + reported as an error. + + When the lookup succeeds, the mapping can result in a list of + alternative delivery addresses rather than a single address, because + of multiple MX records, multihoming, or both. To provide reliable + mail transmission, the SMTP client MUST be able to try (and retry) + each of the relevant addresses in this list in order, until a + delivery attempt succeeds. However, there MAY also be a configurable + limit on the number of alternate addresses that can be tried. In any + case, the SMTP client SHOULD try at least two addresses. + + + +Klensin Standards Track [Page 60] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + Two types of information is used to rank the host addresses: multiple + MX records, and multihomed hosts. + + Multiple MX records contain a preference indication that MUST be used + in sorting (see below). Lower numbers are more preferred than higher + ones. If there are multiple destinations with the same preference + and there is no clear reason to favor one (e.g., by recognition of an + easily-reached address), then the sender-SMTP MUST randomize them to + spread the load across multiple mail exchangers for a specific + organization. + + The destination host (perhaps taken from the preferred MX record) may + be multihomed, in which case the domain name resolver will return a + list of alternative IP addresses. It is the responsibility of the + domain name resolver interface to have ordered this list by + decreasing preference if necessary, and SMTP MUST try them in the + order presented. + + Although the capability to try multiple alternative addresses is + required, specific installations may want to limit or disable the use + of alternative addresses. The question of whether a sender should + attempt retries using the different addresses of a multihomed host + has been controversial. The main argument for using the multiple + addresses is that it maximizes the probability of timely delivery, + and indeed sometimes the probability of any delivery; the counter- + argument is that it may result in unnecessary resource use. Note + that resource use is also strongly determined by the sending strategy + discussed in section 4.5.4.1. + + If an SMTP server receives a message with a destination for which it + is a designated Mail eXchanger, it MAY relay the message (potentially + after having rewritten the MAIL FROM and/or RCPT TO addresses), make + final delivery of the message, or hand it off using some mechanism + outside the SMTP-provided transport environment. Of course, neither + of the latter require that the list of MX records be examined + further. + + If it determines that it should relay the message without rewriting + the address, it MUST sort the MX records to determine candidates for + delivery. The records are first ordered by preference, with the + lowest-numbered records being most preferred. The relay host MUST + then inspect the list for any of the names or addresses by which it + might be known in mail transactions. If a matching record is found, + all records at that preference level and higher-numbered ones MUST be + discarded from consideration. If there are no records left at that + point, it is an error condition, and the message MUST be returned as + undeliverable. If records do remain, they SHOULD be tried, best + preference first, as described above. + + + +Klensin Standards Track [Page 61] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +6. Problem Detection and Handling + +6.1 Reliable Delivery and Replies by Email + + When the receiver-SMTP accepts a piece of mail (by sending a "250 OK" + message in response to DATA), it is accepting responsibility for + delivering or relaying the message. It must take this responsibility + seriously. It MUST NOT lose the message for frivolous reasons, such + as because the host later crashes or because of a predictable + resource shortage. + + If there is a delivery failure after acceptance of a message, the + receiver-SMTP MUST formulate and mail a notification message. This + notification MUST be sent using a null ("<>") reverse path in the + envelope. The recipient of this notification MUST be the address + from the envelope return path (or the Return-Path: line). However, + if this address is null ("<>"), the receiver-SMTP MUST NOT send a + notification. Obviously, nothing in this section can or should + prohibit local decisions (i.e., as part of the same system + environment as the receiver-SMTP) to log or otherwise transmit + information about null address events locally if that is desired. If + the address is an explicit source route, it MUST be stripped down to + its final hop. + + For example, suppose that an error notification must be sent for a + message that arrived with: + + MAIL FROM:<@a,@b:user@d> + + The notification message MUST be sent using: + + RCPT TO: + + Some delivery failures after the message is accepted by SMTP will be + unavoidable. For example, it may be impossible for the receiving + SMTP server to validate all the delivery addresses in RCPT command(s) + due to a "soft" domain system error, because the target is a mailing + list (see earlier discussion of RCPT), or because the server is + acting as a relay and has no immediate access to the delivering + system. + + To avoid receiving duplicate messages as the result of timeouts, a + receiver-SMTP MUST seek to minimize the time required to respond to + the final . end of data indicator. See RFC 1047 [28] for + a discussion of this problem. + + + + + + +Klensin Standards Track [Page 62] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +6.2 Loop Detection + + Simple counting of the number of "Received:" headers in a message has + proven to be an effective, although rarely optimal, method of + detecting loops in mail systems. SMTP servers using this technique + SHOULD use a large rejection threshold, normally at least 100 + Received entries. Whatever mechanisms are used, servers MUST contain + provisions for detecting and stopping trivial loops. + +6.3 Compensating for Irregularities + + Unfortunately, variations, creative interpretations, and outright + violations of Internet mail protocols do occur; some would suggest + that they occur quite frequently. The debate as to whether a well- + behaved SMTP receiver or relay should reject a malformed message, + attempt to pass it on unchanged, or attempt to repair it to increase + the odds of successful delivery (or subsequent reply) began almost + with the dawn of structured network mail and shows no signs of + abating. Advocates of rejection claim that attempted repairs are + rarely completely adequate and that rejection of bad messages is the + only way to get the offending software repaired. Advocates of + "repair" or "deliver no matter what" argue that users prefer that + mail go through it if at all possible and that there are significant + market pressures in that direction. In practice, these market + pressures may be more important to particular vendors than strict + conformance to the standards, regardless of the preference of the + actual developers. + + The problems associated with ill-formed messages were exacerbated by + the introduction of the split-UA mail reading protocols [3, 26, 5, + 21]. These protocols have encouraged the use of SMTP as a posting + protocol, and SMTP servers as relay systems for these client hosts + (which are often only intermittently connected to the Internet). + Historically, many of those client machines lacked some of the + mechanisms and information assumed by SMTP (and indeed, by the mail + format protocol [7]). Some could not keep adequate track of time; + others had no concept of time zones; still others could not identify + their own names or addresses; and, of course, none could satisfy the + assumptions that underlay RFC 822's conception of authenticated + addresses. + + In response to these weak SMTP clients, many SMTP systems now + complete messages that are delivered to them in incomplete or + incorrect form. This strategy is generally considered appropriate + when the server can identify or authenticate the client, and there + are prior agreements between them. By contrast, there is at best + great concern about fixes applied by a relay or delivery SMTP server + that has little or no knowledge of the user or client machine. + + + +Klensin Standards Track [Page 63] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + The following changes to a message being processed MAY be applied + when necessary by an originating SMTP server, or one used as the + target of SMTP as an initial posting protocol: + + - Addition of a message-id field when none appears + + - Addition of a date, time or time zone when none appears + + - Correction of addresses to proper FQDN format + + The less information the server has about the client, the less likely + these changes are to be correct and the more caution and conservatism + should be applied when considering whether or not to perform fixes + and how. These changes MUST NOT be applied by an SMTP server that + provides an intermediate relay function. + + In all cases, properly-operating clients supplying correct + information are preferred to corrections by the SMTP server. In all + cases, documentation of actions performed by the servers (in trace + fields and/or header comments) is strongly encouraged. + +7. Security Considerations + +7.1 Mail Security and Spoofing + + SMTP mail is inherently insecure in that it is feasible for even + fairly casual users to negotiate directly with receiving and relaying + SMTP servers and create messages that will trick a naive recipient + into believing that they came from somewhere else. Constructing such + a message so that the "spoofed" behavior cannot be detected by an + expert is somewhat more difficult, but not sufficiently so as to be a + deterrent to someone who is determined and knowledgeable. + Consequently, as knowledge of Internet mail increases, so does the + knowledge that SMTP mail inherently cannot be authenticated, or + integrity checks provided, at the transport level. Real mail + security lies only in end-to-end methods involving the message + bodies, such as those which use digital signatures (see [14] and, + e.g., PGP [4] or S/MIME [31]). + + Various protocol extensions and configuration options that provide + authentication at the transport level (e.g., from an SMTP client to + an SMTP server) improve somewhat on the traditional situation + described above. However, unless they are accompanied by careful + handoffs of responsibility in a carefully-designed trust environment, + they remain inherently weaker than end-to-end mechanisms which use + digitally signed messages rather than depending on the integrity of + the transport system. + + + + +Klensin Standards Track [Page 64] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + Efforts to make it more difficult for users to set envelope return + path and header "From" fields to point to valid addresses other than + their own are largely misguided: they frustrate legitimate + applications in which mail is sent by one user on behalf of another + or in which error (or normal) replies should be directed to a special + address. (Systems that provide convenient ways for users to alter + these fields on a per-message basis should attempt to establish a + primary and permanent mailbox address for the user so that Sender + fields within the message data can be generated sensibly.) + + This specification does not further address the authentication issues + associated with SMTP other than to advocate that useful functionality + not be disabled in the hope of providing some small margin of + protection against an ignorant user who is trying to fake mail. + +7.2 "Blind" Copies + + Addresses that do not appear in the message headers may appear in the + RCPT commands to an SMTP server for a number of reasons. The two + most common involve the use of a mailing address as a "list exploder" + (a single address that resolves into multiple addresses) and the + appearance of "blind copies". Especially when more than one RCPT + command is present, and in order to avoid defeating some of the + purpose of these mechanisms, SMTP clients and servers SHOULD NOT copy + the full set of RCPT command arguments into the headers, either as + part of trace headers or as informational or private-extension + headers. Since this rule is often violated in practice, and cannot + be enforced, sending SMTP systems that are aware of "bcc" use MAY + find it helpful to send each blind copy as a separate message + transaction containing only a single RCPT command. + + There is no inherent relationship between either "reverse" (from + MAIL, SAML, etc., commands) or "forward" (RCPT) addresses in the SMTP + transaction ("envelope") and the addresses in the headers. Receiving + systems SHOULD NOT attempt to deduce such relationships and use them + to alter the headers of the message for delivery. The popular + "Apparently-to" header is a violation of this principle as well as a + common source of unintended information disclosure and SHOULD NOT be + used. + +7.3 VRFY, EXPN, and Security + + As discussed in section 3.5, individual sites may want to disable + either or both of VRFY or EXPN for security reasons. As a corollary + to the above, implementations that permit this MUST NOT appear to + have verified addresses that are not, in fact, verified. If a site + + + + + +Klensin Standards Track [Page 65] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + disables these commands for security reasons, the SMTP server MUST + return a 252 response, rather than a code that could be confused with + successful or unsuccessful verification. + + Returning a 250 reply code with the address listed in the VRFY + command after having checked it only for syntax violates this rule. + Of course, an implementation that "supports" VRFY by always returning + 550 whether or not the address is valid is equally not in + conformance. + + Within the last few years, the contents of mailing lists have become + popular as an address information source for so-called "spammers." + The use of EXPN to "harvest" addresses has increased as list + administrators have installed protections against inappropriate uses + of the lists themselves. Implementations SHOULD still provide + support for EXPN, but sites SHOULD carefully evaluate the tradeoffs. + As authentication mechanisms are introduced into SMTP, some sites may + choose to make EXPN available only to authenticated requestors. + +7.4 Information Disclosure in Announcements + + There has been an ongoing debate about the tradeoffs between the + debugging advantages of announcing server type and version (and, + sometimes, even server domain name) in the greeting response or in + response to the HELP command and the disadvantages of exposing + information that might be useful in a potential hostile attack. The + utility of the debugging information is beyond doubt. Those who + argue for making it available point out that it is far better to + actually secure an SMTP server rather than hope that trying to + conceal known vulnerabilities by hiding the server's precise identity + will provide more protection. Sites are encouraged to evaluate the + tradeoff with that issue in mind; implementations are strongly + encouraged to minimally provide for making type and version + information available in some way to other network hosts. + +7.5 Information Disclosure in Trace Fields + + In some circumstances, such as when mail originates from within a LAN + whose hosts are not directly on the public Internet, trace + ("Received") fields produced in conformance with this specification + may disclose host names and similar information that would not + normally be available. This ordinarily does not pose a problem, but + sites with special concerns about name disclosure should be aware of + it. Also, the optional FOR clause should be supplied with caution or + not at all when multiple recipients are involved lest it + inadvertently disclose the identities of "blind copy" recipients to + others. + + + + +Klensin Standards Track [Page 66] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +7.6 Information Disclosure in Message Forwarding + + As discussed in section 3.4, use of the 251 or 551 reply codes to + identify the replacement address associated with a mailbox may + inadvertently disclose sensitive information. Sites that are + concerned about those issues should ensure that they select and + configure servers appropriately. + +7.7 Scope of Operation of SMTP Servers + + It is a well-established principle that an SMTP server may refuse to + accept mail for any operational or technical reason that makes sense + to the site providing the server. However, cooperation among sites + and installations makes the Internet possible. If sites take + excessive advantage of the right to reject traffic, the ubiquity of + email availability (one of the strengths of the Internet) will be + threatened; considerable care should be taken and balance maintained + if a site decides to be selective about the traffic it will accept + and process. + + In recent years, use of the relay function through arbitrary sites + has been used as part of hostile efforts to hide the actual origins + of mail. Some sites have decided to limit the use of the relay + function to known or identifiable sources, and implementations SHOULD + provide the capability to perform this type of filtering. When mail + is rejected for these or other policy reasons, a 550 code SHOULD be + used in response to EHLO, MAIL, or RCPT as appropriate. + +8. IANA Considerations + + IANA will maintain three registries in support of this specification. + The first consists of SMTP service extensions with the associated + keywords, and, as needed, parameters and verbs. As specified in + section 2.2.2, no entry may be made in this registry that starts in + an "X". Entries may be made only for service extensions (and + associated keywords, parameters, or verbs) that are defined in + standards-track or experimental RFCs specifically approved by the + IESG for this purpose. + + The second registry consists of "tags" that identify forms of domain + literals other than those for IPv4 addresses (specified in RFC 821 + and in this document) and IPv6 addresses (specified in this + document). Additional literal types require standardization before + being used; none are anticipated at this time. + + The third, established by RFC 821 and renewed by this specification, + is a registry of link and protocol identifiers to be used with the + "via" and "with" subclauses of the time stamp ("Received: header") + + + +Klensin Standards Track [Page 67] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + described in section 4.4. Link and protocol identifiers in addition + to those specified in this document may be registered only by + standardization or by way of an RFC-documented, IESG-approved, + Experimental protocol extension. + +9. References + + [1] American National Standards Institute (formerly United States of + America Standards Institute), X3.4, 1968, "USA Code for + Information Interchange". ANSI X3.4-1968 has been replaced by + newer versions with slight modifications, but the 1968 version + remains definitive for the Internet. + + [2] Braden, R., "Requirements for Internet hosts - application and + support", STD 3, RFC 1123, October 1989. + + [3] Butler, M., Chase, D., Goldberger, J., Postel, J. and J. + Reynolds, "Post Office Protocol - version 2", RFC 937, February + 1985. + + [4] Callas, J., Donnerhacke, L., Finney, H. and R. Thayer, "OpenPGP + Message Format", RFC 2440, November 1998. + + [5] Crispin, M., "Interactive Mail Access Protocol - Version 2", RFC + 1176, August 1990. + + [6] Crispin, M., "Internet Message Access Protocol - Version 4", RFC + 2060, December 1996. + + [7] Crocker, D., "Standard for the Format of ARPA Internet Text + Messages", RFC 822, August 1982. + + [8] Crocker, D. and P. Overell, Eds., "Augmented BNF for Syntax + Specifications: ABNF", RFC 2234, November 1997. + + [9] De Winter, J., "SMTP Service Extension for Remote Message Queue + Starting", RFC 1985, August 1996. + + [10] Fajman, R., "An Extensible Message Format for Message + Disposition Notifications", RFC 2298, March 1998. + + [11] Freed, N, "Behavior of and Requirements for Internet Firewalls", + RFC 2979, October 2000. + + [12] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message Bodies", + RFC 2045, December 1996. + + + + +Klensin Standards Track [Page 68] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + [13] Freed, N., "SMTP Service Extension for Command Pipelining", RFC + 2920, September 2000. + + [14] Galvin, J., Murphy, S., Crocker, S. and N. Freed, "Security + Multiparts for MIME: Multipart/Signed and Multipart/Encrypted", + RFC 1847, October 1995. + + [15] Gellens, R. and J. Klensin, "Message Submission", RFC 2476, + December 1998. + + [16] Kille, S., "Mapping between X.400 and RFC822/MIME", RFC 2156, + January 1998. + + [17] Hinden, R and S. Deering, Eds. "IP Version 6 Addressing + Architecture", RFC 2373, July 1998. + + [18] Klensin, J., Freed, N. and K. Moore, "SMTP Service Extension for + Message Size Declaration", STD 10, RFC 1870, November 1995. + + [19] Klensin, J., Freed, N., Rose, M., Stefferud, E. and D. Crocker, + "SMTP Service Extensions", STD 10, RFC 1869, November 1995. + + [20] Klensin, J., Freed, N., Rose, M., Stefferud, E. and D. Crocker, + "SMTP Service Extension for 8bit-MIMEtransport", RFC 1652, July + 1994. + + [21] Lambert, M., "PCMAIL: A distributed mail system for personal + computers", RFC 1056, July 1988. + + [22] Mockapetris, P., "Domain names - implementation and + specification", STD 13, RFC 1035, November 1987. + + Mockapetris, P., "Domain names - concepts and facilities", STD + 13, RFC 1034, November 1987. + + [23] Moore, K., "MIME (Multipurpose Internet Mail Extensions) Part + Three: Message Header Extensions for Non-ASCII Text", RFC 2047, + December 1996. + + [24] Moore, K., "SMTP Service Extension for Delivery Status + Notifications", RFC 1891, January 1996. + + [25] Moore, K., and G. Vaudreuil, "An Extensible Message Format for + Delivery Status Notifications", RFC 1894, January 1996. + + [26] Myers, J. and M. Rose, "Post Office Protocol - Version 3", STD + 53, RFC 1939, May 1996. + + + + +Klensin Standards Track [Page 69] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + [27] Partridge, C., "Mail routing and the domain system", RFC 974, + January 1986. + + [28] Partridge, C., "Duplicate messages and SMTP", RFC 1047, February + 1988. + + [29] Postel, J., ed., "Transmission Control Protocol - DARPA Internet + Program Protocol Specification", STD 7, RFC 793, September 1981. + + [30] Postel, J., "Simple Mail Transfer Protocol", RFC 821, August + 1982. + + [31] Ramsdell, B., Ed., "S/MIME Version 3 Message Specification", RFC + 2633, June 1999. + + [32] Resnick, P., Ed., "Internet Message Format", RFC 2822, April + 2001. + + [33] Vaudreuil, G., "SMTP Service Extensions for Transmission of + Large and Binary MIME Messages", RFC 1830, August 1995. + + [34] Vaudreuil, G., "Enhanced Mail System Status Codes", RFC 1893, + January 1996. + +10. Editor's Address + + John C. Klensin + AT&T Laboratories + 99 Bedford St + Boston, MA 02111 USA + + Phone: 617-574-3076 + EMail: klensin@research.att.com + +11. Acknowledgments + + Many people worked long and hard on the many iterations of this + document. There was wide-ranging debate in the IETF DRUMS Working + Group, both on its mailing list and in face to face discussions, + about many technical issues and the role of a revised standard for + Internet mail transport, and many contributors helped form the + wording in this specification. The hundreds of participants in the + many discussions since RFC 821 was produced are too numerous to + mention, but they all helped this document become what it is. + + + + + + + +Klensin Standards Track [Page 70] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +APPENDICES + +A. TCP Transport Service + + The TCP connection supports the transmission of 8-bit bytes. The + SMTP data is 7-bit ASCII characters. Each character is transmitted + as an 8-bit byte with the high-order bit cleared to zero. Service + extensions may modify this rule to permit transmission of full 8-bit + data bytes as part of the message body, but not in SMTP commands or + responses. + +B. Generating SMTP Commands from RFC 822 Headers + + Some systems use RFC 822 headers (only) in a mail submission + protocol, or otherwise generate SMTP commands from RFC 822 headers + when such a message is handed to an MTA from a UA. While the MTA-UA + protocol is a private matter, not covered by any Internet Standard, + there are problems with this approach. For example, there have been + repeated problems with proper handling of "bcc" copies and + redistribution lists when information that conceptually belongs to a + mail envelopes is not separated early in processing from header + information (and kept separate). + + It is recommended that the UA provide its initial ("submission + client") MTA with an envelope separate from the message itself. + However, if the envelope is not supplied, SMTP commands SHOULD be + generated as follows: + + 1. Each recipient address from a TO, CC, or BCC header field SHOULD + be copied to a RCPT command (generating multiple message copies if + that is required for queuing or delivery). This includes any + addresses listed in a RFC 822 "group". Any BCC fields SHOULD then + be removed from the headers. Once this process is completed, the + remaining headers SHOULD be checked to verify that at least one + To:, Cc:, or Bcc: header remains. If none do, then a bcc: header + with no additional information SHOULD be inserted as specified in + [32]. + + 2. The return address in the MAIL command SHOULD, if possible, be + derived from the system's identity for the submitting (local) + user, and the "From:" header field otherwise. If there is a + system identity available, it SHOULD also be copied to the Sender + header field if it is different from the address in the From + header field. (Any Sender field that was already there SHOULD be + removed.) Systems may provide a way for submitters to override + the envelope return address, but may want to restrict its use to + privileged users. This will not prevent mail forgery, but may + lessen its incidence; see section 7.1. + + + +Klensin Standards Track [Page 71] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + When an MTA is being used in this way, it bears responsibility for + ensuring that the message being transmitted is valid. The mechanisms + for checking that validity, and for handling (or returning) messages + that are not valid at the time of arrival, are part of the MUA-MTA + interface and not covered by this specification. + + A submission protocol based on Standard RFC 822 information alone + MUST NOT be used to gateway a message from a foreign (non-SMTP) mail + system into an SMTP environment. Additional information to construct + an envelope must come from some source in the other environment, + whether supplemental headers or the foreign system's envelope. + + Attempts to gateway messages using only their header "to" and "cc" + fields have repeatedly caused mail loops and other behavior adverse + to the proper functioning of the Internet mail environment. These + problems have been especially common when the message originates from + an Internet mailing list and is distributed into the foreign + environment using envelope information. When these messages are then + processed by a header-only remailer, loops back to the Internet + environment (and the mailing list) are almost inevitable. + +C. Source Routes + + Historically, the was a reverse source routing list of + hosts and a source mailbox. The first host in the + SHOULD be the host sending the MAIL command. Similarly, the + may be a source routing lists of hosts and a + destination mailbox. However, in general, the SHOULD + contain only a mailbox and domain name, relying on the domain name + system to supply routing information if required. The use of source + routes is deprecated; while servers MUST be prepared to receive and + handle them as discussed in section 3.3 and F.2, clients SHOULD NOT + transmit them and this section was included only to provide context. + + For relay purposes, the forward-path may be a source route of the + form "@ONE,@TWO:JOE@THREE", where ONE, TWO, and THREE MUST BE fully- + qualified domain names. This form is used to emphasize the + distinction between an address and a route. The mailbox is an + absolute address, and the route is information about how to get + there. The two concepts should not be confused. + + If source routes are used, RFC 821 and the text below should be + consulted for the mechanisms for constructing and updating the + forward- and reverse-paths. + + + + + + + +Klensin Standards Track [Page 72] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + The SMTP server transforms the command arguments by moving its own + identifier (its domain name or that of any domain for which it is + acting as a mail exchanger), if it appears, from the forward-path to + the beginning of the reverse-path. + + Notice that the forward-path and reverse-path appear in the SMTP + commands and replies, but not necessarily in the message. That is, + there is no need for these paths and especially this syntax to appear + in the "To:" , "From:", "CC:", etc. fields of the message header. + Conversely, SMTP servers MUST NOT derive final message delivery + information from message header fields. + + When the list of hosts is present, it is a "reverse" source route and + indicates that the mail was relayed through each host on the list + (the first host in the list was the most recent relay). This list is + used as a source route to return non-delivery notices to the sender. + As each relay host adds itself to the beginning of the list, it MUST + use its name as known in the transport environment to which it is + relaying the mail rather than that of the transport environment from + which the mail came (if they are different). + +D. Scenarios + + This section presents complete scenarios of several types of SMTP + sessions. In the examples, "C:" indicates what is said by the SMTP + client, and "S:" indicates what is said by the SMTP server. + +D.1 A Typical SMTP Transaction Scenario + + This SMTP example shows mail sent by Smith at host bar.com, to Jones, + Green, and Brown at host foo.com. Here we assume that host bar.com + contacts host foo.com directly. The mail is accepted for Jones and + Brown. Green does not have a mailbox at host foo.com. + + S: 220 foo.com Simple Mail Transfer Service Ready + C: EHLO bar.com + S: 250-foo.com greets bar.com + S: 250-8BITMIME + S: 250-SIZE + S: 250-DSN + S: 250 HELP + C: MAIL FROM: + S: 250 OK + C: RCPT TO: + S: 250 OK + C: RCPT TO: + S: 550 No such user here + C: RCPT TO: + + + +Klensin Standards Track [Page 73] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + S: 250 OK + C: DATA + S: 354 Start mail input; end with . + C: Blah blah blah... + C: ...etc. etc. etc. + C: . + S: 250 OK + C: QUIT + S: 221 foo.com Service closing transmission channel + +D.2 Aborted SMTP Transaction Scenario + + S: 220 foo.com Simple Mail Transfer Service Ready + C: EHLO bar.com + S: 250-foo.com greets bar.com + S: 250-8BITMIME + S: 250-SIZE + S: 250-DSN + S: 250 HELP + C: MAIL FROM: + S: 250 OK + C: RCPT TO: + S: 250 OK + C: RCPT TO: + S: 550 No such user here + C: RSET + S: 250 OK + C: QUIT + S: 221 foo.com Service closing transmission channel + +D.3 Relayed Mail Scenario + + Step 1 -- Source Host to Relay Host + + S: 220 foo.com Simple Mail Transfer Service Ready + C: EHLO bar.com + S: 250-foo.com greets bar.com + S: 250-8BITMIME + S: 250-SIZE + S: 250-DSN + S: 250 HELP + C: MAIL FROM: + S: 250 OK + C: RCPT TO:<@foo.com:Jones@XYZ.COM> + S: 250 OK + C: DATA + S: 354 Start mail input; end with . + C: Date: Thu, 21 May 1998 05:33:29 -0700 + + + +Klensin Standards Track [Page 74] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + C: From: John Q. Public + C: Subject: The Next Meeting of the Board + C: To: Jones@xyz.com + C: + C: Bill: + C: The next meeting of the board of directors will be + C: on Tuesday. + C: John. + C: . + S: 250 OK + C: QUIT + S: 221 foo.com Service closing transmission channel + + Step 2 -- Relay Host to Destination Host + + S: 220 xyz.com Simple Mail Transfer Service Ready + C: EHLO foo.com + S: 250 xyz.com is on the air + C: MAIL FROM:<@foo.com:JQP@bar.com> + S: 250 OK + C: RCPT TO: + S: 250 OK + C: DATA + S: 354 Start mail input; end with . + C: Received: from bar.com by foo.com ; Thu, 21 May 1998 + C: 05:33:29 -0700 + C: Date: Thu, 21 May 1998 05:33:22 -0700 + C: From: John Q. Public + C: Subject: The Next Meeting of the Board + C: To: Jones@xyz.com + C: + C: Bill: + C: The next meeting of the board of directors will be + C: on Tuesday. + C: John. + C: . + S: 250 OK + C: QUIT + S: 221 foo.com Service closing transmission channel + +D.4 Verifying and Sending Scenario + + S: 220 foo.com Simple Mail Transfer Service Ready + C: EHLO bar.com + S: 250-foo.com greets bar.com + S: 250-8BITMIME + S: 250-SIZE + S: 250-DSN + + + +Klensin Standards Track [Page 75] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + + S: 250-VRFY + S: 250 HELP + C: VRFY Crispin + S: 250 Mark Crispin + C: SEND FROM: + S: 250 OK + C: RCPT TO: + S: 250 OK + C: DATA + S: 354 Start mail input; end with . + C: Blah blah blah... + C: ...etc. etc. etc. + C: . + S: 250 OK + C: QUIT + S: 221 foo.com Service closing transmission channel + +E. Other Gateway Issues + + In general, gateways between the Internet and other mail systems + SHOULD attempt to preserve any layering semantics across the + boundaries between the two mail systems involved. Gateway- + translation approaches that attempt to take shortcuts by mapping, + (such as envelope information from one system to the message headers + or body of another) have generally proven to be inadequate in + important ways. Systems translating between environments that do not + support both envelopes and headers and Internet mail must be written + with the understanding that some information loss is almost + inevitable. + +F. Deprecated Features of RFC 821 + + A few features of RFC 821 have proven to be problematic and SHOULD + NOT be used in Internet mail. + +F.1 TURN + + This command, described in RFC 821, raises important security issues + since, in the absence of strong authentication of the host requesting + that the client and server switch roles, it can easily be used to + divert mail from its correct destination. Its use is deprecated; + SMTP systems SHOULD NOT use it unless the server can authenticate the + client. + + + + + + + + +Klensin Standards Track [Page 76] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +F.2 Source Routing + + RFC 821 utilized the concept of explicit source routing to get mail + from one host to another via a series of relays. The requirement to + utilize source routes in regular mail traffic was eliminated by the + introduction of the domain name system "MX" record and the last + significant justification for them was eliminated by the + introduction, in RFC 1123, of a clear requirement that addresses + following an "@" must all be fully-qualified domain names. + Consequently, the only remaining justifications for the use of source + routes are support for very old SMTP clients or MUAs and in mail + system debugging. They can, however, still be useful in the latter + circumstance and for routing mail around serious, but temporary, + problems such as problems with the relevant DNS records. + + SMTP servers MUST continue to accept source route syntax as specified + in the main body of this document and in RFC 1123. They MAY, if + necessary, ignore the routes and utilize only the target domain in + the address. If they do utilize the source route, the message MUST + be sent to the first domain shown in the address. In particular, a + server MUST NOT guess at shortcuts within the source route. + + Clients SHOULD NOT utilize explicit source routing except under + unusual circumstances, such as debugging or potentially relaying + around firewall or mail system configuration errors. + +F.3 HELO + + As discussed in sections 3.1 and 4.1.1, EHLO is strongly preferred to + HELO when the server will accept the former. Servers must continue + to accept and process HELO in order to support older clients. + +F.4 #-literals + + RFC 821 provided for specifying an Internet address as a decimal + integer host number prefixed by a pound sign, "#". In practice, that + form has been obsolete since the introduction of TCP/IP. It is + deprecated and MUST NOT be used. + +F.5 Dates and Years + + When dates are inserted into messages by SMTP clients or servers + (e.g., in trace fields), four-digit years MUST BE used. Two-digit + years are deprecated; three-digit years were never permitted in the + Internet mail system. + + + + + + +Klensin Standards Track [Page 77] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +F.6 Sending versus Mailing + + In addition to specifying a mechanism for delivering messages to + user's mailboxes, RFC 821 provided additional, optional, commands to + deliver messages directly to the user's terminal screen. These + commands (SEND, SAML, SOML) were rarely implemented, and changes in + workstation technology and the introduction of other protocols may + have rendered them obsolete even where they are implemented. + + Clients SHOULD NOT provide SEND, SAML, or SOML as services. Servers + MAY implement them. If they are implemented by servers, the + implementation model specified in RFC 821 MUST be used and the + command names MUST be published in the response to the EHLO command. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Klensin Standards Track [Page 78] + +RFC 2821 Simple Mail Transfer Protocol April 2001 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2001). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + + + + + + + + + + + + + +Klensin Standards Track [Page 79] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2822.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2822.txt new file mode 100644 index 00000000..9f698f77 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc2822.txt @@ -0,0 +1,2859 @@ + + + + + + +Network Working Group P. Resnick, Editor +Request for Comments: 2822 QUALCOMM Incorporated +Obsoletes: 822 April 2001 +Category: Standards Track + + + Internet Message Format + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2001). All Rights Reserved. + +Abstract + + This standard specifies a syntax for text messages that are sent + between computer users, within the framework of "electronic mail" + messages. This standard supersedes the one specified in Request For + Comments (RFC) 822, "Standard for the Format of ARPA Internet Text + Messages", updating it to reflect current practice and incorporating + incremental changes that were specified in other RFCs. + +Table of Contents + + 1. Introduction ............................................... 3 + 1.1. Scope .................................................... 3 + 1.2. Notational conventions ................................... 4 + 1.2.1. Requirements notation .................................. 4 + 1.2.2. Syntactic notation ..................................... 4 + 1.3. Structure of this document ............................... 4 + 2. Lexical Analysis of Messages ............................... 5 + 2.1. General Description ...................................... 5 + 2.1.1. Line Length Limits ..................................... 6 + 2.2. Header Fields ............................................ 7 + 2.2.1. Unstructured Header Field Bodies ....................... 7 + 2.2.2. Structured Header Field Bodies ......................... 7 + 2.2.3. Long Header Fields ..................................... 7 + 2.3. Body ..................................................... 8 + 3. Syntax ..................................................... 9 + 3.1. Introduction ............................................. 9 + 3.2. Lexical Tokens ........................................... 9 + + + +Resnick Standards Track [Page 1] + +RFC 2822 Internet Message Format April 2001 + + + 3.2.1. Primitive Tokens ....................................... 9 + 3.2.2. Quoted characters ......................................10 + 3.2.3. Folding white space and comments .......................11 + 3.2.4. Atom ...................................................12 + 3.2.5. Quoted strings .........................................13 + 3.2.6. Miscellaneous tokens ...................................13 + 3.3. Date and Time Specification ..............................14 + 3.4. Address Specification ....................................15 + 3.4.1. Addr-spec specification ................................16 + 3.5 Overall message syntax ....................................17 + 3.6. Field definitions ........................................18 + 3.6.1. The origination date field .............................20 + 3.6.2. Originator fields ......................................21 + 3.6.3. Destination address fields .............................22 + 3.6.4. Identification fields ..................................23 + 3.6.5. Informational fields ...................................26 + 3.6.6. Resent fields ..........................................26 + 3.6.7. Trace fields ...........................................28 + 3.6.8. Optional fields ........................................29 + 4. Obsolete Syntax ............................................29 + 4.1. Miscellaneous obsolete tokens ............................30 + 4.2. Obsolete folding white space .............................31 + 4.3. Obsolete Date and Time ...................................31 + 4.4. Obsolete Addressing ......................................33 + 4.5. Obsolete header fields ...................................33 + 4.5.1. Obsolete origination date field ........................34 + 4.5.2. Obsolete originator fields .............................34 + 4.5.3. Obsolete destination address fields ....................34 + 4.5.4. Obsolete identification fields .........................35 + 4.5.5. Obsolete informational fields ..........................35 + 4.5.6. Obsolete resent fields .................................35 + 4.5.7. Obsolete trace fields ..................................36 + 4.5.8. Obsolete optional fields ...............................36 + 5. Security Considerations ....................................36 + 6. Bibliography ...............................................37 + 7. Editor's Address ...........................................38 + 8. Acknowledgements ...........................................39 + Appendix A. Example messages ..................................41 + A.1. Addressing examples ......................................41 + A.1.1. A message from one person to another with simple + addressing .............................................41 + A.1.2. Different types of mailboxes ...........................42 + A.1.3. Group addresses ........................................43 + A.2. Reply messages ...........................................43 + A.3. Resent messages ..........................................44 + A.4. Messages with trace fields ...............................46 + A.5. White space, comments, and other oddities ................47 + A.6. Obsoleted forms ..........................................47 + + + +Resnick Standards Track [Page 2] + +RFC 2822 Internet Message Format April 2001 + + + A.6.1. Obsolete addressing ....................................48 + A.6.2. Obsolete dates .........................................48 + A.6.3. Obsolete white space and comments ......................48 + Appendix B. Differences from earlier standards ................49 + Appendix C. Notices ...........................................50 + Full Copyright Statement ......................................51 + +1. Introduction + +1.1. Scope + + This standard specifies a syntax for text messages that are sent + between computer users, within the framework of "electronic mail" + messages. This standard supersedes the one specified in Request For + Comments (RFC) 822, "Standard for the Format of ARPA Internet Text + Messages" [RFC822], updating it to reflect current practice and + incorporating incremental changes that were specified in other RFCs + [STD3]. + + This standard specifies a syntax only for text messages. In + particular, it makes no provision for the transmission of images, + audio, or other sorts of structured data in electronic mail messages. + There are several extensions published, such as the MIME document + series [RFC2045, RFC2046, RFC2049], which describe mechanisms for the + transmission of such data through electronic mail, either by + extending the syntax provided here or by structuring such messages to + conform to this syntax. Those mechanisms are outside of the scope of + this standard. + + In the context of electronic mail, messages are viewed as having an + envelope and contents. The envelope contains whatever information is + needed to accomplish transmission and delivery. (See [RFC2821] for a + discussion of the envelope.) The contents comprise the object to be + delivered to the recipient. This standard applies only to the format + and some of the semantics of message contents. It contains no + specification of the information in the envelope. + + However, some message systems may use information from the contents + to create the envelope. It is intended that this standard facilitate + the acquisition of such information by programs. + + This specification is intended as a definition of what message + content format is to be passed between systems. Though some message + systems locally store messages in this format (which eliminates the + need for translation between formats) and others use formats that + differ from the one specified in this standard, local storage is + outside of the scope of this standard. + + + + +Resnick Standards Track [Page 3] + +RFC 2822 Internet Message Format April 2001 + + + Note: This standard is not intended to dictate the internal formats + used by sites, the specific message system features that they are + expected to support, or any of the characteristics of user interface + programs that create or read messages. In addition, this standard + does not specify an encoding of the characters for either transport + or storage; that is, it does not specify the number of bits used or + how those bits are specifically transferred over the wire or stored + on disk. + +1.2. Notational conventions + +1.2.1. Requirements notation + + This document occasionally uses terms that appear in capital letters. + When the terms "MUST", "SHOULD", "RECOMMENDED", "MUST NOT", "SHOULD + NOT", and "MAY" appear capitalized, they are being used to indicate + particular requirements of this specification. A discussion of the + meanings of these terms appears in [RFC2119]. + +1.2.2. Syntactic notation + + This standard uses the Augmented Backus-Naur Form (ABNF) notation + specified in [RFC2234] for the formal definitions of the syntax of + messages. Characters will be specified either by a decimal value + (e.g., the value %d65 for uppercase A and %d97 for lowercase A) or by + a case-insensitive literal value enclosed in quotation marks (e.g., + "A" for either uppercase or lowercase A). See [RFC2234] for the full + description of the notation. + +1.3. Structure of this document + + This document is divided into several sections. + + This section, section 1, is a short introduction to the document. + + Section 2 lays out the general description of a message and its + constituent parts. This is an overview to help the reader understand + some of the general principles used in the later portions of this + document. Any examples in this section MUST NOT be taken as + specification of the formal syntax of any part of a message. + + Section 3 specifies formal ABNF rules for the structure of each part + of a message (the syntax) and describes the relationship between + those parts and their meaning in the context of a message (the + semantics). That is, it describes the actual rules for the structure + of each part of a message (the syntax) as well as a description of + the parts and instructions on how they ought to be interpreted (the + semantics). This includes analysis of the syntax and semantics of + + + +Resnick Standards Track [Page 4] + +RFC 2822 Internet Message Format April 2001 + + + subparts of messages that have specific structure. The syntax + included in section 3 represents messages as they MUST be created. + There are also notes in section 3 to indicate if any of the options + specified in the syntax SHOULD be used over any of the others. + + Both sections 2 and 3 describe messages that are legal to generate + for purposes of this standard. + + Section 4 of this document specifies an "obsolete" syntax. There are + references in section 3 to these obsolete syntactic elements. The + rules of the obsolete syntax are elements that have appeared in + earlier revisions of this standard or have previously been widely + used in Internet messages. As such, these elements MUST be + interpreted by parsers of messages in order to be conformant to this + standard. However, since items in this syntax have been determined + to be non-interoperable or to cause significant problems for + recipients of messages, they MUST NOT be generated by creators of + conformant messages. + + Section 5 details security considerations to take into account when + implementing this standard. + + Section 6 is a bibliography of references in this document. + + Section 7 contains the editor's address. + + Section 8 contains acknowledgements. + + Appendix A lists examples of different sorts of messages. These + examples are not exhaustive of the types of messages that appear on + the Internet, but give a broad overview of certain syntactic forms. + + Appendix B lists the differences between this standard and earlier + standards for Internet messages. + + Appendix C has copyright and intellectual property notices. + +2. Lexical Analysis of Messages + +2.1. General Description + + At the most basic level, a message is a series of characters. A + message that is conformant with this standard is comprised of + characters with values in the range 1 through 127 and interpreted as + US-ASCII characters [ASCII]. For brevity, this document sometimes + refers to this range of characters as simply "US-ASCII characters". + + + + + +Resnick Standards Track [Page 5] + +RFC 2822 Internet Message Format April 2001 + + + Note: This standard specifies that messages are made up of characters + in the US-ASCII range of 1 through 127. There are other documents, + specifically the MIME document series [RFC2045, RFC2046, RFC2047, + RFC2048, RFC2049], that extend this standard to allow for values + outside of that range. Discussion of those mechanisms is not within + the scope of this standard. + + Messages are divided into lines of characters. A line is a series of + characters that is delimited with the two characters carriage-return + and line-feed; that is, the carriage return (CR) character (ASCII + value 13) followed immediately by the line feed (LF) character (ASCII + value 10). (The carriage-return/line-feed pair is usually written in + this document as "CRLF".) + + A message consists of header fields (collectively called "the header + of the message") followed, optionally, by a body. The header is a + sequence of lines of characters with special syntax as defined in + this standard. The body is simply a sequence of characters that + follows the header and is separated from the header by an empty line + (i.e., a line with nothing preceding the CRLF). + +2.1.1. Line Length Limits + + There are two limits that this standard places on the number of + characters in a line. Each line of characters MUST be no more than + 998 characters, and SHOULD be no more than 78 characters, excluding + the CRLF. + + The 998 character limit is due to limitations in many implementations + which send, receive, or store Internet Message Format messages that + simply cannot handle more than 998 characters on a line. Receiving + implementations would do well to handle an arbitrarily large number + of characters in a line for robustness sake. However, there are so + many implementations which (in compliance with the transport + requirements of [RFC2821]) do not accept messages containing more + than 1000 character including the CR and LF per line, it is important + for implementations not to create such messages. + + The more conservative 78 character recommendation is to accommodate + the many implementations of user interfaces that display these + messages which may truncate, or disastrously wrap, the display of + more than 78 characters per line, in spite of the fact that such + implementations are non-conformant to the intent of this + specification (and that of [RFC2821] if they actually cause + information to be lost). Again, even though this limitation is put on + messages, it is encumbant upon implementations which display messages + + + + + +Resnick Standards Track [Page 6] + +RFC 2822 Internet Message Format April 2001 + + + to handle an arbitrarily large number of characters in a line + (certainly at least up to the 998 character limit) for the sake of + robustness. + +2.2. Header Fields + + Header fields are lines composed of a field name, followed by a colon + (":"), followed by a field body, and terminated by CRLF. A field + name MUST be composed of printable US-ASCII characters (i.e., + characters that have values between 33 and 126, inclusive), except + colon. A field body may be composed of any US-ASCII characters, + except for CR and LF. However, a field body may contain CRLF when + used in header "folding" and "unfolding" as described in section + 2.2.3. All field bodies MUST conform to the syntax described in + sections 3 and 4 of this standard. + +2.2.1. Unstructured Header Field Bodies + + Some field bodies in this standard are defined simply as + "unstructured" (which is specified below as any US-ASCII characters, + except for CR and LF) with no further restrictions. These are + referred to as unstructured field bodies. Semantically, unstructured + field bodies are simply to be treated as a single line of characters + with no further processing (except for header "folding" and + "unfolding" as described in section 2.2.3). + +2.2.2. Structured Header Field Bodies + + Some field bodies in this standard have specific syntactical + structure more restrictive than the unstructured field bodies + described above. These are referred to as "structured" field bodies. + Structured field bodies are sequences of specific lexical tokens as + described in sections 3 and 4 of this standard. Many of these tokens + are allowed (according to their syntax) to be introduced or end with + comments (as described in section 3.2.3) as well as the space (SP, + ASCII value 32) and horizontal tab (HTAB, ASCII value 9) characters + (together known as the white space characters, WSP), and those WSP + characters are subject to header "folding" and "unfolding" as + described in section 2.2.3. Semantic analysis of structured field + bodies is given along with their syntax. + +2.2.3. Long Header Fields + + Each header field is logically a single line of characters comprising + the field name, the colon, and the field body. For convenience + however, and to deal with the 998/78 character limitations per line, + the field body portion of a header field can be split into a multiple + line representation; this is called "folding". The general rule is + + + +Resnick Standards Track [Page 7] + +RFC 2822 Internet Message Format April 2001 + + + that wherever this standard allows for folding white space (not + simply WSP characters), a CRLF may be inserted before any WSP. For + example, the header field: + + Subject: This is a test + + can be represented as: + + Subject: This + is a test + + Note: Though structured field bodies are defined in such a way that + folding can take place between many of the lexical tokens (and even + within some of the lexical tokens), folding SHOULD be limited to + placing the CRLF at higher-level syntactic breaks. For instance, if + a field body is defined as comma-separated values, it is recommended + that folding occur after the comma separating the structured items in + preference to other places where the field could be folded, even if + it is allowed elsewhere. + + The process of moving from this folded multiple-line representation + of a header field to its single line representation is called + "unfolding". Unfolding is accomplished by simply removing any CRLF + that is immediately followed by WSP. Each header field should be + treated in its unfolded form for further syntactic and semantic + evaluation. + +2.3. Body + + The body of a message is simply lines of US-ASCII characters. The + only two limitations on the body are as follows: + + - CR and LF MUST only occur together as CRLF; they MUST NOT appear + independently in the body. + + - Lines of characters in the body MUST be limited to 998 characters, + and SHOULD be limited to 78 characters, excluding the CRLF. + + Note: As was stated earlier, there are other standards documents, + specifically the MIME documents [RFC2045, RFC2046, RFC2048, RFC2049] + that extend this standard to allow for different sorts of message + bodies. Again, these mechanisms are beyond the scope of this + document. + + + + + + + + +Resnick Standards Track [Page 8] + +RFC 2822 Internet Message Format April 2001 + + +3. Syntax + +3.1. Introduction + + The syntax as given in this section defines the legal syntax of + Internet messages. Messages that are conformant to this standard + MUST conform to the syntax in this section. If there are options in + this section where one option SHOULD be generated, that is indicated + either in the prose or in a comment next to the syntax. + + For the defined expressions, a short description of the syntax and + use is given, followed by the syntax in ABNF, followed by a semantic + analysis. Primitive tokens that are used but otherwise unspecified + come from [RFC2234]. + + In some of the definitions, there will be nonterminals whose names + start with "obs-". These "obs-" elements refer to tokens defined in + the obsolete syntax in section 4. In all cases, these productions + are to be ignored for the purposes of generating legal Internet + messages and MUST NOT be used as part of such a message. However, + when interpreting messages, these tokens MUST be honored as part of + the legal syntax. In this sense, section 3 defines a grammar for + generation of messages, with "obs-" elements that are to be ignored, + while section 4 adds grammar for interpretation of messages. + +3.2. Lexical Tokens + + The following rules are used to define an underlying lexical + analyzer, which feeds tokens to the higher-level parsers. This + section defines the tokens used in structured header field bodies. + + Note: Readers of this standard need to pay special attention to how + these lexical tokens are used in both the lower-level and + higher-level syntax later in the document. Particularly, the white + space tokens and the comment tokens defined in section 3.2.3 get used + in the lower-level tokens defined here, and those lower-level tokens + are in turn used as parts of the higher-level tokens defined later. + Therefore, the white space and comments may be allowed in the + higher-level tokens even though they may not explicitly appear in a + particular definition. + +3.2.1. Primitive Tokens + + The following are primitive tokens referred to elsewhere in this + standard, but not otherwise defined in [RFC2234]. Some of them will + not appear anywhere else in the syntax, but they are convenient to + refer to in other parts of this document. + + + + +Resnick Standards Track [Page 9] + +RFC 2822 Internet Message Format April 2001 + + + Note: The "specials" below are just such an example. Though the + specials token does not appear anywhere else in this standard, it is + useful for implementers who use tools that lexically analyze + messages. Each of the characters in specials can be used to indicate + a tokenization point in lexical analysis. + +NO-WS-CTL = %d1-8 / ; US-ASCII control characters + %d11 / ; that do not include the + %d12 / ; carriage return, line feed, + %d14-31 / ; and white space characters + %d127 + +text = %d1-9 / ; Characters excluding CR and LF + %d11 / + %d12 / + %d14-127 / + obs-text + +specials = "(" / ")" / ; Special characters used in + "<" / ">" / ; other parts of the syntax + "[" / "]" / + ":" / ";" / + "@" / "\" / + "," / "." / + DQUOTE + + No special semantics are attached to these tokens. They are simply + single characters. + +3.2.2. Quoted characters + + Some characters are reserved for special interpretation, such as + delimiting lexical tokens. To permit use of these characters as + uninterpreted data, a quoting mechanism is provided. + +quoted-pair = ("\" text) / obs-qp + + Where any quoted-pair appears, it is to be interpreted as the text + character alone. That is to say, the "\" character that appears as + part of a quoted-pair is semantically "invisible". + + Note: The "\" character may appear in a message where it is not part + of a quoted-pair. A "\" character that does not appear in a + quoted-pair is not semantically invisible. The only places in this + standard where quoted-pair currently appears are ccontent, qcontent, + dcontent, no-fold-quote, and no-fold-literal. + + + + + +Resnick Standards Track [Page 10] + +RFC 2822 Internet Message Format April 2001 + + +3.2.3. Folding white space and comments + + White space characters, including white space used in folding + (described in section 2.2.3), may appear between many elements in + header field bodies. Also, strings of characters that are treated as + comments may be included in structured field bodies as characters + enclosed in parentheses. The following defines the folding white + space (FWS) and comment constructs. + + Strings of characters enclosed in parentheses are considered comments + so long as they do not appear within a "quoted-string", as defined in + section 3.2.5. Comments may nest. + + There are several places in this standard where comments and FWS may + be freely inserted. To accommodate that syntax, an additional token + for "CFWS" is defined for places where comments and/or FWS can occur. + However, where CFWS occurs in this standard, it MUST NOT be inserted + in such a way that any line of a folded header field is made up + entirely of WSP characters and nothing else. + +FWS = ([*WSP CRLF] 1*WSP) / ; Folding white space + obs-FWS + +ctext = NO-WS-CTL / ; Non white space controls + + %d33-39 / ; The rest of the US-ASCII + %d42-91 / ; characters not including "(", + %d93-126 ; ")", or "\" + +ccontent = ctext / quoted-pair / comment + +comment = "(" *([FWS] ccontent) [FWS] ")" + +CFWS = *([FWS] comment) (([FWS] comment) / FWS) + + Throughout this standard, where FWS (the folding white space token) + appears, it indicates a place where header folding, as discussed in + section 2.2.3, may take place. Wherever header folding appears in a + message (that is, a header field body containing a CRLF followed by + any WSP), header unfolding (removal of the CRLF) is performed before + any further lexical analysis is performed on that header field + according to this standard. That is to say, any CRLF that appears in + FWS is semantically "invisible." + + A comment is normally used in a structured field body to provide some + human readable informational text. Since a comment is allowed to + contain FWS, folding is permitted within the comment. Also note that + since quoted-pair is allowed in a comment, the parentheses and + + + +Resnick Standards Track [Page 11] + +RFC 2822 Internet Message Format April 2001 + + + backslash characters may appear in a comment so long as they appear + as a quoted-pair. Semantically, the enclosing parentheses are not + part of the comment; the comment is what is contained between the two + parentheses. As stated earlier, the "\" in any quoted-pair and the + CRLF in any FWS that appears within the comment are semantically + "invisible" and therefore not part of the comment either. + + Runs of FWS, comment or CFWS that occur between lexical tokens in a + structured field header are semantically interpreted as a single + space character. + +3.2.4. Atom + + Several productions in structured header field bodies are simply + strings of certain basic characters. Such productions are called + atoms. + + Some of the structured header field bodies also allow the period + character (".", ASCII value 46) within runs of atext. An additional + "dot-atom" token is defined for those purposes. + +atext = ALPHA / DIGIT / ; Any character except controls, + "!" / "#" / ; SP, and specials. + "$" / "%" / ; Used for atoms + "&" / "'" / + "*" / "+" / + "-" / "/" / + "=" / "?" / + "^" / "_" / + "`" / "{" / + "|" / "}" / + "~" + +atom = [CFWS] 1*atext [CFWS] + +dot-atom = [CFWS] dot-atom-text [CFWS] + +dot-atom-text = 1*atext *("." 1*atext) + + Both atom and dot-atom are interpreted as a single unit, comprised of + the string of characters that make it up. Semantically, the optional + comments and FWS surrounding the rest of the characters are not part + of the atom; the atom is only the run of atext characters in an atom, + or the atext and "." characters in a dot-atom. + + + + + + + +Resnick Standards Track [Page 12] + +RFC 2822 Internet Message Format April 2001 + + +3.2.5. Quoted strings + + Strings of characters that include characters other than those + allowed in atoms may be represented in a quoted string format, where + the characters are surrounded by quote (DQUOTE, ASCII value 34) + characters. + +qtext = NO-WS-CTL / ; Non white space controls + + %d33 / ; The rest of the US-ASCII + %d35-91 / ; characters not including "\" + %d93-126 ; or the quote character + +qcontent = qtext / quoted-pair + +quoted-string = [CFWS] + DQUOTE *([FWS] qcontent) [FWS] DQUOTE + [CFWS] + + A quoted-string is treated as a unit. That is, quoted-string is + identical to atom, semantically. Since a quoted-string is allowed to + contain FWS, folding is permitted. Also note that since quoted-pair + is allowed in a quoted-string, the quote and backslash characters may + appear in a quoted-string so long as they appear as a quoted-pair. + + Semantically, neither the optional CFWS outside of the quote + characters nor the quote characters themselves are part of the + quoted-string; the quoted-string is what is contained between the two + quote characters. As stated earlier, the "\" in any quoted-pair and + the CRLF in any FWS/CFWS that appears within the quoted-string are + semantically "invisible" and therefore not part of the quoted-string + either. + +3.2.6. Miscellaneous tokens + + Three additional tokens are defined, word and phrase for combinations + of atoms and/or quoted-strings, and unstructured for use in + unstructured header fields and in some places within structured + header fields. + +word = atom / quoted-string + +phrase = 1*word / obs-phrase + + + + + + + + +Resnick Standards Track [Page 13] + +RFC 2822 Internet Message Format April 2001 + + +utext = NO-WS-CTL / ; Non white space controls + %d33-126 / ; The rest of US-ASCII + obs-utext + +unstructured = *([FWS] utext) [FWS] + +3.3. Date and Time Specification + + Date and time occur in several header fields. This section specifies + the syntax for a full date and time specification. Though folding + white space is permitted throughout the date-time specification, it + is RECOMMENDED that a single space be used in each place that FWS + appears (whether it is required or optional); some older + implementations may not interpret other occurrences of folding white + space correctly. + +date-time = [ day-of-week "," ] date FWS time [CFWS] + +day-of-week = ([FWS] day-name) / obs-day-of-week + +day-name = "Mon" / "Tue" / "Wed" / "Thu" / + "Fri" / "Sat" / "Sun" + +date = day month year + +year = 4*DIGIT / obs-year + +month = (FWS month-name FWS) / obs-month + +month-name = "Jan" / "Feb" / "Mar" / "Apr" / + "May" / "Jun" / "Jul" / "Aug" / + "Sep" / "Oct" / "Nov" / "Dec" + +day = ([FWS] 1*2DIGIT) / obs-day + +time = time-of-day FWS zone + +time-of-day = hour ":" minute [ ":" second ] + +hour = 2DIGIT / obs-hour + +minute = 2DIGIT / obs-minute + +second = 2DIGIT / obs-second + +zone = (( "+" / "-" ) 4DIGIT) / obs-zone + + + + + +Resnick Standards Track [Page 14] + +RFC 2822 Internet Message Format April 2001 + + + The day is the numeric day of the month. The year is any numeric + year 1900 or later. + + The time-of-day specifies the number of hours, minutes, and + optionally seconds since midnight of the date indicated. + + The date and time-of-day SHOULD express local time. + + The zone specifies the offset from Coordinated Universal Time (UTC, + formerly referred to as "Greenwich Mean Time") that the date and + time-of-day represent. The "+" or "-" indicates whether the + time-of-day is ahead of (i.e., east of) or behind (i.e., west of) + Universal Time. The first two digits indicate the number of hours + difference from Universal Time, and the last two digits indicate the + number of minutes difference from Universal Time. (Hence, +hhmm + means +(hh * 60 + mm) minutes, and -hhmm means -(hh * 60 + mm) + minutes). The form "+0000" SHOULD be used to indicate a time zone at + Universal Time. Though "-0000" also indicates Universal Time, it is + used to indicate that the time was generated on a system that may be + in a local time zone other than Universal Time and therefore + indicates that the date-time contains no information about the local + time zone. + + A date-time specification MUST be semantically valid. That is, the + day-of-the-week (if included) MUST be the day implied by the date, + the numeric day-of-month MUST be between 1 and the number of days + allowed for the specified month (in the specified year), the + time-of-day MUST be in the range 00:00:00 through 23:59:60 (the + number of seconds allowing for a leap second; see [STD12]), and the + zone MUST be within the range -9959 through +9959. + +3.4. Address Specification + + Addresses occur in several message header fields to indicate senders + and recipients of messages. An address may either be an individual + mailbox, or a group of mailboxes. + +address = mailbox / group + +mailbox = name-addr / addr-spec + +name-addr = [display-name] angle-addr + +angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr + +group = display-name ":" [mailbox-list / CFWS] ";" + [CFWS] + + + + +Resnick Standards Track [Page 15] + +RFC 2822 Internet Message Format April 2001 + + +display-name = phrase + +mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list + +address-list = (address *("," address)) / obs-addr-list + + A mailbox receives mail. It is a conceptual entity which does not + necessarily pertain to file storage. For example, some sites may + choose to print mail on a printer and deliver the output to the + addressee's desk. Normally, a mailbox is comprised of two parts: (1) + an optional display name that indicates the name of the recipient + (which could be a person or a system) that could be displayed to the + user of a mail application, and (2) an addr-spec address enclosed in + angle brackets ("<" and ">"). There is also an alternate simple form + of a mailbox where the addr-spec address appears alone, without the + recipient's name or the angle brackets. The Internet addr-spec + address is described in section 3.4.1. + + Note: Some legacy implementations used the simple form where the + addr-spec appears without the angle brackets, but included the name + of the recipient in parentheses as a comment following the addr-spec. + Since the meaning of the information in a comment is unspecified, + implementations SHOULD use the full name-addr form of the mailbox, + instead of the legacy form, to specify the display name associated + with a mailbox. Also, because some legacy implementations interpret + the comment, comments generally SHOULD NOT be used in address fields + to avoid confusing such implementations. + + When it is desirable to treat several mailboxes as a single unit + (i.e., in a distribution list), the group construct can be used. The + group construct allows the sender to indicate a named group of + recipients. This is done by giving a display name for the group, + followed by a colon, followed by a comma separated list of any number + of mailboxes (including zero and one), and ending with a semicolon. + Because the list of mailboxes can be empty, using the group construct + is also a simple way to communicate to recipients that the message + was sent to one or more named sets of recipients, without actually + providing the individual mailbox address for each of those + recipients. + +3.4.1. Addr-spec specification + + An addr-spec is a specific Internet identifier that contains a + locally interpreted string followed by the at-sign character ("@", + ASCII value 64) followed by an Internet domain. The locally + interpreted string is either a quoted-string or a dot-atom. If the + string can be represented as a dot-atom (that is, it contains no + characters other than atext characters or "." surrounded by atext + + + +Resnick Standards Track [Page 16] + +RFC 2822 Internet Message Format April 2001 + + + characters), then the dot-atom form SHOULD be used and the + quoted-string form SHOULD NOT be used. Comments and folding white + space SHOULD NOT be used around the "@" in the addr-spec. + +addr-spec = local-part "@" domain + +local-part = dot-atom / quoted-string / obs-local-part + +domain = dot-atom / domain-literal / obs-domain + +domain-literal = [CFWS] "[" *([FWS] dcontent) [FWS] "]" [CFWS] + +dcontent = dtext / quoted-pair + +dtext = NO-WS-CTL / ; Non white space controls + + %d33-90 / ; The rest of the US-ASCII + %d94-126 ; characters not including "[", + ; "]", or "\" + + The domain portion identifies the point to which the mail is + delivered. In the dot-atom form, this is interpreted as an Internet + domain name (either a host name or a mail exchanger name) as + described in [STD3, STD13, STD14]. In the domain-literal form, the + domain is interpreted as the literal Internet address of the + particular host. In both cases, how addressing is used and how + messages are transported to a particular host is covered in the mail + transport document [RFC2821]. These mechanisms are outside of the + scope of this document. + + The local-part portion is a domain dependent string. In addresses, + it is simply interpreted on the particular host as a name of a + particular mailbox. + +3.5 Overall message syntax + + A message consists of header fields, optionally followed by a message + body. Lines in a message MUST be a maximum of 998 characters + excluding the CRLF, but it is RECOMMENDED that lines be limited to 78 + characters excluding the CRLF. (See section 2.1.1 for explanation.) + In a message body, though all of the characters listed in the text + rule MAY be used, the use of US-ASCII control characters (values 1 + through 8, 11, 12, and 14 through 31) is discouraged since their + interpretation by receivers for display is not guaranteed. + + + + + + + +Resnick Standards Track [Page 17] + +RFC 2822 Internet Message Format April 2001 + + +message = (fields / obs-fields) + [CRLF body] + +body = *(*998text CRLF) *998text + + The header fields carry most of the semantic information and are + defined in section 3.6. The body is simply a series of lines of text + which are uninterpreted for the purposes of this standard. + +3.6. Field definitions + + The header fields of a message are defined here. All header fields + have the same general syntactic structure: A field name, followed by + a colon, followed by the field body. The specific syntax for each + header field is defined in the subsequent sections. + + Note: In the ABNF syntax for each field in subsequent sections, each + field name is followed by the required colon. However, for brevity + sometimes the colon is not referred to in the textual description of + the syntax. It is, nonetheless, required. + + It is important to note that the header fields are not guaranteed to + be in a particular order. They may appear in any order, and they + have been known to be reordered occasionally when transported over + the Internet. However, for the purposes of this standard, header + fields SHOULD NOT be reordered when a message is transported or + transformed. More importantly, the trace header fields and resent + header fields MUST NOT be reordered, and SHOULD be kept in blocks + prepended to the message. See sections 3.6.6 and 3.6.7 for more + information. + + The only required header fields are the origination date field and + the originator address field(s). All other header fields are + syntactically optional. More information is contained in the table + following this definition. + +fields = *(trace + *(resent-date / + resent-from / + resent-sender / + resent-to / + resent-cc / + resent-bcc / + resent-msg-id)) + *(orig-date / + from / + sender / + reply-to / + + + +Resnick Standards Track [Page 18] + +RFC 2822 Internet Message Format April 2001 + + + to / + cc / + bcc / + message-id / + in-reply-to / + references / + subject / + comments / + keywords / + optional-field) + + The following table indicates limits on the number of times each + field may occur in a message header as well as any special + limitations on the use of those fields. An asterisk next to a value + in the minimum or maximum column indicates that a special restriction + appears in the Notes column. + +Field Min number Max number Notes + +trace 0 unlimited Block prepended - see + 3.6.7 + +resent-date 0* unlimited* One per block, required + if other resent fields + present - see 3.6.6 + +resent-from 0 unlimited* One per block - see + 3.6.6 + +resent-sender 0* unlimited* One per block, MUST + occur with multi-address + resent-from - see 3.6.6 + +resent-to 0 unlimited* One per block - see + 3.6.6 + +resent-cc 0 unlimited* One per block - see + 3.6.6 + +resent-bcc 0 unlimited* One per block - see + 3.6.6 + +resent-msg-id 0 unlimited* One per block - see + 3.6.6 + +orig-date 1 1 + +from 1 1 See sender and 3.6.2 + + + +Resnick Standards Track [Page 19] + +RFC 2822 Internet Message Format April 2001 + + +sender 0* 1 MUST occur with multi- + address from - see 3.6.2 + +reply-to 0 1 + +to 0 1 + +cc 0 1 + +bcc 0 1 + +message-id 0* 1 SHOULD be present - see + 3.6.4 + +in-reply-to 0* 1 SHOULD occur in some + replies - see 3.6.4 + +references 0* 1 SHOULD occur in some + replies - see 3.6.4 + +subject 0 1 + +comments 0 unlimited + +keywords 0 unlimited + +optional-field 0 unlimited + + The exact interpretation of each field is described in subsequent + sections. + +3.6.1. The origination date field + + The origination date field consists of the field name "Date" followed + by a date-time specification. + +orig-date = "Date:" date-time CRLF + + The origination date specifies the date and time at which the creator + of the message indicated that the message was complete and ready to + enter the mail delivery system. For instance, this might be the time + that a user pushes the "send" or "submit" button in an application + program. In any case, it is specifically not intended to convey the + time that the message is actually transported, but rather the time at + which the human or other creator of the message has put the message + into its final form, ready for transport. (For example, a portable + computer user who is not connected to a network might queue a message + + + + +Resnick Standards Track [Page 20] + +RFC 2822 Internet Message Format April 2001 + + + for delivery. The origination date is intended to contain the date + and time that the user queued the message, not the time when the user + connected to the network to send the message.) + +3.6.2. Originator fields + + The originator fields of a message consist of the from field, the + sender field (when applicable), and optionally the reply-to field. + The from field consists of the field name "From" and a + comma-separated list of one or more mailbox specifications. If the + from field contains more than one mailbox specification in the + mailbox-list, then the sender field, containing the field name + "Sender" and a single mailbox specification, MUST appear in the + message. In either case, an optional reply-to field MAY also be + included, which contains the field name "Reply-To" and a + comma-separated list of one or more addresses. + +from = "From:" mailbox-list CRLF + +sender = "Sender:" mailbox CRLF + +reply-to = "Reply-To:" address-list CRLF + + The originator fields indicate the mailbox(es) of the source of the + message. The "From:" field specifies the author(s) of the message, + that is, the mailbox(es) of the person(s) or system(s) responsible + for the writing of the message. The "Sender:" field specifies the + mailbox of the agent responsible for the actual transmission of the + message. For example, if a secretary were to send a message for + another person, the mailbox of the secretary would appear in the + "Sender:" field and the mailbox of the actual author would appear in + the "From:" field. If the originator of the message can be indicated + by a single mailbox and the author and transmitter are identical, the + "Sender:" field SHOULD NOT be used. Otherwise, both fields SHOULD + appear. + + The originator fields also provide the information required when + replying to a message. When the "Reply-To:" field is present, it + indicates the mailbox(es) to which the author of the message suggests + that replies be sent. In the absence of the "Reply-To:" field, + replies SHOULD by default be sent to the mailbox(es) specified in the + "From:" field unless otherwise specified by the person composing the + reply. + + In all cases, the "From:" field SHOULD NOT contain any mailbox that + does not belong to the author(s) of the message. See also section + 3.6.3 for more information on forming the destination addresses for a + reply. + + + +Resnick Standards Track [Page 21] + +RFC 2822 Internet Message Format April 2001 + + +3.6.3. Destination address fields + + The destination fields of a message consist of three possible fields, + each of the same form: The field name, which is either "To", "Cc", or + "Bcc", followed by a comma-separated list of one or more addresses + (either mailbox or group syntax). + +to = "To:" address-list CRLF + +cc = "Cc:" address-list CRLF + +bcc = "Bcc:" (address-list / [CFWS]) CRLF + + The destination fields specify the recipients of the message. Each + destination field may have one or more addresses, and each of the + addresses indicate the intended recipients of the message. The only + difference between the three fields is how each is used. + + The "To:" field contains the address(es) of the primary recipient(s) + of the message. + + The "Cc:" field (where the "Cc" means "Carbon Copy" in the sense of + making a copy on a typewriter using carbon paper) contains the + addresses of others who are to receive the message, though the + content of the message may not be directed at them. + + The "Bcc:" field (where the "Bcc" means "Blind Carbon Copy") contains + addresses of recipients of the message whose addresses are not to be + revealed to other recipients of the message. There are three ways in + which the "Bcc:" field is used. In the first case, when a message + containing a "Bcc:" field is prepared to be sent, the "Bcc:" line is + removed even though all of the recipients (including those specified + in the "Bcc:" field) are sent a copy of the message. In the second + case, recipients specified in the "To:" and "Cc:" lines each are sent + a copy of the message with the "Bcc:" line removed as above, but the + recipients on the "Bcc:" line get a separate copy of the message + containing a "Bcc:" line. (When there are multiple recipient + addresses in the "Bcc:" field, some implementations actually send a + separate copy of the message to each recipient with a "Bcc:" + containing only the address of that particular recipient.) Finally, + since a "Bcc:" field may contain no addresses, a "Bcc:" field can be + sent without any addresses indicating to the recipients that blind + copies were sent to someone. Which method to use with "Bcc:" fields + is implementation dependent, but refer to the "Security + Considerations" section of this document for a discussion of each. + + + + + + +Resnick Standards Track [Page 22] + +RFC 2822 Internet Message Format April 2001 + + + When a message is a reply to another message, the mailboxes of the + authors of the original message (the mailboxes in the "From:" field) + or mailboxes specified in the "Reply-To:" field (if it exists) MAY + appear in the "To:" field of the reply since these would normally be + the primary recipients of the reply. If a reply is sent to a message + that has destination fields, it is often desirable to send a copy of + the reply to all of the recipients of the message, in addition to the + author. When such a reply is formed, addresses in the "To:" and + "Cc:" fields of the original message MAY appear in the "Cc:" field of + the reply, since these are normally secondary recipients of the + reply. If a "Bcc:" field is present in the original message, + addresses in that field MAY appear in the "Bcc:" field of the reply, + but SHOULD NOT appear in the "To:" or "Cc:" fields. + + Note: Some mail applications have automatic reply commands that + include the destination addresses of the original message in the + destination addresses of the reply. How those reply commands behave + is implementation dependent and is beyond the scope of this document. + In particular, whether or not to include the original destination + addresses when the original message had a "Reply-To:" field is not + addressed here. + +3.6.4. Identification fields + + Though optional, every message SHOULD have a "Message-ID:" field. + Furthermore, reply messages SHOULD have "In-Reply-To:" and + "References:" fields as appropriate, as described below. + + The "Message-ID:" field contains a single unique message identifier. + The "References:" and "In-Reply-To:" field each contain one or more + unique message identifiers, optionally separated by CFWS. + + The message identifier (msg-id) is similar in syntax to an angle-addr + construct without the internal CFWS. + +message-id = "Message-ID:" msg-id CRLF + +in-reply-to = "In-Reply-To:" 1*msg-id CRLF + +references = "References:" 1*msg-id CRLF + +msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS] + +id-left = dot-atom-text / no-fold-quote / obs-id-left + +id-right = dot-atom-text / no-fold-literal / obs-id-right + +no-fold-quote = DQUOTE *(qtext / quoted-pair) DQUOTE + + + +Resnick Standards Track [Page 23] + +RFC 2822 Internet Message Format April 2001 + + +no-fold-literal = "[" *(dtext / quoted-pair) "]" + + The "Message-ID:" field provides a unique message identifier that + refers to a particular version of a particular message. The + uniqueness of the message identifier is guaranteed by the host that + generates it (see below). This message identifier is intended to be + machine readable and not necessarily meaningful to humans. A message + identifier pertains to exactly one instantiation of a particular + message; subsequent revisions to the message each receive new message + identifiers. + + Note: There are many instances when messages are "changed", but those + changes do not constitute a new instantiation of that message, and + therefore the message would not get a new message identifier. For + example, when messages are introduced into the transport system, they + are often prepended with additional header fields such as trace + fields (described in section 3.6.7) and resent fields (described in + section 3.6.6). The addition of such header fields does not change + the identity of the message and therefore the original "Message-ID:" + field is retained. In all cases, it is the meaning that the sender + of the message wishes to convey (i.e., whether this is the same + message or a different message) that determines whether or not the + "Message-ID:" field changes, not any particular syntactic difference + that appears (or does not appear) in the message. + + The "In-Reply-To:" and "References:" fields are used when creating a + reply to a message. They hold the message identifier of the original + message and the message identifiers of other messages (for example, + in the case of a reply to a message which was itself a reply). The + "In-Reply-To:" field may be used to identify the message (or + messages) to which the new message is a reply, while the + "References:" field may be used to identify a "thread" of + conversation. + + When creating a reply to a message, the "In-Reply-To:" and + "References:" fields of the resultant message are constructed as + follows: + + The "In-Reply-To:" field will contain the contents of the "Message- + ID:" field of the message to which this one is a reply (the "parent + message"). If there is more than one parent message, then the "In- + Reply-To:" field will contain the contents of all of the parents' + "Message-ID:" fields. If there is no "Message-ID:" field in any of + the parent messages, then the new message will have no "In-Reply-To:" + field. + + + + + + +Resnick Standards Track [Page 24] + +RFC 2822 Internet Message Format April 2001 + + + The "References:" field will contain the contents of the parent's + "References:" field (if any) followed by the contents of the parent's + "Message-ID:" field (if any). If the parent message does not contain + a "References:" field but does have an "In-Reply-To:" field + containing a single message identifier, then the "References:" field + will contain the contents of the parent's "In-Reply-To:" field + followed by the contents of the parent's "Message-ID:" field (if + any). If the parent has none of the "References:", "In-Reply-To:", + or "Message-ID:" fields, then the new message will have no + "References:" field. + + Note: Some implementations parse the "References:" field to display + the "thread of the discussion". These implementations assume that + each new message is a reply to a single parent and hence that they + can walk backwards through the "References:" field to find the parent + of each message listed there. Therefore, trying to form a + "References:" field for a reply that has multiple parents is + discouraged and how to do so is not defined in this document. + + The message identifier (msg-id) itself MUST be a globally unique + identifier for a message. The generator of the message identifier + MUST guarantee that the msg-id is unique. There are several + algorithms that can be used to accomplish this. Since the msg-id has + a similar syntax to angle-addr (identical except that comments and + folding white space are not allowed), a good method is to put the + domain name (or a domain literal IP address) of the host on which the + message identifier was created on the right hand side of the "@", and + put a combination of the current absolute date and time along with + some other currently unique (perhaps sequential) identifier available + on the system (for example, a process id number) on the left hand + side. Using a date on the left hand side and a domain name or domain + literal on the right hand side makes it possible to guarantee + uniqueness since no two hosts use the same domain name or IP address + at the same time. Though other algorithms will work, it is + RECOMMENDED that the right hand side contain some domain identifier + (either of the host itself or otherwise) such that the generator of + the message identifier can guarantee the uniqueness of the left hand + side within the scope of that domain. + + Semantically, the angle bracket characters are not part of the + msg-id; the msg-id is what is contained between the two angle bracket + characters. + + + + + + + + + +Resnick Standards Track [Page 25] + +RFC 2822 Internet Message Format April 2001 + + +3.6.5. Informational fields + + The informational fields are all optional. The "Keywords:" field + contains a comma-separated list of one or more words or + quoted-strings. The "Subject:" and "Comments:" fields are + unstructured fields as defined in section 2.2.1, and therefore may + contain text or folding white space. + +subject = "Subject:" unstructured CRLF + +comments = "Comments:" unstructured CRLF + +keywords = "Keywords:" phrase *("," phrase) CRLF + + These three fields are intended to have only human-readable content + with information about the message. The "Subject:" field is the most + common and contains a short string identifying the topic of the + message. When used in a reply, the field body MAY start with the + string "Re: " (from the Latin "res", in the matter of) followed by + the contents of the "Subject:" field body of the original message. + If this is done, only one instance of the literal string "Re: " ought + to be used since use of other strings or more than one instance can + lead to undesirable consequences. The "Comments:" field contains any + additional comments on the text of the body of the message. The + "Keywords:" field contains a comma-separated list of important words + and phrases that might be useful for the recipient. + +3.6.6. Resent fields + + Resent fields SHOULD be added to any message that is reintroduced by + a user into the transport system. A separate set of resent fields + SHOULD be added each time this is done. All of the resent fields + corresponding to a particular resending of the message SHOULD be + together. Each new set of resent fields is prepended to the message; + that is, the most recent set of resent fields appear earlier in the + message. No other fields in the message are changed when resent + fields are added. + + Each of the resent fields corresponds to a particular field elsewhere + in the syntax. For instance, the "Resent-Date:" field corresponds to + the "Date:" field and the "Resent-To:" field corresponds to the "To:" + field. In each case, the syntax for the field body is identical to + the syntax given previously for the corresponding field. + + When resent fields are used, the "Resent-From:" and "Resent-Date:" + fields MUST be sent. The "Resent-Message-ID:" field SHOULD be sent. + "Resent-Sender:" SHOULD NOT be used if "Resent-Sender:" would be + identical to "Resent-From:". + + + +Resnick Standards Track [Page 26] + +RFC 2822 Internet Message Format April 2001 + + +resent-date = "Resent-Date:" date-time CRLF + +resent-from = "Resent-From:" mailbox-list CRLF + +resent-sender = "Resent-Sender:" mailbox CRLF + +resent-to = "Resent-To:" address-list CRLF + +resent-cc = "Resent-Cc:" address-list CRLF + +resent-bcc = "Resent-Bcc:" (address-list / [CFWS]) CRLF + +resent-msg-id = "Resent-Message-ID:" msg-id CRLF + + Resent fields are used to identify a message as having been + reintroduced into the transport system by a user. The purpose of + using resent fields is to have the message appear to the final + recipient as if it were sent directly by the original sender, with + all of the original fields remaining the same. Each set of resent + fields correspond to a particular resending event. That is, if a + message is resent multiple times, each set of resent fields gives + identifying information for each individual time. Resent fields are + strictly informational. They MUST NOT be used in the normal + processing of replies or other such automatic actions on messages. + + Note: Reintroducing a message into the transport system and using + resent fields is a different operation from "forwarding". + "Forwarding" has two meanings: One sense of forwarding is that a mail + reading program can be told by a user to forward a copy of a message + to another person, making the forwarded message the body of the new + message. A forwarded message in this sense does not appear to have + come from the original sender, but is an entirely new message from + the forwarder of the message. On the other hand, forwarding is also + used to mean when a mail transport program gets a message and + forwards it on to a different destination for final delivery. Resent + header fields are not intended for use with either type of + forwarding. + + The resent originator fields indicate the mailbox of the person(s) or + system(s) that resent the message. As with the regular originator + fields, there are two forms: a simple "Resent-From:" form which + contains the mailbox of the individual doing the resending, and the + more complex form, when one individual (identified in the + "Resent-Sender:" field) resends a message on behalf of one or more + others (identified in the "Resent-From:" field). + + Note: When replying to a resent message, replies behave just as they + would with any other message, using the original "From:", + + + +Resnick Standards Track [Page 27] + +RFC 2822 Internet Message Format April 2001 + + + "Reply-To:", "Message-ID:", and other fields. The resent fields are + only informational and MUST NOT be used in the normal processing of + replies. + + The "Resent-Date:" indicates the date and time at which the resent + message is dispatched by the resender of the message. Like the + "Date:" field, it is not the date and time that the message was + actually transported. + + The "Resent-To:", "Resent-Cc:", and "Resent-Bcc:" fields function + identically to the "To:", "Cc:", and "Bcc:" fields respectively, + except that they indicate the recipients of the resent message, not + the recipients of the original message. + + The "Resent-Message-ID:" field provides a unique identifier for the + resent message. + +3.6.7. Trace fields + + The trace fields are a group of header fields consisting of an + optional "Return-Path:" field, and one or more "Received:" fields. + The "Return-Path:" header field contains a pair of angle brackets + that enclose an optional addr-spec. The "Received:" field contains a + (possibly empty) list of name/value pairs followed by a semicolon and + a date-time specification. The first item of the name/value pair is + defined by item-name, and the second item is either an addr-spec, an + atom, a domain, or a msg-id. Further restrictions may be applied to + the syntax of the trace fields by standards that provide for their + use, such as [RFC2821]. + +trace = [return] + 1*received + +return = "Return-Path:" path CRLF + +path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) / + obs-path + +received = "Received:" name-val-list ";" date-time CRLF + +name-val-list = [CFWS] [name-val-pair *(CFWS name-val-pair)] + +name-val-pair = item-name CFWS item-value + +item-name = ALPHA *(["-"] (ALPHA / DIGIT)) + +item-value = 1*angle-addr / addr-spec / + atom / domain / msg-id + + + +Resnick Standards Track [Page 28] + +RFC 2822 Internet Message Format April 2001 + + + A full discussion of the Internet mail use of trace fields is + contained in [RFC2821]. For the purposes of this standard, the trace + fields are strictly informational, and any formal interpretation of + them is outside of the scope of this document. + +3.6.8. Optional fields + + Fields may appear in messages that are otherwise unspecified in this + standard. They MUST conform to the syntax of an optional-field. + This is a field name, made up of the printable US-ASCII characters + except SP and colon, followed by a colon, followed by any text which + conforms to unstructured. + + The field names of any optional-field MUST NOT be identical to any + field name specified elsewhere in this standard. + +optional-field = field-name ":" unstructured CRLF + +field-name = 1*ftext + +ftext = %d33-57 / ; Any character except + %d59-126 ; controls, SP, and + ; ":". + + For the purposes of this standard, any optional field is + uninterpreted. + +4. Obsolete Syntax + + Earlier versions of this standard allowed for different (usually more + liberal) syntax than is allowed in this version. Also, there have + been syntactic elements used in messages on the Internet whose + interpretation have never been documented. Though some of these + syntactic forms MUST NOT be generated according to the grammar in + section 3, they MUST be accepted and parsed by a conformant receiver. + This section documents many of these syntactic elements. Taking the + grammar in section 3 and adding the definitions presented in this + section will result in the grammar to use for interpretation of + messages. + + Note: This section identifies syntactic forms that any implementation + MUST reasonably interpret. However, there are certainly Internet + messages which do not conform to even the additional syntax given in + this section. The fact that a particular form does not appear in any + section of this document is not justification for computer programs + to crash or for malformed data to be irretrievably lost by any + implementation. To repeat an example, though this document requires + lines in messages to be no longer than 998 characters, silently + + + +Resnick Standards Track [Page 29] + +RFC 2822 Internet Message Format April 2001 + + + discarding the 999th and subsequent characters in a line without + warning would still be bad behavior for an implementation. It is up + to the implementation to deal with messages robustly. + + One important difference between the obsolete (interpreting) and the + current (generating) syntax is that in structured header field bodies + (i.e., between the colon and the CRLF of any structured header + field), white space characters, including folding white space, and + comments can be freely inserted between any syntactic tokens. This + allows many complex forms that have proven difficult for some + implementations to parse. + + Another key difference between the obsolete and the current syntax is + that the rule in section 3.2.3 regarding lines composed entirely of + white space in comments and folding white space does not apply. See + the discussion of folding white space in section 4.2 below. + + Finally, certain characters that were formerly allowed in messages + appear in this section. The NUL character (ASCII value 0) was once + allowed, but is no longer for compatibility reasons. CR and LF were + allowed to appear in messages other than as CRLF; this use is also + shown here. + + Other differences in syntax and semantics are noted in the following + sections. + +4.1. Miscellaneous obsolete tokens + + These syntactic elements are used elsewhere in the obsolete syntax or + in the main syntax. The obs-char and obs-qp elements each add ASCII + value 0. Bare CR and bare LF are added to obs-text and obs-utext. + The period character is added to obs-phrase. The obs-phrase-list + provides for "empty" elements in a comma-separated list of phrases. + + Note: The "period" (or "full stop") character (".") in obs-phrase is + not a form that was allowed in earlier versions of this or any other + standard. Period (nor any other character from specials) was not + allowed in phrase because it introduced a parsing difficulty + distinguishing between phrases and portions of an addr-spec (see + section 4.4). It appears here because the period character is + currently used in many messages in the display-name portion of + addresses, especially for initials in names, and therefore must be + interpreted properly. In the future, period may appear in the + regular syntax of phrase. + +obs-qp = "\" (%d0-127) + +obs-text = *LF *CR *(obs-char *LF *CR) + + + +Resnick Standards Track [Page 30] + +RFC 2822 Internet Message Format April 2001 + + +obs-char = %d0-9 / %d11 / ; %d0-127 except CR and + %d12 / %d14-127 ; LF + +obs-utext = obs-text + +obs-phrase = word *(word / "." / CFWS) + +obs-phrase-list = phrase / 1*([phrase] [CFWS] "," [CFWS]) [phrase] + + Bare CR and bare LF appear in messages with two different meanings. + In many cases, bare CR or bare LF are used improperly instead of CRLF + to indicate line separators. In other cases, bare CR and bare LF are + used simply as ASCII control characters with their traditional ASCII + meanings. + +4.2. Obsolete folding white space + + In the obsolete syntax, any amount of folding white space MAY be + inserted where the obs-FWS rule is allowed. This creates the + possibility of having two consecutive "folds" in a line, and + therefore the possibility that a line which makes up a folded header + field could be composed entirely of white space. + + obs-FWS = 1*WSP *(CRLF 1*WSP) + +4.3. Obsolete Date and Time + + The syntax for the obsolete date format allows a 2 digit year in the + date field and allows for a list of alphabetic time zone + specifications that were used in earlier versions of this standard. + It also permits comments and folding white space between many of the + tokens. + +obs-day-of-week = [CFWS] day-name [CFWS] + +obs-year = [CFWS] 2*DIGIT [CFWS] + +obs-month = CFWS month-name CFWS + +obs-day = [CFWS] 1*2DIGIT [CFWS] + +obs-hour = [CFWS] 2DIGIT [CFWS] + +obs-minute = [CFWS] 2DIGIT [CFWS] + +obs-second = [CFWS] 2DIGIT [CFWS] + +obs-zone = "UT" / "GMT" / ; Universal Time + + + +Resnick Standards Track [Page 31] + +RFC 2822 Internet Message Format April 2001 + + + ; North American UT + ; offsets + "EST" / "EDT" / ; Eastern: - 5/ - 4 + "CST" / "CDT" / ; Central: - 6/ - 5 + "MST" / "MDT" / ; Mountain: - 7/ - 6 + "PST" / "PDT" / ; Pacific: - 8/ - 7 + + %d65-73 / ; Military zones - "A" + %d75-90 / ; through "I" and "K" + %d97-105 / ; through "Z", both + %d107-122 ; upper and lower case + + Where a two or three digit year occurs in a date, the year is to be + interpreted as follows: If a two digit year is encountered whose + value is between 00 and 49, the year is interpreted by adding 2000, + ending up with a value between 2000 and 2049. If a two digit year is + encountered with a value between 50 and 99, or any three digit year + is encountered, the year is interpreted by adding 1900. + + In the obsolete time zone, "UT" and "GMT" are indications of + "Universal Time" and "Greenwich Mean Time" respectively and are both + semantically identical to "+0000". + + The remaining three character zones are the US time zones. The first + letter, "E", "C", "M", or "P" stands for "Eastern", "Central", + "Mountain" and "Pacific". The second letter is either "S" for + "Standard" time, or "D" for "Daylight" (or summer) time. Their + interpretations are as follows: + + EDT is semantically equivalent to -0400 + EST is semantically equivalent to -0500 + CDT is semantically equivalent to -0500 + CST is semantically equivalent to -0600 + MDT is semantically equivalent to -0600 + MST is semantically equivalent to -0700 + PDT is semantically equivalent to -0700 + PST is semantically equivalent to -0800 + + The 1 character military time zones were defined in a non-standard + way in [RFC822] and are therefore unpredictable in their meaning. + The original definitions of the military zones "A" through "I" are + equivalent to "+0100" through "+0900" respectively; "K", "L", and "M" + are equivalent to "+1000", "+1100", and "+1200" respectively; "N" + through "Y" are equivalent to "-0100" through "-1200" respectively; + and "Z" is equivalent to "+0000". However, because of the error in + [RFC822], they SHOULD all be considered equivalent to "-0000" unless + there is out-of-band information confirming their meaning. + + + + +Resnick Standards Track [Page 32] + +RFC 2822 Internet Message Format April 2001 + + + Other multi-character (usually between 3 and 5) alphabetic time zones + have been used in Internet messages. Any such time zone whose + meaning is not known SHOULD be considered equivalent to "-0000" + unless there is out-of-band information confirming their meaning. + +4.4. Obsolete Addressing + + There are three primary differences in addressing. First, mailbox + addresses were allowed to have a route portion before the addr-spec + when enclosed in "<" and ">". The route is simply a comma-separated + list of domain names, each preceded by "@", and the list terminated + by a colon. Second, CFWS were allowed between the period-separated + elements of local-part and domain (i.e., dot-atom was not used). In + addition, local-part is allowed to contain quoted-string in addition + to just atom. Finally, mailbox-list and address-list were allowed to + have "null" members. That is, there could be two or more commas in + such a list with nothing in between them. + +obs-angle-addr = [CFWS] "<" [obs-route] addr-spec ">" [CFWS] + +obs-route = [CFWS] obs-domain-list ":" [CFWS] + +obs-domain-list = "@" domain *(*(CFWS / "," ) [CFWS] "@" domain) + +obs-local-part = word *("." word) + +obs-domain = atom *("." atom) + +obs-mbox-list = 1*([mailbox] [CFWS] "," [CFWS]) [mailbox] + +obs-addr-list = 1*([address] [CFWS] "," [CFWS]) [address] + + When interpreting addresses, the route portion SHOULD be ignored. + +4.5. Obsolete header fields + + Syntactically, the primary difference in the obsolete field syntax is + that it allows multiple occurrences of any of the fields and they may + occur in any order. Also, any amount of white space is allowed + before the ":" at the end of the field name. + +obs-fields = *(obs-return / + obs-received / + obs-orig-date / + obs-from / + obs-sender / + obs-reply-to / + obs-to / + + + +Resnick Standards Track [Page 33] + +RFC 2822 Internet Message Format April 2001 + + + obs-cc / + obs-bcc / + obs-message-id / + obs-in-reply-to / + obs-references / + obs-subject / + obs-comments / + obs-keywords / + obs-resent-date / + obs-resent-from / + obs-resent-send / + obs-resent-rply / + obs-resent-to / + obs-resent-cc / + obs-resent-bcc / + obs-resent-mid / + obs-optional) + + Except for destination address fields (described in section 4.5.3), + the interpretation of multiple occurrences of fields is unspecified. + Also, the interpretation of trace fields and resent fields which do + not occur in blocks prepended to the message is unspecified as well. + Unless otherwise noted in the following sections, interpretation of + other fields is identical to the interpretation of their non-obsolete + counterparts in section 3. + +4.5.1. Obsolete origination date field + +obs-orig-date = "Date" *WSP ":" date-time CRLF + +4.5.2. Obsolete originator fields + +obs-from = "From" *WSP ":" mailbox-list CRLF + +obs-sender = "Sender" *WSP ":" mailbox CRLF + +obs-reply-to = "Reply-To" *WSP ":" mailbox-list CRLF + +4.5.3. Obsolete destination address fields + +obs-to = "To" *WSP ":" address-list CRLF + +obs-cc = "Cc" *WSP ":" address-list CRLF + +obs-bcc = "Bcc" *WSP ":" (address-list / [CFWS]) CRLF + + + + + + +Resnick Standards Track [Page 34] + +RFC 2822 Internet Message Format April 2001 + + + When multiple occurrences of destination address fields occur in a + message, they SHOULD be treated as if the address-list in the first + occurrence of the field is combined with the address lists of the + subsequent occurrences by adding a comma and concatenating. + +4.5.4. Obsolete identification fields + + The obsolete "In-Reply-To:" and "References:" fields differ from the + current syntax in that they allow phrase (words or quoted strings) to + appear. The obsolete forms of the left and right sides of msg-id + allow interspersed CFWS, making them syntactically identical to + local-part and domain respectively. + +obs-message-id = "Message-ID" *WSP ":" msg-id CRLF + +obs-in-reply-to = "In-Reply-To" *WSP ":" *(phrase / msg-id) CRLF + +obs-references = "References" *WSP ":" *(phrase / msg-id) CRLF + +obs-id-left = local-part + +obs-id-right = domain + + For purposes of interpretation, the phrases in the "In-Reply-To:" and + "References:" fields are ignored. + + Semantically, none of the optional CFWS surrounding the local-part + and the domain are part of the obs-id-left and obs-id-right + respectively. + +4.5.5. Obsolete informational fields + +obs-subject = "Subject" *WSP ":" unstructured CRLF + +obs-comments = "Comments" *WSP ":" unstructured CRLF + +obs-keywords = "Keywords" *WSP ":" obs-phrase-list CRLF + +4.5.6. Obsolete resent fields + + The obsolete syntax adds a "Resent-Reply-To:" field, which consists + of the field name, the optional comments and folding white space, the + colon, and a comma separated list of addresses. + +obs-resent-from = "Resent-From" *WSP ":" mailbox-list CRLF + +obs-resent-send = "Resent-Sender" *WSP ":" mailbox CRLF + + + + +Resnick Standards Track [Page 35] + +RFC 2822 Internet Message Format April 2001 + + +obs-resent-date = "Resent-Date" *WSP ":" date-time CRLF + +obs-resent-to = "Resent-To" *WSP ":" address-list CRLF + +obs-resent-cc = "Resent-Cc" *WSP ":" address-list CRLF + +obs-resent-bcc = "Resent-Bcc" *WSP ":" + (address-list / [CFWS]) CRLF + +obs-resent-mid = "Resent-Message-ID" *WSP ":" msg-id CRLF + +obs-resent-rply = "Resent-Reply-To" *WSP ":" address-list CRLF + + As with other resent fields, the "Resent-Reply-To:" field is to be + treated as trace information only. + +4.5.7. Obsolete trace fields + + The obs-return and obs-received are again given here as template + definitions, just as return and received are in section 3. Their + full syntax is given in [RFC2821]. + +obs-return = "Return-Path" *WSP ":" path CRLF + +obs-received = "Received" *WSP ":" name-val-list CRLF + +obs-path = obs-angle-addr + +4.5.8. Obsolete optional fields + +obs-optional = field-name *WSP ":" unstructured CRLF + +5. Security Considerations + + Care needs to be taken when displaying messages on a terminal or + terminal emulator. Powerful terminals may act on escape sequences + and other combinations of ASCII control characters with a variety of + consequences. They can remap the keyboard or permit other + modifications to the terminal which could lead to denial of service + or even damaged data. They can trigger (sometimes programmable) + answerback messages which can allow a message to cause commands to be + issued on the recipient's behalf. They can also effect the operation + of terminal attached devices such as printers. Message viewers may + wish to strip potentially dangerous terminal escape sequences from + the message prior to display. However, other escape sequences appear + in messages for useful purposes (cf. [RFC2045, RFC2046, RFC2047, + RFC2048, RFC2049, ISO2022]) and therefore should not be stripped + indiscriminately. + + + +Resnick Standards Track [Page 36] + +RFC 2822 Internet Message Format April 2001 + + + Transmission of non-text objects in messages raises additional + security issues. These issues are discussed in [RFC2045, RFC2046, + RFC2047, RFC2048, RFC2049]. + + Many implementations use the "Bcc:" (blind carbon copy) field + described in section 3.6.3 to facilitate sending messages to + recipients without revealing the addresses of one or more of the + addressees to the other recipients. Mishandling this use of "Bcc:" + has implications for confidential information that might be revealed, + which could eventually lead to security problems through knowledge of + even the existence of a particular mail address. For example, if + using the first method described in section 3.6.3, where the "Bcc:" + line is removed from the message, blind recipients have no explicit + indication that they have been sent a blind copy, except insofar as + their address does not appear in the message header. Because of + this, one of the blind addressees could potentially send a reply to + all of the shown recipients and accidentally reveal that the message + went to the blind recipient. When the second method from section + 3.6.3 is used, the blind recipient's address appears in the "Bcc:" + field of a separate copy of the message. If the "Bcc:" field sent + contains all of the blind addressees, all of the "Bcc:" recipients + will be seen by each "Bcc:" recipient. Even if a separate message is + sent to each "Bcc:" recipient with only the individual's address, + implementations still need to be careful to process replies to the + message as per section 3.6.3 so as not to accidentally reveal the + blind recipient to other recipients. + +6. Bibliography + + [ASCII] American National Standards Institute (ANSI), Coded + Character Set - 7-Bit American National Standard Code for + Information Interchange, ANSI X3.4, 1986. + + [ISO2022] International Organization for Standardization (ISO), + Information processing - ISO 7-bit and 8-bit coded + character sets - Code extension techniques, Third edition + - 1986-05-01, ISO 2022, 1986. + + [RFC822] Crocker, D., "Standard for the Format of ARPA Internet + Text Messages", RFC 822, August 1982. + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part One: Format of Internet Message + Bodies", RFC 2045, November 1996. + + [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, + November 1996. + + + +Resnick Standards Track [Page 37] + +RFC 2822 Internet Message Format April 2001 + + + [RFC2047] Moore, K., "Multipurpose Internet Mail Extensions (MIME) + Part Three: Message Header Extensions for Non-ASCII Text", + RFC 2047, November 1996. + + [RFC2048] Freed, N., Klensin, J. and J. Postel, "Multipurpose + Internet Mail Extensions (MIME) Part Four: Format of + Internet Message Bodies", RFC 2048, November 1996. + + [RFC2049] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Five: Conformance Criteria and + Examples", RFC 2049, November 1996. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC2234] Crocker, D., Editor, and P. Overell, "Augmented BNF for + Syntax Specifications: ABNF", RFC 2234, November 1997. + + [RFC2821] Klensin, J., Editor, "Simple Mail Transfer Protocol", RFC + 2821, March 2001. + + [STD3] Braden, R., "Host Requirements", STD 3, RFC 1122 and RFC + 1123, October 1989. + + [STD12] Mills, D., "Network Time Protocol", STD 12, RFC 1119, + September 1989. + + [STD13] Mockapetris, P., "Domain Name System", STD 13, RFC 1034 + and RFC 1035, November 1987. + + [STD14] Partridge, C., "Mail Routing and the Domain System", STD + 14, RFC 974, January 1986. + +7. Editor's Address + + Peter W. Resnick + QUALCOMM Incorporated + 5775 Morehouse Drive + San Diego, CA 92121-1714 + USA + + Phone: +1 858 651 4478 + Fax: +1 858 651 1102 + EMail: presnick@qualcomm.com + + + + + + + +Resnick Standards Track [Page 38] + +RFC 2822 Internet Message Format April 2001 + + +8. Acknowledgements + + Many people contributed to this document. They included folks who + participated in the Detailed Revision and Update of Messaging + Standards (DRUMS) Working Group of the Internet Engineering Task + Force (IETF), the chair of DRUMS, the Area Directors of the IETF, and + people who simply sent their comments in via e-mail. The editor is + deeply indebted to them all and thanks them sincerely. The below + list includes everyone who sent e-mail concerning this document. + Hopefully, everyone who contributed is named here: + + Matti Aarnio Barry Finkel Larry Masinter + Tanaka Akira Erik Forsberg Denis McKeon + Russ Allbery Chuck Foster William P McQuillan + Eric Allman Paul Fox Alexey Melnikov + Harald Tveit Alvestrand Klaus M. Frank Perry E. Metzger + Ran Atkinson Ned Freed Steven Miller + Jos Backus Jochen Friedrich Keith Moore + Bruce Balden Randall C. Gellens John Gardiner Myers + Dave Barr Sukvinder Singh Gill Chris Newman + Alan Barrett Tim Goodwin John W. Noerenberg + John Beck Philip Guenther Eric Norman + J. Robert von Behren Tony Hansen Mike O'Dell + Jos den Bekker John Hawkinson Larry Osterman + D. J. Bernstein Philip Hazel Paul Overell + James Berriman Kai Henningsen Jacob Palme + Norbert Bollow Robert Herriot Michael A. Patton + Raj Bose Paul Hethmon Uzi Paz + Antony Bowesman Jim Hill Michael A. Quinlan + Scott Bradner Paul E. Hoffman Eric S. Raymond + Randy Bush Steve Hole Sam Roberts + Tom Byrer Kari Hurtta Hugh Sasse + Bruce Campbell Marco S. Hyman Bart Schaefer + Larry Campbell Ofer Inbar Tom Scola + W. J. Carpenter Olle Jarnefors Wolfgang Segmuller + Michael Chapman Kevin Johnson Nick Shelness + Richard Clayton Sudish Joseph John Stanley + Maurizio Codogno Maynard Kang Einar Stefferud + Jim Conklin Prabhat Keni Jeff Stephenson + R. Kelley Cook John C. Klensin Bernard Stern + Steve Coya Graham Klyne Peter Sylvester + Mark Crispin Brad Knowles Mark Symons + Dave Crocker Shuhei Kobayashi Eric Thomas + Matt Curtin Peter Koch Lee Thompson + Michael D'Errico Dan Kohn Karel De Vriendt + Cyrus Daboo Christian Kuhtz Matthew Wall + Jutta Degener Anand Kumria Rolf Weber + Mark Delany Steen Larsen Brent B. Welch + + + +Resnick Standards Track [Page 39] + +RFC 2822 Internet Message Format April 2001 + + + Steve Dorner Eliot Lear Dan Wing + Harold A. Driscoll Barry Leiba Jack De Winter + Michael Elkins Jay Levitt Gregory J. Woodhouse + Robert Elz Lars-Johan Liman Greg A. Woods + Johnny Eriksson Charles Lindsey Kazu Yamamoto + Erik E. Fair Pete Loshin Alain Zahm + Roger Fajman Simon Lyall Jamie Zawinski + Patrik Faltstrom Bill Manning Timothy S. Zurcher + Claus Andre Farber John Martin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 40] + +RFC 2822 Internet Message Format April 2001 + + +Appendix A. Example messages + + This section presents a selection of messages. These are intended to + assist in the implementation of this standard, but should not be + taken as normative; that is to say, although the examples in this + section were carefully reviewed, if there happens to be a conflict + between these examples and the syntax described in sections 3 and 4 + of this document, the syntax in those sections is to be taken as + correct. + + Messages are delimited in this section between lines of "----". The + "----" lines are not part of the message itself. + +A.1. Addressing examples + + The following are examples of messages that might be sent between two + individuals. + +A.1.1. A message from one person to another with simple addressing + + This could be called a canonical message. It has a single author, + John Doe, a single recipient, Mary Smith, a subject, the date, a + message identifier, and a textual message in the body. + +---- +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 41] + +RFC 2822 Internet Message Format April 2001 + + + If John's secretary Michael actually sent the message, though John + was the author and replies to this message should go back to him, the + sender field would be used: + +---- +From: John Doe +Sender: Michael Jones +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + +A.1.2. Different types of mailboxes + + This message includes multiple addresses in the destination fields + and also uses several different forms of addresses. + +---- +From: "Joe Q. Public" +To: Mary Smith , jdoe@example.org, Who? +Cc: , "Giant; \"Big\" Box" +Date: Tue, 1 Jul 2003 10:52:37 +0200 +Message-ID: <5678.21-Nov-1997@example.com> + +Hi everyone. +---- + + Note that the display names for Joe Q. Public and Giant; "Big" Box + needed to be enclosed in double-quotes because the former contains + the period and the latter contains both semicolon and double-quote + characters (the double-quote characters appearing as quoted-pair + construct). Conversely, the display name for Who? could appear + without them because the question mark is legal in an atom. Notice + also that jdoe@example.org and boss@nil.test have no display names + associated with them at all, and jdoe@example.org uses the simpler + address form without the angle brackets. + + + + + + + + + + + +Resnick Standards Track [Page 42] + +RFC 2822 Internet Message Format April 2001 + + +A.1.3. Group addresses + +---- +From: Pete +To: A Group:Chris Jones ,joe@where.test,John ; +Cc: Undisclosed recipients:; +Date: Thu, 13 Feb 1969 23:32:54 -0330 +Message-ID: + +Testing. +---- + + In this message, the "To:" field has a single group recipient named A + Group which contains 3 addresses, and a "Cc:" field with an empty + group recipient named Undisclosed recipients. + +A.2. Reply messages + + The following is a series of three messages that make up a + conversation thread between John and Mary. John firsts sends a + message to Mary, Mary then replies to John's message, and then John + replies to Mary's reply message. + + Note especially the "Message-ID:", "References:", and "In-Reply-To:" + fields in each message. + +---- +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + + + + + + + + + + + + + + + +Resnick Standards Track [Page 43] + +RFC 2822 Internet Message Format April 2001 + + + When sending replies, the Subject field is often retained, though + prepended with "Re: " as described in section 3.6.5. + +---- +From: Mary Smith +To: John Doe +Reply-To: "Mary Smith: Personal Account" +Subject: Re: Saying Hello +Date: Fri, 21 Nov 1997 10:01:10 -0600 +Message-ID: <3456@example.net> +In-Reply-To: <1234@local.machine.example> +References: <1234@local.machine.example> + +This is a reply to your hello. +---- + + Note the "Reply-To:" field in the above message. When John replies + to Mary's message above, the reply should go to the address in the + "Reply-To:" field instead of the address in the "From:" field. + +---- +To: "Mary Smith: Personal Account" +From: John Doe +Subject: Re: Saying Hello +Date: Fri, 21 Nov 1997 11:00:00 -0600 +Message-ID: +In-Reply-To: <3456@example.net> +References: <1234@local.machine.example> <3456@example.net> + +This is a reply to your reply. +---- + +A.3. Resent messages + + Start with the message that has been used as an example several + times: + +---- +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + + + + +Resnick Standards Track [Page 44] + +RFC 2822 Internet Message Format April 2001 + + + Say that Mary, upon receiving this message, wishes to send a copy of + the message to Jane such that (a) the message would appear to have + come straight from John; (b) if Jane replies to the message, the + reply should go back to John; and (c) all of the original + information, like the date the message was originally sent to Mary, + the message identifier, and the original addressee, is preserved. In + this case, resent fields are prepended to the message: + +---- +Resent-From: Mary Smith +Resent-To: Jane Brown +Resent-Date: Mon, 24 Nov 1997 14:22:01 -0800 +Resent-Message-ID: <78910@example.net> +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + + If Jane, in turn, wished to resend this message to another person, + she would prepend her own set of resent header fields to the above + and send that. + + + + + + + + + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 45] + +RFC 2822 Internet Message Format April 2001 + + +A.4. Messages with trace fields + + As messages are sent through the transport system as described in + [RFC2821], trace fields are prepended to the message. The following + is an example of what those trace fields might look like. Note that + there is some folding white space in the first one since these lines + can be long. + +---- +Received: from x.y.test + by example.net + via TCP + with ESMTP + id ABC12345 + for ; 21 Nov 1997 10:05:43 -0600 +Received: from machine.example by x.y.test; 21 Nov 1997 10:01:22 -0600 +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: Fri, 21 Nov 1997 09:55:06 -0600 +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + + + + + + + + + + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 46] + +RFC 2822 Internet Message Format April 2001 + + +A.5. White space, comments, and other oddities + + White space, including folding white space, and comments can be + inserted between many of the tokens of fields. Taking the example + from A.1.3, white space and comments can be inserted into all of the + fields. + +---- +From: Pete(A wonderful \) chap) +To:A Group(Some people) + :Chris Jones , + joe@example.org, + John (my dear friend); (the end of the group) +Cc:(Empty list)(start)Undisclosed recipients :(nobody(that I know)) ; +Date: Thu, + 13 + Feb + 1969 + 23:32 + -0330 (Newfoundland Time) +Message-ID: + +Testing. +---- + + The above example is aesthetically displeasing, but perfectly legal. + Note particularly (1) the comments in the "From:" field (including + one that has a ")" character appearing as part of a quoted-pair); (2) + the white space absent after the ":" in the "To:" field as well as + the comment and folding white space after the group name, the special + character (".") in the comment in Chris Jones's address, and the + folding white space before and after "joe@example.org,"; (3) the + multiple and nested comments in the "Cc:" field as well as the + comment immediately following the ":" after "Cc"; (4) the folding + white space (but no comments except at the end) and the missing + seconds in the time of the date field; and (5) the white space before + (but not within) the identifier in the "Message-ID:" field. + +A.6. Obsoleted forms + + The following are examples of obsolete (that is, the "MUST NOT + generate") syntactic elements described in section 4 of this + document. + + + + + + + + +Resnick Standards Track [Page 47] + +RFC 2822 Internet Message Format April 2001 + + +A.6.1. Obsolete addressing + + Note in the below example the lack of quotes around Joe Q. Public, + the route that appears in the address for Mary Smith, the two commas + that appear in the "To:" field, and the spaces that appear around the + "." in the jdoe address. + +---- +From: Joe Q. Public +To: Mary Smith <@machine.tld:mary@example.net>, , jdoe@test . example +Date: Tue, 1 Jul 2003 10:52:37 +0200 +Message-ID: <5678.21-Nov-1997@example.com> + +Hi everyone. +---- + +A.6.2. Obsolete dates + + The following message uses an obsolete date format, including a non- + numeric time zone and a two digit year. Note that although the + day-of-week is missing, that is not specific to the obsolete syntax; + it is optional in the current syntax as well. + +---- +From: John Doe +To: Mary Smith +Subject: Saying Hello +Date: 21 Nov 97 09:55:06 GMT +Message-ID: <1234@local.machine.example> + +This is a message just to say hello. +So, "Hello". +---- + +A.6.3. Obsolete white space and comments + + White space and comments can appear between many more elements than + in the current syntax. Also, folding lines that are made up entirely + of white space are legal. + + + + + + + + + + + + +Resnick Standards Track [Page 48] + +RFC 2822 Internet Message Format April 2001 + + +---- +From : John Doe +To : Mary Smith +__ + +Subject : Saying Hello +Date : Fri, 21 Nov 1997 09(comment): 55 : 06 -0600 +Message-ID : <1234 @ local(blah) .machine .example> + +This is a message just to say hello. +So, "Hello". +---- + + Note especially the second line of the "To:" field. It starts with + two space characters. (Note that "__" represent blank spaces.) + Therefore, it is considered part of the folding as described in + section 4.2. Also, the comments and white space throughout + addresses, dates, and message identifiers are all part of the + obsolete syntax. + +Appendix B. Differences from earlier standards + + This appendix contains a list of changes that have been made in the + Internet Message Format from earlier standards, specifically [RFC822] + and [STD3]. Items marked with an asterisk (*) below are items which + appear in section 4 of this document and therefore can no longer be + generated. + + 1. Period allowed in obsolete form of phrase. + 2. ABNF moved out of document to [RFC2234]. + 3. Four or more digits allowed for year. + 4. Header field ordering (and lack thereof) made explicit. + 5. Encrypted header field removed. + 6. Received syntax loosened to allow any token/value pair. + 7. Specifically allow and give meaning to "-0000" time zone. + 8. Folding white space is not allowed between every token. + 9. Requirement for destinations removed. + 10. Forwarding and resending redefined. + 11. Extension header fields no longer specifically called out. + 12. ASCII 0 (null) removed.* + 13. Folding continuation lines cannot contain only white space.* + 14. Free insertion of comments not allowed in date.* + 15. Non-numeric time zones not allowed.* + 16. Two digit years not allowed.* + 17. Three digit years interpreted, but not allowed for generation. + 18. Routes in addresses not allowed.* + 19. CFWS within local-parts and domains not allowed.* + 20. Empty members of address lists not allowed.* + + + +Resnick Standards Track [Page 49] + +RFC 2822 Internet Message Format April 2001 + + + 21. Folding white space between field name and colon not allowed.* + 22. Comments between field name and colon not allowed. + 23. Tightened syntax of in-reply-to and references.* + 24. CFWS within msg-id not allowed.* + 25. Tightened semantics of resent fields as informational only. + 26. Resent-Reply-To not allowed.* + 27. No multiple occurrences of fields (except resent and received).* + 28. Free CR and LF not allowed.* + 29. Routes in return path not allowed.* + 30. Line length limits specified. + 31. Bcc more clearly specified. + +Appendix C. Notices + + Intellectual Property + + The IETF takes no position regarding the validity or scope of any + intellectual property or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; neither does it represent that it + has made any effort to identify any such rights. Information on the + IETF's procedures with respect to rights in standards-track and + standards-related documentation can be found in BCP-11. Copies of + claims of rights made available for publication and any assurances of + licenses to be made available, or the result of an attempt made to + obtain a general license or permission for the use of such + proprietary rights by implementors or users of this specification can + be obtained from the IETF Secretariat. + + + + + + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 50] + +RFC 2822 Internet Message Format April 2001 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2001). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + + + + + + + + + + + + + +Resnick Standards Track [Page 51] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3156.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3156.txt new file mode 100644 index 00000000..c8ca1d5f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3156.txt @@ -0,0 +1,842 @@ + + + + + +Network Working Group M. Elkins +Request for Comments: 3156 Network Associates, Inc. +Updates: 2015 D. Del Torto +Category: Standards Track CryptoRights Foundation + R. Levien + University of California at Berkeley + T. Roessler + August 2001 + + + MIME Security with OpenPGP + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2001). All Rights Reserved. + +Abstract + + This document describes how the OpenPGP Message Format can be used to + provide privacy and authentication using the Multipurpose Internet + Mail Extensions (MIME) security content types described in RFC 1847. + +1. Introduction + + Work on integrating PGP (Pretty Good Privacy) with MIME [3] + (including the since withdrawn "application/pgp" content type) prior + to RFC 2015 suffered from a number of problems, the most significant + of which is the inability to recover signed message bodies without + parsing data structures specific to PGP. RFC 2015 makes use of the + elegant solution proposed in RFC 1847, which defines security + multipart formats for MIME. The security multiparts clearly separate + the signed message body from the signature, and have a number of + other desirable properties. This document revises RFC 2015 to adopt + the integration of PGP and MIME to the needs which emerged during the + work on the OpenPGP specification. + + This document defines three content types for implementing security + and privacy with OpenPGP: "application/pgp-encrypted", + "application/pgp-signature" and "application/pgp-keys". + + + + +Elkins, et al. Standards Track [Page 1] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in RFC 2119. + +2. OpenPGP data formats + + OpenPGP implementations can generate either ASCII armor (described in + [1]) or 8-bit binary output when encrypting data, generating a + digital signature, or extracting public key data. The ASCII armor + output is the REQUIRED method for data transfer. This allows those + users who do not have the means to interpret the formats described in + this document to be able to extract and use the OpenPGP information + in the message. + + When the amount of data to be transmitted requires that it be sent in + many parts, the MIME message/partial mechanism SHOULD be used rather + than the multi-part ASCII armor OpenPGP format. + +3. Content-Transfer-Encoding restrictions + + Multipart/signed and multipart/encrypted are to be treated by agents + as opaque, meaning that the data is not to be altered in any way [2], + [7]. However, many existing mail gateways will detect if the next + hop does not support MIME or 8-bit data and perform conversion to + either Quoted-Printable or Base64. This presents serious problems + for multipart/signed, in particular, where the signature is + invalidated when such an operation occurs. For this reason all data + signed according to this protocol MUST be constrained to 7 bits (8- + bit data MUST be encoded using either Quoted-Printable or Base64). + Note that this also includes the case where a signed object is also + encrypted (see section 6). This restriction will increase the + likelihood that the signature will be valid upon receipt. + + Additionally, implementations MUST make sure that no trailing + whitespace is present after the MIME encoding has been applied. + + Note: In most cases, trailing whitespace can either be removed, or + protected by applying an appropriate content-transfer-encoding. + However, special care must be taken when any header lines - either + in MIME entity headers, or in embedded RFC 822 headers - are + present which only consist of whitespace: Such lines must be + removed entirely, since replacing them by empty lines would turn + them into header delimiters, and change the semantics of the + message. The restrictions on whitespace are necessary in order to + make the hash calculated invariant under the text and binary mode + signature mechanisms provided by OpenPGP [1]. Also, they help to + avoid compatibility problems with PGP implementations which + predate the OpenPGP specification. + + + +Elkins, et al. Standards Track [Page 2] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + Note: If any line begins with the string "From ", it is strongly + suggested that either the Quoted-Printable or Base64 MIME encoding + be applied. If Quoted-Printable is used, at least one of the + characters in the string should be encoded using the hexadecimal + coding rule. This is because many mail transfer and delivery + agents treat "From " (the word "from" followed immediately by a + space character) as the start of a new message and thus insert a + right angle-bracket (>) in front of any line beginning with + "From " to distinguish this case, invalidating the signature. + + Data that is ONLY to be encrypted is allowed to contain 8-bit + characters and trailing whitespace and therefore need not undergo the + conversion to a 7bit format, and the stripping of whitespace. + + Implementor's note: It cannot be stressed enough that applications + using this standard follow MIME's suggestion that you "be + conservative in what you generate, and liberal in what you + accept." In this particular case it means it would be wise for an + implementation to accept messages with any content-transfer- + encoding, but restrict generation to the 7-bit format required by + this memo. This will allow future compatibility in the event the + Internet SMTP framework becomes 8-bit friendly. + +4. OpenPGP encrypted data + + Before OpenPGP encryption, the data is written in MIME canonical + format (body and headers). + + OpenPGP encrypted data is denoted by the "multipart/encrypted" + content type, described in [2], and MUST have a "protocol" parameter + value of "application/pgp-encrypted". Note that the value of the + parameter MUST be enclosed in quotes. + + The multipart/encrypted MIME body MUST consist of exactly two body + parts, the first with content type "application/pgp-encrypted". This + body contains the control information. A message complying with this + standard MUST contain a "Version: 1" field in this body. Since the + OpenPGP packet format contains all other information necessary for + decrypting, no other information is required here. + + The second MIME body part MUST contain the actual encrypted data. It + MUST be labeled with a content type of "application/octet-stream". + + Example message: + + From: Michael Elkins + To: Michael Elkins + Mime-Version: 1.0 + + + +Elkins, et al. Standards Track [Page 3] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + Content-Type: multipart/encrypted; boundary=foo; + protocol="application/pgp-encrypted" + + --foo + Content-Type: application/pgp-encrypted + + Version: 1 + + --foo + Content-Type: application/octet-stream + + -----BEGIN PGP MESSAGE----- + Version: 2.6.2 + + hIwDY32hYGCE8MkBA/wOu7d45aUxF4Q0RKJprD3v5Z9K1YcRJ2fve87lMlDlx4Oj + eW4GDdBfLbJE7VUpp13N19GL8e/AqbyyjHH4aS0YoTk10QQ9nnRvjY8nZL3MPXSZ + g9VGQxFeGqzykzmykU6A26MSMexR4ApeeON6xzZWfo+0yOqAq6lb46wsvldZ96YA + AABH78hyX7YX4uT1tNCWEIIBoqqvCeIMpp7UQ2IzBrXg6GtukS8NxbukLeamqVW3 + 1yt21DYOjuLzcMNe/JNsD9vDVCvOOG3OCi8= + =zzaA + -----END PGP MESSAGE----- + + --foo-- + +5. OpenPGP signed data + + OpenPGP signed messages are denoted by the "multipart/signed" content + type, described in [2], with a "protocol" parameter which MUST have a + value of "application/pgp-signature" (MUST be quoted). + + The "micalg" parameter for the "application/pgp-signature" protocol + MUST contain exactly one hash-symbol of the format "pgp-", where identifies the Message + Integrity Check (MIC) algorithm used to generate the signature. + Hash-symbols are constructed from the text names registered in [1] or + according to the mechanism defined in that document by converting the + text name to lower case and prefixing it with the four characters + "pgp-". + + Currently defined values are "pgp-md5", "pgp-sha1", "pgp-ripemd160", + "pgp-md2", "pgp-tiger192", and "pgp-haval-5-160". + + The multipart/signed body MUST consist of exactly two parts. The + first part contains the signed data in MIME canonical format, + including a set of appropriate content headers describing the data. + + The second body MUST contain the OpenPGP digital signature. It MUST + be labeled with a content type of "application/pgp-signature". + + + +Elkins, et al. Standards Track [Page 4] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + Note: Implementations can either generate "signatures of a + canonical text document" or "signatures of a binary document", as + defined in [1]. The restrictions on the signed material put forth + in section 3 and in this section will make sure that the various + MIC algorithm variants specified in [1] and [5] will all produce + the same result. + + When the OpenPGP digital signature is generated: + + (1) The data to be signed MUST first be converted to its content- + type specific canonical form. For text/plain, this means + conversion to an appropriate character set and conversion of + line endings to the canonical sequence. + + (2) An appropriate Content-Transfer-Encoding is then applied; see + section 3. In particular, line endings in the encoded data + MUST use the canonical sequence where appropriate + (note that the canonical line ending may or may not be present + on the last line of encoded data and MUST NOT be included in + the signature if absent). + + (3) MIME content headers are then added to the body, each ending + with the canonical sequence. + + (4) As described in section 3 of this document, any trailing + whitespace MUST then be removed from the signed material. + + (5) As described in [2], the digital signature MUST be calculated + over both the data to be signed and its set of content headers. + + (6) The signature MUST be generated detached from the signed data + so that the process does not alter the signed data in any way. + + Note: The accepted OpenPGP convention is for signed data to end + with a sequence. Note that the sequence + immediately preceding a MIME boundary delimiter line is considered + to be part of the delimiter in [3], 5.1. Thus, it is not part of + the signed data preceding the delimiter line. An implementation + which elects to adhere to the OpenPGP convention has to make sure + it inserts a pair on the last line of the data to be + signed and transmitted (signed message and transmitted message + MUST be identical). + + Example message: + + From: Michael Elkins + To: Michael Elkins + Mime-Version: 1.0 + + + +Elkins, et al. Standards Track [Page 5] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + Content-Type: multipart/signed; boundary=bar; micalg=pgp-md5; + protocol="application/pgp-signature" + + --bar + & Content-Type: text/plain; charset=iso-8859-1 + & Content-Transfer-Encoding: quoted-printable + & + & =A1Hola! + & + & Did you know that talking to yourself is a sign of senility? + & + & It's generally a good idea to encode lines that begin with + & From=20because some mail transport agents will insert a greater- + & than (>) sign, thus invalidating the signature. + & + & Also, in some cases it might be desirable to encode any =20 + & trailing whitespace that occurs on lines in order to ensure =20 + & that the message signature is not invalidated when passing =20 + & a gateway that modifies such whitespace (like BITNET). =20 + & + & me + + --bar + + Content-Type: application/pgp-signature + + -----BEGIN PGP MESSAGE----- + Version: 2.6.2 + + iQCVAwUBMJrRF2N9oWBghPDJAQE9UQQAtl7LuRVndBjrk4EqYBIb3h5QXIX/LC// + jJV5bNvkZIGPIcEmI5iFd9boEgvpirHtIREEqLQRkYNoBActFBZmh9GC3C041WGq + uMbrbxc+nIs1TIKlA08rVi9ig/2Yh7LFrK5Ein57U/W72vgSxLhe/zhdfolT9Brn + HOxEa44b+EI= + =ndaj + -----END PGP MESSAGE----- + + --bar-- + + The "&"s in the previous example indicate the portion of the data + over which the signature was calculated. + + Upon receipt of a signed message, an application MUST: + + (1) Convert line endings to the canonical sequence before + the signature can be verified. This is necessary since the + local MTA may have converted to a local end of line convention. + + + + + +Elkins, et al. Standards Track [Page 6] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + (2) Pass both the signed data and its associated content headers + along with the OpenPGP signature to the signature verification + service. + +6. Encrypted and Signed Data + + Sometimes it is desirable to both digitally sign and then encrypt a + message to be sent. This protocol allows for two methods of + accomplishing this task. + +6.1. RFC 1847 Encapsulation + + In [2], it is stated that the data is first signed as a + multipart/signature body, and then encrypted to form the final + multipart/encrypted body. This is most useful for standard MIME- + compliant message forwarding. + + Example: + + Content-Type: multipart/encrypted; + protocol="application/pgp-encrypted"; boundary=foo + + --foo + Content-Type: application/pgp-encrypted + + Version: 1 + + --foo + Content-Type: application/octet-stream + + -----BEGIN PGP MESSAGE----- + & Content-Type: multipart/signed; micalg=pgp-md5 + & protocol="application/pgp-signature"; boundary=bar + & + & --bar + & Content-Type: text/plain; charset=us-ascii + & + & This message was first signed, and then encrypted. + & + & --bar + & Content-Type: application/pgp-signature + & + & -----BEGIN PGP MESSAGE----- + & Version: 2.6.2 + & + & iQCVAwUBMJrRF2N9oWBghPDJAQE9UQQAtl7LuRVndBjrk4EqYBIb3h5QXIX/LC// + & jJV5bNvkZIGPIcEmI5iFd9boEgvpirHtIREEqLQRkYNoBActFBZmh9GC3C041WGq + & uMbrbxc+nIs1TIKlA08rVi9ig/2Yh7LFrK5Ein57U/W72vgSxLhe/zhdfolT9Brn + + + +Elkins, et al. Standards Track [Page 7] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + & HOxEa44b+EI= + & =ndaj + & -----END PGP MESSAGE----- + & + & --bar-- + -----END PGP MESSAGE----- + + --foo-- + + (The text preceded by '&' indicates that it is really encrypted, but + presented as text for clarity.) + +6.2. Combined method + + The OpenPGP packet format [1] describes a method for signing and + encrypting data in a single OpenPGP message. This method is allowed + in order to reduce processing overhead and increase compatibility + with non-MIME implementations of OpenPGP. The resulting data is + formatted as a "multipart/encrypted" object as described in Section + 4. + + Messages which are encrypted and signed in this combined fashion are + REQUIRED to follow the same canonicalization rules as + multipart/signed objects. + + It is explicitly allowed for an agent to decrypt a combined message + and rewrite it as a multipart/signed object using the signature data + embedded in the encrypted version. + +7. Distribution of OpenPGP public keys + + Content-Type: application/pgp-keys + Required parameters: none + Optional parameters: none + + A MIME body part of the content type "application/pgp-keys" contains + ASCII-armored transferable Public Key Packets as defined in [1], + section 10.1. + +8. Security Considerations + + Signatures of a canonical text document as defined in [1] ignore + trailing white space in signed material. Implementations which + choose to use signatures of canonical text documents will not be able + to detect the addition of whitespace in transit. + + See [3], [4] for more information on the security considerations + concerning the underlying protocols. + + + +Elkins, et al. Standards Track [Page 8] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +9. IANA Considerations + + This document defines three media types: "application/pgp-encrypted", + "application/pgp-signature" and "application/pgp-keys". The + following sections specify the IANA registrations for these types. + +9.1. Registration of the application/pgp-encrypted media type + + MIME media type name: application + MIME subtype name: pgp-encrypted + Required parameters: none + Optional parameters: none + + Encoding considerations: + + Currently this media type always consists of a single 7bit text + string. + + Security considerations: + + See Section 8 and RFC 2440 Section 13. + + Interoperability considerations: none + + Published specification: + + This document. + + Additional information: + + Magic number(s): none + File extension(s): none + Macintosh File Type Code(s): none + + Person & email address to contact for further information: + + Michael Elkins + Email: me@cs.hmc.edu + + Intended usage: common + + Author/Change controller: + + Michael Elkins + Email: me@cs.hmc.edu + + + + + + +Elkins, et al. Standards Track [Page 9] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +9.2. Registration of the application/pgp-signature media type + + MIME media type name: application + MIME subtype name: pgp-signature + Required parameters: none + Optional parameters: none + + Encoding considerations: + + The content of this media type always consists of 7bit text. + + Security considerations: + + See Section 8 and RFC 2440 Section 13. + + Interoperability considerations: none + + Published specification: + + RFC 2440 and this document. + + Additional information: + + Magic number(s): none + File extension(s): asc, sig + Macintosh File Type Code(s): pgDS + + Person & email address to contact for further information: + + Michael Elkins + Email: me@cs.hmc.edu + + Intended usage: common + + Author/Change controller: + + Michael Elkins + Email: me@cs.hmc.edu + +9.3. Registration of the application/pgp-keys media type + + MIME media type name: application + MIME subtype name: pgp-keys + Required parameters: none + Optional parameters: none + + + + + + +Elkins, et al. Standards Track [Page 10] + +RFC 3156 MIME Security with OpenPGP August 2001 + + + Encoding considerations: + + The content of this media type always consists of 7bit text. + + Security considerations: + + See Section 8 and RFC 2440 Section 13. + + Interoperability considerations: none + + Published specification: + + RFC 2440 and this document. + + Additional information: + + Magic number(s): none + File extension(s): asc + Macintosh File Type Code(s): none + + Person & email address to contact for further information: + + Michael Elkins + Email: me@cs.hmc.edu + + Intended usage: common + + Author/Change controller: + + Michael Elkins + Email: me@cs.hmc.edu + + + + + + + + + + + + + + + + + + + + +Elkins, et al. Standards Track [Page 11] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +10. Notes + + "PGP" and "Pretty Good Privacy" are registered trademarks of Network + Associates, Inc. + +11. Acknowledgements + + This document relies on the work of the IETF's OpenPGP Working + Group's definitions of the OpenPGP Message Format. The OpenPGP + message format is currently described in RFC 2440 [1]. + + Special thanks are due: to Philip Zimmermann for his original and + ongoing work on PGP; to Charles Breed, Jon Callas and Dave Del Torto + for originally proposing the formation of the OpenPGP Working Group; + and to Steve Schoenfeld for helpful feedback during the draft + process. The authors would also like to thank the engineers at + Pretty Good Privacy, Inc (now Network Associates, Inc), including + Colin Plumb, Hal Finney, Jon Callas, Mark Elrod, Mark Weaver and + Lloyd Chambers, for their technical commentary. + + Additional thanks are due to Jeff Schiller and Derek Atkins for their + continuing support of strong cryptography and PGP freeware at MIT; to + Rodney Thayer of Sable Technology; to John Noerenberg, Steve Dorner + and Laurence Lundblade of the Eudora team at QUALCOMM, Inc; to Bodo + Moeller for proposing the approach followed with respect to trailing + whitespace; to John Gilmore, Hugh Daniel and Fred Ringel (at + Rivertown) and Ian Bell (at Turnpike) for their timely critical + commentary; and to the international members of the IETF's OpenPGP + mailing list, including William Geiger, Lutz Donnerhacke and Kazu + Yamamoto. The idea to use multipart/mixed with multipart/signed has + been attributed to James Galvin. Finally, our gratitude is due to + the many members of the "Cypherpunks," "Coderpunks" and "pgp-users" + mailing lists and the many users + of PGP worldwide for helping keep the path to privacy open. + + + + + + + + + + + + + + + + + +Elkins, et al. Standards Track [Page 12] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +12. Addresses of the Authors and OpenPGP Working Group Chair + + The OpenPGP working group can be contacted via the current chair: + + John W. Noerenberg II + Qualcomm, Inc. + 5775 Morehouse Dr. + San Diego, CA 92121 USA + + Phone: +1 619 658 3510 + EMail: jwn2@qualcomm.com + + The principal authors of this document are: + + Dave Del Torto + CryptoRights Foundation + 80 Alviso Street, Mailstop: CRF + San Francisco, CA 94127 USA + + Phone: +1.415.334.5533, vm: #2 + EMail: ddt@cryptorights.org, ddt@openpgp.net + + + Michael Elkins + Network Associates, Inc. + 3415 S. Sepulveda Blvd Suite 700 + Los Angeles, CA 90034 USA + + Phone: +1.310.737.1663 + Fax: +1.310.737.1755 + Email: me@cs.hmc.edu, Michael_Elkins@NAI.com + + + Raph Levien + University of California at Berkeley + 579 Soda Hall + Berkeley, CA 94720 USA + + Phone: +1.510.642.6509 + EMail: raph@acm.org + + + Thomas Roessler + Nordstrasse 99 + D-53111 Bonn, Germany + + Phone: +49-228-638007 + EMail: roessler@does-not-exist.org + + + +Elkins, et al. Standards Track [Page 13] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +References + + [1] Callas, J., Donnerhacke, L., Finney, H. and R. Thayer, "OpenPGP + Message Format", RFC 2440, November 1998. + + [2] Galvin, J., Murphy, G., Crocker, S. and N. Freed, "Security + Multiparts for MIME: Multipart/Signed and Multipart/Encrypted", + RFC 1847, October 1995. + + [3] Freed, N. and N. Borenstein, "Multipurpose Internet Mail + Extensions (MIME) Part Two: Media Types", RFC 2046, November + 1996. + + [4] Galvin, J., Murphy, G., Crocker, S. and N. Freed, "MIME Object + Security Services", RFC 1848, October 1995. + + [5] Atkins, D., Stallings, W. and P. Zimmermann, "PGP Message + Exchange Formats", RFC 1991, August 1996. + + [6] Elkins, M., "MIME Security with Pretty Good Privacy (PGP)", RFC + 2015, October 1996. + + [7] Freed, N., "Gateways and MIME Security Multiparts", RFC 2480, + January 1999. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Elkins, et al. Standards Track [Page 14] + +RFC 3156 MIME Security with OpenPGP August 2001 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2001). All Rights Reserved. + + This document and translations of it may be copied and furnished to + others, and derivative works that comment on or otherwise explain it + or assist in its implementation may be prepared, copied, published + and distributed, in whole or in part, without restriction of any + kind, provided that the above copyright notice and this paragraph are + included on all such copies and derivative works. However, this + document itself may not be modified in any way, such as by removing + the copyright notice or references to the Internet Society or other + Internet organizations, except as needed for the purpose of + developing Internet standards in which case the procedures for + copyrights defined in the Internet Standards process must be + followed, or as required to translate it into languages other than + English. + + The limited permissions granted above are perpetual and will not be + revoked by the Internet Society or its successors or assigns. + + This document and the information contained herein is provided on an + "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING + TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING + BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION + HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF + MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + + + + + + + + + + + + + +Elkins, et al. Standards Track [Page 15] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3676.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3676.txt new file mode 100644 index 00000000..bc08fba7 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc3676.txt @@ -0,0 +1,1123 @@ + + + + + + +Network Working Group R. Gellens +Request for Comments: 3676 Qualcomm +Obsoletes: 2646 February 2004 +Category: Standards Track + + + The Text/Plain Format and DelSp Parameters + +Status of this Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2004). All Rights Reserved. + +Abstract + + This specification establishes two parameters (Format and DelSP) to + be used with the Text/Plain media type. In the presence of these + parameters, trailing whitespace is used to indicate flowed lines and + a canonical quote indicator is used to indicate quoted lines. This + results in an encoding which appears as normal Text/Plain in older + implementations, since it is in fact normal Text/Plain, yet provides + for superior wrapping/flowing, and quoting. + + This document supersedes the one specified in RFC 2646, "The + Text/Plain Format Parameter", and adds the DelSp parameter to + accommodate languages/coded character sets in which ASCII spaces are + not used or appear rarely. + +Table of Contents + + 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . 2 + 2. Conventions Used in this Document . . . . . . . . . . . . . . 2 + 3. The Problem . . . . . . . . . . . . . . . . . . . . . . . . . 3 + 3.1. Paragraph Text. . . . . . . . . . . . . . . . . . . . . 3 + 3.2. Embarrassing Line Wrap . . . . . . . . . . . . . . . . 3 + 3.3. New Media Types . . . . . . . . . . . . . . . . . . . . 4 + 4. The Format and DelSp Parameters . . . . . . . . . . . . . . . 5 + 4.1. Interpreting Format=Flowed. . . . . . . . . . . . . . . 6 + 4.2. Generating Format=Flowed . . . . . . . . . . . . . . . 7 + 4.3. Usenet Signature Convention . . . . . . . . . . . . . . 9 + 4.4. Space-Stuffing . . . . . . . . . . . . . . . . . . . . 9 + + + +Gellens Standards Track [Page 1] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + 4.5. Quoting . . . . . . . . . . . . . . . . . . . . . . . . 9 + 4.6. Digital Signatures and Encryption . . . . . . . . . . . 11 + 4.7. Examples. . . . . . . . . . . . . . . . . . . . . . . . 12 + 5. Interoperability. . . . . . . . . . . . . . . . . . . . . . . 12 + 6. ABNF. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 + 7. Failure Modes . . . . . . . . . . . . . . . . . . . . . . . . 14 + 7.1. Trailing White Space Corruption . . . . . . . . . . . . 14 + 8. Security Considerations . . . . . . . . . . . . . . . . . . . 15 + 9. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 15 + 10. Internationalization Considerations . . . . . . . . . . . . . 15 + 11. Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . 15 + 12. Normative References. . . . . . . . . . . . . . . . . . . . . 16 + 13. Informative References. . . . . . . . . . . . . . . . . . . . 16 + Appendix A: Changes from RFC 2646 . . . . . . . . . . . . . . . . 18 + Author's Address. . . . . . . . . . . . . . . . . . . . . . . . . 19 + Full Copyright Statement. . . . . . . . . . . . . . . . . . . . . 20 + +1. Introduction + + Interoperability problems have been observed with erroneous labelling + of paragraph text as Text/Plain, and with various forms of + "embarrassing line wrap". (See Section 3.) + + Attempts to deploy new media types, such as Text/Enriched [Rich] and + Text/HTML [HTML] have suffered from a lack of backwards compatibility + and an often hostile user reaction at the receiving end. + + What is required is a format which is in all significant ways + Text/Plain, and therefore is quite suitable for display as + Text/Plain, and yet allows the sender to express to the receiver + which lines are quoted and which lines are considered a logical + paragraph, and thus eligible to be flowed (wrapped and joined) as + appropriate. + +2. Conventions Used in this Document + + The key words "REQUIRED", "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", + and "MAY" in this document are to be interpreted as described in "Key + words for use in RFCs to Indicate Requirement Levels" [KEYWORDS]. + + The term "paragraph" is used here to mean a series of lines which are + logically to be treated as a unit for display purposes and eligible + to be flowed (wrapped and joined) as appropriate to fit in the + display window and when creating text for replies, forwarding, etc. + + + + + + + +Gellens Standards Track [Page 2] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + +3. The Problem + + The Text/Plain media type is the lowest common denominator of + Internet email, with lines of no more than 998 characters (by + convention usually no more than 78), and where the carriage-return + and line-feed (CRLF) sequence represents a line break (see [MIME-IMT] + and [MSG-FMT]). + + Text/Plain is usually displayed as preformatted text, often in a + fixed font. That is, the characters start at the left margin of the + display window, and advance to the right until a CRLF sequence is + seen, at which point a new line is started, again at the left margin. + When a line length exceeds the display window, some clients will wrap + the line, while others invoke a horizontal scroll bar. + + Text which meets this description is defined by this memo as "fixed". + + Some interoperability problems have been observed with this format: + +3.1. Paragraph Text + + Many modern programs use a proportional-spaced font, and use CRLF to + represent paragraph breaks. Line breaks are "soft", occurring as + needed on display. That is, characters are grouped into a paragraph + until a CRLF sequence is seen, at which point a new paragraph is + started. Each paragraph is displayed, starting at the left margin + (or paragraph indent), and continuing to the right until a word is + encountered which does not fit in the remaining display width. This + word is displayed at the left margin of the next line. This + continues until the paragraph ends (a CRLF is seen). Extra vertical + space is left between paragraphs. + + Text which meets this description is defined by this memo as + "flowed". + + Numerous software products erroneously label this format as + Text/Plain, resulting in much user discomfort. + +3.2. Embarrassing Line Wrap + + As Text/Plain messages are quoted in replies or forwarded messages, + each line gradually increases in length, eventually being arbitrarily + hard wrapped, resulting in "embarrassing line wrap". This produces + text which is, at best, hard to read, and often confuses + attributions. + + + + + + +Gellens Standards Track [Page 3] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + Example: + + >>>>>>This is a comment from the first message to show a + >quoting example. + >>>>>This is a comment from the second message to show a + >quoting example. + >>>>This is a comment from the third message. + >>>This is a comment from the fourth message. + + It can be confusing to assign attribution to lines 2 and 4 above. + + In addition, as devices with display widths smaller than 79 or 80 + characters become more popular, embarrassing line wrap has become + even more prevalent, even with unquoted text. + + Example: + + This is paragraph text that is + meant to be flowed across + several lines. + However, the sending mailer is + converting it to fixed text at + a width of 72 + characters, which causes it to + look like this when shown on a + PDA with only + 30 character lines. + +3.3. New Media Types + + Attempts to deploy new media types, such as Text/Enriched [Rich] and + Text/HTML [HTML] have suffered from a lack of backwards compatibility + and an often hostile user reaction at the receiving end. + + In particular, Text/Enriched requires that open angle brackets ("<") + and hard line breaks be doubled, with resulting user unhappiness when + viewed as Text/Plain. Text/HTML requires even more alteration of + text, with a corresponding increase in user complaints. + + A proposal to define a new media type to explicitly represent the + paragraph form suffered from a lack of interoperability with + currently deployed software. Some programs treat unknown subtypes of + TEXT as an attachment. + + + + + + + + +Gellens Standards Track [Page 4] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + What is desired is a format which is in all significant ways + Text/Plain, and therefore is quite suitable for display as + Text/Plain, and yet allows the sender to express to the receiver + which lines can be considered a logical paragraph, and thus flowed + (wrapped and joined) as appropriate. + +4. The Format and DelSp Parameters + + This specification defines two MIME parameters for use with + Text/Plain: + + Name: Format + Value: Fixed, Flowed + + Name: DelSp + Value: Yes, No + + (Neither the parameter names nor values are case sensitive.) + + If Format is not specified, or if the value is not recognized, a + value of Fixed is assumed. The semantics of the Fixed value are the + usual associated with Text/Plain [MIME-IMT]. + + A Format value of Flowed indicates that the definition of flowed text + (as specified in this memo) was used on generation, and MAY be used + on reception. + + Note that because Format is a parameter of the Text/Plain content- + type, any content-transfer-encoding used is irrelevant to the + processing of flowed text. + + If DelSp is not specified, or if its value is not recognized, a value + of No is assumed. The use of DelSp without a Format value of Flowed + is undefined. When creating messages, DelSp SHOULD NOT be specified + in Text content types other than Text/Plain with Format = Flowed. + When receiving messages, DelSp SHOULD be ignored if used in a Text + content type other than Text/Plain with Format = Flowed. + + This section discusses flowed text; section 6 provides a formal + definition. + + Section 5 discusses interoperability. + + Note that this memo describes an on-the-wire format. It does not + address formats for local file storage. + + + + + + +Gellens Standards Track [Page 5] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + +4.1. Interpreting Format=Flowed + + If the first character of a line is a quote mark (">"), the line is + considered to be quoted (see Section 4.5). Logically, all quote + marks are counted and deleted, resulting in a line with a non-zero + quote depth, and content. (The agent is of course free to display + the content with quote marks or excerpt bars or anything else.) + Logically, this test for quoted lines is done before any other tests + (that is, before checking for space-stuffed and flowed). + + If the first character of a line is a space, the line has been + space-stuffed (see Section 4.4). Logically, this leading space is + deleted before examining the line further (that is, before checking + for flowed). + + If the line ends in a space, the line is flowed. Otherwise it is + fixed. The exception to this rule is a signature separator line, + described in Section 4.3. Such lines end in a space but are neither + flowed nor fixed. + + If the line is flowed and DelSp is "yes", the trailing space + immediately prior to the line's CRLF is logically deleted. If the + DelSp parameter is "no" (or not specified, or set to an unrecognized + value), the trailing space is not deleted. + + Any remaining trailing spaces are part of the line's content, but the + CRLF of a soft line break is not. + + A series of one or more flowed lines followed by one fixed line is + considered a paragraph, and MAY be flowed (wrapped and unwrapped) as + appropriate on display and in the construction of new messages (see + Section 4.5). + + An interpreting agent SHOULD allow for three exceptions to the rule + that paragraphs end with a fixed line. These exceptions are + improperly constructed messages: a flowed line SHOULD be considered + to end the paragraph if it is followed by a line of a different quote + depth (see 4.5) or by a signature separator (see 4.3); the end of the + body also ends the paragraph. + + A line consisting of one or more spaces (after deleting a space + acting as stuffing) is considered a flowed line. + + An empty line (just a CRLF) is a fixed line. + + Note that, for Unicode text, [Annex-14] provides guidance for + choosing at which characters to wrap a line. + + + + +Gellens Standards Track [Page 6] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + +4.2. Generating Format=Flowed + + When generating Format=Flowed text, lines SHOULD be 78 characters or + shorter, including any trailing white space and also including any + space added as part of stuffing (see Section 4.4). As suggested + values, any paragraph longer than 78 characters in total length could + be wrapped using lines of 72 or fewer characters. While the specific + line length used is a matter of aesthetics and preference, longer + lines are more likely to require rewrapping and to encounter + difficulties with older mailers. (It has been suggested that 66 + character lines are the most readable.) + + The restriction to 78 or fewer characters between CRLFs on the wire + is to conform to [MSG-FMT]. + + (In addition to conformance to [MSG-FMT], there is a historical need + that all lines, even when displayed by a non-flowed-aware program, + will fit in a standard 79- or 80-column screen without having to be + wrapped. The limit is 78, not 79 or 80, because while 79 or 80 fit + on a line, the last column is often reserved for a line-wrap + indicator.) + + When creating flowed text, the generating agent wraps, that is, + inserts 'soft' line breaks as needed. Soft line breaks are added at + natural wrapping points, such as between words. A soft line break is + a SP CRLF sequence. + + There are two techniques for inserting soft line breaks. The older + technique, established by RFC 2646, creates a soft line break by + inserting a CRLF after the occurrence of a space. With this + technique, soft line breaks are only possible where spaces already + occur. When this technique is used, the DelSp parameter SHOULD be + used; if used it MUST be set to "no". + + The newer technique, suitable for use even with languages/coded + character sets in which the ASCII space character is rare or not + used, creates a soft line break by inserting a SP CRLF sequence. + When this technique is used, the DelSp parameter MUST be used and + MUST be set to "yes". Note that because of space-stuffing (see + Section 4.4), when this technique is used and a soft line break is + inserted at a point where a SP already exists (such as between + words), if the SP CRLF sequence is added immediately before the SP, + the pre-existing SP becomes leading and thus requires stuffing. It + is RECOMMENDED that agents avoid this by inserting the SP CRLF + sequence following the existing SP. + + Generating agents MAY use either method within each Text/Plain body + part. + + + +Gellens Standards Track [Page 7] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + Regardless of which technique is used, a generating agent SHOULD NOT + insert a space in an unnatural location, such as into a word (a + sequence of printable characters, not containing spaces, in a + language/coded character set in which spaces are common). If faced + with such a word which exceeds 78 characters (but less than 998 + characters, the [SMTP] limit on line length), the agent SHOULD send + the word as is and exceed the 78-character limit on line length. + + A generating agent SHOULD: + + o Ensure all lines (fixed and flowed) are 78 characters or fewer in + length, counting any trailing space as well as a space added as + stuffing, but not counting the CRLF, unless a word by itself + exceeds 78 characters. + + o Trim spaces before user-inserted hard line breaks. + + A generating agent MUST: + + o Space-stuff lines which start with a space, "From ", or ">". + + In order to create messages which do not require space-stuffing, and + are thus more aesthetically pleasing when viewed as Format=Fixed, a + generating agent MAY avoid wrapping immediately before ">", "From ", + or space. + + (See Sections 4.4 and 4.5 for more information on space-stuffing and + quoting, respectively.) + + A Format=Flowed message consists of zero or more paragraphs, each + containing one or more flowed lines followed by one fixed line. The + usual case is a series of flowed text lines with blank (empty) fixed + lines between them. + + Any number of fixed lines can appear between paragraphs. + + When placing soft line breaks in a paragraph, generating agents MUST + NOT place them in a way that causes any line of the paragraph to be a + signature separator line, because paragraphs cannot contain signature + separator lines (see Sections 4.3 and 6). + + [Quoted-Printable] encoding SHOULD NOT be used with Format=Flowed + unless absolutely necessary (for example, non-US-ASCII (8-bit) + characters over a strictly 7-bit transport such as unextended + [SMTP]). In particular, a message SHOULD NOT be encoded in Quoted- + Printable for the sole purpose of protecting the trailing space on + flowed lines unless the body part is cryptographically signed or + encrypted (see Section 4.6). + + + +Gellens Standards Track [Page 8] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + The intent of Format=Flowed is to allow user agents to generate + flowed text which is non-obnoxious when viewed as pure, raw + Text/Plain (without any decoding); use of Quoted-Printable hinders + this and may cause Format=Flowed to be rejected by end users. + +4.3. Usenet Signature Convention + + There is a long-standing convention in Usenet news which also + commonly appears in Internet mail of using "-- " as the separator + line between the body and the signature of a message. When + generating a Format=Flowed message containing a Usenet-style + separator before the signature, the separator line is sent as-is. + This is a special case; an (optionally quoted or quoted and stuffed) + line consisting of DASH DASH SP is neither fixed nor flowed. + + Generating agents MUST NOT end a paragraph with such a signature + line. + + A receiving agent needs to test for a signature line both before the + test for a quoted line (see Section 4.5) and also after logically + counting and deleting quote marks and stuffing (see Section 4.4) from + a quoted line. + +4.4. Space-Stuffing + + In order to allow for unquoted lines which start with ">", and to + protect against systems which "From-munge" in-transit messages + (modifying any line which starts with "From " to ">From "), + Format=Flowed provides for space-stuffing. + + Space-stuffing adds a single space to the start of any line which + needs protection when the message is generated. On reception, if the + first character of a line is a space, it is logically deleted. This + occurs after the test for a quoted line (which logically counts and + deletes any quote marks), and before the test for a flowed line. + + On generation, any unquoted lines which start with ">", and any lines + which start with a space or "From " MUST be space-stuffed. Other + lines MAY be space-stuffed as desired. + + (Note that space-stuffing is conceptually similar to dot-stuffing as + specified in [SMTP].) + +4.5. Quoting + + In Format=Flowed, the canonical quote indicator (or quote mark) is + one or more close angle bracket (">") characters. Lines which start + with the quote indicator are considered quoted. The number of ">" + + + +Gellens Standards Track [Page 9] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + characters at the start of the line specifies the quote depth. + Flowed lines which are also quoted may require special handling on + display and when copied to new messages. + + When creating quoted flowed lines, each such line starts with the + quote indicator. + + Note that because of space-stuffing, the lines + >> Exit, Stage Left + and + >>Exit, Stage Left + are semantically identical; both have a quote-depth of two, and a + content of "Exit, Stage Left". + + However, the line + > > Exit, Stage Left + is different. It has a quote-depth of one, and a content of + "> Exit, Stage Left". + + When generating quoted flowed lines, an agent needs to pay attention + to changes in quote depth. All lines of a paragraph MUST be + unquoted, or else they MUST all be quoted and have the same quote + depth. Therefore, whenever there is a change in quote depth, or a + change from quoted to unquoted, or change from unquoted to quoted, + the line immediately preceding the change MUST NOT be a flowed line. + + If a receiving agent wishes to reformat flowed quoted lines (joining + and/or wrapping them) on display or when generating new messages, the + lines SHOULD be de-quoted, reformatted, and then re-quoted. To de- + quote, the number of close angle brackets in the quote indicator at + the start of each line is counted. To re-quote after reformatting, a + quote indicator containing the same number of close angle brackets + originally present are prefixed to each line. + + On reception, if a change in quote depth occurs on a flowed line, + this is an improperly formatted message. The receiver SHOULD handle + this error by using the 'quote-depth-wins' rule, which is to consider + the paragraph to end with the flowed line immediately preceding the + change in quote depth. + + In other words, whenever two adjacent lines have different quote + depths, senders MUST ensure that the earlier line is not flowed (does + not end in a space), and receivers finding a flowed line there SHOULD + treat it as the last line of a paragraph. + + For example, consider the following sequence of lines (using '*' to + indicate a soft line break, i.e., SP CRLF, and '#' to indicate a hard + line break, i.e., CRLF): + + + +Gellens Standards Track [Page 10] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + > Thou villainous ill-breeding spongy dizzy-eyed* + > reeky elf-skinned pigeon-egg!* <--- problem ---< + >> Thou artless swag-bellied milk-livered* + >> dismal-dreaming idle-headed scut!# + >>> Thou errant folly-fallen spleeny reeling-ripe* + >>> unmuzzled ratsbane!# + >>>> Henceforth, the coding style is to be strictly* + >>>> enforced, including the use of only upper case.# + >>>>> I've noticed a lack of adherence to the coding* + >>>>> styles, of late.# + >>>>>> Any complaints?# + + The second line ends in a soft line break, even though it is the last + line of the one-deep quote block. The question then arises as to how + this line is to be interpreted, considering that the next line is the + first line of the two-deep quote block. + + The example text above, when processed according to quote-depth wins, + results in the first two lines being considered as one quoted, flowed + section, with a quote depth of 1; the third and fourth lines become a + quoted, flowed section, with a quote depth of 2. + + A generating agent MUST NOT create this situation; a receiving agent + SHOULD handle it by giving preference to the quote depth. + +4.6. Digital Signatures and Encryption + + If a message is digitally signed or encrypted it is important that + cryptographic processing use the same text for signature verification + and/or decryption as was used for signature generation and/or + encryption. Since the use of format=flowed allows text to be altered + (by adding or removing line breaks and trailing spaces) between + composition and transmission, and between reception and display, + interoperability problems or security vulnerabilities may arise if + originator and recipient do not both use the on-the-wire format for + cryptographic processing. + + The implications of the interaction between format=flowed and any + specific cryptographic process depend on the details of the + cryptographic processing and should be understood before using + format=flowed in conjunction with signed and/or encrypted messages. + + Note that [OpenPGP] specifies (in Section 7.1) that "any trailing + whitespace (spaces, and tabs, 0x09) at the end of any line is ignored + when the cleartext signature is calculated." + + + + + + +Gellens Standards Track [Page 11] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + Thus it would be possible to add, in transit, a format=flowed header + to a regular, format=fixed vanilla PGP (not [OpenPGP-MIME]) signed + message and add arbitrary trailing space characters without this + addition being detected. This would change the rendering of the + article by a client which supported format=flowed. + + Therefore, the use of [OpenPGP] with format=flowed messages is + strongly discouraged. [OpenPGP-MIME] is recommended instead. + +4.7. Examples + + The following example contains three paragraphs: + + `Take some more tea,' the March Hare said to Alice, very + earnestly. + + `I've had nothing yet,' Alice replied in an offended tone, `so I + can't take more.' + + `You mean you can't take LESS,' said the Hatter: `it's very easy + to take MORE than nothing.' + + This could be encoded as follows (using '*' to indicate a soft line + break, that is, SP CRLF sequence, and '#' to indicate a hard line + break, that is, CRLF): + + `Take some more tea,' the March Hare said to Alice, very* + earnestly.# + # + `I've had nothing yet,' Alice replied in an offended tone, `so* + I can't take more.'# + # + `You mean you can't take LESS,' said the Hatter: `it's very* + easy to take MORE than nothing.'# + + To show an example of quoting, here we have the same exchange, + presented as a series of direct quotes: + + >>>Take some more tea.# + >>I've had nothing yet, so I can't take more.# + >You mean you can't take LESS, it's very easy to take* + >MORE than nothing.# + +5. Interoperability + + Because flowed lines are all-but-indistinguishable from fixed lines, + software which does not recognize Format=Flowed treats flowed lines + as normal Text/Plain (which is what they are). Thus, Format=Flowed + + + +Gellens Standards Track [Page 12] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + interoperates with older clients, although flowed lines will have + trailing white space inserted. + + If a space-stuffed message is received by an agent which handles + Format=Flowed, the space-stuffing is reversed and thus the message + appears unchanged. An agent which is not aware of Format=Flowed will + of course not undo any space-stuffing; thus Format=Flowed messages + may appear with a leading space on some lines (those which start with + a space, ">" which is not a quote indicator, or "From "). Since + lines which require space-stuffing rarely occur, and the aesthetic + consequences of unreversed space-stuffing are minimal, this is not + expected to be a significant problem. + + If some lines begin with one or more spaces, the generating agent MAY + space-stuff all lines, to maintain the relative indentation of the + lines when viewed by clients which are not aware of Format=Flowed. + + Messages generated with DelSp=yes and received by clients which are + aware of Format=Flowed but are not aware of the DelSp parameter will + have an extra space remaining after removal of soft line breaks. + Thus, when generating text in languages/coded character sets in which + spaces are common, the generating agent MAY always use the DelSp=no + method. + + Hand-aligned text, such as ASCII tables or art, source code, etc., + SHOULD be sent as fixed, not flowed lines. + +6. ABNF + + The constructs used in Text/Plain; Format=Flowed body parts are + described using Augmented Backus-Naur Form [ABNF], including the core + rules defined in Appendix A. + + Note that the SP (space) and ">" characters are encoded according to + the charset parameter. + +flowed-body = *( paragraph / fixed-line / sig-sep ) +paragraph = 1*flowed-line fixed-line + ; all lines in paragraph MUST be unquoted or + ; have same quote depth +flowed-line = ( flowed-line-qt / flowed-line-unqt ) flow CRLF +flowed-line-qt = quote ( ( stuffing stuffed-flowed ) / + unstuffed-flowed ) +flowed-line-unqt = ( stuffing stuffed-flowed ) / unstuffed-flowed +stuffed-flowed = *text-char +unstuffed-flowed = non-sp-quote *text-char +fixed-line = fixed-line-qt / fixed-line-unqt +fixed-line-qt = quote ( ( stuffing stuffed-fixed ) / + + + +Gellens Standards Track [Page 13] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + unstuffed-fixed ) CRLF +fixed-line-unqt = ( stuffed-fixed / unstuffed-fixed ) CRLF +stuffed-fixed = *text-char non-sp +unstuffed-fixed = non-sp-quote [ *text-char non-sp ] +sig-sep = [ quote [stuffing] ] "--" SP CRLF +quote-mark = ">" +quote = 1*quote-mark +stuffing = SP ; space-stuffed, added on generation if + ; needed, deleted on reception +flow = SP ; space before CRLF indicates flowed line, + ; if DelSp=yes, space was added on generation + ; and is deleted on reception +non-sp-quote = < any character except NUL, CR, LF, SP, quote-mark > +non-sp = non-sp-quote / quote-mark +text-char = non-sp / SP + + That is, a Format=Flowed message body consists of any number of + paragraphs and/or fixed lines and/or signature separator lines; + paragraphs need at least one flowed line and are terminated by a + fixed line; the fixed line terminating the paragraph is part of the + paragraph. (There are some exceptions to this described in the + text.) + + Without at least one flowed line, there is a series of fixed lines, + each independent. There is no paragraph. + + With at least one flowed line, there is a paragraph, and the received + lines can be reformed and flowed to fit the display window size. + This can only be done if the lines are part of a logical grouping, + the paragraph. + + Note that the definitions of flowed-line and sig-sep are potentially + ambiguous: a signature separator line matches both, but is treated as + a signature separator line and not a flowed line. + +7. Failure Modes + +7.1. Trailing White Space Corruption + + There are systems in existence which alter trailing whitespace on + messages which pass through them. Such systems may strip, or in + rarer cases, add trailing whitespace, in violation of RFC 2821 [SMTP] + Section 4.5.2. + + Stripping trailing whitespace has the effect of converting flowed + lines to fixed lines, which results in a message no worse than if + Format=Flowed had not been used. + + + + +Gellens Standards Track [Page 14] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + Adding trailing whitespace to a Format=Flowed message may result in a + malformed display or reply. + + Since most systems which add trailing white space do so to create a + line which fills an internal record format, the result is almost + always a line which contains an even number of characters (counting + the added trailing white space). + + One possible avoidance, therefore, would be to define Format=Flowed + lines to use either one or two trailing space characters to indicate + a flowed line, such that the total line length is odd. However, + considering the scarcity of such systems today, it is not worth the + added complexity. + +8. Security Considerations + + Any security considerations which apply to Text/Plain also apply to + Text/Plain with Format=Flowed. + + Section 4.6 discusses the interaction between Format=Flowed and + digital signatures or encryption. + +9. IANA Considerations + + IANA has added a reference to this specification in the Text/Plain + Media Type registration. + +10. Internationalization Considerations + + The line wrap and quoting specifications of Format=Flowed may not be + suitable for certain charsets, such as for Arabic and Hebrew + characters that read from right to left. Care needs to be taken in + applying format=flowed in these cases, as format=fixed combined with + [quoted-printable] encoding may be more suitable. + + The DelSp parameter was added specifically to permit Format=Flowed to + be used with languages/coded character sets in which the ASCII space + character is rarely used, or not used at all. + +11. Acknowledgments + + The DelSp parameter was developed during a series of discussions + among a number of people, including Harald Alvestrand, Grant Baillie, + Ian Bell, Steve Dorner, Patrik Faltstrom, Eric Fischer, Ned Freed, + Alexey Melnikov, John Myers, and Pete Resnick. + + + + + + +Gellens Standards Track [Page 15] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + Corrections and clarifications to RFC 2646 and early versions of this + document were pointed out by several people, including Adam Costello, + Jutta Degener, Tony Hansen, Simon Josefsson, Dan Kohn, Ragho + Mahalingam, Keith Moore, Greg Troxel, and Dan Wing. + + I'm told that NeXT's mail application used a very similar mechanism + (without support for non-Western languages) in 1992. + +12. Normative References + + [ABNF] Crocker, D., Ed. and P. Overell, "Augmented BNF + for Syntax Specifications: ABNF", RFC 2234, + November 1997. + + [KEYWORDS] Bradner, S., "Key words for use in RFCs to + Indicate Requirement Levels", BCP 14, RFC 2119, + March 1997. + + [MIME-IMT] Freed, N. and N. Borenstein, "Multipurpose + Internet Mail Extensions (MIME) Part Two: Media + Types", RFC 2046, November 1996. + + [Quoted-Printable] Freed, N. and N. Borenstein, "Multipurpose + Internet Mail Extensions (MIME) Part One: Format + of Internet Message Bodies", RFC 2045, November + 1996. + +13. Informative References + + [Annex-14] Unicode Standard Annex #14, "Line Breaking + Properties" + + + [MSG-FMT] Resnick, P., Ed., "Internet Message Format", RFC + 2822, April 2001. + + [OpenPGP] Callas, J., Donnerhacke, L., Finney, H. and R. + Thayer, "OpenPGP Message Format", RFC 2440, + November 1998. + + [OpenPGP-MIME] Elkins, M., "MIME Security with Pretty Good + Privacy (PGP)", RFC 2015, October 1996. + + Elkins, M., Del Torto, D., Levien, R. and J. + Roessler, "MIME Security with OpenPGP", RFC 3156, + August 2001. + + + + + +Gellens Standards Track [Page 16] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + [Rich] Resnick, P. and A. Walker, "The text/enriched MIME + Content-type", RFC 1896, February 1996. + + [SMTP] Klensin, J., Ed., "Simple Mail Transfer Protocol", + RFC 2821, April 2001. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Gellens Standards Track [Page 17] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + +Appendix A: Changes from RFC 2646 + + Substantive: + + o Added DelSp parameter to handle languages and coded character sets + in which space is less common or not used. + o Updated text on generating and interpreting to accommodate the + DelSp parameter. + o Changed the limits of 79 or 80 to be 78 in conformance with RFC + 2822. + o Added text on generating to clarify that the 78-character limit + includes trailing white space and stuffing. + o Changed sig-sep in ABNF to allow stuffing. + o Changed fixed-line to allow empty lines in ABNF. + o Added explanatory text following ABNF. + o Moved text from Abstract to new Introduction; rewrote Abstract. + o Moved interoperability text to new section, and updated. + o Clarified Security Considerations. + o Text on digital signatures now discusses that OpenPGP ignores + trailing white space. + o Mention Unicode Annex 14. + o Added mention of quoting to Abstract and Introduction. + o Deleted line analysis table. + o Added recommendations for OpenPGP and OpenPGP-MIME. + o Rewrote ABNF rules to remove most ambiguity and note remaining + case. + o Added note that c-t-e is irrelevant to flowed text processing. + o Added text indicating that end of data terminates a paragraph. + o Moved sig-sep out of fixed-line ABNF. + o Changed some SHOULDs to MUSTs (space-stuffing, quoted paragraphs). + o Added note to ABNF that space and ">" are encoded according to + charset. + o Mentioned exceptions in section on interpreting. + o Clarified and made consistent treatment of signature separator + lines. + + Editorial: + + o Added mention of NeXT's mail application to Acknowledgments. + o Updated Acknowledgments. + o Updated [SMTP] reference to 2821. + o Added Notices. + o Split References into Normative and Informative. + o Improved text wording in some areas. + o Standardize on "quote depth", not "quoting depth". + o Moved section on interpreting before section on generating. + o Reworded non-normative "should"s. + o Noted meaning of "paragraph". + + + +Gellens Standards Track [Page 18] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + + The DelSp parameter was added specifically to permit Format=Flowed to + be used with languages/coded character sets in which the ASCII space + character is rarely used, or not used at all. The DelSp mechanism + was selected despite having been initially rejected as too much of a + kludge, because among the many different techniques proposed, it + allows for maximum interoperability among clients which support + neither this specification nor RFC 2646, those which do support RFC + 2646 but not this specification, and those that do support this + specification; this set is multiplied by those that handle + languages/coded character sets in which spaces are common, and in + which they are uncommon or not used. + +Author's Address + + Randall Gellens + QUALCOMM Incorporated + 5775 Morehouse Drive + San Diego, CA 92121 + USA + + Phone: +1 858 651 5115 + EMail: randy@qualcomm.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Gellens Standards Track [Page 19] + +RFC 3676 Text/Plain Format and DelSp Parameters February 2004 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2004). This document is subject + to the rights, licenses and restrictions contained in BCP 78 and + except as set forth therein, the authors retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE + REPRESENTS OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE + INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF + THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed + to pertain to the implementation or use of the technology + described in this document or the extent to which any license + under such rights might or might not be available; nor does it + represent that it has made any independent effort to identify any + such rights. Information on the procedures with respect to + rights in RFC documents can be found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use + of such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository + at http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention + any copyrights, patents or patent applications, or other + proprietary rights that may cover technology that may be required + to implement this standard. Please address the information to the + IETF at ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + + + +Gellens Standards Track [Page 20] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4505.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4505.txt new file mode 100644 index 00000000..6b8a4a11 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4505.txt @@ -0,0 +1,507 @@ + + + + + + +Network Working Group K. Zeilenga, Ed. +Request for Comments: 4505 OpenLDAP Foundation +Obsoletes: 2245 June 2006 +Category: Standards Track + + + Anonymous Simple Authentication and Security Layer (SASL) Mechanism + +Status of This Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2006). + +Abstract + + On the Internet, it is common practice to permit anonymous access to + various services. Traditionally, this has been done with a plain- + text password mechanism using "anonymous" as the user name and using + optional trace information, such as an email address, as the + password. As plain-text login commands are not permitted in new IETF + protocols, a new way to provide anonymous login is needed within the + context of the Simple Authentication and Security Layer (SASL) + framework. + +1. Introduction + + This document defines an anonymous mechanism for the Simple + Authentication and Security Layer ([SASL]) framework. The name + associated with this mechanism is "ANONYMOUS". + + Unlike many other SASL mechanisms, whose purpose is to authenticate + and identify the user to a server, the purpose of this SASL mechanism + is to allow the user to gain access to services or resources without + requiring the user to establish or otherwise disclose their identity + to the server. That is, this mechanism provides an anonymous login + method. + + This mechanism does not provide a security layer. + + This document replaces RFC 2245. Changes since RFC 2245 are detailed + in Appendix A. + + + +Zeilenga Standards Track [Page 1] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + +2. The Anonymous Mechanism + + The mechanism consists of a single message from the client to the + server. The client may include in this message trace information in + the form of a string of [UTF-8]-encoded [Unicode] characters prepared + in accordance with [StringPrep] and the "trace" stringprep profile + defined in Section 3 of this document. The trace information, which + has no semantical value, should take one of two forms: an Internet + email address, or an opaque string that does not contain the '@' + (U+0040) character and that can be interpreted by the system + administrator of the client's domain. For privacy reasons, an + Internet email address or other information identifying the user + should only be used with permission from the user. + + A server that permits anonymous access will announce support for the + ANONYMOUS mechanism and allow anyone to log in using that mechanism, + usually with restricted access. + + A formal grammar for the client message using Augmented BNF [ABNF] is + provided below as a tool for understanding this technical + specification. + + message = [ email / token ] + ;; to be prepared in accordance with Section 3 + + UTF1 = %x00-3F / %x41-7F ;; less '@' (U+0040) + UTF2 = %xC2-DF UTF0 + UTF3 = %xE0 %xA0-BF UTF0 / %xE1-EC 2(UTF0) / + %xED %x80-9F UTF0 / %xEE-EF 2(UTF0) + UTF4 = %xF0 %x90-BF 2(UTF0) / %xF1-F3 3(UTF0) / + %xF4 %x80-8F 2(UTF0) + UTF0 = %x80-BF + + TCHAR = UTF1 / UTF2 / UTF3 / UTF4 + ;; any UTF-8 encoded Unicode character + ;; except '@' (U+0040) + + email = addr-spec + ;; as defined in [IMAIL] + + token = 1*255TCHAR + + Note to implementors: + The production is restricted to 255 UTF-8-encoded Unicode + characters. As the encoding of a characters uses a sequence of 1 + to 4 octets, a token may be as long as 1020 octets. + + + + + +Zeilenga Standards Track [Page 2] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + +3. The "trace" Profile of "Stringprep" + + This section defines the "trace" profile of [StringPrep]. This + profile is designed for use with the SASL ANONYMOUS Mechanism. + Specifically, the client is to prepare the production in + accordance with this profile. + + The character repertoire of this profile is Unicode 3.2 [Unicode]. + + No mapping is required by this profile. + + No Unicode normalization is required by this profile. + + The list of unassigned code points for this profile is that provided + in Appendix A of [StringPrep]. Unassigned code points are not + prohibited. + + Characters from the following tables of [StringPrep] are prohibited: + + - C.2.1 (ASCII control characters) + - C.2.2 (Non-ASCII control characters) + - C.3 (Private use characters) + - C.4 (Non-character code points) + - C.5 (Surrogate codes) + - C.6 (Inappropriate for plain text) + - C.8 (Change display properties are deprecated) + - C.9 (Tagging characters) + + No additional characters are prohibited. + + This profile requires bidirectional character checking per Section 6 + of [StringPrep]. + +4. Example + + Here is a sample ANONYMOUS login between an IMAP client and server. + In this example, "C:" and "S:" indicate lines sent by the client and + server, respectively. If such lines are wrapped without a new "C:" + or "S:" label, then the wrapping is for editorial clarity and is not + part of the command. + + Note that this example uses the IMAP profile [IMAP4] of SASL. The + base64 encoding of challenges and responses as well as the "+ " + preceding the responses are part of the IMAP4 profile, not part of + SASL itself. Additionally, protocols with SASL profiles permitting + an initial client response will be able to avoid the extra round trip + below (the server response with an empty "+ "). + + + + +Zeilenga Standards Track [Page 3] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + + In this example, the trace information is "sirhc". + + S: * OK IMAP4 server ready + C: A001 CAPABILITY + S: * CAPABILITY IMAP4 IMAP4rev1 AUTH=DIGEST-MD5 AUTH=ANONYMOUS + S: A001 OK done + C: A002 AUTHENTICATE ANONYMOUS + S: + + C: c2lyaGM= + S: A003 OK Welcome, trace information has been logged. + +5. Security Considerations + + The ANONYMOUS mechanism grants access to services and/or resources by + anyone. For this reason, it should be disabled by default so that + the administrator can make an explicit decision to enable it. + + If the anonymous user has any write privileges, a denial-of-service + attack is possible by filling up all available space. This can be + prevented by disabling all write access by anonymous users. + + If anonymous users have read and write access to the same area, the + server can be used as a communication mechanism to exchange + information anonymously. Servers that accept anonymous submissions + should implement the common "drop box" model, which forbids anonymous + read access to the area where anonymous submissions are accepted. + + If the anonymous user can run many expensive operations (e.g., an + IMAP SEARCH BODY command), this could enable a denial-of-service + attack. Servers are encouraged to reduce the priority of anonymous + users or limit their resource usage. + + While servers may impose a limit on the number of anonymous users, + note that such limits enable denial-of-service attacks and should be + used with caution. + + The trace information is not authenticated, so it can be falsified. + This can be used as an attempt to get someone else in trouble for + access to questionable information. Administrators investigating + abuse need to realize that this trace information may be falsified. + + A client that uses the user's correct email address as trace + information without explicit permission may violate that user's + privacy. Anyone who accesses an anonymous archive on a sensitive + subject (e.g., sexual abuse) likely has strong privacy needs. + Clients should not send the email address without the explicit + permission of the user and should offer the option of supplying no + trace information, thus only exposing the source IP address and time. + + + +Zeilenga Standards Track [Page 4] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + + Anonymous proxy servers could enhance this privacy but would have to + consider the resulting potential denial-of-service attacks. + + Anonymous connections are susceptible to man-in-the-middle attacks + that view or alter the data transferred. Clients and servers are + encouraged to support external data security services. + + Protocols that fail to require an explicit anonymous login are more + susceptible to break-ins given certain common implementation + techniques. Specifically, Unix servers that offer user login may + initially start up as root and switch to the appropriate user id + after an explicit login command. Normally, such servers refuse all + data access commands prior to explicit login and may enter a + restricted security environment (e.g., the Unix chroot(2) function) + for anonymous users. If anonymous access is not explicitly + requested, the entire data access machinery is exposed to external + security attacks without the chance for explicit protective measures. + Protocols that offer restricted data access should not allow + anonymous data access without an explicit login step. + + General [SASL] security considerations apply to this mechanism. + + [StringPrep] security considerations and [Unicode] security + considerations discussed in [StringPrep] apply to this mechanism. + [UTF-8] security considerations also apply. + +6. IANA Considerations + + The SASL Mechanism registry [IANA-SASL] entry for the ANONYMOUS + mechanism has been updated by the IANA to reflect that this document + now provides its technical specification. + + To: iana@iana.org + Subject: Updated Registration of SASL mechanism ANONYMOUS + + SASL mechanism name: ANONYMOUS + Security considerations: See RFC 4505. + Published specification (optional, recommended): RFC 4505 + Person & email address to contact for further information: + Kurt Zeilenga + Chris Newman + Intended usage: COMMON + Author/Change controller: IESG + Note: Updates existing entry for ANONYMOUS + + + + + + + +Zeilenga Standards Track [Page 5] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + + The [StringPrep] profile "trace", first defined in this RFC, has been + registered: + + To: iana@iana.org + Subject: Initial Registration of Stringprep "trace" profile + + Stringprep profile: trace + Published specification: RFC 4505 + Person & email address to contact for further information: + Kurt Zeilenga + +7. Acknowledgement + + This document is a revision of RFC 2245 by Chris Newman. Portions of + the grammar defined in Section 1 were borrowed from RFC 3629 by + Francois Yergeau. + + This document is a product of the IETF SASL WG. + +8. Normative References + + [ABNF] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", RFC 4234, October 2005. + + [IMAIL] Resnick, P., "Internet Message Format", RFC 2822, April + 2001. + + [SASL] Melnikov, A., Ed. and K. Zeilenga, Ed., "Simple + Authentication and Security Layer (SASL)", RFC 4422, + June 2006. + + [StringPrep] Hoffman, P. and M. Blanchet, "Preparation of + Internationalized Strings ('stringprep')", RFC 3454, + December 2002. + + [Unicode] The Unicode Consortium, "The Unicode Standard, Version + 3.2.0" is defined by "The Unicode Standard, Version 3.0" + (Reading, MA, Addison-Wesley, 2000. ISBN 0-201-61633-5), + as amended by the "Unicode Standard Annex #27: Unicode + 3.1" (http://www.unicode.org/reports/tr27/) and by the + "Unicode Standard Annex #28: Unicode 3.2" + (http://www.unicode.org/reports/tr28/). + + [UTF-8] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", RFC 3629 (also STD 63), November 2003. + + + + + + +Zeilenga Standards Track [Page 6] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + +9. Informative References + + [IMAP4] Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - VERSION + 4rev1", RFC 3501, March 2003. + + [IANA-SASL] IANA, "SIMPLE AUTHENTICATION AND SECURITY LAYER (SASL) + MECHANISMS", . + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Zeilenga Standards Track [Page 7] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + +Appendix A. Changes since RFC 2245 + + This appendix is non-normative. + + RFC 2245 allows the client to include optional trace information in + the form of a human readable string. RFC 2245 restricted this string + to US-ASCII. As the Internet is international, this document uses a + string restricted to UTF-8 encoded Unicode characters. A + "stringprep" profile is defined to precisely define which Unicode + characters are allowed in this string. While the string remains + restricted to 255 characters, the encoded length of each character + may now range from 1 to 4 octets. + + Additionally, a number of editorial changes were made. + +Editor's Address + + Kurt D. Zeilenga + OpenLDAP Foundation + + EMail: Kurt@OpenLDAP.org + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Zeilenga Standards Track [Page 8] + +RFC 4505 Anonymous SASL Mechanism June 2006 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2006). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET + ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE + INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is provided by the IETF + Administrative Support Activity (IASA). + + + + + + + +Zeilenga Standards Track [Page 9] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4616.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4616.txt new file mode 100644 index 00000000..991189d5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4616.txt @@ -0,0 +1,619 @@ + + + + + + +Network Working Group K. Zeilenga, Ed. +Request for Comments: 4616 OpenLDAP Foundation +Updates: 2595 August 2006 +Category: Standards Track + + + The PLAIN Simple Authentication and Security Layer (SASL) Mechanism + +Status of This Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The Internet Society (2006). + +Abstract + + This document defines a simple clear-text user/password Simple + Authentication and Security Layer (SASL) mechanism called the PLAIN + mechanism. The PLAIN mechanism is intended to be used, in + combination with data confidentiality services provided by a lower + layer, in protocols that lack a simple password authentication + command. + + + + + + + + + + + + + + + + + + + + + + + +Zeilenga Standards Track [Page 1] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + +1. Introduction + + Clear-text, multiple-use passwords are simple, interoperate with + almost all existing operating system authentication databases, and + are useful for a smooth transition to a more secure password-based + authentication mechanism. The drawback is that they are unacceptable + for use over network connections where data confidentiality is not + ensured. + + This document defines the PLAIN Simple Authentication and Security + Layer ([SASL]) mechanism for use in protocols with no clear-text + login command (e.g., [ACAP] or [SMTP-AUTH]). This document updates + RFC 2595, replacing Section 6. Changes since RFC 2595 are detailed + in Appendix A. + + The name associated with this mechanism is "PLAIN". + + The PLAIN SASL mechanism does not provide a security layer. + + The PLAIN mechanism should not be used without adequate data security + protection as this mechanism affords no integrity or confidentiality + protections itself. The mechanism is intended to be used with data + security protections provided by application-layer protocol, + generally through its use of Transport Layer Security ([TLS]) + services. + + By default, implementations SHOULD advertise and make use of the + PLAIN mechanism only when adequate data security services are in + place. Specifications for IETF protocols that indicate that this + mechanism is an applicable authentication mechanism MUST mandate that + implementations support an strong data security service, such as TLS. + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [Keywords]. + +2. PLAIN SASL Mechanism + + The mechanism consists of a single message, a string of [UTF-8] + encoded [Unicode] characters, from the client to the server. The + client presents the authorization identity (identity to act as), + followed by a NUL (U+0000) character, followed by the authentication + identity (identity whose password will be used), followed by a NUL + (U+0000) character, followed by the clear-text password. As with + other SASL mechanisms, the client does not provide an authorization + identity when it wishes the server to derive an identity from the + credentials and use that as the authorization identity. + + + + +Zeilenga Standards Track [Page 2] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + + The formal grammar for the client message using Augmented BNF [ABNF] + follows. + + message = [authzid] UTF8NUL authcid UTF8NUL passwd + authcid = 1*SAFE ; MUST accept up to 255 octets + authzid = 1*SAFE ; MUST accept up to 255 octets + passwd = 1*SAFE ; MUST accept up to 255 octets + UTF8NUL = %x00 ; UTF-8 encoded NUL character + + SAFE = UTF1 / UTF2 / UTF3 / UTF4 + ;; any UTF-8 encoded Unicode character except NUL + + UTF1 = %x01-7F ;; except NUL + UTF2 = %xC2-DF UTF0 + UTF3 = %xE0 %xA0-BF UTF0 / %xE1-EC 2(UTF0) / + %xED %x80-9F UTF0 / %xEE-EF 2(UTF0) + UTF4 = %xF0 %x90-BF 2(UTF0) / %xF1-F3 3(UTF0) / + %xF4 %x80-8F 2(UTF0) + UTF0 = %x80-BF + + The authorization identity (authzid), authentication identity + (authcid), password (passwd), and NUL character deliminators SHALL be + transferred as [UTF-8] encoded strings of [Unicode] characters. As + the NUL (U+0000) character is used as a deliminator, the NUL (U+0000) + character MUST NOT appear in authzid, authcid, or passwd productions. + + The form of the authzid production is specific to the application- + level protocol's SASL profile [SASL]. The authcid and passwd + productions are form-free. Use of non-visible characters or + characters that a user may be unable to enter on some keyboards is + discouraged. + + Servers MUST be capable of accepting authzid, authcid, and passwd + productions up to and including 255 octets. It is noted that the + UTF-8 encoding of a Unicode character may be as long as 4 octets. + + Upon receipt of the message, the server will verify the presented (in + the message) authentication identity (authcid) and password (passwd) + with the system authentication database, and it will verify that the + authentication credentials permit the client to act as the (presented + or derived) authorization identity (authzid). If both steps succeed, + the user is authenticated. + + The presented authentication identity and password strings, as well + as the database authentication identity and password strings, are to + be prepared before being used in the verification process. The + [SASLPrep] profile of the [StringPrep] algorithm is the RECOMMENDED + preparation algorithm. The SASLprep preparation algorithm is + + + +Zeilenga Standards Track [Page 3] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + + recommended to improve the likelihood that comparisons behave in an + expected manner. The SASLprep preparation algorithm is not mandatory + so as to allow the server to employ other preparation algorithms + (including none) when appropriate. For instance, use of a different + preparation algorithm may be necessary for the server to interoperate + with an external system. + + When preparing the presented strings using [SASLPrep], the presented + strings are to be treated as "query" strings (Section 7 of + [StringPrep]) and hence unassigned code points are allowed to appear + in their prepared output. When preparing the database strings using + [SASLPrep], the database strings are to be treated as "stored" + strings (Section 7 of [StringPrep]) and hence unassigned code points + are prohibited from appearing in their prepared output. + + Regardless of the preparation algorithm used, if the output of a + non-invertible function (e.g., hash) of the expected string is + stored, the string MUST be prepared before input to that function. + + Regardless of the preparation algorithm used, if preparation fails or + results in an empty string, verification SHALL fail. + + When no authorization identity is provided, the server derives an + authorization identity from the prepared representation of the + provided authentication identity string. This ensures that the + derivation of different representations of the authentication + identity produces the same authorization identity. + + The server MAY use the credentials to initialize any new + authentication database, such as one suitable for [CRAM-MD5] or + [DIGEST-MD5]. + +3. Pseudo-Code + + This section provides pseudo-code illustrating the verification + process (using hashed passwords and the SASLprep preparation + function) discussed above. This section is not definitive. + + boolean Verify(string authzid, string authcid, string passwd) { + string pAuthcid = SASLprep(authcid, true); # prepare authcid + string pPasswd = SASLprep(passwd, true); # prepare passwd + if (pAuthcid == NULL || pPasswd == NULL) { + return false; # preparation failed + } + if (pAuthcid == "" || pPasswd == "") { + return false; # empty prepared string + } + + + + +Zeilenga Standards Track [Page 4] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + + storedHash = FetchPasswordHash(pAuthcid); + if (storedHash == NULL || storedHash == "") { + return false; # error or unknown authcid + } + + if (!Compare(storedHash, Hash(pPasswd))) { + return false; # incorrect password + } + + if (authzid == NULL ) { + authzid = DeriveAuthzid(pAuthcid); + if (authzid == NULL || authzid == "") { + return false; # could not derive authzid + } + } + + if (!Authorize(pAuthcid, authzid)) { + return false; # not authorized + } + + return true; + } + + The second parameter of the SASLprep function, when true, indicates + that unassigned code points are allowed in the input. When the + SASLprep function is called to prepare the password prior to + computing the stored hash, the second parameter would be false. + + The second parameter provided to the Authorize function is not + prepared by this code. The application-level SASL profile should be + consulted to determine what, if any, preparation is necessary. + + Note that the DeriveAuthzid and Authorize functions (whether + implemented as one function or two, whether designed in a manner in + which these functions or whether the mechanism implementation can be + reused elsewhere) require knowledge and understanding of mechanism + and the application-level protocol specification and/or + implementation details to implement. + + Note that the Authorize function outcome is clearly dependent on + details of the local authorization model and policy. Both functions + may be dependent on other factors as well. + + + + + + + + + +Zeilenga Standards Track [Page 5] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + +4. Examples + + This section provides examples of PLAIN authentication exchanges. + The examples are intended to help the readers understand the above + text. The examples are not definitive. + + "C:" and "S:" indicate lines sent by the client and server, + respectively. "" represents a single NUL (U+0000) character. + The Application Configuration Access Protocol ([ACAP]) is used in the + examples. + + The first example shows how the PLAIN mechanism might be used for + user authentication. + + S: * ACAP (SASL "CRAM-MD5") (STARTTLS) + C: a001 STARTTLS + S: a001 OK "Begin TLS negotiation now" + + S: * ACAP (SASL "CRAM-MD5" "PLAIN") + C: a002 AUTHENTICATE "PLAIN" + S: + "" + C: {21} + C: timtanstaaftanstaaf + S: a002 OK "Authenticated" + + The second example shows how the PLAIN mechanism might be used to + attempt to assume the identity of another user. In this example, the + server rejects the request. Also, this example makes use of the + protocol optional initial response capability to eliminate a round- + trip. + + S: * ACAP (SASL "CRAM-MD5") (STARTTLS) + C: a001 STARTTLS + S: a001 OK "Begin TLS negotiation now" + + S: * ACAP (SASL "CRAM-MD5" "PLAIN") + C: a002 AUTHENTICATE "PLAIN" {20+} + C: UrselKurtxipj3plmq + S: a002 NO "Not authorized to requested authorization identity" + +5. Security Considerations + + As the PLAIN mechanism itself provided no integrity or + confidentiality protections, it should not be used without adequate + external data security protection, such as TLS services provided by + many application-layer protocols. By default, implementations SHOULD + NOT advertise and SHOULD NOT make use of the PLAIN mechanism unless + adequate data security services are in place. + + + +Zeilenga Standards Track [Page 6] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + + When the PLAIN mechanism is used, the server gains the ability to + impersonate the user to all services with the same password + regardless of any encryption provided by TLS or other confidentiality + protection mechanisms. Whereas many other authentication mechanisms + have similar weaknesses, stronger SASL mechanisms address this issue. + Clients are encouraged to have an operational mode where all + mechanisms that are likely to reveal the user's password to the + server are disabled. + + General [SASL] security considerations apply to this mechanism. + + Unicode, [UTF-8], and [StringPrep] security considerations also + apply. + +6. IANA Considerations + + The SASL Mechanism registry [IANA-SASL] entry for the PLAIN mechanism + has been updated by the IANA to reflect that this document now + provides its technical specification. + + To: iana@iana.org + Subject: Updated Registration of SASL mechanism PLAIN + + SASL mechanism name: PLAIN + Security considerations: See RFC 4616. + Published specification (optional, recommended): RFC 4616 + Person & email address to contact for further information: + Kurt Zeilenga + IETF SASL WG + Intended usage: COMMON + Author/Change controller: IESG + Note: Updates existing entry for PLAIN + +7. Acknowledgements + + This document is a revision of RFC 2595 by Chris Newman. Portions of + the grammar defined in Section 2 were borrowed from [UTF-8] by + Francois Yergeau. + + This document is a product of the IETF Simple Authentication and + Security Layer (SASL) Working Group. + + + + + + + + + + +Zeilenga Standards Track [Page 7] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + +8. Normative References + + [ABNF] Crocker, D., Ed. and P. Overell, "Augmented BNF for + Syntax Specifications: ABNF", RFC 4234, October 2005. + + [Keywords] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [SASL] Melnikov, A., Ed., and K. Zeilenga, Ed., "Simple + Authentication and Security Layer (SASL)", RFC 4422, + June 2006. + + [SASLPrep] Zeilenga, K., "SASLprep: Stringprep Profile for User + Names and Passwords", RFC 4013, February 2005. + + [StringPrep] Hoffman, P. and M. Blanchet, "Preparation of + Internationalized Strings ("stringprep")", RFC 3454, + December 2002. + + [Unicode] The Unicode Consortium, "The Unicode Standard, Version + 3.2.0" is defined by "The Unicode Standard, Version + 3.0" (Reading, MA, Addison-Wesley, 2000. ISBN 0-201- + 61633-5), as amended by the "Unicode Standard Annex + #27: Unicode 3.1" + (http://www.unicode.org/reports/tr27/) and by the + "Unicode Standard Annex #28: Unicode 3.2" + (http://www.unicode.org/reports/tr28/). + + [UTF-8] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, November 2003. + + [TLS] Dierks, T. and E. Rescorla, "The Transport Layer + Security (TLS) Protocol Version 1.1", RFC 4346, April + 2006. + +9. Informative References + + [ACAP] Newman, C. and J. Myers, "ACAP -- Application + Configuration Access Protocol", RFC 2244, November + 1997. + + [CRAM-MD5] Nerenberg, L., Ed., "The CRAM-MD5 SASL Mechanism", Work + in Progress, June 2006. + + [DIGEST-MD5] Melnikov, A., Ed., "Using Digest Authentication as a + SASL Mechanism", Work in Progress, June 2006. + + + + + +Zeilenga Standards Track [Page 8] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + + [IANA-SASL] IANA, "SIMPLE AUTHENTICATION AND SECURITY LAYER (SASL) + MECHANISMS", + . + + [SMTP-AUTH] Myers, J., "SMTP Service Extension for Authentication", + RFC 2554, March 1999. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Zeilenga Standards Track [Page 9] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + +Appendix A. Changes since RFC 2595 + + This appendix is non-normative. + + This document replaces Section 6 of RFC 2595. + + The specification details how the server is to compare client- + provided character strings with stored character strings. + + The ABNF grammar was updated. In particular, the grammar now allows + LINE FEED (U+000A) and CARRIAGE RETURN (U+000D) characters in the + authzid, authcid, passwd productions. However, whether these control + characters may be used depends on the string preparation rules + applicable to the production. For passwd and authcid productions, + control characters are prohibited. For authzid, one must consult the + application-level SASL profile. This change allows PLAIN to carry + all possible authorization identity strings allowed in SASL. + + Pseudo-code was added. + + The example section was expanded to illustrate more features of the + PLAIN mechanism. + +Editor's Address + + Kurt D. Zeilenga + OpenLDAP Foundation + + EMail: Kurt@OpenLDAP.org + + + + + + + + + + + + + + + + + + + + + + +Zeilenga Standards Track [Page 10] + +RFC 4616 The PLAIN SASL Mechanism August 2006 + + +Full Copyright Statement + + Copyright (C) The Internet Society (2006). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET + ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE + INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is provided by the IETF + Administrative Support Activity (IASA). + + + + + + + +Zeilenga Standards Track [Page 11] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4870.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4870.txt new file mode 100644 index 00000000..55ba5e2e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4870.txt @@ -0,0 +1,2298 @@ + + + + + +Network Working Group M. Delany +Request for Comments: 4870 Yahoo! Inc +Obsoleted By: 4871 May 2007 +Category: Historic + + + Domain-Based Email Authentication Using Public Keys + Advertised in the DNS (DomainKeys) + +Status of This Memo + + This memo defines a Historic Document for the Internet community. It + does not specify an Internet standard of any kind. Distribution of + this memo is unlimited. + +Copyright Notice + + Copyright (C) The IETF Trust (2007). + +Abstract + + "DomainKeys" creates a domain-level authentication framework for + email by using public key technology and the DNS to prove the + provenance and contents of an email. + + This document defines a framework for digitally signing email on a + per-domain basis. The ultimate goal of this framework is to + unequivocally prove and protect identity while retaining the + semantics of Internet email as it is known today. + + Proof and protection of email identity may assist in the global + control of "spam" and "phishing". + + + + + + + + + + + + + + + + + + + +Delany Historic [Page 1] + +RFC 4870 DomainKeys May 2007 + + +Table of Contents + + 1. Introduction ....................................................3 + 1.1. Lack of Authentication Is Damaging Internet Email ..........3 + 1.2. Digitally Signing Email Creates Credible Domain + Authentication .............................................4 + 1.3. Public Keys in the DNS .....................................4 + 1.4. Initial Deployment Is Likely at the Border MTA .............5 + 1.5. Conveying Verification Results to MUAs .....................5 + 1.6. Technical Minutiae Are Not Completely Covered ..............5 + 1.7. Motivation .................................................6 + 1.8. Benefits of DomainKeys .....................................6 + 1.9. Definitions ................................................7 + 1.10. Requirements Notation .....................................8 + 2. DomainKeys Overview .............................................8 + 3. DomainKeys Detailed View ........................................8 + 3.1. Determining the Sending Address of an Email ................9 + 3.2. Retrieving the Public Key Given the Sending Domain ........10 + 3.2.1. Introducing "selectors" ............................10 + 3.2.2. Public Key Signing and Verification Algorithm ......11 + 3.2.3. Public key Representation in the DNS ...............13 + 3.2.4. Key Sizes ..........................................14 + 3.3. Storing the Signature in the Email Header .................15 + 3.4. Preparation of Email for Transit and Signing ..............17 + 3.4.1. Preparation for Transit ............................18 + 3.4.2. Canonicalization for Signing .......................18 + 3.4.2.1. The "simple" Canonicalization Algorithm ...19 + 3.4.2.2. The "nofws" Canonicalization Algorithm ....19 + 3.5. The Signing Process .......................................20 + 3.5.1. Identifying the Sending Domain .....................20 + 3.5.2. Determining Whether an Email Should Be Signed ......21 + 3.5.3. Selecting a Private Key and Corresponding + Selector Information ...............................21 + 3.5.4. Calculating the Signature Value ....................21 + 3.5.5. Prepending the "DomainKey-Signature:" Header .......21 + 3.6. Policy Statement of Sending Domain ........................22 + 3.7. The Verification Process ..................................23 + 3.7.1. Presumption that Headers Are Not Reordered .........24 + 3.7.2. Verification Should Render a Binary Result .........24 + 3.7.3. Selecting the Most Appropriate + "DomainKey-Signature:" Header ......................24 + 3.7.4. Retrieve the Public Key Based on the + Signature Information ..............................26 + 3.7.5. Verify the Signature ...............................27 + 3.7.6. Retrieving Sending Domain Policy ...................27 + 3.7.7. Applying Local Policy ..............................27 + 3.8. Conveying Verification Results to MUAs ....................27 + + + + +Delany Historic [Page 2] + +RFC 4870 DomainKeys May 2007 + + + 4. Example of Use .................................................29 + 4.1. The User Composes an Email ................................29 + 4.2. The Email Is Signed .......................................29 + 4.3. The Email Signature Is Verified ...........................30 + 5. Association with a Certificate Authority .......................31 + 5.1. The "DomainKey-X509:" Header ..............................31 + 6. Topics for Discussion ..........................................32 + 6.1. The Benefits of Selectors .................................32 + 6.2. Canonicalization of Email .................................33 + 6.3. Mailing Lists .............................................33 + 6.4. Roving Users ..............................................33 + 7. Security Considerations ........................................34 + 7.1. DNS .......................................................34 + 7.1.1. The DNS Is Not Currently Secure ....................34 + 7.1.2. DomainKeys Creates Additional DNS Load .............35 + 7.2. Key Management ............................................35 + 7.3. Implementation Risks ......................................35 + 7.4. Privacy Assumptions with Forwarding Addresses .............35 + 7.5. Cryptographic Processing Is Computationally Intensive .....36 + 8. The Trial ......................................................36 + 8.1. Goals .....................................................36 + 8.2. Results of Trial ..........................................37 + 9. Note to Implementors Regarding TXT Records .....................37 + 10. References ....................................................37 + 10.1. Normative References .....................................37 + 10.2. Informative References ...................................38 + Appendix A - Syntax Rules for the Tag=Value Format .............39 + Acknowledgments ................................................40 + +1. Introduction + + This document proposes an authentication framework for email that + stores public keys in the DNS and digitally signs email on a domain + basis. Separate documents discuss how this framework can be extended + to validate the delivery path of email as well as facilitate per-user + authentication. + + The DomainKeys specification was a primary source from which the + DomainKeys Identified Mail [DKIM] specification has been derived. + The purpose in submitting this document is as an historical reference + for deployed implementations written prior to the DKIM specification. + +1.1. Lack of Authentication Is Damaging Internet Email + + Authentication of email is not currently widespread. Not only is it + difficult to prove your own identity, it is impossible to prevent + others from abusing your identity. + + + + +Delany Historic [Page 3] + +RFC 4870 DomainKeys May 2007 + + + While most email exchanges do not intrinsically need authentication + beyond context, it is the rampant abuse of identity by "spammers", + "phishers", and their criminal ilk that makes proof necessary. In + other words, authentication is as much about protection as proof. + + Importantly, the inability to authenticate email effectively + delegates much of the control of the disposition of inbound email to + the sender, since senders can trivially assume any email address. + Creating email authentication is the first step to returning + dispositional control of email to the recipient. + + For the purposes of this document, authentication is seen from a user + perspective, and is intended to answer the question "who sent this + email?" where "who" is the email address the recipient sees and "this + email" is the content that the recipient sees. + +1.2. Digitally Signing Email Creates Credible Domain Authentication + + DomainKeys combines public key cryptography and the DNS to provide + credible domain-level authentication for email. + + When an email claims to originate from a certain domain, DomainKeys + provides a mechanism by which the recipient system can credibly + determine that the email did in fact originate from a person or + system authorized to send email for that domain. + + The authentication provided by DomainKeys works in a number of + scenarios in which other authentication systems fail or create + complex operational requirements. These include the following: + + o forwarded email + + o distributed sending systems + + o authorized third-party sending + + This base definition of DomainKeys is intended to primarily enable + domain-level authenticity. Whether a given message is really sent by + the purported user within the domain is outside the scope of the base + definition. Having said that, this specification includes the + possibility that some domains may wish to delegate fine-grained + authentication to individual users. + +1.3. Public Keys in the DNS + + DomainKeys differs from traditional hierarchical public key systems + in that it leverages the DNS for public key management, placing + complete and direct control of key generation and management with the + + + +Delany Historic [Page 4] + +RFC 4870 DomainKeys May 2007 + + + owner of the domain. That is, if you have control over the DNS for a + given domain, you have control over your DomainKeys for that domain. + + The DNS is proposed as the initial mechanism for publishing public + keys. DomainKeys is specifically designed to be extensible to other + key-fetching services as they become available. + +1.4. Initial Deployment Is Likely at the Border MTA + + For practical reasons, it is expected that initial implementations of + DomainKeys will be deployed on Mail Transfer Agents (MTAs) that + accept or relay email across administrative or organizational + boundaries. There are numerous advantages to deployment at the + border MTA, including: + + o a reduction in the number of MTAs that have to be changed to + support an implementation of DomainKeys + + o a reduction in the number of MTAs involved in transmitting the + email between a signing system and a verifying system, thus + reducing the number of places that can make accidental changes + to the contents + + o removing the need to implement DomainKeys within an internal + email network. + + However, there is no necessity to deploy DomainKeys at the border as + signing and verifying can effectively occur anywhere from the border + MTA right back to the Mail User Agent (MUA). In particular, the best + place to sign an email for many domains is likely to be at the point + of SUBMISSION where the sender is often authenticated through SMTP + AUTH or other identifying mechanisms. + +1.5. Conveying Verification Results to MUAs + + It follows that testing the authenticity of an email results in some + action based on the results of the test. Oftentimes, the action is + to notify the MUA in some way -- typically via a header line. + + The "Domainkey-Status:" header is defined in this specification for + recording authentication results in the email. + +1.6. Technical Minutiae Are Not Completely Covered + + The intent of this specification is to communicate the fundamental + characteristics of DomainKeys for an implementor. However, some + aspects are derived from the functionality of the openssl command + [OPENSSL] and, rather than duplicate that documentation, implementors + + + +Delany Historic [Page 5] + +RFC 4870 DomainKeys May 2007 + + + are expected to understand the mechanics of the openssl command, + sufficient to complete the implementation. + +1.7. Motivation + + The motivation for DomainKeys is to define a simple, cheap, and + "sufficiently effective" mechanism by which domain owners can control + who has authority to send email using their domain. To this end, the + designers of DomainKeys set out to build a framework that: + + o is transparent and compatible with the existing email + infrastructure + + o requires no new infrastructure + + o can be implemented independently of clients in order to reduce + deployment time + + o does not require the use of a central certificate authority + that might impose fees for certificates or introduce delays to + deployment + + o can be deployed incrementally + + While we believe that DomainKeys meets these criteria, it is by no + means a perfect solution. The current Internet imposes considerable + compromises on any similar scheme, and readers should be careful not + to misinterpret the information provided in this document to imply + that DomainKeys makes stronger credibility statements than it is able + to do. + +1.8. Benefits of DomainKeys + + As the reader will discover, DomainKeys is solely an authentication + system. It is not a magic bullet for spam, nor is it an + authorization system, a reputation system, a certification system, or + a trust system. + + However, a strong authentication system such as DomainKeys creates an + unimpeachable framework within which comprehensive authorization + systems, reputations systems, and their ilk can be developed. + + + + + + + + + + +Delany Historic [Page 6] + +RFC 4870 DomainKeys May 2007 + + +1.9. Definitions + + With reference to the following sample email: + + Line Data + Number Bytes Content + ---- --- -------------------------------------------- + 01 46 From: "Joe SixPack" + 02 40 To: "Suzie Q" + 03 25 Subject: Is dinner ready? + 04 43 Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + 05 40 Comment: This comment has a continuation + 06 51 because this line begins with folding white space + 07 60 Message-ID: <20030712040037.46341@football.example.com> + 08 00 + 09 03 Hi. + 10 00 + 11 37 We lost the game. Are you hungry yet? + 12 00 + 13 04 Joe. + 14 00 + 15 00 + + Line 01 is the first line of the email and the first line of the + headers. + + Lines 05 and 06 constitute the "Comment:" header. + + Line 06 is a continuation header line. + + Line 07 is the last line of the headers. + + Line 08 is the empty line that separates the header from the body. + + Line 09 is the first line of the body. + + Lines 10, 12, 14, and 15 are empty lines. + + Line 13 is the last non-empty line of the email. + + Line 15 is the last line of the body and the last line of the email. + + Lines 01 to 15 constitute the complete email. + + Line 01 is earlier than line 02, and line 02 is later than line 01. + + + + + + +Delany Historic [Page 7] + +RFC 4870 DomainKeys May 2007 + + +1.10. Requirements Notation + + This document occasionally uses terms that appear in capital letters. + When the terms "MUST", "SHOULD", "RECOMMENDED", "MUST NOT", "SHOULD + NOT", and "MAY" appear capitalized, they are being used to indicate + particular requirements of this specification. A discussion of the + meanings of these terms appears in [RFC2119]. + +2. DomainKeys Overview + + Under DomainKeys, a domain owner generates one or more private/public + key pairs that will be used to sign messages originating from that + domain. The domain owner places the public key in his domain + namespace (i.e., in a DNS record associated with that domain), and + makes the private key available to the outbound email system. When + an email is submitted by an authorized user of that domain, the email + system uses the private key to digitally sign the email associated + with the sending domain. The signature is added as a header to the + email, and the message is transferred to its recipients in the usual + way. + + When a message is received with a DomainKey signature header, the + receiving system can verify the signature as follows: + + 1. Extract the signature and claimed sending domain from the + email. + + 2. Fetch the public key from the claimed sending domain namespace. + + 3. Use public key to determine whether the signature of the email + has been generated with the corresponding private key, and thus + whether the email was sent with the authority of the claimed + sending domain. + + In the event that an email arrives without a signature or when the + signature verification fails, the receiving system retrieves the + policy of the claimed sending domain to ascertain the preferred + disposition of such email. + + Armed with this information, the recipient system can apply local + policy based on the results of the signature test. + +3. DomainKeys Detailed View + + This section discusses the specifics of DomainKeys that are needed to + create interoperable implementations. This section answers the + following questions: + + + + +Delany Historic [Page 8] + +RFC 4870 DomainKeys May 2007 + + + Given an email, how is the sending domain determined? + + How is the public key retrieved for a sending domain? + + As email transits the email system, it can potentially go through + a number of changes. Which parts of the email are included in the + signature and how are they protected from such transformations? + + How is the signature represented in the email? + + If a signature is not present, or a verification fails, how does + the recipient determine the policy intent of the sending domain? + + Finally, on verifying the authenticity of an email, how is that + result conveyed to participating MUAs? + + While there are many alternative design choices, most lead to + comparable functionality. The overriding selection criteria used to + choose among the alternatives are as follows: + + o use deployed technology whenever possible + + o prefer ease of implementation + + o avoid trading risk for excessive flexibility or + interoperability + + o include basic flexibility + + Adherence to these criteria implies that some existing email + implementations will require changes to participate in DomainKeys. + Ultimately, some hard choices need to be made regarding which + requirements are more important. + +3.1. Determining the Sending Address of an Email + + The goal of DomainKeys is to give the recipient confidence that the + email originated from the claimed sender. As with much of Internet + email, agreement over what constitutes the "sender" is no easy + matter. Forwarding systems and mailing lists add serious + complications to an overtly simple question. From the point of view + of the recipient, the authenticity claim should be directed at the + domain most visible to the recipient. + + In the first instance, the most visible address is clearly the RFC + 2822 "From:" address [RFC2822]. Therefore, a conforming email MUST + contain a single "From:" header from which an email address with a + domain name can be extracted. + + + +Delany Historic [Page 9] + +RFC 4870 DomainKeys May 2007 + + + A conforming email MAY contain a single RFC 2822 "Sender:" header + from which an email address with a domain name can be extracted. + + If the email has a valid "From:" and a valid "Sender:" header, then + the signer MUST use the sending address in the "Sender:" header. + + If the email has a valid "From:" and no "Sender:" header, then the + signer MUST use the first sending address in the "From:" header. + + In all other cases, a signer MUST NOT sign the email. Implementors + should note that an email with a "Sender:" header and no "From:" + header MUST NOT be signed. + + The domain name in the sending address constitutes the "sending + domain". + +3.2. Retrieving the Public Key Given the Sending Domain + + To avoid namespace conflicts, it is proposed that the DNS namespace + "_domainkey." be reserved within the sending domain for storing + public keys, e.g., if the sending domain is example.net, then the + public keys for that domain are stored in the _domainkey.example.net + namespace. + +3.2.1. Introducing "selectors" + + To support multiple concurrent public keys per sending domain, the + DNS namespace is further subdivided with "selectors". Selectors are + arbitrary names below the "_domainkey." namespace. A selector value + and length MUST be legal in the DNS namespace and in email headers + with the additional provision that they cannot contain a semicolon. + + Examples of namespaces using selectors are as follows: + + "coolumbeach._domainkey.example.net" + "sebastopol._domainkey.example.net" + "reykjavik._domainkey.example.net" + "default._domainkey.example.net" + + and + + "2005.pao._domainkey.example.net" + "2005.sql._domainkey.example.net" + "2005.rhv._domainkey.example.net" + + Periods are allowed in selectors and are to be treated as component + separators. In the case of DNS queries, that means the period + defines subdomain boundaries. + + + +Delany Historic [Page 10] + +RFC 4870 DomainKeys May 2007 + + + The number of public keys and corresponding selectors for each domain + is determined by the domain owner. Many domain owners will be + satisfied with just one selector, whereas administratively + distributed organizations may choose to manage disparate selectors + and key pairs in different regions, or on different email servers. + + Beyond administrative convenience, selectors make it possible to + seamlessly replace public keys on a routine basis. If a domain + wishes to change from using a public key associated with selector + "2005" to a public key associated with selector "2006", it merely + makes sure that both public keys are advertised in the DNS + concurrently for the transition period during which email may be in + transit prior to verification. At the start of the transition + period, the outbound email servers are configured to sign with the + "2006" private key. At the end of the transition period, the "2005" + public key is removed from the DNS. + + While some domains may wish to make selector values well known, + others will want to take care not to allocate selector names in a way + that allows harvesting of data by outside parties. For example, if + per-user keys are issued, the domain owner will need to make the + decision as to whether to make this selector associated directly with + the user name or make it some unassociated random value, such as the + fingerprint of the public key. + +3.2.2. Public Key Signing and Verification Algorithm + + The default signature is an RSA signed SHA1 digest of the complete + email. + + For ease of explanation, the openssl command is used throughout this + document to describe the mechanism by which keys and signatures are + managed. + + One way to generate a 768-bit private key suitable for DomainKeys is + to use openssl like this: + + $ openssl genrsa -out rsa.private 768 + + + + + + + + + + + + + +Delany Historic [Page 11] + +RFC 4870 DomainKeys May 2007 + + + which results in the file rsa.private containing the key information + similar to this: + + -----BEGIN RSA PRIVATE KEY----- + MIIByQIBAAJhAKJ2lzDLZ8XlVambQfMXn3LRGKOD5o6lMIgulclWjZwP56LRqdg5 + ZX15bhc/GsvW8xW/R5Sh1NnkJNyL/cqY1a+GzzL47t7EXzVc+nRLWT1kwTvFNGIo + AUsFUq+J6+OprwIDAQABAmBOX0UaLdWWusYzNol++nNZ0RLAtr1/LKMX3tk1MkLH + +Ug13EzB2RZjjDOWlUOY98yxW9/hX05Uc9V5MPo+q2Lzg8wBtyRLqlORd7pfxYCn + Kapi2RPMcR1CxEJdXOkLCFECMQDTO0fzuShRvL8q0m5sitIHlLA/L+0+r9KaSRM/ + 3WQrmUpV+fAC3C31XGjhHv2EuAkCMQDE5U2nP2ZWVlSbxOKBqX724amoL7rrkUew + ti9TEjfaBndGKF2yYF7/+g53ZowRkfcCME/xOJr58VN17pejSl1T8Icj88wGNHCs + FDWGAH4EKNwDSMnfLMG4WMBqd9rzYpkvGQIwLhAHDq2CX4hq2tZAt1zT2yYH7tTb + weiHAQxeHe0RK+x/UuZ2pRhuoSv63mwbMLEZAjAP2vy6Yn+f9SKw2mKuj1zLjEhG + 6ppw+nKD50ncnPoP322UMxVNG4Eah0GYJ4DLP0U= + -----END RSA PRIVATE KEY----- + + Once a private key has been generated, the openssl command can be + used to sign an appropriately prepared email, like this: + + $ openssl dgst -sign rsa.private -sha1 + To: "Suzie Q" + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + +4.2. The Email Is Signed + + This email is signed by the football.example.com outbound email + server and now looks like this: + + DomainKey-Signature: a=rsa-sha1; s=brisbane; d=football.example.com; + c=simple; q=dns; + b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZ + VoG4ZHRNiYzR; + Received: from dsl-10.2.3.4.football.example.com [10.2.3.4] + by submitserver.football.example.com with SUBMISSION; + Fri, 11 Jul 2003 21:01:54 -0700 (PDT) + From: "Joe SixPack" + To: "Suzie Q" + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + + The signing email server requires access to the private key + associated with the "brisbane" selector to generate this signature. + Distribution and management of private keys are outside the scope of + this document. + + + +Delany Historic [Page 29] + +RFC 4870 DomainKeys May 2007 + + +4.3. The Email Signature Is Verified + + The signature is normally verified by an inbound SMTP server or + possibly the final delivery agent. However, intervening MTAs can + also perform this verification if they choose to do so. + + The verification process uses the domain "football.example.com" + extracted from the "From:" header and the selector "brisbane" from + the "DomainKey-Signature:" header to form the DNS TXT query for: + + brisbane._domainkey.football.example.com + + Since there is no "h" tag in the "DomainKey-Signature:" header, + signature verification starts with the line following the + "DomainKey-Signature:" line. The email is canonically prepared for + verifying with the "simple" method. + + The result of the query and subsequent verification of the signature + is stored in the "DomainKey-Status:" header line. After successful + verification, the email looks like this: + + DomainKey-Status: good + from=joe@football.example.com; domainkeys=pass + Received: from mout23.brisbane.football.example.com (192.168.1.1) + by shopping.example.net with SMTP; + Fri, 11 Jul 2003 21:01:59 -0700 (PDT) + DomainKey-Signature: a=rsa-sha1; s=brisbane; d=football.example.com; + c=simple; q=dns; + b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZ + VoG4ZHRNiYzR; + Received: from dsl-10.2.3.4.network.example.com [10.2.3.4] + by submitserver.example.com with SUBMISSION; + Fri, 11 Jul 2003 21:01:54 -0700 (PDT) + From: "Joe SixPack" + To: "Suzie Q" + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + + + + + + + +Delany Historic [Page 30] + +RFC 4870 DomainKeys May 2007 + + +5. Association with a Certificate Authority + + A fundamental aspect of DomainKeys is that public keys are generated + and advertised by each domain at no additional cost. This + accessibility markedly differs from traditional Public Key + Infrastructures where there is typically a Certificate Authority (CA) + who validates an applicant and issues a signed certificate -- + containing their public key -- often for a recurring fee. + + While CAs do impose costs, they also have the potential to provide + additional value as part of their certification process. Consider + financial institutions, public utilities, law enforcement agencies, + and the like. In many cases, such entities justifiably need to + discriminate themselves above and beyond the authentication that + DomainKeys offers. + + Creating a link between DomainKeys and CA-issued certificates has the + potential to access additional authentication mechanisms that are + more authoritative than domain-owner-issued authentication. It is + well beyond the scope of this specification to describe such + authorities apart from defining how the linkage could be achieved + with the "DomainKey-X509:" header. + +5.1. The "DomainKey-X509:" Header + + The "DomainKey-X509:" header provides a link between the public key + used to sign the email and the certificate issued by a CA. + + The exact content, syntax, and semantics of this header are yet to be + resolved. One possibility is that this header contains an encoding + of the certificate issued by a CA. Another possibility is that this + header contains a URL that points to a certificate issued by a CA. + + In either case, this header can only be consulted if the signature + verifies and MUST be part of the content signed by the corresponding + "DomainKey-Signature:" header. Furthermore, it is likely that MUAs + rather than MTAs will confirm that the link to the CA-issued + certificate is valid. In part, this is because many MUAs already + have built-in capabilities as a consequence of Secure/Multipurpose + Internet Mail Extensions (S/MIME) [SMIME] and Secure Socket Layer + (SSL) [SSL] support. + + The proof of linkage is made by testing that the public key in the + certificate matches the public key used to sign the email. + + + + + + + +Delany Historic [Page 31] + +RFC 4870 DomainKeys May 2007 + + + An example of an email containing the "DomainKey-X509:" header is: + + DomainKey-Signature: a=rsa-sha1; s=statements; + d=largebank.example.com; c=simple; q=dns; + b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZ + VoG4ZHRNiYzR; + DomainKey-X509: https://ca.example.net/largebank.example.com + From: "Large Bank" + To: "Suzie Q" + Subject: Statement for Account: 1234-5678 + ... + + The format of the retrieved value from the URL is not yet defined, + nor is the determination of valid CAs. + + The whole matter of linkage to CA-issued certificates is one aspect + of DomainKeys that needs to be resolved with relevant CA's and + certificate-issuing entities. The primary point is that a link is + possible to a higher authority. + +6. Topics for Discussion + +6.1. The Benefits of Selectors + + Selectors are at the heart of the flexibility of DomainKeys. A + domain administrator is free to use a single DomainKey for all + outbound mail. Alternatively, the domain administrator may use many + DomainKeys differentiated by selector and assign each key to + different servers. + + For example, a large outbound email farm might have a unique + DomainKey for each server, and thus their DNS will advertise + potentially hundreds of keys via their unique selectors. + + Another example is a corporate email administrator who might generate + a separate DomainKey for each regional office email server. + + In essence, selectors allow a domain owner to distribute authority to + send on behalf of that domain. Combined with the ability to revoke + by removal or Time to Live (TTL) expiration, a domain owner has + coarse-grained control over the duration of the distributed + authority. + + Selectors are particularly useful for domain owners who want to + contract a third-party mailing system to send a particular set of + mail. The domain owner can generate a special key pair and selector + just for this mail-out. The domain owner has to provide the private + key and selector to the third party for the life of the mail-out. + + + +Delany Historic [Page 32] + +RFC 4870 DomainKeys May 2007 + + + However, as soon as the mail-out is completely delivered, the domain + owner can revoke the public key by the simple expedient of removing + the entry from the DNS. + +6.2. Canonicalization of Email + + It is an unfortunate fact that some email software routinely (and + often unnecessarily) transforms email as it transits through the + network. Such transformations conflict with the fundamental purpose + of cryptographic signatures - to detect modifications. + + While two canonicalization algorithms are defined in this + specification, the primary goal of "nofws" is to provide a transition + path to "simple". With a mixture of "simple" and "nofws" email, a + receiver can determine which systems are modifying email in ways that + cause the signature to fail and thus provide feedback to the + modifying system. + +6.3. Mailing Lists + + Integrating existing Mailing List Managers (MLMs) into the DomainKeys + authentication system is a complicated area, as the behavior of MLMs + is highly variable. Essentially, there are two types of MLMs under + consideration: those that modify email to such an extent that + verification of the original content is not possible, and those that + make minimal or no modifications to an email. + + MLMs that modify email in a way that causes verification to fail MUST + prepend a "Sender:" header and SHOULD prepend a "List-ID:" header + prior to signing for distribution to list recipients. + + A participating SUBMISSION server can deduce the need to re-sign such + an email by the presence of a "Sender:" or "List-ID:" header from an + authorized submission. + + MLMs that do not modify email in a way that causes verification to + fail MAY perform the same actions as a modifying MLM. + +6.4. Roving Users + + One scenario that presents a particular problem with any form of + email authentication, including DomainKeys, is the roving user: a + user who is obliged to use a third-party SUBMISSION service when + unable to connect to the user's own SUBMISSION service. The classic + example cited is a traveling salesperson being redirected to a hotel + email server to send email. + + + + + +Delany Historic [Page 33] + +RFC 4870 DomainKeys May 2007 + + + As far as DomainKeys is concerned, email of this nature clearly + originates from an email server that does not have authority to send + on behalf of the domain of the salesperson and is therefore + indistinguishable from a forgery. While DomainKeys does not + prescribe any specific action for such email, it is likely that over + time, such email will be treated as second-class email. + + The typical solution offered to roving users is to submit email via + an authorized server for their domain -- perhaps via a Virtual + Private Network (VPN) or a web interface or even SMTP AUTH back to a + SUBMISSION server. + + While these are perfectly acceptable solutions for many, they are not + necessarily solutions that are available or possible for all such + users. + + One possible way to address the needs of this contingent of + potentially disenfranchised users is for the domain to issue per-user + DomainKeys. Per-user DomainKeys are identified by a non-empty "g" + tag value in the corresponding DNS record. + +7. Security Considerations + +7.1. DNS + + DomainKeys is primarily a security mechanism. Its core purpose is to + make claims about email authentication in a credible way. However, + DomainKeys, like virtually all Internet applications, relies on the + DNS, which has well-known security flaws [RFC3833]. + +7.1.1. The DNS Is Not Currently Secure + + While the DNS is currently insecure, it is expected that the security + problems should and will be solved by DNS Security (DNSSEC) [DNSSEC], + and all users of the DNS will reap the benefit of that work. + + Secondly, the types of DNS attacks relevant to DomainKeys are very + costly and are far less rewarding than DNS attacks on other Internet + applications. + + To systematically thwart the intent of DomainKeys, an attacker must + conduct a very costly and very extensive attack on many parts of the + DNS over an extended period. No one knows for sure how attackers + will respond; however, the cost/benefit of conducting prolonged DNS + attacks of this nature is expected to be uneconomical. + + Finally, DomainKeys is only intended as a "sufficient" method of + proving authenticity. It is not intended to provide strong + + + +Delany Historic [Page 34] + +RFC 4870 DomainKeys May 2007 + + + cryptographic proof about authorship or contents. Other technologies + such as GnuPG and S/MIME address those requirements. + +7.1.2. DomainKeys Creates Additional DNS Load + + A second security issue related to the DNS revolves around the + increased DNS traffic as a consequence of fetching selector-based + data, as well as fetching sending domain policy. Widespread + deployment of DomainKeys will result in a significant increase in DNS + queries to the claimed sending domain. In the case of forgeries on a + large scale, DNS servers could see a substantial increase in queries. + +7.2. Key Management + + All public key systems require management of key pairs. Private keys + in particular need to be securely distributed to each signing mail + server and protected on those servers. For those familiar with SSL, + the key management issues are similar to those of managing SSL + certificates. Poor key management may result in unauthorized access + to private keys, which in essence gives unauthorized access to your + identity. + +7.3. Implementation Risks + + It is well recognized in cryptographic circles that many security + failures are caused by poor implementations rather than poor + algorithms. For example, early SSL implementations were vulnerable + because the implementors used predictable "random numbers". + + While some MTA software already supports various cryptographic + techniques, such as TLS, many do not. This proposal introduces + cryptographic requirements into MTA software that implies a much + higher duty of care to manage the increased risk. + + There are numerous articles, books, courses, and consultants that + help programming security applications. Potential implementors are + strongly encouraged to avail themselves of all possible resources to + ensure secure implementations. + +7.4. Privacy Assumptions with Forwarding Addresses + + Some people believe that they can achieve anonymity by using an email + forwarding service. While this has never been particularly true, as + bounces, over-quota messages, vacation messages, and web bugs all + conspire to expose IP addresses and domain names associated with the + delivery path, the DNS queries that are required to verify DomainKeys + signature can provide additional information to the sender. + + + + +Delany Historic [Page 35] + +RFC 4870 DomainKeys May 2007 + + + In particular, as mail is forwarded through the mail network, the DNS + queries for the selector will typically identify the DNS cache used + by the forwarding and delivery MTAs. + +7.5. Cryptographic Processing Is Computationally Intensive + + Verifying a signature is computationally significant. Early + indications are that a typical mail server can expect to increase CPU + demands by 8-15 percent. While this increased demand is modest + compared to other common mail processing costs -- such as Bayesian + filtering -- any increase in resource requirements can make a + denial-of-service attack more effective against a mail system. + + A constraining factor of such attacks is that the net computational + cost of verifying is bounded by the maximum key size allowed by this + specification and is essentially linear to the rate at which mail is + accepted by the verifying system. Consequently, the additional + computational cost may augment a denial-of-service attack, but it + does not add a non-linear component to such attacks. + +8. The Trial + + The DomainKeys protocol was deployed as a trial to better understand + the implications of deploying wide-scale cryptographic email + authentication. + + Open Source implementations were made available at various places, + particularly Source Forge [SOURCEFORGE], which includes links to + numerous implementations, both Open Source and commercial. + +8.1. Goals + + The primary goals of the trial were to: + + o understand the operational implications of running a DNS-based + public key system for email + + o measure the effectiveness of the canonicalization algorithms + + o experiment with possible per-user key deployment models + + o fully define the semantics of the "DomainKey-X509:" header + + + + + + + + + +Delany Historic [Page 36] + +RFC 4870 DomainKeys May 2007 + + +8.2. Results of Trial + + The DomainKeys trial ran for approximately 2 years, in which time + numerous large ISPs and many thousands of smaller domains + participated in signing or verifying with DomainKeys. The low order + numbers are that at least one billion DomainKey signed emails transit + the Internet each day between some 12,000 participating domains. + + The operational and development experience of that trial was applied + to DKIM. + +9. Note to Implementors Regarding TXT Records + + The DNS is very flexible in that it is possible to have multiple TXT + records for a single name and for those TXT records to contain + multiple strings. + + In all cases, implementors of DomainKeys should expect a single TXT + record for any particular name. If multiple TXT records are + returned, the implementation is free to pick any single TXT record as + the authoritative data. In other words, if a name server returns + different TXT records for the same name, it can expect unpredictable + results. + + Within a single TXT record, implementors should concatenate multiple + strings in the order presented and ignore string boundaries. Note + that a number of popular DNS command-line tools render multiple + strings as separately quoted strings, which can be misleading to a + novice implementor. + +10. References + +10.1. Normative References + + [BASE64] Josefsson, S., "The Base16, Base32, and Base64 Data + Encodings", RFC 4648, October 2006. + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [PEM] Linn, J., "Privacy Enhancement for Internet Electronic + Mail: Part I: Message Encryption and Authentication + Procedures", RFC 1421 February, 1993. + + + + + + + + +Delany Historic [Page 37] + +RFC 4870 DomainKeys May 2007 + + +10.2. Informative References + + [DKIM] Allman, E., Callas, J., Delany, M., Libbey, M., Fenton, + J., and M. Thomas, "DomainKeys Identified Mail (DKIM) + Signatures", RFC 4871, May 2007. + + [DNSSEC] http://www.ietf.org/html.charters/dnsext-charter.html + + [OPENSSL] http://www.openssl.org + + [RFC2822] Resnick, P., Editor, "Internet Message Format", RFC + 2822, April 2001. + + [RFC3833] Atkins, D. and R. Austein, "Threat Analysis of the + Domain Name System (DNS)", RFC 3833, August 2004. + + [SMIME] Ramsdell, B., Ed., "Secure/Multipurpose Internet Mail + Extensions (S/MIME) Version 3.1 Message Specification", + RFC 3851, July 2004. + + [SOURCEFORGE] http://domainkeys.sourceforge.net + + [SSL] http://wp.netscape.com/security/techbriefs/ssl.html + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Delany Historic [Page 38] + +RFC 4870 DomainKeys May 2007 + + +Appendix A - Syntax Rules for the Tag=Value Format + + A simple tag=value syntax is used to encode data in the response + values for DNS queries as well as headers embedded in emails. This + section summarized the syntactic rules for this encoding: + + o A tag=value pair consists of three tokens, a "tag", the "=" + character, and the "value" + + o A tag MUST be one character long and MUST be a lowercase + alphabetic character + + o Duplicate tags are not allowed + + o A value MUST only consist of characters that are valid in RFC + 2822 headers and DNS TXT records and are within the ASCII range + of characters from SPACE (0x20) to TILDE (0x7E) inclusive. + Values MUST NOT contain a semicolon but they may contain "=" + characters. + + o A tag=value pair MUST be terminated by a semicolon or the end + of the data + + o Values MUST be processed as case sensitive unless the specific + tag description of semantics imply case insensitivity. + + o Values MAY be zero bytes long + + o Whitespace MAY surround any of the tokens; however, whitespace + within a value MUST be retained unless explicitly excluded by + the specific tag description. Currently, the only tags that + specifically ignore embedded whitespace are the "b" and "h" + tags in the "DomainKey-Signature:" header. + + o Tag=value pairs that represent the default value MAY be + included to aid legibility. + + o Unrecognized tags MUST be ignored + + + + + + + + + + + + + +Delany Historic [Page 39] + +RFC 4870 DomainKeys May 2007 + + +Acknowledgments + + The editor wishes to thank Russ Allbery, Eric Allman, Edwin Aoki, + Claus Asmann, Steve Atkins, Jon Callas, Dave Crocker, Michael Cudahy, + Jutta Degener, Timothy Der, Jim Fenton, Duncan Findlay, Phillip + Hallam-Baker, Murray S. Kucherawy, John Levine, Miles Libbey, David + Margrave, Justin Mason, David Mayne, Russell Nelson, Juan Altmayer + Pizzorno, Blake Ramsdell, Scott Renfro, the Spamhaus.org team, Malte + S. Stretz, Robert Sanders, Bradley Taylor, and Rand Wacker for their + valuable suggestions and constructive criticism. + +Author's Address + + Mark Delany + Yahoo! Inc + 701 First Avenue + Sunnyvale, CA 95087 + USA + + EMail: markd+domainkeys@yahoo-inc.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Delany Historic [Page 40] + +RFC 4870 DomainKeys May 2007 + + +Full Copyright Statement + + Copyright (C) The IETF Trust (2007). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND + THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF + THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + +Delany Historic [Page 41] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4871.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4871.txt new file mode 100644 index 00000000..80410e61 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4871.txt @@ -0,0 +1,3978 @@ + + + + + +Network Working Group E. Allman +Request for Comments: 4871 Sendmail, Inc. +Obsoletes: 4870 J. Callas +Category: Standards Track PGP Corporation + M. Delany + M. Libbey + Yahoo! Inc + J. Fenton + M. Thomas + Cisco Systems, Inc. + May 2007 + + + DomainKeys Identified Mail (DKIM) Signatures + +Status of This Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The IETF Trust (2007). + +Abstract + + DomainKeys Identified Mail (DKIM) defines a domain-level + authentication framework for email using public-key cryptography and + key server technology to permit verification of the source and + contents of messages by either Mail Transfer Agents (MTAs) or Mail + User Agents (MUAs). The ultimate goal of this framework is to permit + a signing domain to assert responsibility for a message, thus + protecting message signer identity and the integrity of the messages + they convey while retaining the functionality of Internet email as it + is known today. Protection of email identity may assist in the + global control of "spam" and "phishing". + + + + + + + + + + + + +Allman, et al. Standards Track [Page 1] + +RFC 4871 DKIM Signatures May 2007 + + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 4 + 1.1. Signing Identity . . . . . . . . . . . . . . . . . . . . . 5 + 1.2. Scalability . . . . . . . . . . . . . . . . . . . . . . . 5 + 1.3. Simple Key Management . . . . . . . . . . . . . . . . . . 5 + 2. Terminology and Definitions . . . . . . . . . . . . . . . . . 5 + 2.1. Signers . . . . . . . . . . . . . . . . . . . . . . . . . 6 + 2.2. Verifiers . . . . . . . . . . . . . . . . . . . . . . . . 6 + 2.3. Whitespace . . . . . . . . . . . . . . . . . . . . . . . . 6 + 2.4. Common ABNF Tokens . . . . . . . . . . . . . . . . . . . . 6 + 2.5. Imported ABNF Tokens . . . . . . . . . . . . . . . . . . . 7 + 2.6. DKIM-Quoted-Printable . . . . . . . . . . . . . . . . . . 7 + 3. Protocol Elements . . . . . . . . . . . . . . . . . . . . . . 8 + 3.1. Selectors . . . . . . . . . . . . . . . . . . . . . . . . 8 + 3.2. Tag=Value Lists . . . . . . . . . . . . . . . . . . . . . 10 + 3.3. Signing and Verification Algorithms . . . . . . . . . . . 11 + 3.4. Canonicalization . . . . . . . . . . . . . . . . . . . . . 13 + 3.5. The DKIM-Signature Header Field . . . . . . . . . . . . . 17 + 3.6. Key Management and Representation . . . . . . . . . . . . 25 + 3.7. Computing the Message Hashes . . . . . . . . . . . . . . . 29 + 3.8. Signing by Parent Domains . . . . . . . . . . . . . . . . 31 + 4. Semantics of Multiple Signatures . . . . . . . . . . . . . . . 32 + 4.1. Example Scenarios . . . . . . . . . . . . . . . . . . . . 32 + 4.2. Interpretation . . . . . . . . . . . . . . . . . . . . . . 33 + 5. Signer Actions . . . . . . . . . . . . . . . . . . . . . . . . 34 + 5.1. Determine Whether the Email Should Be Signed and by + Whom . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 + 5.2. Select a Private Key and Corresponding Selector + Information . . . . . . . . . . . . . . . . . . . . . . . 35 + 5.3. Normalize the Message to Prevent Transport Conversions . . 35 + 5.4. Determine the Header Fields to Sign . . . . . . . . . . . 36 + 5.5. Recommended Signature Content . . . . . . . . . . . . . . 38 + 5.6. Compute the Message Hash and Signature . . . . . . . . . . 39 + 5.7. Insert the DKIM-Signature Header Field . . . . . . . . . . 40 + 6. Verifier Actions . . . . . . . . . . . . . . . . . . . . . . . 40 + 6.1. Extract Signatures from the Message . . . . . . . . . . . 41 + 6.2. Communicate Verification Results . . . . . . . . . . . . . 46 + 6.3. Interpret Results/Apply Local Policy . . . . . . . . . . . 47 + 7. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 48 + 7.1. DKIM-Signature Tag Specifications . . . . . . . . . . . . 48 + 7.2. DKIM-Signature Query Method Registry . . . . . . . . . . . 49 + 7.3. DKIM-Signature Canonicalization Registry . . . . . . . . . 49 + 7.4. _domainkey DNS TXT Record Tag Specifications . . . . . . . 50 + 7.5. DKIM Key Type Registry . . . . . . . . . . . . . . . . . . 50 + 7.6. DKIM Hash Algorithms Registry . . . . . . . . . . . . . . 51 + 7.7. DKIM Service Types Registry . . . . . . . . . . . . . . . 51 + 7.8. DKIM Selector Flags Registry . . . . . . . . . . . . . . . 52 + + + +Allman, et al. Standards Track [Page 2] + +RFC 4871 DKIM Signatures May 2007 + + + 7.9. DKIM-Signature Header Field . . . . . . . . . . . . . . . 52 + 8. Security Considerations . . . . . . . . . . . . . . . . . . . 52 + 8.1. Misuse of Body Length Limits ("l=" Tag) . . . . . . . . . 52 + 8.2. Misappropriated Private Key . . . . . . . . . . . . . . . 53 + 8.3. Key Server Denial-of-Service Attacks . . . . . . . . . . . 54 + 8.4. Attacks Against the DNS . . . . . . . . . . . . . . . . . 54 + 8.5. Replay Attacks . . . . . . . . . . . . . . . . . . . . . . 55 + 8.6. Limits on Revoking Keys . . . . . . . . . . . . . . . . . 55 + 8.7. Intentionally Malformed Key Records . . . . . . . . . . . 56 + 8.8. Intentionally Malformed DKIM-Signature Header Fields . . . 56 + 8.9. Information Leakage . . . . . . . . . . . . . . . . . . . 56 + 8.10. Remote Timing Attacks . . . . . . . . . . . . . . . . . . 56 + 8.11. Reordered Header Fields . . . . . . . . . . . . . . . . . 56 + 8.12. RSA Attacks . . . . . . . . . . . . . . . . . . . . . . . 56 + 8.13. Inappropriate Signing by Parent Domains . . . . . . . . . 57 + 9. References . . . . . . . . . . . . . . . . . . . . . . . . . . 57 + 9.1. Normative References . . . . . . . . . . . . . . . . . . . 57 + 9.2. Informative References . . . . . . . . . . . . . . . . . . 58 + Appendix A. Example of Use (INFORMATIVE) . . . . . . . . . . . . 60 + A.1. The user composes an email . . . . . . . . . . . . . . . . 60 + A.2. The email is signed . . . . . . . . . . . . . . . . . . . 61 + A.3. The email signature is verified . . . . . . . . . . . . . 61 + Appendix B. Usage Examples (INFORMATIVE) . . . . . . . . . . . . 62 + B.1. Alternate Submission Scenarios . . . . . . . . . . . . . . 63 + B.2. Alternate Delivery Scenarios . . . . . . . . . . . . . . . 65 + Appendix C. Creating a Public Key (INFORMATIVE) . . . . . . . . . 67 + Appendix D. MUA Considerations . . . . . . . . . . . . . . . . . 68 + Appendix E. Acknowledgements . . . . . . . . . . . . . . . . . . 69 + + + + + + + + + + + + + + + + + + + + + + + +Allman, et al. Standards Track [Page 3] + +RFC 4871 DKIM Signatures May 2007 + + +1. Introduction + + DomainKeys Identified Mail (DKIM) defines a mechanism by which email + messages can be cryptographically signed, permitting a signing domain + to claim responsibility for the introduction of a message into the + mail stream. Message recipients can verify the signature by querying + the signer's domain directly to retrieve the appropriate public key, + and thereby confirm that the message was attested to by a party in + possession of the private key for the signing domain. + + The approach taken by DKIM differs from previous approaches to + message signing (e.g., Secure/Multipurpose Internet Mail Extensions + (S/MIME) [RFC1847], OpenPGP [RFC2440]) in that: + + o the message signature is written as a message header field so that + neither human recipients nor existing MUA (Mail User Agent) + software is confused by signature-related content appearing in the + message body; + + o there is no dependency on public and private key pairs being + issued by well-known, trusted certificate authorities; + + o there is no dependency on the deployment of any new Internet + protocols or services for public key distribution or revocation; + + o signature verification failure does not force rejection of the + message; + + o no attempt is made to include encryption as part of the mechanism; + + o message archiving is not a design goal. + + DKIM: + + o is compatible with the existing email infrastructure and + transparent to the fullest extent possible; + + o requires minimal new infrastructure; + + o can be implemented independently of clients in order to reduce + deployment time; + + o can be deployed incrementally; + + o allows delegation of signing to third parties. + + + + + + +Allman, et al. Standards Track [Page 4] + +RFC 4871 DKIM Signatures May 2007 + + +1.1. Signing Identity + + DKIM separates the question of the identity of the signer of the + message from the purported author of the message. In particular, a + signature includes the identity of the signer. Verifiers can use the + signing information to decide how they want to process the message. + The signing identity is included as part of the signature header + field. + + INFORMATIVE RATIONALE: The signing identity specified by a DKIM + signature is not required to match an address in any particular + header field because of the broad methods of interpretation by + recipient mail systems, including MUAs. + +1.2. Scalability + + DKIM is designed to support the extreme scalability requirements that + characterize the email identification problem. There are currently + over 70 million domains and a much larger number of individual + addresses. DKIM seeks to preserve the positive aspects of the + current email infrastructure, such as the ability for anyone to + communicate with anyone else without introduction. + +1.3. Simple Key Management + + DKIM differs from traditional hierarchical public-key systems in that + no Certificate Authority infrastructure is required; the verifier + requests the public key from a repository in the domain of the + claimed signer directly rather than from a third party. + + The DNS is proposed as the initial mechanism for the public keys. + Thus, DKIM currently depends on DNS administration and the security + of the DNS system. DKIM is designed to be extensible to other key + fetching services as they become available. + +2. Terminology and Definitions + + This section defines terms used in the rest of the document. Syntax + descriptions use the form described in Augmented BNF for Syntax + Specifications [RFC4234]. + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [RFC2119]. + + + + + + + +Allman, et al. Standards Track [Page 5] + +RFC 4871 DKIM Signatures May 2007 + + +2.1. Signers + + Elements in the mail system that sign messages on behalf of a domain + are referred to as signers. These may be MUAs (Mail User Agents), + MSAs (Mail Submission Agents), MTAs (Mail Transfer Agents), or other + agents such as mailing list exploders. In general, any signer will + be involved in the injection of a message into the message system in + some way. The key issue is that a message must be signed before it + leaves the administrative domain of the signer. + +2.2. Verifiers + + Elements in the mail system that verify signatures are referred to as + verifiers. These may be MTAs, Mail Delivery Agents (MDAs), or MUAs. + In most cases it is expected that verifiers will be close to an end + user (reader) of the message or some consuming agent such as a + mailing list exploder. + +2.3. Whitespace + + There are three forms of whitespace: + + o WSP represents simple whitespace, i.e., a space or a tab character + (formal definition in [RFC4234]). + + o LWSP is linear whitespace, defined as WSP plus CRLF (formal + definition in [RFC4234]). + + o FWS is folding whitespace. It allows multiple lines separated by + CRLF followed by at least one whitespace, to be joined. + + The formal ABNF for these are (WSP and LWSP are given for information + only): + + WSP = SP / HTAB + LWSP = *(WSP / CRLF WSP) + FWS = [*WSP CRLF] 1*WSP + + The definition of FWS is identical to that in [RFC2822] except for + the exclusion of obs-FWS. + +2.4. Common ABNF Tokens + + The following ABNF tokens are used elsewhere in this document: + hyphenated-word = ALPHA [ *(ALPHA / DIGIT / "-") (ALPHA / DIGIT) ] + base64string = 1*(ALPHA / DIGIT / "+" / "/" / [FWS]) + [ "=" [FWS] [ "=" [FWS] ] ] + + + + +Allman, et al. Standards Track [Page 6] + +RFC 4871 DKIM Signatures May 2007 + + +2.5. Imported ABNF Tokens + + The following tokens are imported from other RFCs as noted. Those + RFCs should be considered definitive. + + The following tokens are imported from [RFC2821]: + + o "Local-part" (implementation warning: this permits quoted strings) + + o "sub-domain" + + The following tokens are imported from [RFC2822]: + + o "field-name" (name of a header field) + + o "dot-atom-text" (in the Local-part of an email address) + + The following tokens are imported from [RFC2045]: + + o "qp-section" (a single line of quoted-printable-encoded text) + + o "hex-octet" (a quoted-printable encoded octet) + + INFORMATIVE NOTE: Be aware that the ABNF in RFC 2045 does not obey + the rules of RFC 4234 and must be interpreted accordingly, + particularly as regards case folding. + + Other tokens not defined herein are imported from [RFC4234]. These + are intuitive primitives such as SP, HTAB, WSP, ALPHA, DIGIT, CRLF, + etc. + +2.6. DKIM-Quoted-Printable + + The DKIM-Quoted-Printable encoding syntax resembles that described in + Quoted-Printable [RFC2045], Section 6.7: any character MAY be encoded + as an "=" followed by two hexadecimal digits from the alphabet + "0123456789ABCDEF" (no lowercase characters permitted) representing + the hexadecimal-encoded integer value of that character. All control + characters (those with values < %x20), 8-bit characters (values > + %x7F), and the characters DEL (%x7F), SPACE (%x20), and semicolon + (";", %x3B) MUST be encoded. Note that all whitespace, including + SPACE, CR, and LF characters, MUST be encoded. After encoding, FWS + MAY be added at arbitrary locations in order to avoid excessively + long lines; such whitespace is NOT part of the value, and MUST be + removed before decoding. + + + + + + +Allman, et al. Standards Track [Page 7] + +RFC 4871 DKIM Signatures May 2007 + + + ABNF: + + dkim-quoted-printable = + *(FWS / hex-octet / dkim-safe-char) + ; hex-octet is from RFC 2045 + dkim-safe-char = %x21-3A / %x3C / %x3E-7E + ; '!' - ':', '<', '>' - '~' + ; Characters not listed as "mail-safe" in + ; RFC 2049 are also not recommended. + + INFORMATIVE NOTE: DKIM-Quoted-Printable differs from Quoted- + Printable as defined in RFC 2045 in several important ways: + + 1. Whitespace in the input text, including CR and LF, must be + encoded. RFC 2045 does not require such encoding, and does + not permit encoding of CR or LF characters that are part of a + CRLF line break. + + 2. Whitespace in the encoded text is ignored. This is to allow + tags encoded using DKIM-Quoted-Printable to be wrapped as + needed. In particular, RFC 2045 requires that line breaks in + the input be represented as physical line breaks; that is not + the case here. + + 3. The "soft line break" syntax ("=" as the last non-whitespace + character on the line) does not apply. + + 4. DKIM-Quoted-Printable does not require that encoded lines be + no more than 76 characters long (although there may be other + requirements depending on the context in which the encoded + text is being used). + +3. Protocol Elements + + Protocol Elements are conceptual parts of the protocol that are not + specific to either signers or verifiers. The protocol descriptions + for signers and verifiers are described in later sections (Signer + Actions (Section 5) and Verifier Actions (Section 6)). NOTE: This + section must be read in the context of those sections. + +3.1. Selectors + + To support multiple concurrent public keys per signing domain, the + key namespace is subdivided using "selectors". For example, + selectors might indicate the names of office locations (e.g., + "sanfrancisco", "coolumbeach", and "reykjavik"), the signing date + (e.g., "january2005", "february2005", etc.), or even the individual + user. + + + +Allman, et al. Standards Track [Page 8] + +RFC 4871 DKIM Signatures May 2007 + + + Selectors are needed to support some important use cases. For + example: + + o Domains that want to delegate signing capability for a specific + address for a given duration to a partner, such as an advertising + provider or other outsourced function. + + o Domains that want to allow frequent travelers to send messages + locally without the need to connect with a particular MSA. + + o "Affinity" domains (e.g., college alumni associations) that + provide forwarding of incoming mail, but that do not operate a + mail submission agent for outgoing mail. + + Periods are allowed in selectors and are component separators. When + keys are retrieved from the DNS, periods in selectors define DNS + label boundaries in a manner similar to the conventional use in + domain names. Selector components might be used to combine dates + with locations, for example, "march2005.reykjavik". In a DNS + implementation, this can be used to allow delegation of a portion of + the selector namespace. + + ABNF: + + selector = sub-domain *( "." sub-domain ) + + The number of public keys and corresponding selectors for each domain + is determined by the domain owner. Many domain owners will be + satisfied with just one selector, whereas administratively + distributed organizations may choose to manage disparate selectors + and key pairs in different regions or on different email servers. + + Beyond administrative convenience, selectors make it possible to + seamlessly replace public keys on a routine basis. If a domain + wishes to change from using a public key associated with selector + "january2005" to a public key associated with selector + "february2005", it merely makes sure that both public keys are + advertised in the public-key repository concurrently for the + transition period during which email may be in transit prior to + verification. At the start of the transition period, the outbound + email servers are configured to sign with the "february2005" private + key. At the end of the transition period, the "january2005" public + key is removed from the public-key repository. + + INFORMATIVE NOTE: A key may also be revoked as described below. + The distinction between revoking and removing a key selector + record is subtle. When phasing out keys as described above, a + signing domain would probably simply remove the key record after + + + +Allman, et al. Standards Track [Page 9] + +RFC 4871 DKIM Signatures May 2007 + + + the transition period. However, a signing domain could elect to + revoke the key (but maintain the key record) for a further period. + There is no defined semantic difference between a revoked key and + a removed key. + + While some domains may wish to make selector values well known, + others will want to take care not to allocate selector names in a way + that allows harvesting of data by outside parties. For example, if + per-user keys are issued, the domain owner will need to make the + decision as to whether to associate this selector directly with the + user name, or make it some unassociated random value, such as a + fingerprint of the public key. + + INFORMATIVE OPERATIONS NOTE: Reusing a selector with a new key + (for example, changing the key associated with a user's name) + makes it impossible to tell the difference between a message that + didn't verify because the key is no longer valid versus a message + that is actually forged. For this reason, signers are ill-advised + to reuse selectors for new keys. A better strategy is to assign + new keys to new selectors. + +3.2. Tag=Value Lists + + DKIM uses a simple "tag=value" syntax in several contexts, including + in messages and domain signature records. + + Values are a series of strings containing either plain text, "base64" + text (as defined in [RFC2045], Section 6.8), "qp-section" (ibid, + Section 6.7), or "dkim-quoted-printable" (as defined in Section 2.6). + The name of the tag will determine the encoding of each value. + Unencoded semicolon (";") characters MUST NOT occur in the tag value, + since that separates tag-specs. + + INFORMATIVE IMPLEMENTATION NOTE: Although the "plain text" defined + below (as "tag-value") only includes 7-bit characters, an + implementation that wished to anticipate future standards would be + advised not to preclude the use of UTF8-encoded text in tag=value + lists. + + + + + + + + + + + + + +Allman, et al. Standards Track [Page 10] + +RFC 4871 DKIM Signatures May 2007 + + + Formally, the syntax rules are as follows: + + tag-list = tag-spec 0*( ";" tag-spec ) [ ";" ] + tag-spec = [FWS] tag-name [FWS] "=" [FWS] tag-value [FWS] + tag-name = ALPHA 0*ALNUMPUNC + tag-value = [ tval 0*( 1*(WSP / FWS) tval ) ] + ; WSP and FWS prohibited at beginning and end + tval = 1*VALCHAR + VALCHAR = %x21-3A / %x3C-7E + ; EXCLAMATION to TILDE except SEMICOLON + ALNUMPUNC = ALPHA / DIGIT / "_" + + Note that WSP is allowed anywhere around tags. In particular, any + WSP after the "=" and any WSP before the terminating ";" is not part + of the value; however, WSP inside the value is significant. + + Tags MUST be interpreted in a case-sensitive manner. Values MUST be + processed as case sensitive unless the specific tag description of + semantics specifies case insensitivity. + + Tags with duplicate names MUST NOT occur within a single tag-list; if + a tag name does occur more than once, the entire tag-list is invalid. + + Whitespace within a value MUST be retained unless explicitly excluded + by the specific tag description. + + Tag=value pairs that represent the default value MAY be included to + aid legibility. + + Unrecognized tags MUST be ignored. + + Tags that have an empty value are not the same as omitted tags. An + omitted tag is treated as having the default value; a tag with an + empty value explicitly designates the empty string as the value. For + example, "g=" does not mean "g=*", even though "g=*" is the default + for that tag. + +3.3. Signing and Verification Algorithms + + DKIM supports multiple digital signature algorithms. Two algorithms + are defined by this specification at this time: rsa-sha1 and rsa- + sha256. The rsa-sha256 algorithm is the default if no algorithm is + specified. Verifiers MUST implement both rsa-sha1 and rsa-sha256. + Signers MUST implement and SHOULD sign using rsa-sha256. + + + + + + + +Allman, et al. Standards Track [Page 11] + +RFC 4871 DKIM Signatures May 2007 + + + INFORMATIVE NOTE: Although sha256 is strongly encouraged, some + senders of low-security messages (such as routine newsletters) may + prefer to use sha1 because of reduced CPU requirements to compute + a sha1 hash. In general, sha256 should always be used whenever + possible. + +3.3.1. The rsa-sha1 Signing Algorithm + + The rsa-sha1 Signing Algorithm computes a message hash as described + in Section 3.7 below using SHA-1 [FIPS.180-2.2002] as the hash-alg. + That hash is then signed by the signer using the RSA algorithm + (defined in PKCS#1 version 1.5 [RFC3447]) as the crypt-alg and the + signer's private key. The hash MUST NOT be truncated or converted + into any form other than the native binary form before being signed. + The signing algorithm SHOULD use a public exponent of 65537. + +3.3.2. The rsa-sha256 Signing Algorithm + + The rsa-sha256 Signing Algorithm computes a message hash as described + in Section 3.7 below using SHA-256 [FIPS.180-2.2002] as the hash-alg. + That hash is then signed by the signer using the RSA algorithm + (defined in PKCS#1 version 1.5 [RFC3447]) as the crypt-alg and the + signer's private key. The hash MUST NOT be truncated or converted + into any form other than the native binary form before being signed. + +3.3.3. Key Sizes + + Selecting appropriate key sizes is a trade-off between cost, + performance, and risk. Since short RSA keys more easily succumb to + off-line attacks, signers MUST use RSA keys of at least 1024 bits for + long-lived keys. Verifiers MUST be able to validate signatures with + keys ranging from 512 bits to 2048 bits, and they MAY be able to + validate signatures with larger keys. Verifier policies may use the + length of the signing key as one metric for determining whether a + signature is acceptable. + + Factors that should influence the key size choice include the + following: + + o The practical constraint that large (e.g., 4096 bit) keys may not + fit within a 512-byte DNS UDP response packet + + o The security constraint that keys smaller than 1024 bits are + subject to off-line attacks + + o Larger keys impose higher CPU costs to verify and sign email + + + + + +Allman, et al. Standards Track [Page 12] + +RFC 4871 DKIM Signatures May 2007 + + + o Keys can be replaced on a regular basis, thus their lifetime can + be relatively short + + o The security goals of this specification are modest compared to + typical goals of other systems that employ digital signatures + + See [RFC3766] for further discussion on selecting key sizes. + +3.3.4. Other Algorithms + + Other algorithms MAY be defined in the future. Verifiers MUST ignore + any signatures using algorithms that they do not implement. + +3.4. Canonicalization + + Empirical evidence demonstrates that some mail servers and relay + systems modify email in transit, potentially invalidating a + signature. There are two competing perspectives on such + modifications. For most signers, mild modification of email is + immaterial to the authentication status of the email. For such + signers, a canonicalization algorithm that survives modest in-transit + modification is preferred. + + Other signers demand that any modification of the email, however + minor, result in a signature verification failure. These signers + prefer a canonicalization algorithm that does not tolerate in-transit + modification of the signed email. + + Some signers may be willing to accept modifications to header fields + that are within the bounds of email standards such as [RFC2822], but + are unwilling to accept any modification to the body of messages. + + To satisfy all requirements, two canonicalization algorithms are + defined for each of the header and the body: a "simple" algorithm + that tolerates almost no modification and a "relaxed" algorithm that + tolerates common modifications such as whitespace replacement and + header field line rewrapping. A signer MAY specify either algorithm + for header or body when signing an email. If no canonicalization + algorithm is specified by the signer, the "simple" algorithm defaults + for both header and body. Verifiers MUST implement both + canonicalization algorithms. Note that the header and body may use + different canonicalization algorithms. Further canonicalization + algorithms MAY be defined in the future; verifiers MUST ignore any + signatures that use unrecognized canonicalization algorithms. + + Canonicalization simply prepares the email for presentation to the + signing or verification algorithm. It MUST NOT change the + + + + +Allman, et al. Standards Track [Page 13] + +RFC 4871 DKIM Signatures May 2007 + + + transmitted data in any way. Canonicalization of header fields and + body are described below. + + NOTE: This section assumes that the message is already in "network + normal" format (text is ASCII encoded, lines are separated with CRLF + characters, etc.). See also Section 5.3 for information about + normalizing the message. + +3.4.1. The "simple" Header Canonicalization Algorithm + + The "simple" header canonicalization algorithm does not change header + fields in any way. Header fields MUST be presented to the signing or + verification algorithm exactly as they are in the message being + signed or verified. In particular, header field names MUST NOT be + case folded and whitespace MUST NOT be changed. + +3.4.2. The "relaxed" Header Canonicalization Algorithm + + The "relaxed" header canonicalization algorithm MUST apply the + following steps in order: + + o Convert all header field names (not the header field values) to + lowercase. For example, convert "SUBJect: AbC" to "subject: AbC". + + o Unfold all header field continuation lines as described in + [RFC2822]; in particular, lines with terminators embedded in + continued header field values (that is, CRLF sequences followed by + WSP) MUST be interpreted without the CRLF. Implementations MUST + NOT remove the CRLF at the end of the header field value. + + o Convert all sequences of one or more WSP characters to a single SP + character. WSP characters here include those before and after a + line folding boundary. + + o Delete all WSP characters at the end of each unfolded header field + value. + + o Delete any WSP characters remaining before and after the colon + separating the header field name from the header field value. The + colon separator MUST be retained. + +3.4.3. The "simple" Body Canonicalization Algorithm + + The "simple" body canonicalization algorithm ignores all empty lines + at the end of the message body. An empty line is a line of zero + length after removal of the line terminator. If there is no body or + no trailing CRLF on the message body, a CRLF is added. It makes no + + + + +Allman, et al. Standards Track [Page 14] + +RFC 4871 DKIM Signatures May 2007 + + + other changes to the message body. In more formal terms, the + "simple" body canonicalization algorithm converts "0*CRLF" at the end + of the body to a single "CRLF". + + Note that a completely empty or missing body is canonicalized as a + single "CRLF"; that is, the canonicalized length will be 2 octets. + +3.4.4. The "relaxed" Body Canonicalization Algorithm + + The "relaxed" body canonicalization algorithm: + + o Ignores all whitespace at the end of lines. Implementations MUST + NOT remove the CRLF at the end of the line. + + o Reduces all sequences of WSP within a line to a single SP + character. + + o Ignores all empty lines at the end of the message body. "Empty + line" is defined in Section 3.4.3. + + INFORMATIVE NOTE: It should be noted that the relaxed body + canonicalization algorithm may enable certain types of extremely + crude "ASCII Art" attacks where a message may be conveyed by + adjusting the spacing between words. If this is a concern, the + "simple" body canonicalization algorithm should be used instead. + +3.4.5. Body Length Limits + + A body length count MAY be specified to limit the signature + calculation to an initial prefix of the body text, measured in + octets. If the body length count is not specified, the entire + message body is signed. + + INFORMATIVE RATIONALE: This capability is provided because it is + very common for mailing lists to add trailers to messages (e.g., + instructions how to get off the list). Until those messages are + also signed, the body length count is a useful tool for the + verifier since it may as a matter of policy accept messages having + valid signatures with extraneous data. + + INFORMATIVE IMPLEMENTATION NOTE: Using body length limits enables + an attack in which an attacker modifies a message to include + content that solely benefits the attacker. It is possible for the + appended content to completely replace the original content in the + end recipient's eyes and to defeat duplicate message detection + algorithms. To avoid this attack, signers should be wary of using + + + + + +Allman, et al. Standards Track [Page 15] + +RFC 4871 DKIM Signatures May 2007 + + + this tag, and verifiers might wish to ignore the tag or remove + text that appears after the specified content length, perhaps + based on other criteria. + + The body length count allows the signer of a message to permit data + to be appended to the end of the body of a signed message. The body + length count MUST be calculated following the canonicalization + algorithm; for example, any whitespace ignored by a canonicalization + algorithm is not included as part of the body length count. Signers + of MIME messages that include a body length count SHOULD be sure that + the length extends to the closing MIME boundary string. + + INFORMATIVE IMPLEMENTATION NOTE: A signer wishing to ensure that + the only acceptable modifications are to add to the MIME postlude + would use a body length count encompassing the entire final MIME + boundary string, including the final "--CRLF". A signer wishing + to allow additional MIME parts but not modification of existing + parts would use a body length count extending through the final + MIME boundary string, omitting the final "--CRLF". Note that this + only works for some MIME types, e.g., multipart/mixed but not + multipart/signed. + + A body length count of zero means that the body is completely + unsigned. + + Signers wishing to ensure that no modification of any sort can occur + should specify the "simple" canonicalization algorithm for both + header and body and omit the body length count. + +3.4.6. Canonicalization Examples (INFORMATIVE) + + In the following examples, actual whitespace is used only for + clarity. The actual input and output text is designated using + bracketed descriptors: "" for a space character, "" for a + tab character, and "" for a carriage-return/line-feed sequence. + For example, "X Y" and "XY" represent the same three + characters. + + Example 1: A message reading: + + A: X + B : Y + Z + + C + D E + + + + + +Allman, et al. Standards Track [Page 16] + +RFC 4871 DKIM Signatures May 2007 + + + when canonicalized using relaxed canonicalization for both header and + body results in a header reading: + + a:X + b:Y Z + + and a body reading: + + C + D E + + Example 2: The same message canonicalized using simple + canonicalization for both header and body results in a header + reading: + + A: X + B : Y + Z + + and a body reading: + + C + D E + + Example 3: When processed using relaxed header canonicalization and + simple body canonicalization, the canonicalized version has a header + of: + + a:X + b:Y Z + + and a body reading: + + C + D E + +3.5. The DKIM-Signature Header Field + + The signature of the email is stored in the DKIM-Signature header + field. This header field contains all of the signature and key- + fetching data. The DKIM-Signature value is a tag-list as described + in Section 3.2. + + The DKIM-Signature header field SHOULD be treated as though it were a + trace header field as defined in Section 3.6 of [RFC2822], and hence + SHOULD NOT be reordered and SHOULD be prepended to the message. + + + + + +Allman, et al. Standards Track [Page 17] + +RFC 4871 DKIM Signatures May 2007 + + + The DKIM-Signature header field being created or verified is always + included in the signature calculation, after the rest of the header + fields being signed; however, when calculating or verifying the + signature, the value of the "b=" tag (signature value) of that DKIM- + Signature header field MUST be treated as though it were an empty + string. Unknown tags in the DKIM-Signature header field MUST be + included in the signature calculation but MUST be otherwise ignored + by verifiers. Other DKIM-Signature header fields that are included + in the signature should be treated as normal header fields; in + particular, the "b=" tag is not treated specially. + + The encodings for each field type are listed below. Tags described + as qp-section are encoded as described in Section 6.7 of MIME Part + One [RFC2045], with the additional conversion of semicolon characters + to "=3B"; intuitively, this is one line of quoted-printable encoded + text. The dkim-quoted-printable syntax is defined in Section 2.6. + + Tags on the DKIM-Signature header field along with their type and + requirement status are shown below. Unrecognized tags MUST be + ignored. + + v= Version (MUST be included). This tag defines the version of this + specification that applies to the signature record. It MUST have + the value "1". Note that verifiers must do a string comparison + on this value; for example, "1" is not the same as "1.0". + + ABNF: + + sig-v-tag = %x76 [FWS] "=" [FWS] "1" + + INFORMATIVE NOTE: DKIM-Signature version numbers are expected + to increase arithmetically as new versions of this + specification are released. + + a= The algorithm used to generate the signature (plain-text; + REQUIRED). Verifiers MUST support "rsa-sha1" and "rsa-sha256"; + signers SHOULD sign using "rsa-sha256". See Section 3.3 for a + description of algorithms. + + ABNF: + + sig-a-tag = %x61 [FWS] "=" [FWS] sig-a-tag-alg + sig-a-tag-alg = sig-a-tag-k "-" sig-a-tag-h + sig-a-tag-k = "rsa" / x-sig-a-tag-k + sig-a-tag-h = "sha1" / "sha256" / x-sig-a-tag-h + x-sig-a-tag-k = ALPHA *(ALPHA / DIGIT) ; for later extension + x-sig-a-tag-h = ALPHA *(ALPHA / DIGIT) ; for later extension + + + + +Allman, et al. Standards Track [Page 18] + +RFC 4871 DKIM Signatures May 2007 + + + b= The signature data (base64; REQUIRED). Whitespace is ignored in + this value and MUST be ignored when reassembling the original + signature. In particular, the signing process can safely insert + FWS in this value in arbitrary places to conform to line-length + limits. See Signer Actions (Section 5) for how the signature is + computed. + + ABNF: + + sig-b-tag = %x62 [FWS] "=" [FWS] sig-b-tag-data + sig-b-tag-data = base64string + + bh= The hash of the canonicalized body part of the message as limited + by the "l=" tag (base64; REQUIRED). Whitespace is ignored in + this value and MUST be ignored when reassembling the original + signature. In particular, the signing process can safely insert + FWS in this value in arbitrary places to conform to line-length + limits. See Section 3.7 for how the body hash is computed. + + ABNF: + + sig-bh-tag = %x62 %x68 [FWS] "=" [FWS] sig-bh-tag-data + sig-bh-tag-data = base64string + + c= Message canonicalization (plain-text; OPTIONAL, default is + "simple/simple"). This tag informs the verifier of the type of + canonicalization used to prepare the message for signing. It + consists of two names separated by a "slash" (%d47) character, + corresponding to the header and body canonicalization algorithms + respectively. These algorithms are described in Section 3.4. If + only one algorithm is named, that algorithm is used for the + header and "simple" is used for the body. For example, + "c=relaxed" is treated the same as "c=relaxed/simple". + + ABNF: + + sig-c-tag = %x63 [FWS] "=" [FWS] sig-c-tag-alg + ["/" sig-c-tag-alg] + sig-c-tag-alg = "simple" / "relaxed" / x-sig-c-tag-alg + x-sig-c-tag-alg = hyphenated-word ; for later extension + + d= The domain of the signing entity (plain-text; REQUIRED). This is + the domain that will be queried for the public key. This domain + MUST be the same as or a parent domain of the "i=" tag (the + signing identity, as described below), or it MUST meet the + requirements for parent domain signing described in Section 3.8. + When presented with a signature that does not meet these + requirement, verifiers MUST consider the signature invalid. + + + +Allman, et al. Standards Track [Page 19] + +RFC 4871 DKIM Signatures May 2007 + + + Internationalized domain names MUST be encoded as described in + [RFC3490]. + + ABNF: + + sig-d-tag = %x64 [FWS] "=" [FWS] domain-name + domain-name = sub-domain 1*("." sub-domain) + ; from RFC 2821 Domain, but excluding address-literal + + h= Signed header fields (plain-text, but see description; REQUIRED). + A colon-separated list of header field names that identify the + header fields presented to the signing algorithm. The field MUST + contain the complete list of header fields in the order presented + to the signing algorithm. The field MAY contain names of header + fields that do not exist when signed; nonexistent header fields + do not contribute to the signature computation (that is, they are + treated as the null input, including the header field name, the + separating colon, the header field value, and any CRLF + terminator). The field MUST NOT include the DKIM-Signature + header field that is being created or verified, but may include + others. Folding whitespace (FWS) MAY be included on either side + of the colon separator. Header field names MUST be compared + against actual header field names in a case-insensitive manner. + This list MUST NOT be empty. See Section 5.4 for a discussion of + choosing header fields to sign. + + ABNF: + + sig-h-tag = %x68 [FWS] "=" [FWS] hdr-name + 0*( *FWS ":" *FWS hdr-name ) + hdr-name = field-name + + INFORMATIVE EXPLANATION: By "signing" header fields that do not + actually exist, a signer can prevent insertion of those + header fields before verification. However, since a signer + cannot possibly know what header fields might be created in + the future, and that some MUAs might present header fields + that are embedded inside a message (e.g., as a message/rfc822 + content type), the security of this solution is not total. + + INFORMATIVE EXPLANATION: The exclusion of the header field name + and colon as well as the header field value for non-existent + header fields prevents an attacker from inserting an actual + header field with a null value. + + + + + + + +Allman, et al. Standards Track [Page 20] + +RFC 4871 DKIM Signatures May 2007 + + + i= Identity of the user or agent (e.g., a mailing list manager) on + behalf of which this message is signed (dkim-quoted-printable; + OPTIONAL, default is an empty Local-part followed by an "@" + followed by the domain from the "d=" tag). The syntax is a + standard email address where the Local-part MAY be omitted. The + domain part of the address MUST be the same as or a subdomain of + the value of the "d=" tag. + + Internationalized domain names MUST be converted using the steps + listed in Section 4 of [RFC3490] using the "ToASCII" function. + + ABNF: + + sig-i-tag = %x69 [FWS] "=" [FWS] [ Local-part ] "@" domain-name + + INFORMATIVE NOTE: The Local-part of the "i=" tag is optional + because in some cases a signer may not be able to establish a + verified individual identity. In such cases, the signer may + wish to assert that although it is willing to go as far as + signing for the domain, it is unable or unwilling to commit + to an individual user name within their domain. It can do so + by including the domain part but not the Local-part of the + identity. + + INFORMATIVE DISCUSSION: This document does not require the value + of the "i=" tag to match the identity in any message header + fields. This is considered to be a verifier policy issue. + Constraints between the value of the "i=" tag and other + identities in other header fields seek to apply basic + authentication into the semantics of trust associated with a + role such as content author. Trust is a broad and complex + topic and trust mechanisms are subject to highly creative + attacks. The real-world efficacy of any but the most basic + bindings between the "i=" value and other identities is not + well established, nor is its vulnerability to subversion by + an attacker. Hence reliance on the use of these options + should be strictly limited. In particular, it is not at all + clear to what extent a typical end-user recipient can rely on + any assurances that might be made by successful use of the + "i=" options. + + l= Body length count (plain-text unsigned decimal integer; OPTIONAL, + default is entire body). This tag informs the verifier of the + number of octets in the body of the email after canonicalization + included in the cryptographic hash, starting from 0 immediately + following the CRLF preceding the body. This value MUST NOT be + larger than the actual number of octets in the canonicalized + message body. + + + +Allman, et al. Standards Track [Page 21] + +RFC 4871 DKIM Signatures May 2007 + + + INFORMATIVE IMPLEMENTATION WARNING: Use of the "l=" tag might + allow display of fraudulent content without appropriate + warning to end users. The "l=" tag is intended for + increasing signature robustness when sending to mailing lists + that both modify their content and do not sign their + messages. However, using the "l=" tag enables attacks in + which an intermediary with malicious intent modifies a + message to include content that solely benefits the attacker. + It is possible for the appended content to completely replace + the original content in the end recipient's eyes and to + defeat duplicate message detection algorithms. Examples are + described in Security Considerations (Section 8). To avoid + this attack, signers should be extremely wary of using this + tag, and verifiers might wish to ignore the tag or remove + text that appears after the specified content length. + + INFORMATIVE NOTE: The value of the "l=" tag is constrained to 76 + decimal digits. This constraint is not intended to predict + the size of future messages or to require implementations to + use an integer representation large enough to represent the + maximum possible value, but is intended to remind the + implementer to check the length of this and all other tags + during verification and to test for integer overflow when + decoding the value. Implementers may need to limit the + actual value expressed to a value smaller than 10^76, e.g., + to allow a message to fit within the available storage space. + + ABNF: + + sig-l-tag = %x6c [FWS] "=" [FWS] 1*76DIGIT + + q= A colon-separated list of query methods used to retrieve the + public key (plain-text; OPTIONAL, default is "dns/txt"). Each + query method is of the form "type[/options]", where the syntax + and semantics of the options depend on the type and specified + options. If there are multiple query mechanisms listed, the + choice of query mechanism MUST NOT change the interpretation of + the signature. Implementations MUST use the recognized query + mechanisms in the order presented. + + Currently, the only valid value is "dns/txt", which defines the DNS + TXT record lookup algorithm described elsewhere in this document. + The only option defined for the "dns" query type is "txt", which + MUST be included. Verifiers and signers MUST support "dns/txt". + + + + + + + +Allman, et al. Standards Track [Page 22] + +RFC 4871 DKIM Signatures May 2007 + + + ABNF: + + sig-q-tag = %x71 [FWS] "=" [FWS] sig-q-tag-method + *([FWS] ":" [FWS] sig-q-tag-method) + sig-q-tag-method = "dns/txt" / x-sig-q-tag-type + ["/" x-sig-q-tag-args] + x-sig-q-tag-type = hyphenated-word ; for future extension + x-sig-q-tag-args = qp-hdr-value + + s= The selector subdividing the namespace for the "d=" (domain) tag + (plain-text; REQUIRED). + + ABNF: + + sig-s-tag = %x73 [FWS] "=" [FWS] selector + + t= Signature Timestamp (plain-text unsigned decimal integer; + RECOMMENDED, default is an unknown creation time). The time that + this signature was created. The format is the number of seconds + since 00:00:00 on January 1, 1970 in the UTC time zone. The + value is expressed as an unsigned integer in decimal ASCII. This + value is not constrained to fit into a 31- or 32-bit integer. + Implementations SHOULD be prepared to handle values up to at + least 10^12 (until approximately AD 200,000; this fits into 40 + bits). To avoid denial-of-service attacks, implementations MAY + consider any value longer than 12 digits to be infinite. Leap + seconds are not counted. Implementations MAY ignore signatures + that have a timestamp in the future. + + ABNF: + + sig-t-tag = %x74 [FWS] "=" [FWS] 1*12DIGIT + + x= Signature Expiration (plain-text unsigned decimal integer; + RECOMMENDED, default is no expiration). The format is the same + as in the "t=" tag, represented as an absolute date, not as a + time delta from the signing timestamp. The value is expressed as + an unsigned integer in decimal ASCII, with the same constraints + on the value in the "t=" tag. Signatures MAY be considered + invalid if the verification time at the verifier is past the + expiration date. The verification time should be the time that + the message was first received at the administrative domain of + the verifier if that time is reliably available; otherwise the + current time should be used. The value of the "x=" tag MUST be + greater than the value of the "t=" tag if both are present. + + + + + + +Allman, et al. Standards Track [Page 23] + +RFC 4871 DKIM Signatures May 2007 + + + INFORMATIVE NOTE: The "x=" tag is not intended as an anti-replay + defense. + + ABNF: + + sig-x-tag = %x78 [FWS] "=" [FWS] 1*12DIGIT + + z= Copied header fields (dkim-quoted-printable, but see description; + OPTIONAL, default is null). A vertical-bar-separated list of + selected header fields present when the message was signed, + including both the field name and value. It is not required to + include all header fields present at the time of signing. This + field need not contain the same header fields listed in the "h=" + tag. The header field text itself must encode the vertical bar + ("|", %x7C) character (i.e., vertical bars in the "z=" text are + metacharacters, and any actual vertical bar characters in a + copied header field must be encoded). Note that all whitespace + must be encoded, including whitespace between the colon and the + header field value. After encoding, FWS MAY be added at + arbitrary locations in order to avoid excessively long lines; + such whitespace is NOT part of the value of the header field, and + MUST be removed before decoding. + + The header fields referenced by the "h=" tag refer to the fields in + the RFC 2822 header of the message, not to any copied fields in + the "z=" tag. Copied header field values are for diagnostic use. + + Header fields with characters requiring conversion (perhaps from + legacy MTAs that are not [RFC2822] compliant) SHOULD be converted + as described in MIME Part Three [RFC2047]. + + ABNF: + sig-z-tag = %x7A [FWS] "=" [FWS] sig-z-tag-copy + *( [FWS] "|" sig-z-tag-copy ) + sig-z-tag-copy = hdr-name ":" qp-hdr-value + qp-hdr-value = dkim-quoted-printable ; with "|" encoded + + INFORMATIVE EXAMPLE of a signature header field spread across + multiple continuation lines: + + + + + + + + + + + + +Allman, et al. Standards Track [Page 24] + +RFC 4871 DKIM Signatures May 2007 + + + DKIM-Signature: a=rsa-sha256; d=example.net; s=brisbane; + c=simple; q=dns/txt; i=@eng.example.net; + t=1117574938; x=1118006938; + h=from:to:subject:date; + z=From:foo@eng.example.net|To:joe@example.com| + Subject:demo=20run|Date:July=205,=202005=203:44:08=20PM=20-0700; + bh=MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=; + b=dzdVyOfAKCdLXdJOc9G2q8LoXSlEniSbav+yuU4zGeeruD00lszZ + VoG4ZHRNiYzR + +3.6. Key Management and Representation + + Signature applications require some level of assurance that the + verification public key is associated with the claimed signer. Many + applications achieve this by using public key certificates issued by + a trusted third party. However, DKIM can achieve a sufficient level + of security, with significantly enhanced scalability, by simply + having the verifier query the purported signer's DNS entry (or some + security-equivalent) in order to retrieve the public key. + + DKIM keys can potentially be stored in multiple types of key servers + and in multiple formats. The storage and format of keys are + irrelevant to the remainder of the DKIM algorithm. + + Parameters to the key lookup algorithm are the type of the lookup + (the "q=" tag), the domain of the signer (the "d=" tag of the DKIM- + Signature header field), and the selector (the "s=" tag). + + public_key = dkim_find_key(q_val, d_val, s_val) + + This document defines a single binding, using DNS TXT records to + distribute the keys. Other bindings may be defined in the future. + +3.6.1. Textual Representation + + It is expected that many key servers will choose to present the keys + in an otherwise unstructured text format (for example, an XML form + would not be considered to be unstructured text for this purpose). + The following definition MUST be used for any DKIM key represented in + an otherwise unstructured textual form. + + The overall syntax is a tag-list as described in Section 3.2. The + current valid tags are described below. Other tags MAY be present + and MUST be ignored by any implementation that does not understand + them. + + + + + + +Allman, et al. Standards Track [Page 25] + +RFC 4871 DKIM Signatures May 2007 + + + v= Version of the DKIM key record (plain-text; RECOMMENDED, default + is "DKIM1"). If specified, this tag MUST be set to "DKIM1" + (without the quotes). This tag MUST be the first tag in the + record. Records beginning with a "v=" tag with any other value + MUST be discarded. Note that verifiers must do a string + comparison on this value; for example, "DKIM1" is not the same as + "DKIM1.0". + + ABNF: + + key-v-tag = %x76 [FWS] "=" [FWS] "DKIM1" + + g= Granularity of the key (plain-text; OPTIONAL, default is "*"). + This value MUST match the Local-part of the "i=" tag of the DKIM- + Signature header field (or its default value of the empty string + if "i=" is not specified), with a single, optional "*" character + matching a sequence of zero or more arbitrary characters + ("wildcarding"). An email with a signing address that does not + match the value of this tag constitutes a failed verification. + The intent of this tag is to constrain which signing address can + legitimately use this selector, for example, when delegating a + key to a third party that should only be used for special + purposes. Wildcarding allows matching for addresses such as + "user+*" or "*-offer". An empty "g=" value never matches any + addresses. + + ABNF: + + key-g-tag = %x67 [FWS] "=" [FWS] key-g-tag-lpart + key-g-tag-lpart = [dot-atom-text] ["*" [dot-atom-text] ] + + h= Acceptable hash algorithms (plain-text; OPTIONAL, defaults to + allowing all algorithms). A colon-separated list of hash + algorithms that might be used. Signers and Verifiers MUST + support the "sha256" hash algorithm. Verifiers MUST also support + the "sha1" hash algorithm. + + ABNF: + + key-h-tag = %x68 [FWS] "=" [FWS] key-h-tag-alg + 0*( [FWS] ":" [FWS] key-h-tag-alg ) + key-h-tag-alg = "sha1" / "sha256" / x-key-h-tag-alg + x-key-h-tag-alg = hyphenated-word ; for future extension + + + + + + + + +Allman, et al. Standards Track [Page 26] + +RFC 4871 DKIM Signatures May 2007 + + + k= Key type (plain-text; OPTIONAL, default is "rsa"). Signers and + verifiers MUST support the "rsa" key type. The "rsa" key type + indicates that an ASN.1 DER-encoded [ITU.X660.1997] RSAPublicKey + [RFC3447] (see Sections 3.1 and A.1.1) is being used in the "p=" + tag. (Note: the "p=" tag further encodes the value using the + base64 algorithm.) + + ABNF: + + key-k-tag = %x76 [FWS] "=" [FWS] key-k-tag-type + key-k-tag-type = "rsa" / x-key-k-tag-type + x-key-k-tag-type = hyphenated-word ; for future extension + + n= Notes that might be of interest to a human (qp-section; OPTIONAL, + default is empty). No interpretation is made by any program. + This tag should be used sparingly in any key server mechanism + that has space limitations (notably DNS). This is intended for + use by administrators, not end users. + + ABNF: + + key-n-tag = %x6e [FWS] "=" [FWS] qp-section + + p= Public-key data (base64; REQUIRED). An empty value means that + this public key has been revoked. The syntax and semantics of + this tag value before being encoded in base64 are defined by the + "k=" tag. + + INFORMATIVE RATIONALE: If a private key has been compromised + or otherwise disabled (e.g., an outsourcing contract has been + terminated), a signer might want to explicitly state that it + knows about the selector, but all messages using that + selector should fail verification. Verifiers should ignore + any DKIM-Signature header fields with a selector referencing + a revoked key. + + ABNF: + + key-p-tag = %x70 [FWS] "=" [ [FWS] base64string ] + + INFORMATIVE NOTE: A base64string is permitted to include white + space (FWS) at arbitrary places; however, any CRLFs must be + followed by at least one WSP character. Implementors and + administrators are cautioned to ensure that selector TXT + records conform to this specification. + + + + + + +Allman, et al. Standards Track [Page 27] + +RFC 4871 DKIM Signatures May 2007 + + + s= Service Type (plain-text; OPTIONAL; default is "*"). A colon- + separated list of service types to which this record applies. + Verifiers for a given service type MUST ignore this record if the + appropriate type is not listed. Currently defined service types + are as follows: + + * matches all service types + + email electronic mail (not necessarily limited to SMTP) + + This tag is intended to constrain the use of keys for other + purposes, should use of DKIM be defined by other services in the + future. + + ABNF: + + key-s-tag = %x73 [FWS] "=" [FWS] key-s-tag-type + 0*( [FWS] ":" [FWS] key-s-tag-type ) + key-s-tag-type = "email" / "*" / x-key-s-tag-type + x-key-s-tag-type = hyphenated-word ; for future extension + + t= Flags, represented as a colon-separated list of names (plain- + text; OPTIONAL, default is no flags set). The defined flags are + as follows: + + y This domain is testing DKIM. Verifiers MUST NOT treat + messages from signers in testing mode differently from + unsigned email, even should the signature fail to verify. + Verifiers MAY wish to track testing mode results to assist + the signer. + + s Any DKIM-Signature header fields using the "i=" tag MUST have + the same domain value on the right-hand side of the "@" in + the "i=" tag and the value of the "d=" tag. That is, the + "i=" domain MUST NOT be a subdomain of "d=". Use of this + flag is RECOMMENDED unless subdomaining is required. + + ABNF: + + key-t-tag = %x74 [FWS] "=" [FWS] key-t-tag-flag + 0*( [FWS] ":" [FWS] key-t-tag-flag ) + key-t-tag-flag = "y" / "s" / x-key-t-tag-flag + x-key-t-tag-flag = hyphenated-word ; for future extension + + Unrecognized flags MUST be ignored. + + + + + + +Allman, et al. Standards Track [Page 28] + +RFC 4871 DKIM Signatures May 2007 + + +3.6.2. DNS Binding + + A binding using DNS TXT records as a key service is hereby defined. + All implementations MUST support this binding. + +3.6.2.1. Namespace + + All DKIM keys are stored in a subdomain named "_domainkey". Given a + DKIM-Signature field with a "d=" tag of "example.com" and an "s=" tag + of "foo.bar", the DNS query will be for + "foo.bar._domainkey.example.com". + + INFORMATIVE OPERATIONAL NOTE: Wildcard DNS records (e.g., + *.bar._domainkey.example.com) do not make sense in this context + and should not be used. Note also that wildcards within domains + (e.g., s._domainkey.*.example.com) are not supported by the DNS. + +3.6.2.2. Resource Record Types for Key Storage + + The DNS Resource Record type used is specified by an option to the + query-type ("q=") tag. The only option defined in this base + specification is "txt", indicating the use of a TXT Resource Record + (RR). A later extension of this standard may define another RR type. + + Strings in a TXT RR MUST be concatenated together before use with no + intervening whitespace. TXT RRs MUST be unique for a particular + selector name; that is, if there are multiple records in an RRset, + the results are undefined. + + TXT RRs are encoded as described in Section 3.6.1. + +3.7. Computing the Message Hashes + + Both signing and verifying message signatures start with a step of + computing two cryptographic hashes over the message. Signers will + choose the parameters of the signature as described in Signer Actions + (Section 5); verifiers will use the parameters specified in the DKIM- + Signature header field being verified. In the following discussion, + the names of the tags in the DKIM-Signature header field that either + exists (when verifying) or will be created (when signing) are used. + Note that canonicalization (Section 3.4) is only used to prepare the + email for signing or verifying; it does not affect the transmitted + email in any way. + + The signer/verifier MUST compute two hashes, one over the body of the + message and one over the selected header fields of the message. + + + + + +Allman, et al. Standards Track [Page 29] + +RFC 4871 DKIM Signatures May 2007 + + + Signers MUST compute them in the order shown. Verifiers MAY compute + them in any order convenient to the verifier, provided that the + result is semantically identical to the semantics that would be the + case had they been computed in this order. + + In hash step 1, the signer/verifier MUST hash the message body, + canonicalized using the body canonicalization algorithm specified in + the "c=" tag and then truncated to the length specified in the "l=" + tag. That hash value is then converted to base64 form and inserted + into (signers) or compared to (verifiers) the "bh=" tag of the DKIM- + Signature header field. + + In hash step 2, the signer/verifier MUST pass the following to the + hash algorithm in the indicated order. + + 1. The header fields specified by the "h=" tag, in the order + specified in that tag, and canonicalized using the header + canonicalization algorithm specified in the "c=" tag. Each + header field MUST be terminated with a single CRLF. + + 2. The DKIM-Signature header field that exists (verifying) or will + be inserted (signing) in the message, with the value of the "b=" + tag deleted (i.e., treated as the empty string), canonicalized + using the header canonicalization algorithm specified in the "c=" + tag, and without a trailing CRLF. + + All tags and their values in the DKIM-Signature header field are + included in the cryptographic hash with the sole exception of the + value portion of the "b=" (signature) tag, which MUST be treated as + the null string. All tags MUST be included even if they might not be + understood by the verifier. The header field MUST be presented to + the hash algorithm after the body of the message rather than with the + rest of the header fields and MUST be canonicalized as specified in + the "c=" (canonicalization) tag. The DKIM-Signature header field + MUST NOT be included in its own h= tag, although other DKIM-Signature + header fields MAY be signed (see Section 4). + + When calculating the hash on messages that will be transmitted using + base64 or quoted-printable encoding, signers MUST compute the hash + after the encoding. Likewise, the verifier MUST incorporate the + values into the hash before decoding the base64 or quoted-printable + text. However, the hash MUST be computed before transport level + encodings such as SMTP "dot-stuffing" (the modification of lines + beginning with a "." to avoid confusion with the SMTP end-of-message + marker, as specified in [RFC2821]). + + With the exception of the canonicalization procedure described in + Section 3.4, the DKIM signing process treats the body of messages as + + + +Allman, et al. Standards Track [Page 30] + +RFC 4871 DKIM Signatures May 2007 + + + simply a string of octets. DKIM messages MAY be either in plain-text + or in MIME format; no special treatment is afforded to MIME content. + Message attachments in MIME format MUST be included in the content + that is signed. + + More formally, the algorithm for the signature is as follows: + body-hash = hash-alg(canon_body) + header-hash = hash-alg(canon_header || DKIM-SIG) + signature = sig-alg(header-hash, key) + + where "sig-alg" is the signature algorithm specified by the "a=" tag, + "hash-alg" is the hash algorithm specified by the "a=" tag, + "canon_header" and "canon_body" are the canonicalized message header + and body (respectively) as defined in Section 3.4 (excluding the + DKIM-Signature header field), and "DKIM-SIG" is the canonicalized + DKIM-Signature header field sans the signature value itself, but with + "body-hash" included as the "bh=" tag. + + INFORMATIVE IMPLEMENTERS' NOTE: Many digital signature APIs + provide both hashing and application of the RSA private key using + a single "sign()" primitive. When using such an API, the last two + steps in the algorithm would probably be combined into a single + call that would perform both the "hash-alg" and the "sig-alg". + +3.8. Signing by Parent Domains + + In some circumstances, it is desirable for a domain to apply a + signature on behalf of any of its subdomains without the need to + maintain separate selectors (key records) in each subdomain. By + default, private keys corresponding to key records can be used to + sign messages for any subdomain of the domain in which they reside; + e.g., a key record for the domain example.com can be used to verify + messages where the signing identity ("i=" tag of the signature) is + sub.example.com, or even sub1.sub2.example.com. In order to limit + the capability of such keys when this is not intended, the "s" flag + may be set in the "t=" tag of the key record to constrain the + validity of the record to exactly the domain of the signing identity. + If the referenced key record contains the "s" flag as part of the + "t=" tag, the domain of the signing identity ("i=" flag) MUST be the + same as that of the d= domain. If this flag is absent, the domain of + the signing identity MUST be the same as, or a subdomain of, the d= + domain. Key records that are not intended for use with subdomains + SHOULD specify the "s" flag in the "t=" tag. + + + + + + + + +Allman, et al. Standards Track [Page 31] + +RFC 4871 DKIM Signatures May 2007 + + +4. Semantics of Multiple Signatures + +4.1. Example Scenarios + + There are many reasons why a message might have multiple signatures. + For example, a given signer might sign multiple times, perhaps with + different hashing or signing algorithms during a transition phase. + + INFORMATIVE EXAMPLE: Suppose SHA-256 is in the future found to be + insufficiently strong, and DKIM usage transitions to SHA-1024. A + signer might immediately sign using the newer algorithm, but + continue to sign using the older algorithm for interoperability + with verifiers that had not yet upgraded. The signer would do + this by adding two DKIM-Signature header fields, one using each + algorithm. Older verifiers that did not recognize SHA-1024 as an + acceptable algorithm would skip that signature and use the older + algorithm; newer verifiers could use either signature at their + option, and all other things being equal might not even attempt to + verify the other signature. + + Similarly, a signer might sign a message including all headers and no + "l=" tag (to satisfy strict verifiers) and a second time with a + limited set of headers and an "l=" tag (in anticipation of possible + message modifications in route to other verifiers). Verifiers could + then choose which signature they preferred. + + INFORMATIVE EXAMPLE: A verifier might receive a message with two + signatures, one covering more of the message than the other. If + the signature covering more of the message verified, then the + verifier could make one set of policy decisions; if that signature + failed but the signature covering less of the message verified, + the verifier might make a different set of policy decisions. + + Of course, a message might also have multiple signatures because it + passed through multiple signers. A common case is expected to be + that of a signed message that passes through a mailing list that also + signs all messages. Assuming both of those signatures verify, a + recipient might choose to accept the message if either of those + signatures were known to come from trusted sources. + + INFORMATIVE EXAMPLE: Recipients might choose to whitelist mailing + lists to which they have subscribed and that have acceptable anti- + abuse policies so as to accept messages sent to that list even + from unknown authors. They might also subscribe to less trusted + mailing lists (e.g., those without anti-abuse protection) and be + willing to accept all messages from specific authors, but insist + on doing additional abuse scanning for other messages. + + + + +Allman, et al. Standards Track [Page 32] + +RFC 4871 DKIM Signatures May 2007 + + + Another related example of multiple signers might be forwarding + services, such as those commonly associated with academic alumni + sites. + + INFORMATIVE EXAMPLE: A recipient might have an address at + members.example.org, a site that has anti-abuse protection that is + somewhat less effective than the recipient would prefer. Such a + recipient might have specific authors whose messages would be + trusted absolutely, but messages from unknown authors that had + passed the forwarder's scrutiny would have only medium trust. + +4.2. Interpretation + + A signer that is adding a signature to a message merely creates a new + DKIM-Signature header, using the usual semantics of the h= option. A + signer MAY sign previously existing DKIM-Signature header fields + using the method described in Section 5.4 to sign trace header + fields. + + INFORMATIVE NOTE: Signers should be cognizant that signing DKIM- + Signature header fields may result in signature failures with + intermediaries that do not recognize that DKIM-Signature header + fields are trace header fields and unwittingly reorder them, thus + breaking such signatures. For this reason, signing existing DKIM- + Signature header fields is unadvised, albeit legal. + + INFORMATIVE NOTE: If a header field with multiple instances is + signed, those header fields are always signed from the bottom up. + Thus, it is not possible to sign only specific DKIM-Signature + header fields. For example, if the message being signed already + contains three DKIM-Signature header fields A, B, and C, it is + possible to sign all of them, B and C only, or C only, but not A + only, B only, A and B only, or A and C only. + + A signer MAY add more than one DKIM-Signature header field using + different parameters. For example, during a transition period a + signer might want to produce signatures using two different hash + algorithms. + + Signers SHOULD NOT remove any DKIM-Signature header fields from + messages they are signing, even if they know that the signatures + cannot be verified. + + When evaluating a message with multiple signatures, a verifier SHOULD + evaluate signatures independently and on their own merits. For + example, a verifier that by policy chooses not to accept signatures + with deprecated cryptographic algorithms would consider such + signatures invalid. Verifiers MAY process signatures in any order of + + + +Allman, et al. Standards Track [Page 33] + +RFC 4871 DKIM Signatures May 2007 + + + their choice; for example, some verifiers might choose to process + signatures corresponding to the From field in the message header + before other signatures. See Section 6.1 for more information about + signature choices. + + INFORMATIVE IMPLEMENTATION NOTE: Verifier attempts to correlate + valid signatures with invalid signatures in an attempt to guess + why a signature failed are ill-advised. In particular, there is + no general way that a verifier can determine that an invalid + signature was ever valid. + + Verifiers SHOULD ignore failed signatures as though they were not + present in the message. Verifiers SHOULD continue to check + signatures until a signature successfully verifies to the + satisfaction of the verifier. To limit potential denial-of-service + attacks, verifiers MAY limit the total number of signatures they will + attempt to verify. + +5. Signer Actions + + The following steps are performed in order by signers. + +5.1. Determine Whether the Email Should Be Signed and by Whom + + A signer can obviously only sign email for domains for which it has a + private key and the necessary knowledge of the corresponding public + key and selector information. However, there are a number of other + reasons beyond the lack of a private key why a signer could choose + not to sign an email. + + INFORMATIVE NOTE: Signing modules may be incorporated into any + portion of the mail system as deemed appropriate, including an + MUA, a SUBMISSION server, or an MTA. Wherever implemented, + signers should beware of signing (and thereby asserting + responsibility for) messages that may be problematic. In + particular, within a trusted enclave the signing address might be + derived from the header according to local policy; SUBMISSION + servers might only sign messages from users that are properly + authenticated and authorized. + + INFORMATIVE IMPLEMENTER ADVICE: SUBMISSION servers should not sign + Received header fields if the outgoing gateway MTA obfuscates + Received header fields, for example, to hide the details of + internal topology. + + If an email cannot be signed for some reason, it is a local policy + decision as to what to do with that email. + + + + +Allman, et al. Standards Track [Page 34] + +RFC 4871 DKIM Signatures May 2007 + + +5.2. Select a Private Key and Corresponding Selector Information + + This specification does not define the basis by which a signer should + choose which private key and selector information to use. Currently, + all selectors are equal as far as this specification is concerned, so + the decision should largely be a matter of administrative + convenience. Distribution and management of private keys is also + outside the scope of this document. + + INFORMATIVE OPERATIONS ADVICE: A signer should not sign with a + private key when the selector containing the corresponding public + key is expected to be revoked or removed before the verifier has + an opportunity to validate the signature. The signer should + anticipate that verifiers may choose to defer validation, perhaps + until the message is actually read by the final recipient. In + particular, when rotating to a new key pair, signing should + immediately commence with the new private key and the old public + key should be retained for a reasonable validation interval before + being removed from the key server. + +5.3. Normalize the Message to Prevent Transport Conversions + + Some messages, particularly those using 8-bit characters, are subject + to modification during transit, notably conversion to 7-bit form. + Such conversions will break DKIM signatures. In order to minimize + the chances of such breakage, signers SHOULD convert the message to a + suitable MIME content transfer encoding such as quoted-printable or + base64 as described in MIME Part One [RFC2045] before signing. Such + conversion is outside the scope of DKIM; the actual message SHOULD be + converted to 7-bit MIME by an MUA or MSA prior to presentation to the + DKIM algorithm. + + If the message is submitted to the signer with any local encoding + that will be modified before transmission, that modification to + canonical [RFC2822] form MUST be done before signing. In particular, + bare CR or LF characters (used by some systems as a local line + separator convention) MUST be converted to the SMTP-standard CRLF + sequence before the message is signed. Any conversion of this sort + SHOULD be applied to the message actually sent to the recipient(s), + not just to the version presented to the signing algorithm. + + More generally, the signer MUST sign the message as it is expected to + be received by the verifier rather than in some local or internal + form. + + + + + + + +Allman, et al. Standards Track [Page 35] + +RFC 4871 DKIM Signatures May 2007 + + +5.4. Determine the Header Fields to Sign + + The From header field MUST be signed (that is, included in the "h=" + tag of the resulting DKIM-Signature header field). Signers SHOULD + NOT sign an existing header field likely to be legitimately modified + or removed in transit. In particular, [RFC2821] explicitly permits + modification or removal of the Return-Path header field in transit. + Signers MAY include any other header fields present at the time of + signing at the discretion of the signer. + + INFORMATIVE OPERATIONS NOTE: The choice of which header fields to + sign is non-obvious. One strategy is to sign all existing, non- + repeatable header fields. An alternative strategy is to sign only + header fields that are likely to be displayed to or otherwise be + likely to affect the processing of the message at the receiver. A + third strategy is to sign only "well known" headers. Note that + verifiers may treat unsigned header fields with extreme + skepticism, including refusing to display them to the end user or + even ignoring the signature if it does not cover certain header + fields. For this reason, signing fields present in the message + such as Date, Subject, Reply-To, Sender, and all MIME header + fields are highly advised. + + The DKIM-Signature header field is always implicitly signed and MUST + NOT be included in the "h=" tag except to indicate that other + preexisting signatures are also signed. + + Signers MAY claim to have signed header fields that do not exist + (that is, signers MAY include the header field name in the "h=" tag + even if that header field does not exist in the message). When + computing the signature, the non-existing header field MUST be + treated as the null string (including the header field name, header + field value, all punctuation, and the trailing CRLF). + + INFORMATIVE RATIONALE: This allows signers to explicitly assert + the absence of a header field; if that header field is added later + the signature will fail. + + INFORMATIVE NOTE: A header field name need only be listed once + more than the actual number of that header field in a message at + the time of signing in order to prevent any further additions. + For example, if there is a single Comments header field at the + time of signing, listing Comments twice in the "h=" tag is + sufficient to prevent any number of Comments header fields from + being appended; it is not necessary (but is legal) to list + Comments three or more times in the "h=" tag. + + + + + +Allman, et al. Standards Track [Page 36] + +RFC 4871 DKIM Signatures May 2007 + + + Signers choosing to sign an existing header field that occurs more + than once in the message (such as Received) MUST sign the physically + last instance of that header field in the header block. Signers + wishing to sign multiple instances of such a header field MUST + include the header field name multiple times in the h= tag of the + DKIM-Signature header field, and MUST sign such header fields in + order from the bottom of the header field block to the top. The + signer MAY include more instances of a header field name in h= than + there are actual corresponding header fields to indicate that + additional header fields of that name SHOULD NOT be added. + + INFORMATIVE EXAMPLE: + + If the signer wishes to sign two existing Received header fields, + and the existing header contains: + + Received: + Received: + Received: + + then the resulting DKIM-Signature header field should read: + + DKIM-Signature: ... h=Received : Received : ... + + and Received header fields and will be signed in that + order. + + Signers should be careful of signing header fields that might have + additional instances added later in the delivery process, since such + header fields might be inserted after the signed instance or + otherwise reordered. Trace header fields (such as Received) and + Resent-* blocks are the only fields prohibited by [RFC2822] from + being reordered. In particular, since DKIM-Signature header fields + may be reordered by some intermediate MTAs, signing existing DKIM- + Signature header fields is error-prone. + + INFORMATIVE ADMONITION: Despite the fact that [RFC2822] permits + header fields to be reordered (with the exception of Received + header fields), reordering of signed header fields with multiple + instances by intermediate MTAs will cause DKIM signatures to be + broken; such anti-social behavior should be avoided. + + INFORMATIVE IMPLEMENTER'S NOTE: Although not required by this + specification, all end-user visible header fields should be signed + to avoid possible "indirect spamming". For example, if the + Subject header field is not signed, a spammer can resend a + previously signed mail, replacing the legitimate subject with a + one-line spam. + + + +Allman, et al. Standards Track [Page 37] + +RFC 4871 DKIM Signatures May 2007 + + +5.5. Recommended Signature Content + + In order to maximize compatibility with a variety of verifiers, it is + recommended that signers follow the practices outlined in this + section when signing a message. However, these are generic + recommendations applying to the general case; specific senders may + wish to modify these guidelines as required by their unique + situations. Verifiers MUST be capable of verifying signatures even + if one or more of the recommended header fields is not signed (with + the exception of From, which must always be signed) or if one or more + of the disrecommended header fields is signed. Note that verifiers + do have the option of ignoring signatures that do not cover a + sufficient portion of the header or body, just as they may ignore + signatures from an identity they do not trust. + + The following header fields SHOULD be included in the signature, if + they are present in the message being signed: + + o From (REQUIRED in all signatures) + + o Sender, Reply-To + + o Subject + + o Date, Message-ID + + o To, Cc + + o MIME-Version + + o Content-Type, Content-Transfer-Encoding, Content-ID, Content- + Description + + o Resent-Date, Resent-From, Resent-Sender, Resent-To, Resent-Cc, + Resent-Message-ID + + o In-Reply-To, References + + o List-Id, List-Help, List-Unsubscribe, List-Subscribe, List-Post, + List-Owner, List-Archive + + The following header fields SHOULD NOT be included in the signature: + + o Return-Path + + o Received + + o Comments, Keywords + + + +Allman, et al. Standards Track [Page 38] + +RFC 4871 DKIM Signatures May 2007 + + + o Bcc, Resent-Bcc + + o DKIM-Signature + + Optional header fields (those not mentioned above) normally SHOULD + NOT be included in the signature, because of the potential for + additional header fields of the same name to be legitimately added or + reordered prior to verification. There are likely to be legitimate + exceptions to this rule, because of the wide variety of application- + specific header fields that may be applied to a message, some of + which are unlikely to be duplicated, modified, or reordered. + + Signers SHOULD choose canonicalization algorithms based on the types + of messages they process and their aversion to risk. For example, + e-commerce sites sending primarily purchase receipts, which are not + expected to be processed by mailing lists or other software likely to + modify messages, will generally prefer "simple" canonicalization. + Sites sending primarily person-to-person email will likely prefer to + be more resilient to modification during transport by using "relaxed" + canonicalization. + + Signers SHOULD NOT use "l=" unless they intend to accommodate + intermediate mail processors that append text to a message. For + example, many mailing list processors append "unsubscribe" + information to message bodies. If signers use "l=", they SHOULD + include the entire message body existing at the time of signing in + computing the count. In particular, signers SHOULD NOT specify a + body length of 0 since this may be interpreted as a meaningless + signature by some verifiers. + +5.6. Compute the Message Hash and Signature + + The signer MUST compute the message hash as described in Section 3.7 + and then sign it using the selected public-key algorithm. This will + result in a DKIM-Signature header field that will include the body + hash and a signature of the header hash, where that header includes + the DKIM-Signature header field itself. + + Entities such as mailing list managers that implement DKIM and that + modify the message or a header field (for example, inserting + unsubscribe information) before retransmitting the message SHOULD + check any existing signature on input and MUST make such + modifications before re-signing the message. + + The signer MAY elect to limit the number of bytes of the body that + will be included in the hash and hence signed. The length actually + hashed should be inserted in the "l=" tag of the DKIM-Signature + header field. + + + +Allman, et al. Standards Track [Page 39] + +RFC 4871 DKIM Signatures May 2007 + + +5.7. Insert the DKIM-Signature Header Field + + Finally, the signer MUST insert the DKIM-Signature header field + created in the previous step prior to transmitting the email. The + DKIM-Signature header field MUST be the same as used to compute the + hash as described above, except that the value of the "b=" tag MUST + be the appropriately signed hash computed in the previous step, + signed using the algorithm specified in the "a=" tag of the DKIM- + Signature header field and using the private key corresponding to the + selector given in the "s=" tag of the DKIM-Signature header field, as + chosen above in Section 5.2 + + The DKIM-Signature header field MUST be inserted before any other + DKIM-Signature fields in the header block. + + INFORMATIVE IMPLEMENTATION NOTE: The easiest way to achieve this + is to insert the DKIM-Signature header field at the beginning of + the header block. In particular, it may be placed before any + existing Received header fields. This is consistent with treating + DKIM-Signature as a trace header field. + +6. Verifier Actions + + Since a signer MAY remove or revoke a public key at any time, it is + recommended that verification occur in a timely manner. In many + configurations, the most timely place is during acceptance by the + border MTA or shortly thereafter. In particular, deferring + verification until the message is accessed by the end user is + discouraged. + + A border or intermediate MTA MAY verify the message signature(s). An + MTA who has performed verification MAY communicate the result of that + verification by adding a verification header field to incoming + messages. This considerably simplifies things for the user, who can + now use an existing mail user agent. Most MUAs have the ability to + filter messages based on message header fields or content; these + filters would be used to implement whatever policy the user wishes + with respect to unsigned mail. + + A verifying MTA MAY implement a policy with respect to unverifiable + mail, regardless of whether or not it applies the verification header + field to signed messages. + + Verifiers MUST produce a result that is semantically equivalent to + applying the following steps in the order listed. In practice, + several of these steps can be performed in parallel in order to + improve performance. + + + + +Allman, et al. Standards Track [Page 40] + +RFC 4871 DKIM Signatures May 2007 + + +6.1. Extract Signatures from the Message + + The order in which verifiers try DKIM-Signature header fields is not + defined; verifiers MAY try signatures in any order they like. For + example, one implementation might try the signatures in textual + order, whereas another might try signatures by identities that match + the contents of the From header field before trying other signatures. + Verifiers MUST NOT attribute ultimate meaning to the order of + multiple DKIM-Signature header fields. In particular, there is + reason to believe that some relays will reorder the header fields in + potentially arbitrary ways. + + INFORMATIVE IMPLEMENTATION NOTE: Verifiers might use the order as + a clue to signing order in the absence of any other information. + However, other clues as to the semantics of multiple signatures + (such as correlating the signing host with Received header fields) + may also be considered. + + A verifier SHOULD NOT treat a message that has one or more bad + signatures and no good signatures differently from a message with no + signature at all; such treatment is a matter of local policy and is + beyond the scope of this document. + + When a signature successfully verifies, a verifier will either stop + processing or attempt to verify any other signatures, at the + discretion of the implementation. A verifier MAY limit the number of + signatures it tries to avoid denial-of-service attacks. + + INFORMATIVE NOTE: An attacker could send messages with large + numbers of faulty signatures, each of which would require a DNS + lookup and corresponding CPU time to verify the message. This + could be an attack on the domain that receives the message, by + slowing down the verifier by requiring it to do a large number of + DNS lookups and/or signature verifications. It could also be an + attack against the domains listed in the signatures, essentially + by enlisting innocent verifiers in launching an attack against the + DNS servers of the actual victim. + + In the following description, text reading "return status + (explanation)" (where "status" is one of "PERMFAIL" or "TEMPFAIL") + means that the verifier MUST immediately cease processing that + signature. The verifier SHOULD proceed to the next signature, if any + is present, and completely ignore the bad signature. If the status + is "PERMFAIL", the signature failed and should not be reconsidered. + If the status is "TEMPFAIL", the signature could not be verified at + this time but may be tried again later. A verifier MAY either defer + the message for later processing, perhaps by queueing it locally or + issuing a 451/4.7.5 SMTP reply, or try another signature; if no good + + + +Allman, et al. Standards Track [Page 41] + +RFC 4871 DKIM Signatures May 2007 + + + signature is found and any of the signatures resulted in a TEMPFAIL + status, the verifier MAY save the message for later processing. The + "(explanation)" is not normative text; it is provided solely for + clarification. + + Verifiers SHOULD ignore any DKIM-Signature header fields where the + signature does not validate. Verifiers that are prepared to validate + multiple signature header fields SHOULD proceed to the next signature + header field, should it exist. However, verifiers MAY make note of + the fact that an invalid signature was present for consideration at a + later step. + + INFORMATIVE NOTE: The rationale of this requirement is to permit + messages that have invalid signatures but also a valid signature + to work. For example, a mailing list exploder might opt to leave + the original submitter signature in place even though the exploder + knows that it is modifying the message in some way that will break + that signature, and the exploder inserts its own signature. In + this case, the message should succeed even in the presence of the + known-broken signature. + + For each signature to be validated, the following steps should be + performed in such a manner as to produce a result that is + semantically equivalent to performing them in the indicated order. + +6.1.1. Validate the Signature Header Field + + Implementers MUST meticulously validate the format and values in the + DKIM-Signature header field; any inconsistency or unexpected values + MUST cause the header field to be completely ignored and the verifier + to return PERMFAIL (signature syntax error). Being "liberal in what + you accept" is definitely a bad strategy in this security context. + Note however that this does not include the existence of unknown tags + in a DKIM-Signature header field, which are explicitly permitted. + + Verifiers MUST ignore DKIM-Signature header fields with a "v=" tag + that is inconsistent with this specification and return PERMFAIL + (incompatible version). + + INFORMATIVE IMPLEMENTATION NOTE: An implementation may, of course, + choose to also verify signatures generated by older versions of + this specification. + + If any tag listed as "required" in Section 3.5 is omitted from the + DKIM-Signature header field, the verifier MUST ignore the DKIM- + Signature header field and return PERMFAIL (signature missing + required tag). + + + + +Allman, et al. Standards Track [Page 42] + +RFC 4871 DKIM Signatures May 2007 + + + INFORMATIONAL NOTE: The tags listed as required in Section 3.5 are + "v=", "a=", "b=", "bh=", "d=", "h=", and "s=". Should there be a + conflict between this note and Section 3.5, Section 3.5 is + normative. + + If the DKIM-Signature header field does not contain the "i=" tag, the + verifier MUST behave as though the value of that tag were "@d", where + "d" is the value from the "d=" tag. + + Verifiers MUST confirm that the domain specified in the "d=" tag is + the same as or a parent domain of the domain part of the "i=" tag. + If not, the DKIM-Signature header field MUST be ignored and the + verifier should return PERMFAIL (domain mismatch). + + If the "h=" tag does not include the From header field, the verifier + MUST ignore the DKIM-Signature header field and return PERMFAIL (From + field not signed). + + Verifiers MAY ignore the DKIM-Signature header field and return + PERMFAIL (signature expired) if it contains an "x=" tag and the + signature has expired. + + Verifiers MAY ignore the DKIM-Signature header field if the domain + used by the signer in the "d=" tag is not associated with a valid + signing entity. For example, signatures with "d=" values such as + "com" and "co.uk" may be ignored. The list of unacceptable domains + SHOULD be configurable. + + Verifiers MAY ignore the DKIM-Signature header field and return + PERMFAIL (unacceptable signature header) for any other reason, for + example, if the signature does not sign header fields that the + verifier views to be essential. As a case in point, if MIME header + fields are not signed, certain attacks may be possible that the + verifier would prefer to avoid. + +6.1.2. Get the Public Key + + The public key for a signature is needed to complete the verification + process. The process of retrieving the public key depends on the + query type as defined by the "q=" tag in the DKIM-Signature header + field. Obviously, a public key need only be retrieved if the process + of extracting the signature information is completely successful. + Details of key management and representation are described in + Section 3.6. The verifier MUST validate the key record and MUST + ignore any public key records that are malformed. + + When validating a message, a verifier MUST perform the following + steps in a manner that is semantically the same as performing them in + + + +Allman, et al. Standards Track [Page 43] + +RFC 4871 DKIM Signatures May 2007 + + + the order indicated (in some cases, the implementation may + parallelize or reorder these steps, as long as the semantics remain + unchanged): + + 1. Retrieve the public key as described in Section 3.6 using the + algorithm in the "q=" tag, the domain from the "d=" tag, and the + selector from the "s=" tag. + + 2. If the query for the public key fails to respond, the verifier + MAY defer acceptance of this email and return TEMPFAIL (key + unavailable). If verification is occurring during the incoming + SMTP session, this MAY be achieved with a 451/4.7.5 SMTP reply + code. Alternatively, the verifier MAY store the message in the + local queue for later trial or ignore the signature. Note that + storing a message in the local queue is subject to denial-of- + service attacks. + + 3. If the query for the public key fails because the corresponding + key record does not exist, the verifier MUST immediately return + PERMFAIL (no key for signature). + + 4. If the query for the public key returns multiple key records, the + verifier may choose one of the key records or may cycle through + the key records performing the remainder of these steps on each + record at the discretion of the implementer. The order of the + key records is unspecified. If the verifier chooses to cycle + through the key records, then the "return ..." wording in the + remainder of this section means "try the next key record, if any; + if none, return to try another signature in the usual way". + + 5. If the result returned from the query does not adhere to the + format defined in this specification, the verifier MUST ignore + the key record and return PERMFAIL (key syntax error). Verifiers + are urged to validate the syntax of key records carefully to + avoid attempted attacks. In particular, the verifier MUST ignore + keys with a version code ("v=" tag) that they do not implement. + + 6. If the "g=" tag in the public key does not match the Local-part + of the "i=" tag in the message signature header field, the + verifier MUST ignore the key record and return PERMFAIL + (inapplicable key). If the Local-part of the "i=" tag on the + message signature is not present, the "g=" tag must be "*" (valid + for all addresses in the domain) or the entire g= tag must be + omitted (which defaults to "g=*"), otherwise the verifier MUST + ignore the key record and return PERMFAIL (inapplicable key). + Other than this test, verifiers SHOULD NOT treat a message signed + with a key record having a "g=" tag any differently than one + without; in particular, verifiers SHOULD NOT prefer messages that + + + +Allman, et al. Standards Track [Page 44] + +RFC 4871 DKIM Signatures May 2007 + + + seem to have an individual signature by virtue of a "g=" tag + versus a domain signature. + + 7. If the "h=" tag exists in the public key record and the hash + algorithm implied by the a= tag in the DKIM-Signature header + field is not included in the contents of the "h=" tag, the + verifier MUST ignore the key record and return PERMFAIL + (inappropriate hash algorithm). + + 8. If the public key data (the "p=" tag) is empty, then this key has + been revoked and the verifier MUST treat this as a failed + signature check and return PERMFAIL (key revoked). There is no + defined semantic difference between a key that has been revoked + and a key record that has been removed. + + 9. If the public key data is not suitable for use with the algorithm + and key types defined by the "a=" and "k=" tags in the DKIM- + Signature header field, the verifier MUST immediately return + PERMFAIL (inappropriate key algorithm). + +6.1.3. Compute the Verification + + Given a signer and a public key, verifying a signature consists of + actions semantically equivalent to the following steps. + + 1. Based on the algorithm defined in the "c=" tag, the body length + specified in the "l=" tag, and the header field names in the "h=" + tag, prepare a canonicalized version of the message as is + described in Section 3.7 (note that this version does not + actually need to be instantiated). When matching header field + names in the "h=" tag against the actual message header field, + comparisons MUST be case-insensitive. + + 2. Based on the algorithm indicated in the "a=" tag, compute the + message hashes from the canonical copy as described in + Section 3.7. + + 3. Verify that the hash of the canonicalized message body computed + in the previous step matches the hash value conveyed in the "bh=" + tag. If the hash does not match, the verifier SHOULD ignore the + signature and return PERMFAIL (body hash did not verify). + + 4. Using the signature conveyed in the "b=" tag, verify the + signature against the header hash using the mechanism appropriate + for the public key algorithm described in the "a=" tag. If the + signature does not validate, the verifier SHOULD ignore the + signature and return PERMFAIL (signature did not verify). + + + + +Allman, et al. Standards Track [Page 45] + +RFC 4871 DKIM Signatures May 2007 + + + 5. Otherwise, the signature has correctly verified. + + INFORMATIVE IMPLEMENTER'S NOTE: Implementations might wish to + initiate the public-key query in parallel with calculating the + hash as the public key is not needed until the final decryption is + calculated. Implementations may also verify the signature on the + message header before validating that the message hash listed in + the "bh=" tag in the DKIM-Signature header field matches that of + the actual message body; however, if the body hash does not match, + the entire signature must be considered to have failed. + + A body length specified in the "l=" tag of the signature limits the + number of bytes of the body passed to the verification algorithm. + All data beyond that limit is not validated by DKIM. Hence, + verifiers might treat a message that contains bytes beyond the + indicated body length with suspicion, such as by truncating the + message at the indicated body length, declaring the signature invalid + (e.g., by returning PERMFAIL (unsigned content)), or conveying the + partial verification to the policy module. + + INFORMATIVE IMPLEMENTATION NOTE: Verifiers that truncate the body + at the indicated body length might pass on a malformed MIME + message if the signer used the "N-4" trick (omitting the final + "--CRLF") described in the informative note in Section 3.4.5. + Such verifiers may wish to check for this case and include a + trailing "--CRLF" to avoid breaking the MIME structure. A simple + way to achieve this might be to append "--CRLF" to any "multipart" + message with a body length; if the MIME structure is already + correctly formed, this will appear in the postlude and will not be + displayed to the end user. + +6.2. Communicate Verification Results + + Verifiers wishing to communicate the results of verification to other + parts of the mail system may do so in whatever manner they see fit. + For example, implementations might choose to add an email header + field to the message before passing it on. Any such header field + SHOULD be inserted before any existing DKIM-Signature or preexisting + authentication status header fields in the header field block. + + INFORMATIVE ADVICE to MUA filter writers: Patterns intended to + search for results header fields to visibly mark authenticated + mail for end users should verify that such header field was added + by the appropriate verifying domain and that the verified identity + matches the author identity that will be displayed by the MUA. In + particular, MUA filters should not be influenced by bogus results + + + + + +Allman, et al. Standards Track [Page 46] + +RFC 4871 DKIM Signatures May 2007 + + + header fields added by attackers. To circumvent this attack, + verifiers may wish to delete existing results header fields after + verification and before adding a new header field. + +6.3. Interpret Results/Apply Local Policy + + It is beyond the scope of this specification to describe what actions + a verifier system should make, but an authenticated email presents an + opportunity to a receiving system that unauthenticated email cannot. + Specifically, an authenticated email creates a predictable identifier + by which other decisions can reliably be managed, such as trust and + reputation. Conversely, unauthenticated email lacks a reliable + identifier that can be used to assign trust and reputation. It is + reasonable to treat unauthenticated email as lacking any trust and + having no positive reputation. + + In general, verifiers SHOULD NOT reject messages solely on the basis + of a lack of signature or an unverifiable signature; such rejection + would cause severe interoperability problems. However, if the + verifier does opt to reject such messages (for example, when + communicating with a peer who, by prior agreement, agrees to only + send signed messages), and the verifier runs synchronously with the + SMTP session and a signature is missing or does not verify, the MTA + SHOULD use a 550/5.7.x reply code. + + If it is not possible to fetch the public key, perhaps because the + key server is not available, a temporary failure message MAY be + generated using a 451/4.7.5 reply code, such as: + + 451 4.7.5 Unable to verify signature - key server unavailable + + Temporary failures such as inability to access the key server or + other external service are the only conditions that SHOULD use a 4xx + SMTP reply code. In particular, cryptographic signature verification + failures MUST NOT return 4xx SMTP replies. + + Once the signature has been verified, that information MUST be + conveyed to higher-level systems (such as explicit allow/whitelists + and reputation systems) and/or to the end user. If the message is + signed on behalf of any address other than that in the From: header + field, the mail system SHOULD take pains to ensure that the actual + signing identity is clear to the reader. + + The verifier MAY treat unsigned header fields with extreme + skepticism, including marking them as untrusted or even deleting them + before display to the end user. + + + + + +Allman, et al. Standards Track [Page 47] + +RFC 4871 DKIM Signatures May 2007 + + + While the symptoms of a failed verification are obvious -- the + signature doesn't verify -- establishing the exact cause can be more + difficult. If a selector cannot be found, is that because the + selector has been removed, or was the value changed somehow in + transit? If the signature line is missing, is that because it was + never there, or was it removed by an overzealous filter? For + diagnostic purposes, the exact reason why the verification fails + SHOULD be made available to the policy module and possibly recorded + in the system logs. If the email cannot be verified, then it SHOULD + be rendered the same as all unverified email regardless of whether or + not it looks like it was signed. + +7. IANA Considerations + + DKIM introduces some new namespaces that have been registered with + IANA. In all cases, new values are assigned only for values that + have been documented in a published RFC that has IETF Consensus + [RFC2434]. + +7.1. DKIM-Signature Tag Specifications + + A DKIM-Signature provides for a list of tag specifications. IANA has + established the DKIM-Signature Tag Specification Registry for tag + specifications that can be used in DKIM-Signature fields. + + The initial entries in the registry comprise: + + +------+-----------------+ + | TYPE | REFERENCE | + +------+-----------------+ + | v | (this document) | + | a | (this document) | + | b | (this document) | + | bh | (this document) | + | c | (this document) | + | d | (this document) | + | h | (this document) | + | i | (this document) | + | l | (this document) | + | q | (this document) | + | s | (this document) | + | t | (this document) | + | x | (this document) | + | z | (this document) | + +------+-----------------+ + + DKIM-Signature Tag Specification Registry Initial Values + + + + +Allman, et al. Standards Track [Page 48] + +RFC 4871 DKIM Signatures May 2007 + + +7.2. DKIM-Signature Query Method Registry + + The "q=" tag-spec (specified in Section 3.5) provides for a list of + query methods. + + IANA has established the DKIM-Signature Query Method Registry for + mechanisms that can be used to retrieve the key that will permit + validation processing of a message signed using DKIM. + + The initial entry in the registry comprises: + + +------+--------+-----------------+ + | TYPE | OPTION | REFERENCE | + +------+--------+-----------------+ + | dns | txt | (this document) | + +------+--------+-----------------+ + + DKIM-Signature Query Method Registry Initial Values + +7.3. DKIM-Signature Canonicalization Registry + + The "c=" tag-spec (specified in Section 3.5) provides for a specifier + for canonicalization algorithms for the header and body of the + message. + + IANA has established the DKIM-Signature Canonicalization Algorithm + Registry for algorithms for converting a message into a canonical + form before signing or verifying using DKIM. + + The initial entries in the header registry comprise: + + +---------+-----------------+ + | TYPE | REFERENCE | + +---------+-----------------+ + | simple | (this document) | + | relaxed | (this document) | + +---------+-----------------+ + + DKIM-Signature Header Canonicalization Algorithm Registry + Initial Values + + + + + + + + + + + +Allman, et al. Standards Track [Page 49] + +RFC 4871 DKIM Signatures May 2007 + + + The initial entries in the body registry comprise: + + +---------+-----------------+ + | TYPE | REFERENCE | + +---------+-----------------+ + | simple | (this document) | + | relaxed | (this document) | + +---------+-----------------+ + + DKIM-Signature Body Canonicalization Algorithm Registry + Initial Values + +7.4. _domainkey DNS TXT Record Tag Specifications + + A _domainkey DNS TXT record provides for a list of tag + specifications. IANA has established the DKIM _domainkey DNS TXT Tag + Specification Registry for tag specifications that can be used in DNS + TXT Records. + + The initial entries in the registry comprise: + + +------+-----------------+ + | TYPE | REFERENCE | + +------+-----------------+ + | v | (this document) | + | g | (this document) | + | h | (this document) | + | k | (this document) | + | n | (this document) | + | p | (this document) | + | s | (this document) | + | t | (this document) | + +------+-----------------+ + + DKIM _domainkey DNS TXT Record Tag Specification Registry + Initial Values + +7.5. DKIM Key Type Registry + + The "k=" (specified in Section 3.6.1) and the "a=" (specified in Section 3.5) tags provide for a list of + mechanisms that can be used to decode a DKIM signature. + + IANA has established the DKIM Key Type Registry for such mechanisms. + + + + + + + +Allman, et al. Standards Track [Page 50] + +RFC 4871 DKIM Signatures May 2007 + + + The initial entry in the registry comprises: + + +------+-----------+ + | TYPE | REFERENCE | + +------+-----------+ + | rsa | [RFC3447] | + +------+-----------+ + + DKIM Key Type Initial Values + +7.6. DKIM Hash Algorithms Registry + + The "h=" (specified in Section 3.6.1) and the "a=" (specified in Section 3.5) tags provide for a list of + mechanisms that can be used to produce a digest of message data. + + IANA has established the DKIM Hash Algorithms Registry for such + mechanisms. + + The initial entries in the registry comprise: + + +--------+-------------------+ + | TYPE | REFERENCE | + +--------+-------------------+ + | sha1 | [FIPS.180-2.2002] | + | sha256 | [FIPS.180-2.2002] | + +--------+-------------------+ + + DKIM Hash Algorithms Initial Values + +7.7. DKIM Service Types Registry + + The "s=" tag (specified in Section 3.6.1) provides for a + list of service types to which this selector may apply. + + IANA has established the DKIM Service Types Registry for service + types. + + The initial entries in the registry comprise: + + +-------+-----------------+ + | TYPE | REFERENCE | + +-------+-----------------+ + | email | (this document) | + | * | (this document) | + +-------+-----------------+ + + DKIM Service Types Registry Initial Values + + + +Allman, et al. Standards Track [Page 51] + +RFC 4871 DKIM Signatures May 2007 + + +7.8. DKIM Selector Flags Registry + + The "t=" tag (specified in Section 3.6.1) provides for a + list of flags to modify interpretation of the selector. + + IANA has established the DKIM Selector Flags Registry for additional + flags. + + The initial entries in the registry comprise: + + +------+-----------------+ + | TYPE | REFERENCE | + +------+-----------------+ + | y | (this document) | + | s | (this document) | + +------+-----------------+ + + DKIM Selector Flags Registry Initial Values + +7.9. DKIM-Signature Header Field + + IANA has added DKIM-Signature to the "Permanent Message Header + Fields" registry (see [RFC3864]) for the "mail" protocol, using this + document as the reference. + +8. Security Considerations + + It has been observed that any mechanism that is introduced that + attempts to stem the flow of spam is subject to intensive attack. + DKIM needs to be carefully scrutinized to identify potential attack + vectors and the vulnerability to each. See also [RFC4686]. + +8.1. Misuse of Body Length Limits ("l=" Tag) + + Body length limits (in the form of the "l=" tag) are subject to + several potential attacks. + +8.1.1. Addition of New MIME Parts to Multipart/* + + If the body length limit does not cover a closing MIME multipart + section (including the trailing "--CRLF" portion), then it is + possible for an attacker to intercept a properly signed multipart + message and add a new body part. Depending on the details of the + MIME type and the implementation of the verifying MTA and the + receiving MUA, this could allow an attacker to change the information + displayed to an end user from an apparently trusted source. + + + + + +Allman, et al. Standards Track [Page 52] + +RFC 4871 DKIM Signatures May 2007 + + + For example, if attackers can append information to a "text/html" + body part, they may be able to exploit a bug in some MUAs that + continue to read after a "" marker, and thus display HTML text + on top of already displayed text. If a message has a + "multipart/alternative" body part, they might be able to add a new + body part that is preferred by the displaying MUA. + +8.1.2. Addition of new HTML content to existing content + + Several receiving MUA implementations do not cease display after a + """" tag. In particular, this allows attacks involving + overlaying images on top of existing text. + + INFORMATIVE EXAMPLE: Appending the following text to an existing, + properly closed message will in many MUAs result in inappropriate + data being rendered on top of existing, correct data: +
+ +
+ +8.2. Misappropriated Private Key + + If the private key for a user is resident on their computer and is + not protected by an appropriately secure mechanism, it is possible + for malware to send mail as that user and any other user sharing the + same private key. The malware would not, however, be able to + generate signed spoofs of other signers' addresses, which would aid + in identification of the infected user and would limit the + possibilities for certain types of attacks involving socially + engineered messages. This threat applies mainly to MUA-based + implementations; protection of private keys on servers can be easily + achieved through the use of specialized cryptographic hardware. + + A larger problem occurs if malware on many users' computers obtains + the private keys for those users and transmits them via a covert + channel to a site where they can be shared. The compromised users + would likely not know of the misappropriation until they receive + "bounce" messages from messages they are purported to have sent. + Many users might not understand the significance of these bounce + messages and would not take action. + + One countermeasure is to use a user-entered passphrase to encrypt the + private key, although users tend to choose weak passphrases and often + reuse them for different purposes, possibly allowing an attack + against DKIM to be extended into other domains. Nevertheless, the + decoded private key might be briefly available to compromise by + malware when it is entered, or might be discovered via keystroke + + + +Allman, et al. Standards Track [Page 53] + +RFC 4871 DKIM Signatures May 2007 + + + logging. The added complexity of entering a passphrase each time one + sends a message would also tend to discourage the use of a secure + passphrase. + + A somewhat more effective countermeasure is to send messages through + an outgoing MTA that can authenticate the submitter using existing + techniques (e.g., SMTP Authentication), possibly validate the message + itself (e.g., verify that the header is legitimate and that the + content passes a spam content check), and sign the message using a + key appropriate for the submitter address. Such an MTA can also + apply controls on the volume of outgoing mail each user is permitted + to originate in order to further limit the ability of malware to + generate bulk email. + +8.3. Key Server Denial-of-Service Attacks + + Since the key servers are distributed (potentially separate for each + domain), the number of servers that would need to be attacked to + defeat this mechanism on an Internet-wide basis is very large. + Nevertheless, key servers for individual domains could be attacked, + impeding the verification of messages from that domain. This is not + significantly different from the ability of an attacker to deny + service to the mail exchangers for a given domain, although it + affects outgoing, not incoming, mail. + + A variation on this attack is that if a very large amount of mail + were to be sent using spoofed addresses from a given domain, the key + servers for that domain could be overwhelmed with requests. However, + given the low overhead of verification compared with handling of the + email message itself, such an attack would be difficult to mount. + +8.4. Attacks Against the DNS + + Since the DNS is a required binding for key services, specific + attacks against the DNS must be considered. + + While the DNS is currently insecure [RFC3833], these security + problems are the motivation behind DNS Security (DNSSEC) [RFC4033], + and all users of the DNS will reap the benefit of that work. + + DKIM is only intended as a "sufficient" method of proving + authenticity. It is not intended to provide strong cryptographic + proof about authorship or contents. Other technologies such as + OpenPGP [RFC2440] and S/MIME [RFC3851] address those requirements. + + A second security issue related to the DNS revolves around the + increased DNS traffic as a consequence of fetching selector-based + data as well as fetching signing domain policy. Widespread + + + +Allman, et al. Standards Track [Page 54] + +RFC 4871 DKIM Signatures May 2007 + + + deployment of DKIM will result in a significant increase in DNS + queries to the claimed signing domain. In the case of forgeries on a + large scale, DNS servers could see a substantial increase in queries. + + A specific DNS security issue that should be considered by DKIM + verifiers is the name chaining attack described in Section 2.3 of the + DNS Threat Analysis [RFC3833]. A DKIM verifier, while verifying a + DKIM-Signature header field, could be prompted to retrieve a key + record of an attacker's choosing. This threat can be minimized by + ensuring that name servers, including recursive name servers, used by + the verifier enforce strict checking of "glue" and other additional + information in DNS responses and are therefore not vulnerable to this + attack. + +8.5. Replay Attacks + + In this attack, a spammer sends a message to be spammed to an + accomplice, which results in the message being signed by the + originating MTA. The accomplice resends the message, including the + original signature, to a large number of recipients, possibly by + sending the message to many compromised machines that act as MTAs. + The messages, not having been modified by the accomplice, have valid + signatures. + + Partial solutions to this problem involve the use of reputation + services to convey the fact that the specific email address is being + used for spam and that messages from that signer are likely to be + spam. This requires a real-time detection mechanism in order to + react quickly enough. However, such measures might be prone to + abuse, if for example an attacker resent a large number of messages + received from a victim in order to make them appear to be a spammer. + + Large verifiers might be able to detect unusually large volumes of + mails with the same signature in a short time period. Smaller + verifiers can get substantially the same volume of information via + existing collaborative systems. + +8.6. Limits on Revoking Keys + + When a large domain detects undesirable behavior on the part of one + of its users, it might wish to revoke the key used to sign that + user's messages in order to disavow responsibility for messages that + have not yet been verified or that are the subject of a replay + attack. However, the ability of the domain to do so can be limited + if the same key, for scalability reasons, is used to sign messages + for many other users. Mechanisms for explicitly revoking keys on a + per-address basis have been proposed but require further study as to + their utility and the DNS load they represent. + + + +Allman, et al. Standards Track [Page 55] + +RFC 4871 DKIM Signatures May 2007 + + +8.7. Intentionally Malformed Key Records + + It is possible for an attacker to publish key records in DNS that are + intentionally malformed, with the intent of causing a denial-of- + service attack on a non-robust verifier implementation. The attacker + could then cause a verifier to read the malformed key record by + sending a message to one of its users referencing the malformed + record in a (not necessarily valid) signature. Verifiers MUST + thoroughly verify all key records retrieved from the DNS and be + robust against intentionally as well as unintentionally malformed key + records. + +8.8. Intentionally Malformed DKIM-Signature Header Fields + + Verifiers MUST be prepared to receive messages with malformed DKIM- + Signature header fields, and thoroughly verify the header field + before depending on any of its contents. + +8.9. Information Leakage + + An attacker could determine when a particular signature was verified + by using a per-message selector and then monitoring their DNS traffic + for the key lookup. This would act as the equivalent of a "web bug" + for verification time rather than when the message was read. + +8.10. Remote Timing Attacks + + In some cases, it may be possible to extract private keys using a + remote timing attack [BONEH03]. Implementations should consider + obfuscating the timing to prevent such attacks. + +8.11. Reordered Header Fields + + Existing standards allow intermediate MTAs to reorder header fields. + If a signer signs two or more header fields of the same name, this + can cause spurious verification errors on otherwise legitimate + messages. In particular, signers that sign any existing DKIM- + Signature fields run the risk of having messages incorrectly fail to + verify. + +8.12. RSA Attacks + + An attacker could create a large RSA signing key with a small + exponent, thus requiring that the verification key have a large + exponent. This will force verifiers to use considerable computing + resources to verify the signature. Verifiers might avoid this attack + by refusing to verify signatures that reference selectors with public + keys having unreasonable exponents. + + + +Allman, et al. Standards Track [Page 56] + +RFC 4871 DKIM Signatures May 2007 + + + In general, an attacker might try to overwhelm a verifier by flooding + it with messages requiring verification. This is similar to other + MTA denial-of-service attacks and should be dealt with in a similar + fashion. + +8.13. Inappropriate Signing by Parent Domains + + The trust relationship described in Section 3.8 could conceivably be + used by a parent domain to sign messages with identities in a + subdomain not administratively related to the parent. For example, + the ".com" registry could create messages with signatures using an + "i=" value in the example.com domain. There is no general solution + to this problem, since the administrative cut could occur anywhere in + the domain name. For example, in the domain "example.podunk.ca.us" + there are three administrative cuts (podunk.ca.us, ca.us, and us), + any of which could create messages with an identity in the full + domain. + + INFORMATIVE NOTE: This is considered an acceptable risk for the + same reason that it is acceptable for domain delegation. For + example, in the example above any of the domains could potentially + simply delegate "example.podunk.ca.us" to a server of their choice + and completely replace all DNS-served information. Note that a + verifier MAY ignore signatures that come from an unlikely domain + such as ".com", as discussed in Section 6.1.1. + +9. References + +9.1. Normative References + + [FIPS.180-2.2002] U.S. Department of Commerce, "Secure Hash + Standard", FIPS PUB 180-2, August 2002. + + [ITU.X660.1997] "Information Technology - ASN.1 encoding rules: + Specification of Basic Encoding Rules (BER), + Canonical Encoding Rules (CER) and Distinguished + Encoding Rules (DER)", ITU-T Recommendation X.660, + 1997. + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose + Internet Mail Extensions (MIME) Part One: Format + of Internet Message Bodies", RFC 2045, + November 1996. + + [RFC2047] Moore, K., "MIME (Multipurpose Internet Mail + Extensions) Part Three: Message header field + Extensions for Non-ASCII Text", RFC 2047, + November 1996. + + + +Allman, et al. Standards Track [Page 57] + +RFC 4871 DKIM Signatures May 2007 + + + [RFC2119] Bradner, S., "Key words for use in RFCs to + Indicate Requirement Levels", BCP 14, RFC 2119, + March 1997. + + [RFC2821] Klensin, J., "Simple Mail Transfer Protocol", + RFC 2821, April 2001. + + [RFC2822] Resnick, P., "Internet Message Format", RFC 2822, + April 2001. + + [RFC3447] Jonsson, J. and B. Kaliski, "Public-Key + Cryptography Standards (PKCS) #1: RSA Cryptography + Specifications Version 2.1", RFC 3447, + February 2003. + + [RFC3490] Faltstrom, P., Hoffman, P., and A. Costello, + "Internationalizing Domain Names in Applications + (IDNA)", RFC 3490, March 2003. + + [RFC4234] Crocker, D., Ed. and P. Overell, "Augmented BNF + for Syntax Specifications: ABNF", RFC 4234, + October 2005. + +9.2. Informative References + + [BONEH03] Proc. 12th USENIX Security Symposium, "Remote + Timing Attacks are Practical", 2003. + + [RFC1847] Galvin, J., Murphy, S., Crocker, S., and N. Freed, + "Security Multiparts for MIME: Multipart/Signed + and Multipart/Encrypted", RFC 1847, October 1995. + + [RFC2434] Narten, T. and H. Alvestrand, "Guidelines for + Writing an IANA Considerations Section in RFCs", + BCP 26, RFC 2434, October 1998. + + [RFC2440] Callas, J., Donnerhacke, L., Finney, H., and R. + Thayer, "OpenPGP Message Format", RFC 2440, + November 1998. + + [RFC3766] Orman, H. and P. Hoffman, "Determining Strengths + for Public Keys Used For Exchanging Symmetric + Keys", RFC 3766, April 2004. + + [RFC3833] Atkins, D. and R. Austein, "Threat Analysis of the + Domain Name System (DNS)", RFC 3833, August 2004. + + + + + +Allman, et al. Standards Track [Page 58] + +RFC 4871 DKIM Signatures May 2007 + + + [RFC3851] Ramsdell, B., "S/MIME Version 3 Message + Specification", RFC 3851, June 1999. + + [RFC3864] Klyne, G., Nottingham, M., and J. Mogul, + "Registration Procedures for Message Header + Fields", BCP 90, September 2004. + + [RFC4033] Arends, R., Austein, R., Larson, M., Massey, D., + and S. Rose, "DNS Security Introduction and + Requirements", RFC 4033, March 2005. + + [RFC4686] Fenton, J., "Analysis of Threats Motivating + DomainKeys Identified Mail (DKIM)", RFC 4686, + September 2006. + + [RFC4870] Delany, M., "Domain-Based Email Authentication + Using Public Keys Advertised in the DNS + (DomainKeys)", RFC 4870, May 2007. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Allman, et al. Standards Track [Page 59] + +RFC 4871 DKIM Signatures May 2007 + + +Appendix A. Example of Use (INFORMATIVE) + + This section shows the complete flow of an email from submission to + final delivery, demonstrating how the various components fit + together. The key used in this example is shown in Appendix C. + +A.1. The User Composes an Email + + + From: Joe SixPack + To: Suzie Q + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Allman, et al. Standards Track [Page 60] + +RFC 4871 DKIM Signatures May 2007 + + +A.2. The Email Is Signed + + This email is signed by the example.com outbound email server and now + looks like this: + + DKIM-Signature: v=1; a=rsa-sha256; s=brisbane; d=example.com; + c=simple/simple; q=dns/txt; i=joe@football.example.com; + h=Received : From : To : Subject : Date : Message-ID; + bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=; + b=AuUoFEfDxTDkHlLXSZEpZj79LICEps6eda7W3deTVFOk4yAUoqOB + 4nujc7YopdG5dWLSdNg6xNAZpOPr+kHxt1IrE+NahM6L/LbvaHut + KVdkLLkpVaVVQPzeRDI009SO2Il5Lu7rDNH6mZckBdrIx0orEtZV + 4bmp/YzhwvcubU4=; + Received: from client1.football.example.com [192.0.2.1] + by submitserver.example.com with SUBMISSION; + Fri, 11 Jul 2003 21:01:54 -0700 (PDT) + From: Joe SixPack + To: Suzie Q + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + + The signing email server requires access to the private key + associated with the "brisbane" selector to generate this signature. + +A.3. The Email Signature Is Verified + + The signature is normally verified by an inbound SMTP server or + possibly the final delivery agent. However, intervening MTAs can + also perform this verification if they choose to do so. The + verification process uses the domain "example.com" extracted from the + "d=" tag and the selector "brisbane" from the "s=" tag in the DKIM- + Signature header field to form the DNS DKIM query for: + + brisbane._domainkey.example.com + + Signature verification starts with the physically last Received + header field, the From header field, and so forth, in the order + listed in the "h=" tag. Verification follows with a single CRLF + followed by the body (starting with "Hi."). The email is canonically + prepared for verifying with the "simple" method. The result of the + query and subsequent verification of the signature is stored (in this + + + +Allman, et al. Standards Track [Page 61] + +RFC 4871 DKIM Signatures May 2007 + + + example) in the X-Authentication-Results header field line. After + successful verification, the email looks like this: + + X-Authentication-Results: shopping.example.net + header.from=joe@football.example.com; dkim=pass + Received: from mout23.football.example.com (192.168.1.1) + by shopping.example.net with SMTP; + Fri, 11 Jul 2003 21:01:59 -0700 (PDT) + DKIM-Signature: v=1; a=rsa-sha256; s=brisbane; d=example.com; + c=simple/simple; q=dns/txt; i=joe@football.example.com; + h=Received : From : To : Subject : Date : Message-ID; + bh=2jUSOH9NhtVGCQWNr9BrIAPreKQjO6Sn7XIkfJVOzv8=; + b=AuUoFEfDxTDkHlLXSZEpZj79LICEps6eda7W3deTVFOk4yAUoqOB + 4nujc7YopdG5dWLSdNg6xNAZpOPr+kHxt1IrE+NahM6L/LbvaHut + KVdkLLkpVaVVQPzeRDI009SO2Il5Lu7rDNH6mZckBdrIx0orEtZV + 4bmp/YzhwvcubU4=; + Received: from client1.football.example.com [192.0.2.1] + by submitserver.example.com with SUBMISSION; + Fri, 11 Jul 2003 21:01:54 -0700 (PDT) + From: Joe SixPack + To: Suzie Q + Subject: Is dinner ready? + Date: Fri, 11 Jul 2003 21:00:37 -0700 (PDT) + Message-ID: <20030712040037.46341.5F8J@football.example.com> + + Hi. + + We lost the game. Are you hungry yet? + + Joe. + +Appendix B. Usage Examples (INFORMATIVE) + + DKIM signing and validating can be used in different ways, for + different operational scenarios. This Appendix discusses some common + examples. + + NOTE: Descriptions in this Appendix are for informational purposes + only. They describe various ways that DKIM can be used, given + particular constraints and needs. In no case are these examples + intended to be taken as providing explanation or guidance + concerning DKIM specification details, when creating an + implementation. + + + + + + + + +Allman, et al. Standards Track [Page 62] + +RFC 4871 DKIM Signatures May 2007 + + +B.1. Alternate Submission Scenarios + + In the most simple scenario, a user's MUA, MSA, and Internet + (boundary) MTA are all within the same administrative environment, + using the same domain name. Therefore, all of the components + involved in submission and initial transfer are related. However, it + is common for two or more of the components to be under independent + administrative control. This creates challenges for choosing and + administering the domain name to use for signing, and for its + relationship to common email identity header fields. + +B.1.1. Delegated Business Functions + + Some organizations assign specific business functions to discrete + groups, inside or outside the organization. The goal, then, is to + authorize that group to sign some mail, but to constrain what + signatures they can generate. DKIM selectors (the "s=" signature + tag) and granularity (the "g=" key tag) facilitate this kind of + restricted authorization. Examples of these outsourced business + functions are legitimate email marketing providers and corporate + benefits providers. + + Here, the delegated group needs to be able to send messages that are + signed, using the email domain of the client company. At the same + time, the client often is reluctant to register a key for the + provider that grants the ability to send messages for arbitrary + addresses in the domain. + + There are multiple ways to administer these usage scenarios. In one + case, the client organization provides all of the public query + service (for example, DNS) administration, and in another it uses DNS + delegation to enable all ongoing administration of the DKIM key + record by the delegated group. + + If the client organization retains responsibility for all of the DNS + administration, the outsourcing company can generate a key pair, + supplying the public key to the client company, which then registers + it in the query service, using a unique selector that authorizes a + specific From header field Local-part. For example, a client with + the domain "example.com" could have the selector record specify + "g=winter-promotions" so that this signature is only valid for mail + with a From address of "winter-promotions@example.com". This would + enable the provider to send messages using that specific address and + have them verify properly. The client company retains control over + the email address because it retains the ability to revoke the key at + any time. + + + + + +Allman, et al. Standards Track [Page 63] + +RFC 4871 DKIM Signatures May 2007 + + + If the client wants the delegated group to do the DNS administration, + it can have the domain name that is specified with the selector point + to the provider's DNS server. The provider then creates and + maintains all of the DKIM signature information for that selector. + Hence, the client cannot provide constraints on the Local-part of + addresses that get signed, but it can revoke the provider's signing + rights by removing the DNS delegation record. + +B.1.2. PDAs and Similar Devices + + PDAs demonstrate the need for using multiple keys per domain. + Suppose that John Doe wanted to be able to send messages using his + corporate email address, jdoe@example.com, and his email device did + not have the ability to make a Virtual Private Network (VPN) + connection to the corporate network, either because the device is + limited or because there are restrictions enforced by his Internet + access provider. If the device was equipped with a private key + registered for jdoe@example.com by the administrator of the + example.com domain, and appropriate software to sign messages, John + could sign the message on the device itself before transmission + through the outgoing network of the access service provider. + +B.1.3. Roaming Users + + Roaming users often find themselves in circumstances where it is + convenient or necessary to use an SMTP server other than their home + server; examples are conferences and many hotels. In such + circumstances, a signature that is added by the submission service + will use an identity that is different from the user's home system. + + Ideally, roaming users would connect back to their home server using + either a VPN or a SUBMISSION server running with SMTP AUTHentication + on port 587. If the signing can be performed on the roaming user's + laptop, then they can sign before submission, although the risk of + further modification is high. If neither of these are possible, + these roaming users will not be able to send mail signed using their + own domain key. + +B.1.4. Independent (Kiosk) Message Submission + + Stand-alone services, such as walk-up kiosks and web-based + information services, have no enduring email service relationship + with the user, but users occasionally request that mail be sent on + their behalf. For example, a website providing news often allows the + reader to forward a copy of the article to a friend. This is + typically done using the reader's own email address, to indicate who + the author is. This is sometimes referred to as the "Evite problem", + + + + +Allman, et al. Standards Track [Page 64] + +RFC 4871 DKIM Signatures May 2007 + + + named after the website of the same name that allows a user to send + invitations to friends. + + A common way this is handled is to continue to put the reader's email + address in the From header field of the message, but put an address + owned by the email posting site into the Sender header field. The + posting site can then sign the message, using the domain that is in + the Sender field. This provides useful information to the receiving + email site, which is able to correlate the signing domain with the + initial submission email role. + + Receiving sites often wish to provide their end users with + information about mail that is mediated in this fashion. Although + the real efficacy of different approaches is a subject for human + factors usability research, one technique that is used is for the + verifying system to rewrite the From header field, to indicate the + address that was verified. For example: From: John Doe via + news@news-site.com . (Note that such rewriting + will break a signature, unless it is done after the verification pass + is complete.) + +B.2. Alternate Delivery Scenarios + + Email is often received at a mailbox that has an address different + from the one used during initial submission. In these cases, an + intermediary mechanism operates at the address originally used and it + then passes the message on to the final destination. This mediation + process presents some challenges for DKIM signatures. + +B.2.1. Affinity Addresses + + "Affinity addresses" allow a user to have an email address that + remains stable, even as the user moves among different email + providers. They are typically associated with college alumni + associations, professional organizations, and recreational + organizations with which they expect to have a long-term + relationship. These domains usually provide forwarding of incoming + email, and they often have an associated Web application that + authenticates the user and allows the forwarding address to be + changed. However, these services usually depend on users sending + outgoing messages through their own service providers' MTAs. Hence, + mail that is signed with the domain of the affinity address is not + signed by an entity that is administered by the organization owning + that domain. + + With DKIM, affinity domains could use the Web application to allow + users to register per-user keys to be used to sign messages on behalf + of their affinity address. The user would take away the secret half + + + +Allman, et al. Standards Track [Page 65] + +RFC 4871 DKIM Signatures May 2007 + + + of the key pair for signing, and the affinity domain would publish + the public half in DNS for access by verifiers. + + This is another application that takes advantage of user-level + keying, and domains used for affinity addresses would typically have + a very large number of user-level keys. Alternatively, the affinity + domain could handle outgoing mail, operating a mail submission agent + that authenticates users before accepting and signing messages for + them. This is of course dependent on the user's service provider not + blocking the relevant TCP ports used for mail submission. + +B.2.2. Simple Address Aliasing (.forward) + + In some cases, a recipient is allowed to configure an email address + to cause automatic redirection of email messages from the original + address to another, such as through the use of a Unix .forward file. + In this case, messages are typically redirected by the mail handling + service of the recipient's domain, without modification, except for + the addition of a Received header field to the message and a change + in the envelope recipient address. In this case, the recipient at + the final address' mailbox is likely to be able to verify the + original signature since the signed content has not changed, and DKIM + is able to validate the message signature. + +B.2.3. Mailing Lists and Re-Posters + + There is a wide range of behaviors in services that take delivery of + a message and then resubmit it. A primary example is with mailing + lists (collectively called "forwarders" below), ranging from those + that make no modification to the message itself, other than to add a + Received header field and change the envelope information, to those + that add header fields, change the Subject header field, add content + to the body (typically at the end), or reformat the body in some + manner. The simple ones produce messages that are quite similar to + the automated alias services. More elaborate systems essentially + create a new message. + + A Forwarder that does not modify the body or signed header fields of + a message is likely to maintain the validity of the existing + signature. It also could choose to add its own signature to the + message. + + Forwarders which modify a message in a way that could make an + existing signature invalid are particularly good candidates for + adding their own signatures (e.g., mailing-list-name@example.net). + Since (re-)signing is taking responsibility for the content of the + message, these signing forwarders are likely to be selective, and + forward or re-sign a message only if it is received with a valid + + + +Allman, et al. Standards Track [Page 66] + +RFC 4871 DKIM Signatures May 2007 + + + signature or if they have some other basis for knowing that the + message is not spoofed. + + A common practice among systems that are primarily redistributors of + mail is to add a Sender header field to the message, to identify the + address being used to sign the message. This practice will remove + any preexisting Sender header field as required by [RFC2822]. The + forwarder applies a new DKIM-Signature header field with the + signature, public key, and related information of the forwarder. + +Appendix C. Creating a Public Key (INFORMATIVE) + + The default signature is an RSA signed SHA256 digest of the complete + email. For ease of explanation, the openssl command is used to + describe the mechanism by which keys and signatures are managed. One + way to generate a 1024-bit, unencrypted private key suitable for DKIM + is to use openssl like this: + + $ openssl genrsa -out rsa.private 1024 + + For increased security, the "-passin" parameter can also be added to + encrypt the private key. Use of this parameter will require entering + a password for several of the following steps. Servers may prefer to + use hardware cryptographic support. + + The "genrsa" step results in the file rsa.private containing the key + information similar to this: + + -----BEGIN RSA PRIVATE KEY----- + MIICXwIBAAKBgQDwIRP/UC3SBsEmGqZ9ZJW3/DkMoGeLnQg1fWn7/zYtIxN2SnFC + jxOCKG9v3b4jYfcTNh5ijSsq631uBItLa7od+v/RtdC2UzJ1lWT947qR+Rcac2gb + to/NMqJ0fzfVjH4OuKhitdY9tf6mcwGjaNBcWToIMmPSPDdQPNUYckcQ2QIDAQAB + AoGBALmn+XwWk7akvkUlqb+dOxyLB9i5VBVfje89Teolwc9YJT36BGN/l4e0l6QX + /1//6DWUTB3KI6wFcm7TWJcxbS0tcKZX7FsJvUz1SbQnkS54DJck1EZO/BLa5ckJ + gAYIaqlA9C0ZwM6i58lLlPadX/rtHb7pWzeNcZHjKrjM461ZAkEA+itss2nRlmyO + n1/5yDyCluST4dQfO8kAB3toSEVc7DeFeDhnC1mZdjASZNvdHS4gbLIA1hUGEF9m + 3hKsGUMMPwJBAPW5v/U+AWTADFCS22t72NUurgzeAbzb1HWMqO4y4+9Hpjk5wvL/ + eVYizyuce3/fGke7aRYw/ADKygMJdW8H/OcCQQDz5OQb4j2QDpPZc0Nc4QlbvMsj + 7p7otWRO5xRa6SzXqqV3+F0VpqvDmshEBkoCydaYwc2o6WQ5EBmExeV8124XAkEA + qZzGsIxVP+sEVRWZmW6KNFSdVUpk3qzK0Tz/WjQMe5z0UunY9Ax9/4PVhp/j61bf + eAYXunajbBSOLlx4D+TunwJBANkPI5S9iylsbLs6NkaMHV6k5ioHBBmgCak95JGX + GMot/L2x0IYyMLAz6oLWh2hm7zwtb0CgOrPo1ke44hFYnfc= + -----END RSA PRIVATE KEY----- + + To extract the public-key component from the private key, use openssl + like this: + + $ openssl rsa -in rsa.private -out rsa.public -pubout -outform PEM + + + +Allman, et al. Standards Track [Page 67] + +RFC 4871 DKIM Signatures May 2007 + + + This results in the file rsa.public containing the key information + similar to this: + + -----BEGIN PUBLIC KEY----- + MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwIRP/UC3SBsEmGqZ9ZJW3/DkM + oGeLnQg1fWn7/zYtIxN2SnFCjxOCKG9v3b4jYfcTNh5ijSsq631uBItLa7od+v/R + tdC2UzJ1lWT947qR+Rcac2gbto/NMqJ0fzfVjH4OuKhitdY9tf6mcwGjaNBcWToI + MmPSPDdQPNUYckcQ2QIDAQAB + -----END PUBLIC KEY----- + + This public-key data (without the BEGIN and END tags) is placed in + the DNS: + + brisbane IN TXT ("v=DKIM1; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ" + "KBgQDwIRP/UC3SBsEmGqZ9ZJW3/DkMoGeLnQg1fWn7/zYt" + "IxN2SnFCjxOCKG9v3b4jYfcTNh5ijSsq631uBItLa7od+v" + "/RtdC2UzJ1lWT947qR+Rcac2gbto/NMqJ0fzfVjH4OuKhi" + "tdY9tf6mcwGjaNBcWToIMmPSPDdQPNUYckcQ2QIDAQAB") + +Appendix D. MUA Considerations + + When a DKIM signature is verified, the processing system sometimes + makes the result available to the recipient user's MUA. How to + present this information to the user in a way that helps them is a + matter of continuing human factors usability research. The tendency + is to have the MUA highlight the address associated with this signing + identity in some way, in an attempt to show the user the address from + which the mail was sent. An MUA might do this with visual cues such + as graphics, or it might include the address in an alternate view, or + it might even rewrite the original From address using the verified + information. Some MUAs might indicate which header fields were + protected by the validated DKIM signature. This could be done with a + positive indication on the signed header fields, with a negative + indication on the unsigned header fields, by visually hiding the + unsigned header fields, or some combination of these. If an MUA uses + visual indications for signed header fields, the MUA probably needs + to be careful not to display unsigned header fields in a way that + might be construed by the end user as having been signed. If the + message has an l= tag whose value does not extend to the end of the + message, the MUA might also hide or mark the portion of the message + body that was not signed. + + The aforementioned information is not intended to be exhaustive. The + MUA may choose to highlight, accentuate, hide, or otherwise display + any other information that may, in the opinion of the MUA author, be + deemed important to the end user. + + + + + +Allman, et al. Standards Track [Page 68] + +RFC 4871 DKIM Signatures May 2007 + + +Appendix E. Acknowledgements + + The authors wish to thank Russ Allbery, Edwin Aoki, Claus Assmann, + Steve Atkins, Rob Austein, Fred Baker, Mark Baugher, Steve Bellovin, + Nathaniel Borenstein, Dave Crocker, Michael Cudahy, Dennis Dayman, + Jutta Degener, Frank Ellermann, Patrik Faeltstroem, Mark Fanto, + Stephen Farrell, Duncan Findlay, Elliot Gillum, Olafur + Gu[eth]mundsson, Phillip Hallam-Baker, Tony Hansen, Sam Hartman, + Arvel Hathcock, Amir Herzberg, Paul Hoffman, Russ Housley, Craig + Hughes, Cullen Jennings, Don Johnsen, Harry Katz, Murray S. + Kucherawy, Barry Leiba, John Levine, Charles Lindsey, Simon + Longsdale, David Margrave, Justin Mason, David Mayne, Thierry Moreau, + Steve Murphy, Russell Nelson, Dave Oran, Doug Otis, Shamim Pirzada, + Juan Altmayer Pizzorno, Sanjay Pol, Blake Ramsdell, Christian Renaud, + Scott Renfro, Neil Rerup, Eric Rescorla, Dave Rossetti, Hector + Santos, Jim Schaad, the Spamhaus.org team, Malte S. Stretz, Robert + Sanders, Rand Wacker, Sam Weiler, and Dan Wing for their valuable + suggestions and constructive criticism. + + The DomainKeys specification was a primary source from which this + specification has been derived. Further information about DomainKeys + is at [RFC4870]. + +Authors' Addresses + + Eric Allman + Sendmail, Inc. + 6425 Christie Ave, Suite 400 + Emeryville, CA 94608 + USA + + Phone: +1 510 594 5501 + EMail: eric+dkim@sendmail.org + URI: + + + Jon Callas + PGP Corporation + 3460 West Bayshore + Palo Alto, CA 94303 + USA + + Phone: +1 650 319 9016 + EMail: jon@pgp.com + + + + + + + +Allman, et al. Standards Track [Page 69] + +RFC 4871 DKIM Signatures May 2007 + + + Mark Delany + Yahoo! Inc + 701 First Avenue + Sunnyvale, CA 95087 + USA + + Phone: +1 408 349 6831 + EMail: markd+dkim@yahoo-inc.com + URI: + + + Miles Libbey + Yahoo! Inc + 701 First Avenue + Sunnyvale, CA 95087 + USA + + EMail: mlibbeymail-mailsig@yahoo.com + URI: + + + Jim Fenton + Cisco Systems, Inc. + MS SJ-9/2 + 170 W. Tasman Drive + San Jose, CA 95134-1706 + USA + + Phone: +1 408 526 5914 + EMail: fenton@cisco.com + URI: + + + Michael Thomas + Cisco Systems, Inc. + MS SJ-9/2 + 170 W. Tasman Drive + San Jose, CA 95134-1706 + + Phone: +1 408 525 5386 + EMail: mat@cisco.com + + + + + + + + + + +Allman, et al. Standards Track [Page 70] + +RFC 4871 DKIM Signatures May 2007 + + +Full Copyright Statement + + Copyright (C) The IETF Trust (2007). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND + THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF + THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + +Allman, et al. Standards Track [Page 71] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4880.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4880.txt new file mode 100644 index 00000000..0db94537 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4880.txt @@ -0,0 +1,5042 @@ + + + + + +Network Working Group J. Callas +Request for Comments: 4880 PGP Corporation +Obsoletes: 1991, 2440 L. Donnerhacke +Category: Standards Track IKS GmbH + H. Finney + PGP Corporation + D. Shaw + R. Thayer + November 2007 + + + OpenPGP Message Format + +Status of This Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Abstract + + This document is maintained in order to publish all necessary + information needed to develop interoperable applications based on the + OpenPGP format. It is not a step-by-step cookbook for writing an + application. It describes only the format and methods needed to + read, check, generate, and write conforming packets crossing any + network. It does not deal with storage and implementation questions. + It does, however, discuss implementation issues necessary to avoid + security flaws. + + OpenPGP software uses a combination of strong public-key and + symmetric cryptography to provide security services for electronic + communications and data storage. These services include + confidentiality, key management, authentication, and digital + signatures. This document specifies the message formats used in + OpenPGP. + + + + + + + + + + + + + +Callas, et al Standards Track [Page 1] + +RFC 4880 OpenPGP Message Format November 2007 + + +Table of Contents + + 1. Introduction ....................................................5 + 1.1. Terms ......................................................5 + 2. General functions ...............................................6 + 2.1. Confidentiality via Encryption .............................6 + 2.2. Authentication via Digital Signature .......................7 + 2.3. Compression ................................................7 + 2.4. Conversion to Radix-64 .....................................8 + 2.5. Signature-Only Applications ................................8 + 3. Data Element Formats ............................................8 + 3.1. Scalar Numbers .............................................8 + 3.2. Multiprecision Integers ....................................9 + 3.3. Key IDs ....................................................9 + 3.4. Text .......................................................9 + 3.5. Time Fields ...............................................10 + 3.6. Keyrings ..................................................10 + 3.7. String-to-Key (S2K) Specifiers ............................10 + 3.7.1. String-to-Key (S2K) Specifier Types ................10 + 3.7.1.1. Simple S2K ................................10 + 3.7.1.2. Salted S2K ................................11 + 3.7.1.3. Iterated and Salted S2K ...................11 + 3.7.2. String-to-Key Usage ................................12 + 3.7.2.1. Secret-Key Encryption .....................12 + 3.7.2.2. Symmetric-Key Message Encryption ..........13 + 4. Packet Syntax ..................................................13 + 4.1. Overview ..................................................13 + 4.2. Packet Headers ............................................13 + 4.2.1. Old Format Packet Lengths ..........................14 + 4.2.2. New Format Packet Lengths ..........................15 + 4.2.2.1. One-Octet Lengths .........................15 + 4.2.2.2. Two-Octet Lengths .........................15 + 4.2.2.3. Five-Octet Lengths ........................15 + 4.2.2.4. Partial Body Lengths ......................16 + 4.2.3. Packet Length Examples .............................16 + 4.3. Packet Tags ...............................................17 + 5. Packet Types ...................................................17 + 5.1. Public-Key Encrypted Session Key Packets (Tag 1) ..........17 + 5.2. Signature Packet (Tag 2) ..................................19 + 5.2.1. Signature Types ....................................19 + 5.2.2. Version 3 Signature Packet Format ..................21 + 5.2.3. Version 4 Signature Packet Format ..................24 + 5.2.3.1. Signature Subpacket Specification .........25 + 5.2.3.2. Signature Subpacket Types .................27 + 5.2.3.3. Notes on Self-Signatures ..................27 + 5.2.3.4. Signature Creation Time ...................28 + 5.2.3.5. Issuer ....................................28 + 5.2.3.6. Key Expiration Time .......................28 + + + +Callas, et al Standards Track [Page 2] + +RFC 4880 OpenPGP Message Format November 2007 + + + 5.2.3.7. Preferred Symmetric Algorithms ............28 + 5.2.3.8. Preferred Hash Algorithms .................29 + 5.2.3.9. Preferred Compression Algorithms ..........29 + 5.2.3.10. Signature Expiration Time ................29 + 5.2.3.11. Exportable Certification .................29 + 5.2.3.12. Revocable ................................30 + 5.2.3.13. Trust Signature ..........................30 + 5.2.3.14. Regular Expression .......................31 + 5.2.3.15. Revocation Key ...........................31 + 5.2.3.16. Notation Data ............................31 + 5.2.3.17. Key Server Preferences ...................32 + 5.2.3.18. Preferred Key Server .....................33 + 5.2.3.19. Primary User ID ..........................33 + 5.2.3.20. Policy URI ...............................33 + 5.2.3.21. Key Flags ................................33 + 5.2.3.22. Signer's User ID .........................34 + 5.2.3.23. Reason for Revocation ....................35 + 5.2.3.24. Features .................................36 + 5.2.3.25. Signature Target .........................36 + 5.2.3.26. Embedded Signature .......................37 + 5.2.4. Computing Signatures ...............................37 + 5.2.4.1. Subpacket Hints ...........................38 + 5.3. Symmetric-Key Encrypted Session Key Packets (Tag 3) .......38 + 5.4. One-Pass Signature Packets (Tag 4) ........................39 + 5.5. Key Material Packet .......................................40 + 5.5.1. Key Packet Variants ................................40 + 5.5.1.1. Public-Key Packet (Tag 6) .................40 + 5.5.1.2. Public-Subkey Packet (Tag 14) .............40 + 5.5.1.3. Secret-Key Packet (Tag 5) .................41 + 5.5.1.4. Secret-Subkey Packet (Tag 7) ..............41 + 5.5.2. Public-Key Packet Formats ..........................41 + 5.5.3. Secret-Key Packet Formats ..........................43 + 5.6. Compressed Data Packet (Tag 8) ............................45 + 5.7. Symmetrically Encrypted Data Packet (Tag 9) ...............45 + 5.8. Marker Packet (Obsolete Literal Packet) (Tag 10) ..........46 + 5.9. Literal Data Packet (Tag 11) ..............................46 + 5.10. Trust Packet (Tag 12) ....................................47 + 5.11. User ID Packet (Tag 13) ..................................48 + 5.12. User Attribute Packet (Tag 17) ...........................48 + 5.12.1. The Image Attribute Subpacket .....................48 + 5.13. Sym. Encrypted Integrity Protected Data Packet (Tag 18) ..49 + 5.14. Modification Detection Code Packet (Tag 19) ..............52 + 6. Radix-64 Conversions ...........................................53 + 6.1. An Implementation of the CRC-24 in "C" ....................54 + 6.2. Forming ASCII Armor .......................................54 + 6.3. Encoding Binary in Radix-64 ...............................57 + 6.4. Decoding Radix-64 .........................................58 + 6.5. Examples of Radix-64 ......................................59 + + + +Callas, et al Standards Track [Page 3] + +RFC 4880 OpenPGP Message Format November 2007 + + + 6.6. Example of an ASCII Armored Message .......................59 + 7. Cleartext Signature Framework ..................................59 + 7.1. Dash-Escaped Text .........................................60 + 8. Regular Expressions ............................................61 + 9. Constants ......................................................61 + 9.1. Public-Key Algorithms .....................................62 + 9.2. Symmetric-Key Algorithms ..................................62 + 9.3. Compression Algorithms ....................................63 + 9.4. Hash Algorithms ...........................................63 + 10. IANA Considerations ...........................................63 + 10.1. New String-to-Key Specifier Types ........................64 + 10.2. New Packets ..............................................64 + 10.2.1. User Attribute Types ..............................64 + 10.2.1.1. Image Format Subpacket Types .............64 + 10.2.2. New Signature Subpackets ..........................64 + 10.2.2.1. Signature Notation Data Subpackets .......65 + 10.2.2.2. Key Server Preference Extensions .........65 + 10.2.2.3. Key Flags Extensions .....................65 + 10.2.2.4. Reason For Revocation Extensions .........65 + 10.2.2.5. Implementation Features ..................66 + 10.2.3. New Packet Versions ...............................66 + 10.3. New Algorithms ...........................................66 + 10.3.1. Public-Key Algorithms .............................66 + 10.3.2. Symmetric-Key Algorithms ..........................67 + 10.3.3. Hash Algorithms ...................................67 + 10.3.4. Compression Algorithms ............................67 + 11. Packet Composition ............................................67 + 11.1. Transferable Public Keys .................................67 + 11.2. Transferable Secret Keys .................................69 + 11.3. OpenPGP Messages .........................................69 + 11.4. Detached Signatures ......................................70 + 12. Enhanced Key Formats ..........................................70 + 12.1. Key Structures ...........................................70 + 12.2. Key IDs and Fingerprints .................................71 + 13. Notes on Algorithms ...........................................72 + 13.1. PKCS#1 Encoding in OpenPGP ...............................72 + 13.1.1. EME-PKCS1-v1_5-ENCODE .............................73 + 13.1.2. EME-PKCS1-v1_5-DECODE .............................73 + 13.1.3. EMSA-PKCS1-v1_5 ...................................74 + 13.2. Symmetric Algorithm Preferences ..........................75 + 13.3. Other Algorithm Preferences ..............................76 + 13.3.1. Compression Preferences ...........................76 + 13.3.2. Hash Algorithm Preferences ........................76 + 13.4. Plaintext ................................................77 + 13.5. RSA ......................................................77 + 13.6. DSA ......................................................77 + 13.7. Elgamal ..................................................78 + 13.8. Reserved Algorithm Numbers ...............................78 + + + +Callas, et al Standards Track [Page 4] + +RFC 4880 OpenPGP Message Format November 2007 + + + 13.9. OpenPGP CFB Mode .........................................78 + 13.10. Private or Experimental Parameters ......................79 + 13.11. Extension of the MDC System .............................80 + 13.12. Meta-Considerations for Expansion .......................80 + 14. Security Considerations .......................................81 + 15. Implementation Nits ...........................................84 + 16. References ....................................................86 + 16.1. Normative References .....................................86 + 16.2. Informative References ...................................88 + +1. Introduction + + This document provides information on the message-exchange packet + formats used by OpenPGP to provide encryption, decryption, signing, + and key management functions. It is a revision of RFC 2440, "OpenPGP + Message Format", which itself replaces RFC 1991, "PGP Message + Exchange Formats" [RFC1991] [RFC2440]. + +1.1. Terms + + * OpenPGP - This is a term for security software that uses PGP 5.x + as a basis, formalized in RFC 2440 and this document. + + * PGP - Pretty Good Privacy. PGP is a family of software systems + developed by Philip R. Zimmermann from which OpenPGP is based. + + * PGP 2.6.x - This version of PGP has many variants, hence the term + PGP 2.6.x. It used only RSA, MD5, and IDEA for its cryptographic + transforms. An informational RFC, RFC 1991, was written + describing this version of PGP. + + * PGP 5.x - This version of PGP is formerly known as "PGP 3" in the + community and also in the predecessor of this document, RFC 1991. + It has new formats and corrects a number of problems in the PGP + 2.6.x design. It is referred to here as PGP 5.x because that + software was the first release of the "PGP 3" code base. + + * GnuPG - GNU Privacy Guard, also called GPG. GnuPG is an OpenPGP + implementation that avoids all encumbered algorithms. + Consequently, early versions of GnuPG did not include RSA public + keys. GnuPG may or may not have (depending on version) support + for IDEA or other encumbered algorithms. + + "PGP", "Pretty Good", and "Pretty Good Privacy" are trademarks of PGP + Corporation and are used with permission. The term "OpenPGP" refers + to the protocol described in this and related documents. + + + + + +Callas, et al Standards Track [Page 5] + +RFC 4880 OpenPGP Message Format November 2007 + + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [RFC2119]. + + The key words "PRIVATE USE", "HIERARCHICAL ALLOCATION", "FIRST COME + FIRST SERVED", "EXPERT REVIEW", "SPECIFICATION REQUIRED", "IESG + APPROVAL", "IETF CONSENSUS", and "STANDARDS ACTION" that appear in + this document when used to describe namespace allocation are to be + interpreted as described in [RFC2434]. + +2. General functions + + OpenPGP provides data integrity services for messages and data files + by using these core technologies: + + - digital signatures + + - encryption + + - compression + + - Radix-64 conversion + + In addition, OpenPGP provides key management and certificate + services, but many of these are beyond the scope of this document. + +2.1. Confidentiality via Encryption + + OpenPGP combines symmetric-key encryption and public-key encryption + to provide confidentiality. When made confidential, first the object + is encrypted using a symmetric encryption algorithm. Each symmetric + key is used only once, for a single object. A new "session key" is + generated as a random number for each object (sometimes referred to + as a session). Since it is used only once, the session key is bound + to the message and transmitted with it. To protect the key, it is + encrypted with the receiver's public key. The sequence is as + follows: + + 1. The sender creates a message. + + 2. The sending OpenPGP generates a random number to be used as a + session key for this message only. + + 3. The session key is encrypted using each recipient's public key. + These "encrypted session keys" start the message. + + + + + + +Callas, et al Standards Track [Page 6] + +RFC 4880 OpenPGP Message Format November 2007 + + + 4. The sending OpenPGP encrypts the message using the session key, + which forms the remainder of the message. Note that the message + is also usually compressed. + + 5. The receiving OpenPGP decrypts the session key using the + recipient's private key. + + 6. The receiving OpenPGP decrypts the message using the session key. + If the message was compressed, it will be decompressed. + + With symmetric-key encryption, an object may be encrypted with a + symmetric key derived from a passphrase (or other shared secret), or + a two-stage mechanism similar to the public-key method described + above in which a session key is itself encrypted with a symmetric + algorithm keyed from a shared secret. + + Both digital signature and confidentiality services may be applied to + the same message. First, a signature is generated for the message + and attached to the message. Then the message plus signature is + encrypted using a symmetric session key. Finally, the session key is + encrypted using public-key encryption and prefixed to the encrypted + block. + +2.2. Authentication via Digital Signature + + The digital signature uses a hash code or message digest algorithm, + and a public-key signature algorithm. The sequence is as follows: + + 1. The sender creates a message. + + 2. The sending software generates a hash code of the message. + + 3. The sending software generates a signature from the hash code + using the sender's private key. + + 4. The binary signature is attached to the message. + + 5. The receiving software keeps a copy of the message signature. + + 6. The receiving software generates a new hash code for the received + message and verifies it using the message's signature. If the + verification is successful, the message is accepted as authentic. + +2.3. Compression + + OpenPGP implementations SHOULD compress the message after applying + the signature but before encryption. + + + + +Callas, et al Standards Track [Page 7] + +RFC 4880 OpenPGP Message Format November 2007 + + + If an implementation does not implement compression, its authors + should be aware that most OpenPGP messages in the world are + compressed. Thus, it may even be wise for a space-constrained + implementation to implement decompression, but not compression. + + Furthermore, compression has the added side effect that some types of + attacks can be thwarted by the fact that slightly altered, compressed + data rarely uncompresses without severe errors. This is hardly + rigorous, but it is operationally useful. These attacks can be + rigorously prevented by implementing and using Modification Detection + Codes as described in sections following. + +2.4. Conversion to Radix-64 + + OpenPGP's underlying native representation for encrypted messages, + signature certificates, and keys is a stream of arbitrary octets. + Some systems only permit the use of blocks consisting of seven-bit, + printable text. For transporting OpenPGP's native raw binary octets + through channels that are not safe to raw binary data, a printable + encoding of these binary octets is needed. OpenPGP provides the + service of converting the raw 8-bit binary octet stream to a stream + of printable ASCII characters, called Radix-64 encoding or ASCII + Armor. + + Implementations SHOULD provide Radix-64 conversions. + +2.5. Signature-Only Applications + + OpenPGP is designed for applications that use both encryption and + signatures, but there are a number of problems that are solved by a + signature-only implementation. Although this specification requires + both encryption and signatures, it is reasonable for there to be + subset implementations that are non-conformant only in that they omit + encryption. + +3. Data Element Formats + + This section describes the data elements used by OpenPGP. + +3.1. Scalar Numbers + + Scalar numbers are unsigned and are always stored in big-endian + format. Using n[k] to refer to the kth octet being interpreted, the + value of a two-octet scalar is ((n[0] << 8) + n[1]). The value of a + four-octet scalar is ((n[0] << 24) + (n[1] << 16) + (n[2] << 8) + + n[3]). + + + + + +Callas, et al Standards Track [Page 8] + +RFC 4880 OpenPGP Message Format November 2007 + + +3.2. Multiprecision Integers + + Multiprecision integers (also called MPIs) are unsigned integers used + to hold large integers such as the ones used in cryptographic + calculations. + + An MPI consists of two pieces: a two-octet scalar that is the length + of the MPI in bits followed by a string of octets that contain the + actual integer. + + These octets form a big-endian number; a big-endian number can be + made into an MPI by prefixing it with the appropriate length. + + Examples: + + (all numbers are in hexadecimal) + + The string of octets [00 01 01] forms an MPI with the value 1. The + string [00 09 01 FF] forms an MPI with the value of 511. + + Additional rules: + + The size of an MPI is ((MPI.length + 7) / 8) + 2 octets. + + The length field of an MPI describes the length starting from its + most significant non-zero bit. Thus, the MPI [00 02 01] is not + formed correctly. It should be [00 01 01]. + + Unused bits of an MPI MUST be zero. + + Also note that when an MPI is encrypted, the length refers to the + plaintext MPI. It may be ill-formed in its ciphertext. + +3.3. Key IDs + + A Key ID is an eight-octet scalar that identifies a key. + Implementations SHOULD NOT assume that Key IDs are unique. The + section "Enhanced Key Formats" below describes how Key IDs are + formed. + +3.4. Text + + Unless otherwise specified, the character set for text is the UTF-8 + [RFC3629] encoding of Unicode [ISO10646]. + + + + + + + +Callas, et al Standards Track [Page 9] + +RFC 4880 OpenPGP Message Format November 2007 + + +3.5. Time Fields + + A time field is an unsigned four-octet number containing the number + of seconds elapsed since midnight, 1 January 1970 UTC. + +3.6. Keyrings + + A keyring is a collection of one or more keys in a file or database. + Traditionally, a keyring is simply a sequential list of keys, but may + be any suitable database. It is beyond the scope of this standard to + discuss the details of keyrings or other databases. + +3.7. String-to-Key (S2K) Specifiers + + String-to-key (S2K) specifiers are used to convert passphrase strings + into symmetric-key encryption/decryption keys. They are used in two + places, currently: to encrypt the secret part of private keys in the + private keyring, and to convert passphrases to encryption keys for + symmetrically encrypted messages. + +3.7.1. String-to-Key (S2K) Specifier Types + + There are three types of S2K specifiers currently supported, and + some reserved values: + + ID S2K Type + -- -------- + 0 Simple S2K + 1 Salted S2K + 2 Reserved value + 3 Iterated and Salted S2K + 100 to 110 Private/Experimental S2K + + These are described in Sections 3.7.1.1 - 3.7.1.3. + +3.7.1.1. Simple S2K + + This directly hashes the string to produce the key data. See below + for how this hashing is done. + + Octet 0: 0x00 + Octet 1: hash algorithm + + Simple S2K hashes the passphrase to produce the session key. The + manner in which this is done depends on the size of the session key + (which will depend on the cipher used) and the size of the hash + + + + + +Callas, et al Standards Track [Page 10] + +RFC 4880 OpenPGP Message Format November 2007 + + + algorithm's output. If the hash size is greater than the session key + size, the high-order (leftmost) octets of the hash are used as the + key. + + If the hash size is less than the key size, multiple instances of the + hash context are created -- enough to produce the required key data. + These instances are preloaded with 0, 1, 2, ... octets of zeros (that + is to say, the first instance has no preloading, the second gets + preloaded with 1 octet of zero, the third is preloaded with two + octets of zeros, and so forth). + + As the data is hashed, it is given independently to each hash + context. Since the contexts have been initialized differently, they + will each produce different hash output. Once the passphrase is + hashed, the output data from the multiple hashes is concatenated, + first hash leftmost, to produce the key data, with any excess octets + on the right discarded. + +3.7.1.2. Salted S2K + + This includes a "salt" value in the S2K specifier -- some arbitrary + data -- that gets hashed along with the passphrase string, to help + prevent dictionary attacks. + + Octet 0: 0x01 + Octet 1: hash algorithm + Octets 2-9: 8-octet salt value + + Salted S2K is exactly like Simple S2K, except that the input to the + hash function(s) consists of the 8 octets of salt from the S2K + specifier, followed by the passphrase. + +3.7.1.3. Iterated and Salted S2K + + This includes both a salt and an octet count. The salt is combined + with the passphrase and the resulting value is hashed repeatedly. + This further increases the amount of work an attacker must do to try + dictionary attacks. + + Octet 0: 0x03 + Octet 1: hash algorithm + Octets 2-9: 8-octet salt value + Octet 10: count, a one-octet, coded value + + + + + + + + +Callas, et al Standards Track [Page 11] + +RFC 4880 OpenPGP Message Format November 2007 + + + The count is coded into a one-octet number using the following + formula: + + #define EXPBIAS 6 + count = ((Int32)16 + (c & 15)) << ((c >> 4) + EXPBIAS); + + The above formula is in C, where "Int32" is a type for a 32-bit + integer, and the variable "c" is the coded count, Octet 10. + + Iterated-Salted S2K hashes the passphrase and salt data multiple + times. The total number of octets to be hashed is specified in the + encoded count in the S2K specifier. Note that the resulting count + value is an octet count of how many octets will be hashed, not an + iteration count. + + Initially, one or more hash contexts are set up as with the other S2K + algorithms, depending on how many octets of key data are needed. + Then the salt, followed by the passphrase data, is repeatedly hashed + until the number of octets specified by the octet count has been + hashed. The one exception is that if the octet count is less than + the size of the salt plus passphrase, the full salt plus passphrase + will be hashed even though that is greater than the octet count. + After the hashing is done, the data is unloaded from the hash + context(s) as with the other S2K algorithms. + +3.7.2. String-to-Key Usage + + Implementations SHOULD use salted or iterated-and-salted S2K + specifiers, as simple S2K specifiers are more vulnerable to + dictionary attacks. + +3.7.2.1. Secret-Key Encryption + + An S2K specifier can be stored in the secret keyring to specify how + to convert the passphrase to a key that unlocks the secret data. + Older versions of PGP just stored a cipher algorithm octet preceding + the secret data or a zero to indicate that the secret data was + unencrypted. The MD5 hash function was always used to convert the + passphrase to a key for the specified cipher algorithm. + + For compatibility, when an S2K specifier is used, the special value + 254 or 255 is stored in the position where the hash algorithm octet + would have been in the old data structure. This is then followed + immediately by a one-octet algorithm identifier, and then by the S2K + specifier as encoded above. + + + + + + +Callas, et al Standards Track [Page 12] + +RFC 4880 OpenPGP Message Format November 2007 + + + Therefore, preceding the secret data there will be one of these + possibilities: + + 0: secret data is unencrypted (no passphrase) + 255 or 254: followed by algorithm octet and S2K specifier + Cipher alg: use Simple S2K algorithm using MD5 hash + + This last possibility, the cipher algorithm number with an implicit + use of MD5 and IDEA, is provided for backward compatibility; it MAY + be understood, but SHOULD NOT be generated, and is deprecated. + + These are followed by an Initial Vector of the same length as the + block size of the cipher for the decryption of the secret values, if + they are encrypted, and then the secret-key values themselves. + +3.7.2.2. Symmetric-Key Message Encryption + + OpenPGP can create a Symmetric-key Encrypted Session Key (ESK) packet + at the front of a message. This is used to allow S2K specifiers to + be used for the passphrase conversion or to create messages with a + mix of symmetric-key ESKs and public-key ESKs. This allows a message + to be decrypted either with a passphrase or a public-key pair. + + PGP 2.X always used IDEA with Simple string-to-key conversion when + encrypting a message with a symmetric algorithm. This is deprecated, + but MAY be used for backward-compatibility. + +4. Packet Syntax + + This section describes the packets used by OpenPGP. + +4.1. Overview + + An OpenPGP message is constructed from a number of records that are + traditionally called packets. A packet is a chunk of data that has a + tag specifying its meaning. An OpenPGP message, keyring, + certificate, and so forth consists of a number of packets. Some of + those packets may contain other OpenPGP packets (for example, a + compressed data packet, when uncompressed, contains OpenPGP packets). + + Each packet consists of a packet header, followed by the packet body. + The packet header is of variable length. + +4.2. Packet Headers + + The first octet of the packet header is called the "Packet Tag". It + determines the format of the header and denotes the packet contents. + The remainder of the packet header is the length of the packet. + + + +Callas, et al Standards Track [Page 13] + +RFC 4880 OpenPGP Message Format November 2007 + + + Note that the most significant bit is the leftmost bit, called bit 7. + A mask for this bit is 0x80 in hexadecimal. + + +---------------+ + PTag |7 6 5 4 3 2 1 0| + +---------------+ + Bit 7 -- Always one + Bit 6 -- New packet format if set + + PGP 2.6.x only uses old format packets. Thus, software that + interoperates with those versions of PGP must only use old format + packets. If interoperability is not an issue, the new packet format + is RECOMMENDED. Note that old format packets have four bits of + packet tags, and new format packets have six; some features cannot be + used and still be backward-compatible. + + Also note that packets with a tag greater than or equal to 16 MUST + use new format packets. The old format packets can only express tags + less than or equal to 15. + + Old format packets contain: + + Bits 5-2 -- packet tag + Bits 1-0 -- length-type + + New format packets contain: + + Bits 5-0 -- packet tag + +4.2.1. Old Format Packet Lengths + + The meaning of the length-type in old format packets is: + + 0 - The packet has a one-octet length. The header is 2 octets long. + + 1 - The packet has a two-octet length. The header is 3 octets long. + + 2 - The packet has a four-octet length. The header is 5 octets long. + + 3 - The packet is of indeterminate length. The header is 1 octet + long, and the implementation must determine how long the packet + is. If the packet is in a file, this means that the packet + extends until the end of the file. In general, an implementation + SHOULD NOT use indeterminate-length packets except where the end + of the data will be clear from the context, and even then it is + better to use a definite length, or a new format header. The new + format headers described below have a mechanism for precisely + encoding data of indeterminate length. + + + +Callas, et al Standards Track [Page 14] + +RFC 4880 OpenPGP Message Format November 2007 + + +4.2.2. New Format Packet Lengths + + New format packets have four possible ways of encoding length: + + 1. A one-octet Body Length header encodes packet lengths of up to 191 + octets. + + 2. A two-octet Body Length header encodes packet lengths of 192 to + 8383 octets. + + 3. A five-octet Body Length header encodes packet lengths of up to + 4,294,967,295 (0xFFFFFFFF) octets in length. (This actually + encodes a four-octet scalar number.) + + 4. When the length of the packet body is not known in advance by the + issuer, Partial Body Length headers encode a packet of + indeterminate length, effectively making it a stream. + +4.2.2.1. One-Octet Lengths + + A one-octet Body Length header encodes a length of 0 to 191 octets. + This type of length header is recognized because the one octet value + is less than 192. The body length is equal to: + + bodyLen = 1st_octet; + +4.2.2.2. Two-Octet Lengths + + A two-octet Body Length header encodes a length of 192 to 8383 + octets. It is recognized because its first octet is in the range 192 + to 223. The body length is equal to: + + bodyLen = ((1st_octet - 192) << 8) + (2nd_octet) + 192 + +4.2.2.3. Five-Octet Lengths + + A five-octet Body Length header consists of a single octet holding + the value 255, followed by a four-octet scalar. The body length is + equal to: + + bodyLen = (2nd_octet << 24) | (3rd_octet << 16) | + (4th_octet << 8) | 5th_octet + + This basic set of one, two, and five-octet lengths is also used + internally to some packets. + + + + + + +Callas, et al Standards Track [Page 15] + +RFC 4880 OpenPGP Message Format November 2007 + + +4.2.2.4. Partial Body Lengths + + A Partial Body Length header is one octet long and encodes the length + of only part of the data packet. This length is a power of 2, from 1 + to 1,073,741,824 (2 to the 30th power). It is recognized by its one + octet value that is greater than or equal to 224, and less than 255. + The Partial Body Length is equal to: + + partialBodyLen = 1 << (1st_octet & 0x1F); + + Each Partial Body Length header is followed by a portion of the + packet body data. The Partial Body Length header specifies this + portion's length. Another length header (one octet, two-octet, + five-octet, or partial) follows that portion. The last length header + in the packet MUST NOT be a Partial Body Length header. Partial Body + Length headers may only be used for the non-final parts of the + packet. + + Note also that the last Body Length header can be a zero-length + header. + + An implementation MAY use Partial Body Lengths for data packets, be + they literal, compressed, or encrypted. The first partial length + MUST be at least 512 octets long. Partial Body Lengths MUST NOT be + used for any other packet types. + +4.2.3. Packet Length Examples + + These examples show ways that new format packets might encode the + packet lengths. + + A packet with length 100 may have its length encoded in one octet: + 0x64. This is followed by 100 octets of data. + + A packet with length 1723 may have its length encoded in two octets: + 0xC5, 0xFB. This header is followed by the 1723 octets of data. + + A packet with length 100000 may have its length encoded in five + octets: 0xFF, 0x00, 0x01, 0x86, 0xA0. + + It might also be encoded in the following octet stream: 0xEF, first + 32768 octets of data; 0xE1, next two octets of data; 0xE0, next one + octet of data; 0xF0, next 65536 octets of data; 0xC5, 0xDD, last 1693 + octets of data. This is just one possible encoding, and many + variations are possible on the size of the Partial Body Length + headers, as long as a regular Body Length header encodes the last + portion of the data. + + + + +Callas, et al Standards Track [Page 16] + +RFC 4880 OpenPGP Message Format November 2007 + + + Please note that in all of these explanations, the total length of + the packet is the length of the header(s) plus the length of the + body. + +4.3. Packet Tags + + The packet tag denotes what type of packet the body holds. Note that + old format headers can only have tags less than 16, whereas new + format headers can have tags as great as 63. The defined tags (in + decimal) are as follows: + + 0 -- Reserved - a packet tag MUST NOT have this value + 1 -- Public-Key Encrypted Session Key Packet + 2 -- Signature Packet + 3 -- Symmetric-Key Encrypted Session Key Packet + 4 -- One-Pass Signature Packet + 5 -- Secret-Key Packet + 6 -- Public-Key Packet + 7 -- Secret-Subkey Packet + 8 -- Compressed Data Packet + 9 -- Symmetrically Encrypted Data Packet + 10 -- Marker Packet + 11 -- Literal Data Packet + 12 -- Trust Packet + 13 -- User ID Packet + 14 -- Public-Subkey Packet + 17 -- User Attribute Packet + 18 -- Sym. Encrypted and Integrity Protected Data Packet + 19 -- Modification Detection Code Packet + 60 to 63 -- Private or Experimental Values + +5. Packet Types + +5.1. Public-Key Encrypted Session Key Packets (Tag 1) + + A Public-Key Encrypted Session Key packet holds the session key used + to encrypt a message. Zero or more Public-Key Encrypted Session Key + packets and/or Symmetric-Key Encrypted Session Key packets may + precede a Symmetrically Encrypted Data Packet, which holds an + encrypted message. The message is encrypted with the session key, + and the session key is itself encrypted and stored in the Encrypted + Session Key packet(s). The Symmetrically Encrypted Data Packet is + preceded by one Public-Key Encrypted Session Key packet for each + OpenPGP key to which the message is encrypted. The recipient of the + message finds a session key that is encrypted to their public key, + decrypts the session key, and then uses the session key to decrypt + the message. + + + + +Callas, et al Standards Track [Page 17] + +RFC 4880 OpenPGP Message Format November 2007 + + + The body of this packet consists of: + + - A one-octet number giving the version number of the packet type. + The currently defined value for packet version is 3. + + - An eight-octet number that gives the Key ID of the public key to + which the session key is encrypted. If the session key is + encrypted to a subkey, then the Key ID of this subkey is used + here instead of the Key ID of the primary key. + + - A one-octet number giving the public-key algorithm used. + + - A string of octets that is the encrypted session key. This + string takes up the remainder of the packet, and its contents are + dependent on the public-key algorithm used. + + Algorithm Specific Fields for RSA encryption + + - multiprecision integer (MPI) of RSA encrypted value m**e mod n. + + Algorithm Specific Fields for Elgamal encryption: + + - MPI of Elgamal (Diffie-Hellman) value g**k mod p. + + - MPI of Elgamal (Diffie-Hellman) value m * y**k mod p. + + The value "m" in the above formulas is derived from the session key + as follows. First, the session key is prefixed with a one-octet + algorithm identifier that specifies the symmetric encryption + algorithm used to encrypt the following Symmetrically Encrypted Data + Packet. Then a two-octet checksum is appended, which is equal to the + sum of the preceding session key octets, not including the algorithm + identifier, modulo 65536. This value is then encoded as described in + PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to + form the "m" value used in the formulas above. See Section 13.1 of + this document for notes on OpenPGP's use of PKCS#1. + + Note that when an implementation forms several PKESKs with one + session key, forming a message that can be decrypted by several keys, + the implementation MUST make a new PKCS#1 encoding for each key. + + An implementation MAY accept or use a Key ID of zero as a "wild card" + or "speculative" Key ID. In this case, the receiving implementation + would try all available private keys, checking for a valid decrypted + session key. This format helps reduce traffic analysis of messages. + + + + + + +Callas, et al Standards Track [Page 18] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2. Signature Packet (Tag 2) + + A Signature packet describes a binding between some public key and + some data. The most common signatures are a signature of a file or a + block of text, and a signature that is a certification of a User ID. + + Two versions of Signature packets are defined. Version 3 provides + basic signature information, while version 4 provides an expandable + format with subpackets that can specify more information about the + signature. PGP 2.6.x only accepts version 3 signatures. + + Implementations SHOULD accept V3 signatures. Implementations SHOULD + generate V4 signatures. + + Note that if an implementation is creating an encrypted and signed + message that is encrypted to a V3 key, it is reasonable to create a + V3 signature. + +5.2.1. Signature Types + + There are a number of possible meanings for a signature, which are + indicated in a signature type octet in any given signature. Please + note that the vagueness of these meanings is not a flaw, but a + feature of the system. Because OpenPGP places final authority for + validity upon the receiver of a signature, it may be that one + signer's casual act might be more rigorous than some other + authority's positive act. See Section 5.2.4, "Computing Signatures", + for detailed information on how to compute and verify signatures of + each type. + + These meanings are as follows: + + 0x00: Signature of a binary document. + This means the signer owns it, created it, or certifies that it + has not been modified. + + 0x01: Signature of a canonical text document. + This means the signer owns it, created it, or certifies that it + has not been modified. The signature is calculated over the text + data with its line endings converted to . + + 0x02: Standalone signature. + This signature is a signature of only its own subpacket contents. + It is calculated identically to a signature over a zero-length + binary document. Note that it doesn't make sense to have a V3 + standalone signature. + + + + + +Callas, et al Standards Track [Page 19] + +RFC 4880 OpenPGP Message Format November 2007 + + + 0x10: Generic certification of a User ID and Public-Key packet. + The issuer of this certification does not make any particular + assertion as to how well the certifier has checked that the owner + of the key is in fact the person described by the User ID. + + 0x11: Persona certification of a User ID and Public-Key packet. + The issuer of this certification has not done any verification of + the claim that the owner of this key is the User ID specified. + + 0x12: Casual certification of a User ID and Public-Key packet. + The issuer of this certification has done some casual + verification of the claim of identity. + + 0x13: Positive certification of a User ID and Public-Key packet. + The issuer of this certification has done substantial + verification of the claim of identity. + + Most OpenPGP implementations make their "key signatures" as 0x10 + certifications. Some implementations can issue 0x11-0x13 + certifications, but few differentiate between the types. + + 0x18: Subkey Binding Signature + This signature is a statement by the top-level signing key that + indicates that it owns the subkey. This signature is calculated + directly on the primary key and subkey, and not on any User ID or + other packets. A signature that binds a signing subkey MUST have + an Embedded Signature subpacket in this binding signature that + contains a 0x19 signature made by the signing subkey on the + primary key and subkey. + + 0x19: Primary Key Binding Signature + This signature is a statement by a signing subkey, indicating + that it is owned by the primary key and subkey. This signature + is calculated the same way as a 0x18 signature: directly on the + primary key and subkey, and not on any User ID or other packets. + + 0x1F: Signature directly on a key + This signature is calculated directly on a key. It binds the + information in the Signature subpackets to the key, and is + appropriate to be used for subpackets that provide information + about the key, such as the Revocation Key subpacket. It is also + appropriate for statements that non-self certifiers want to make + about the key itself, rather than the binding between a key and a + name. + + + + + + + +Callas, et al Standards Track [Page 20] + +RFC 4880 OpenPGP Message Format November 2007 + + + 0x20: Key revocation signature + The signature is calculated directly on the key being revoked. A + revoked key is not to be used. Only revocation signatures by the + key being revoked, or by an authorized revocation key, should be + considered valid revocation signatures. + + 0x28: Subkey revocation signature + The signature is calculated directly on the subkey being revoked. + A revoked subkey is not to be used. Only revocation signatures + by the top-level signature key that is bound to this subkey, or + by an authorized revocation key, should be considered valid + revocation signatures. + + 0x30: Certification revocation signature + This signature revokes an earlier User ID certification signature + (signature class 0x10 through 0x13) or direct-key signature + (0x1F). It should be issued by the same key that issued the + revoked signature or an authorized revocation key. The signature + is computed over the same data as the certificate that it + revokes, and should have a later creation date than that + certificate. + + 0x40: Timestamp signature. + This signature is only meaningful for the timestamp contained in + it. + + 0x50: Third-Party Confirmation signature. + This signature is a signature over some other OpenPGP Signature + packet(s). It is analogous to a notary seal on the signed data. + A third-party signature SHOULD include Signature Target + subpacket(s) to give easy identification. Note that we really do + mean SHOULD. There are plausible uses for this (such as a blind + party that only sees the signature, not the key or source + document) that cannot include a target subpacket. + +5.2.2. Version 3 Signature Packet Format + + The body of a version 3 Signature Packet contains: + + - One-octet version number (3). + + - One-octet length of following hashed material. MUST be 5. + + - One-octet signature type. + + - Four-octet creation time. + + - Eight-octet Key ID of signer. + + + +Callas, et al Standards Track [Page 21] + +RFC 4880 OpenPGP Message Format November 2007 + + + - One-octet public-key algorithm. + + - One-octet hash algorithm. + + - Two-octet field holding left 16 bits of signed hash value. + + - One or more multiprecision integers comprising the signature. + This portion is algorithm specific, as described below. + + The concatenation of the data to be signed, the signature type, and + creation time from the Signature packet (5 additional octets) is + hashed. The resulting hash value is used in the signature algorithm. + The high 16 bits (first two octets) of the hash are included in the + Signature packet to provide a quick test to reject some invalid + signatures. + + Algorithm-Specific Fields for RSA signatures: + + - multiprecision integer (MPI) of RSA signature value m**d mod n. + + Algorithm-Specific Fields for DSA signatures: + + - MPI of DSA value r. + + - MPI of DSA value s. + + The signature calculation is based on a hash of the signed data, as + described above. The details of the calculation are different for + DSA signatures than for RSA signatures. + + With RSA signatures, the hash value is encoded using PKCS#1 encoding + type EMSA-PKCS1-v1_5 as described in Section 9.2 of RFC 3447. This + requires inserting the hash value as an octet string into an ASN.1 + structure. The object identifier for the type of hash being used is + included in the structure. The hexadecimal representations for the + currently defined hash algorithms are as follows: + + - MD5: 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 + + - RIPEMD-160: 0x2B, 0x24, 0x03, 0x02, 0x01 + + - SHA-1: 0x2B, 0x0E, 0x03, 0x02, 0x1A + + - SHA224: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04 + + - SHA256: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01 + + - SHA384: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02 + + + +Callas, et al Standards Track [Page 22] + +RFC 4880 OpenPGP Message Format November 2007 + + + - SHA512: 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03 + + The ASN.1 Object Identifiers (OIDs) are as follows: + + - MD5: 1.2.840.113549.2.5 + + - RIPEMD-160: 1.3.36.3.2.1 + + - SHA-1: 1.3.14.3.2.26 + + - SHA224: 2.16.840.1.101.3.4.2.4 + + - SHA256: 2.16.840.1.101.3.4.2.1 + + - SHA384: 2.16.840.1.101.3.4.2.2 + + - SHA512: 2.16.840.1.101.3.4.2.3 + + The full hash prefixes for these are as follows: + + MD5: 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, + 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, + 0x04, 0x10 + + RIPEMD-160: 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, + 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 + + SHA-1: 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0E, + 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14 + + SHA224: 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, + 0x00, 0x04, 0x1C + + SHA256: 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04, 0x20 + + SHA384: 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, + 0x00, 0x04, 0x30 + + SHA512: 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, + 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, + 0x00, 0x04, 0x40 + + DSA signatures MUST use hashes that are equal in size to the number + of bits of q, the group generated by the DSA key's generator value. + + + +Callas, et al Standards Track [Page 23] + +RFC 4880 OpenPGP Message Format November 2007 + + + If the output size of the chosen hash is larger than the number of + bits of q, the hash result is truncated to fit by taking the number + of leftmost bits equal to the number of bits of q. This (possibly + truncated) hash function result is treated as a number and used + directly in the DSA signature algorithm. + +5.2.3. Version 4 Signature Packet Format + + The body of a version 4 Signature packet contains: + + - One-octet version number (4). + + - One-octet signature type. + + - One-octet public-key algorithm. + + - One-octet hash algorithm. + + - Two-octet scalar octet count for following hashed subpacket data. + Note that this is the length in octets of all of the hashed + subpackets; a pointer incremented by this number will skip over + the hashed subpackets. + + - Hashed subpacket data set (zero or more subpackets). + + - Two-octet scalar octet count for the following unhashed subpacket + data. Note that this is the length in octets of all of the + unhashed subpackets; a pointer incremented by this number will + skip over the unhashed subpackets. + + - Unhashed subpacket data set (zero or more subpackets). + + - Two-octet field holding the left 16 bits of the signed hash + value. + + - One or more multiprecision integers comprising the signature. + This portion is algorithm specific, as described above. + + The concatenation of the data being signed and the signature data + from the version number through the hashed subpacket data (inclusive) + is hashed. The resulting hash value is what is signed. The left 16 + bits of the hash are included in the Signature packet to provide a + quick test to reject some invalid signatures. + + There are two fields consisting of Signature subpackets. The first + field is hashed with the rest of the signature data, while the second + is unhashed. The second set of subpackets is not cryptographically + + + + +Callas, et al Standards Track [Page 24] + +RFC 4880 OpenPGP Message Format November 2007 + + + protected by the signature and should include only advisory + information. + + The algorithms for converting the hash function result to a signature + are described in a section below. + +5.2.3.1. Signature Subpacket Specification + + A subpacket data set consists of zero or more Signature subpackets. + In Signature packets, the subpacket data set is preceded by a two- + octet scalar count of the length in octets of all the subpackets. A + pointer incremented by this number will skip over the subpacket data + set. + + Each subpacket consists of a subpacket header and a body. The header + consists of: + + - the subpacket length (1, 2, or 5 octets), + + - the subpacket type (1 octet), + + and is followed by the subpacket-specific data. + + The length includes the type octet but not this length. Its format + is similar to the "new" format packet header lengths, but cannot have + Partial Body Lengths. That is: + + if the 1st octet < 192, then + lengthOfLength = 1 + subpacketLen = 1st_octet + + if the 1st octet >= 192 and < 255, then + lengthOfLength = 2 + subpacketLen = ((1st_octet - 192) << 8) + (2nd_octet) + 192 + + if the 1st octet = 255, then + lengthOfLength = 5 + subpacket length = [four-octet scalar starting at 2nd_octet] + + The value of the subpacket type octet may be: + + 0 = Reserved + 1 = Reserved + 2 = Signature Creation Time + 3 = Signature Expiration Time + 4 = Exportable Certification + 5 = Trust Signature + 6 = Regular Expression + + + +Callas, et al Standards Track [Page 25] + +RFC 4880 OpenPGP Message Format November 2007 + + + 7 = Revocable + 8 = Reserved + 9 = Key Expiration Time + 10 = Placeholder for backward compatibility + 11 = Preferred Symmetric Algorithms + 12 = Revocation Key + 13 = Reserved + 14 = Reserved + 15 = Reserved + 16 = Issuer + 17 = Reserved + 18 = Reserved + 19 = Reserved + 20 = Notation Data + 21 = Preferred Hash Algorithms + 22 = Preferred Compression Algorithms + 23 = Key Server Preferences + 24 = Preferred Key Server + 25 = Primary User ID + 26 = Policy URI + 27 = Key Flags + 28 = Signer's User ID + 29 = Reason for Revocation + 30 = Features + 31 = Signature Target + 32 = Embedded Signature + 100 To 110 = Private or experimental + + An implementation SHOULD ignore any subpacket of a type that it does + not recognize. + + Bit 7 of the subpacket type is the "critical" bit. If set, it + denotes that the subpacket is one that is critical for the evaluator + of the signature to recognize. If a subpacket is encountered that is + marked critical but is unknown to the evaluating software, the + evaluator SHOULD consider the signature to be in error. + + An evaluator may "recognize" a subpacket, but not implement it. The + purpose of the critical bit is to allow the signer to tell an + evaluator that it would prefer a new, unknown feature to generate an + error than be ignored. + + Implementations SHOULD implement the three preferred algorithm + subpackets (11, 21, and 22), as well as the "Reason for Revocation" + subpacket. Note, however, that if an implementation chooses not to + implement some of the preferences, it is required to behave in a + polite manner to respect the wishes of those users who do implement + these preferences. + + + +Callas, et al Standards Track [Page 26] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2.3.2. Signature Subpacket Types + + A number of subpackets are currently defined. Some subpackets apply + to the signature itself and some are attributes of the key. + Subpackets that are found on a self-signature are placed on a + certification made by the key itself. Note that a key may have more + than one User ID, and thus may have more than one self-signature, and + differing subpackets. + + A subpacket may be found either in the hashed or unhashed subpacket + sections of a signature. If a subpacket is not hashed, then the + information in it cannot be considered definitive because it is not + part of the signature proper. + +5.2.3.3. Notes on Self-Signatures + + A self-signature is a binding signature made by the key to which the + signature refers. There are three types of self-signatures, the + certification signatures (types 0x10-0x13), the direct-key signature + (type 0x1F), and the subkey binding signature (type 0x18). For + certification self-signatures, each User ID may have a self- + signature, and thus different subpackets in those self-signatures. + For subkey binding signatures, each subkey in fact has a self- + signature. Subpackets that appear in a certification self-signature + apply to the user name, and subpackets that appear in the subkey + self-signature apply to the subkey. Lastly, subpackets on the + direct-key signature apply to the entire key. + + Implementing software should interpret a self-signature's preference + subpackets as narrowly as possible. For example, suppose a key has + two user names, Alice and Bob. Suppose that Alice prefers the + symmetric algorithm CAST5, and Bob prefers IDEA or TripleDES. If the + software locates this key via Alice's name, then the preferred + algorithm is CAST5; if software locates the key via Bob's name, then + the preferred algorithm is IDEA. If the key is located by Key ID, + the algorithm of the primary User ID of the key provides the + preferred symmetric algorithm. + + Revoking a self-signature or allowing it to expire has a semantic + meaning that varies with the signature type. Revoking the self- + signature on a User ID effectively retires that user name. The + self-signature is a statement, "My name X is tied to my signing key + K" and is corroborated by other users' certifications. If another + user revokes their certification, they are effectively saying that + they no longer believe that name and that key are tied together. + Similarly, if the users themselves revoke their self-signature, then + the users no longer go by that name, no longer have that email + address, etc. Revoking a binding signature effectively retires that + + + +Callas, et al Standards Track [Page 27] + +RFC 4880 OpenPGP Message Format November 2007 + + + subkey. Revoking a direct-key signature cancels that signature. + Please see the "Reason for Revocation" subpacket (Section 5.2.3.23) + for more relevant detail. + + Since a self-signature contains important information about the key's + use, an implementation SHOULD allow the user to rewrite the self- + signature, and important information in it, such as preferences and + key expiration. + + It is good practice to verify that a self-signature imported into an + implementation doesn't advertise features that the implementation + doesn't support, rewriting the signature as appropriate. + + An implementation that encounters multiple self-signatures on the + same object may resolve the ambiguity in any way it sees fit, but it + is RECOMMENDED that priority be given to the most recent self- + signature. + +5.2.3.4. Signature Creation Time + + (4-octet time field) + + The time the signature was made. + + MUST be present in the hashed area. + +5.2.3.5. Issuer + + (8-octet Key ID) + + The OpenPGP Key ID of the key issuing the signature. + +5.2.3.6. Key Expiration Time + + (4-octet time field) + + The validity period of the key. This is the number of seconds after + the key creation time that the key expires. If this is not present + or has a value of zero, the key never expires. This is found only on + a self-signature. + +5.2.3.7. Preferred Symmetric Algorithms + + (array of one-octet values) + + Symmetric algorithm numbers that indicate which algorithms the key + holder prefers to use. The subpacket body is an ordered list of + octets with the most preferred listed first. It is assumed that only + + + +Callas, et al Standards Track [Page 28] + +RFC 4880 OpenPGP Message Format November 2007 + + + algorithms listed are supported by the recipient's software. + Algorithm numbers are in Section 9. This is only found on a self- + signature. + +5.2.3.8. Preferred Hash Algorithms + + (array of one-octet values) + + Message digest algorithm numbers that indicate which algorithms the + key holder prefers to receive. Like the preferred symmetric + algorithms, the list is ordered. Algorithm numbers are in Section 9. + This is only found on a self-signature. + +5.2.3.9. Preferred Compression Algorithms + + (array of one-octet values) + + Compression algorithm numbers that indicate which algorithms the key + holder prefers to use. Like the preferred symmetric algorithms, the + list is ordered. Algorithm numbers are in Section 9. If this + subpacket is not included, ZIP is preferred. A zero denotes that + uncompressed data is preferred; the key holder's software might have + no compression software in that implementation. This is only found + on a self-signature. + +5.2.3.10. Signature Expiration Time + + (4-octet time field) + + The validity period of the signature. This is the number of seconds + after the signature creation time that the signature expires. If + this is not present or has a value of zero, it never expires. + +5.2.3.11. Exportable Certification + + (1 octet of exportability, 0 for not, 1 for exportable) + + This subpacket denotes whether a certification signature is + "exportable", to be used by other users than the signature's issuer. + The packet body contains a Boolean flag indicating whether the + signature is exportable. If this packet is not present, the + certification is exportable; it is equivalent to a flag containing a + 1. + + Non-exportable, or "local", certifications are signatures made by a + user to mark a key as valid within that user's implementation only. + + + + + +Callas, et al Standards Track [Page 29] + +RFC 4880 OpenPGP Message Format November 2007 + + + Thus, when an implementation prepares a user's copy of a key for + transport to another user (this is the process of "exporting" the + key), any local certification signatures are deleted from the key. + + The receiver of a transported key "imports" it, and likewise trims + any local certifications. In normal operation, there won't be any, + assuming the import is performed on an exported key. However, there + are instances where this can reasonably happen. For example, if an + implementation allows keys to be imported from a key database in + addition to an exported key, then this situation can arise. + + Some implementations do not represent the interest of a single user + (for example, a key server). Such implementations always trim local + certifications from any key they handle. + +5.2.3.12. Revocable + + (1 octet of revocability, 0 for not, 1 for revocable) + + Signature's revocability status. The packet body contains a Boolean + flag indicating whether the signature is revocable. Signatures that + are not revocable have any later revocation signatures ignored. They + represent a commitment by the signer that he cannot revoke his + signature for the life of his key. If this packet is not present, + the signature is revocable. + +5.2.3.13. Trust Signature + + (1 octet "level" (depth), 1 octet of trust amount) + + Signer asserts that the key is not only valid but also trustworthy at + the specified level. Level 0 has the same meaning as an ordinary + validity signature. Level 1 means that the signed key is asserted to + be a valid trusted introducer, with the 2nd octet of the body + specifying the degree of trust. Level 2 means that the signed key is + asserted to be trusted to issue level 1 trust signatures, i.e., that + it is a "meta introducer". Generally, a level n trust signature + asserts that a key is trusted to issue level n-1 trust signatures. + The trust amount is in a range from 0-255, interpreted such that + values less than 120 indicate partial trust and values of 120 or + greater indicate complete trust. Implementations SHOULD emit values + of 60 for partial trust and 120 for complete trust. + + + + + + + + + +Callas, et al Standards Track [Page 30] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2.3.14. Regular Expression + + (null-terminated regular expression) + + Used in conjunction with trust Signature packets (of level > 0) to + limit the scope of trust that is extended. Only signatures by the + target key on User IDs that match the regular expression in the body + of this packet have trust extended by the trust Signature subpacket. + The regular expression uses the same syntax as the Henry Spencer's + "almost public domain" regular expression [REGEX] package. A + description of the syntax is found in Section 8 below. + +5.2.3.15. Revocation Key + + (1 octet of class, 1 octet of public-key algorithm ID, 20 octets of + fingerprint) + + Authorizes the specified key to issue revocation signatures for this + key. Class octet must have bit 0x80 set. If the bit 0x40 is set, + then this means that the revocation information is sensitive. Other + bits are for future expansion to other kinds of authorizations. This + is found on a self-signature. + + If the "sensitive" flag is set, the keyholder feels this subpacket + contains private trust information that describes a real-world + sensitive relationship. If this flag is set, implementations SHOULD + NOT export this signature to other users except in cases where the + data needs to be available: when the signature is being sent to the + designated revoker, or when it is accompanied by a revocation + signature from that revoker. Note that it may be appropriate to + isolate this subpacket within a separate signature so that it is not + combined with other subpackets that need to be exported. + +5.2.3.16. Notation Data + + (4 octets of flags, 2 octets of name length (M), + 2 octets of value length (N), + M octets of name data, + N octets of value data) + + This subpacket describes a "notation" on the signature that the + issuer wishes to make. The notation has a name and a value, each of + which are strings of octets. There may be more than one notation in + a signature. Notations can be used for any extension the issuer of + the signature cares to make. The "flags" field holds four octets of + flags. + + + + + +Callas, et al Standards Track [Page 31] + +RFC 4880 OpenPGP Message Format November 2007 + + + All undefined flags MUST be zero. Defined flags are as follows: + + First octet: 0x80 = human-readable. This note value is text. + Other octets: none. + + Notation names are arbitrary strings encoded in UTF-8. They reside + in two namespaces: The IETF namespace and the user namespace. + + The IETF namespace is registered with IANA. These names MUST NOT + contain the "@" character (0x40). This is a tag for the user + namespace. + + Names in the user namespace consist of a UTF-8 string tag followed by + "@" followed by a DNS domain name. Note that the tag MUST NOT + contain an "@" character. For example, the "sample" tag used by + Example Corporation could be "sample@example.com". + + Names in a user space are owned and controlled by the owners of that + domain. Obviously, it's bad form to create a new name in a DNS space + that you don't own. + + Since the user namespace is in the form of an email address, + implementers MAY wish to arrange for that address to reach a person + who can be consulted about the use of the named tag. Note that due + to UTF-8 encoding, not all valid user space name tags are valid email + addresses. + + If there is a critical notation, the criticality applies to that + specific notation and not to notations in general. + +5.2.3.17. Key Server Preferences + + (N octets of flags) + + This is a list of one-bit flags that indicate preferences that the + key holder has about how the key is handled on a key server. All + undefined flags MUST be zero. + + First octet: 0x80 = No-modify + the key holder requests that this key only be modified or updated + by the key holder or an administrator of the key server. + + This is found only on a self-signature. + + + + + + + + +Callas, et al Standards Track [Page 32] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2.3.18. Preferred Key Server + + (String) + + This is a URI of a key server that the key holder prefers be used for + updates. Note that keys with multiple User IDs can have a preferred + key server for each User ID. Note also that since this is a URI, the + key server can actually be a copy of the key retrieved by ftp, http, + finger, etc. + +5.2.3.19. Primary User ID + + (1 octet, Boolean) + + This is a flag in a User ID's self-signature that states whether this + User ID is the main User ID for this key. It is reasonable for an + implementation to resolve ambiguities in preferences, etc. by + referring to the primary User ID. If this flag is absent, its value + is zero. If more than one User ID in a key is marked as primary, the + implementation may resolve the ambiguity in any way it sees fit, but + it is RECOMMENDED that priority be given to the User ID with the most + recent self-signature. + + When appearing on a self-signature on a User ID packet, this + subpacket applies only to User ID packets. When appearing on a + self-signature on a User Attribute packet, this subpacket applies + only to User Attribute packets. That is to say, there are two + different and independent "primaries" -- one for User IDs, and one + for User Attributes. + +5.2.3.20. Policy URI + + (String) + + This subpacket contains a URI of a document that describes the policy + under which the signature was issued. + +5.2.3.21. Key Flags + + (N octets of flags) + + This subpacket contains a list of binary flags that hold information + about a key. It is a string of octets, and an implementation MUST + NOT assume a fixed size. This is so it can grow over time. If a + list is shorter than an implementation expects, the unstated flags + are considered to be zero. The defined flags are as follows: + + + + + +Callas, et al Standards Track [Page 33] + +RFC 4880 OpenPGP Message Format November 2007 + + + First octet: + + 0x01 - This key may be used to certify other keys. + + 0x02 - This key may be used to sign data. + + 0x04 - This key may be used to encrypt communications. + + 0x08 - This key may be used to encrypt storage. + + 0x10 - The private component of this key may have been split + by a secret-sharing mechanism. + + 0x20 - This key may be used for authentication. + + 0x80 - The private component of this key may be in the + possession of more than one person. + + Usage notes: + + The flags in this packet may appear in self-signatures or in + certification signatures. They mean different things depending on + who is making the statement -- for example, a certification signature + that has the "sign data" flag is stating that the certification is + for that use. On the other hand, the "communications encryption" + flag in a self-signature is stating a preference that a given key be + used for communications. Note however, that it is a thorny issue to + determine what is "communications" and what is "storage". This + decision is left wholly up to the implementation; the authors of this + document do not claim any special wisdom on the issue and realize + that accepted opinion may change. + + The "split key" (0x10) and "group key" (0x80) flags are placed on a + self-signature only; they are meaningless on a certification + signature. They SHOULD be placed only on a direct-key signature + (type 0x1F) or a subkey signature (type 0x18), one that refers to the + key the flag applies to. + +5.2.3.22. Signer's User ID + + (String) + + This subpacket allows a keyholder to state which User ID is + responsible for the signing. Many keyholders use a single key for + different purposes, such as business communications as well as + personal communications. This subpacket allows such a keyholder to + state which of their roles is making a signature. + + + + +Callas, et al Standards Track [Page 34] + +RFC 4880 OpenPGP Message Format November 2007 + + + This subpacket is not appropriate to use to refer to a User Attribute + packet. + +5.2.3.23. Reason for Revocation + + (1 octet of revocation code, N octets of reason string) + + This subpacket is used only in key revocation and certification + revocation signatures. It describes the reason why the key or + certificate was revoked. + + The first octet contains a machine-readable code that denotes the + reason for the revocation: + + 0 - No reason specified (key revocations or cert revocations) + 1 - Key is superseded (key revocations) + 2 - Key material has been compromised (key revocations) + 3 - Key is retired and no longer used (key revocations) + 32 - User ID information is no longer valid (cert revocations) + 100-110 - Private Use + + Following the revocation code is a string of octets that gives + information about the Reason for Revocation in human-readable form + (UTF-8). The string may be null, that is, of zero length. The + length of the subpacket is the length of the reason string plus one. + An implementation SHOULD implement this subpacket, include it in all + revocation signatures, and interpret revocations appropriately. + There are important semantic differences between the reasons, and + there are thus important reasons for revoking signatures. + + If a key has been revoked because of a compromise, all signatures + created by that key are suspect. However, if it was merely + superseded or retired, old signatures are still valid. If the + revoked signature is the self-signature for certifying a User ID, a + revocation denotes that that user name is no longer in use. Such a + revocation SHOULD include a 0x20 code. + + Note that any signature may be revoked, including a certification on + some other person's key. There are many good reasons for revoking a + certification signature, such as the case where the keyholder leaves + the employ of a business with an email address. A revoked + certification is no longer a part of validity calculations. + + + + + + + + + +Callas, et al Standards Track [Page 35] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2.3.24. Features + + (N octets of flags) + + The Features subpacket denotes which advanced OpenPGP features a + user's implementation supports. This is so that as features are + added to OpenPGP that cannot be backwards-compatible, a user can + state that they can use that feature. The flags are single bits that + indicate that a given feature is supported. + + This subpacket is similar to a preferences subpacket, and only + appears in a self-signature. + + An implementation SHOULD NOT use a feature listed when sending to a + user who does not state that they can use it. + + Defined features are as follows: + + First octet: + + 0x01 - Modification Detection (packets 18 and 19) + + If an implementation implements any of the defined features, it + SHOULD implement the Features subpacket, too. + + An implementation may freely infer features from other suitable + implementation-dependent mechanisms. + +5.2.3.25. Signature Target + + (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash) + + This subpacket identifies a specific target signature to which a + signature refers. For revocation signatures, this subpacket + provides explicit designation of which signature is being revoked. + For a third-party or timestamp signature, this designates what + signature is signed. All arguments are an identifier of that target + signature. + + The N octets of hash data MUST be the size of the hash of the + signature. For example, a target signature with a SHA-1 hash MUST + have 20 octets of hash data. + + + + + + + + + +Callas, et al Standards Track [Page 36] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.2.3.26. Embedded Signature + + (1 signature packet body) + + This subpacket contains a complete Signature packet body as + specified in Section 5.2 above. It is useful when one signature + needs to refer to, or be incorporated in, another signature. + +5.2.4. Computing Signatures + + All signatures are formed by producing a hash over the signature + data, and then using the resulting hash in the signature algorithm. + + For binary document signatures (type 0x00), the document data is + hashed directly. For text document signatures (type 0x01), the + document is canonicalized by converting line endings to , + and the resulting data is hashed. + + When a signature is made over a key, the hash data starts with the + octet 0x99, followed by a two-octet length of the key, and then body + of the key packet. (Note that this is an old-style packet header for + a key packet with two-octet length.) A subkey binding signature + (type 0x18) or primary key binding signature (type 0x19) then hashes + the subkey using the same format as the main key (also using 0x99 as + the first octet). Key revocation signatures (types 0x20 and 0x28) + hash only the key being revoked. + + A certification signature (type 0x10 through 0x13) hashes the User + ID being bound to the key into the hash context after the above + data. A V3 certification hashes the contents of the User ID or + attribute packet packet, without any header. A V4 certification + hashes the constant 0xB4 for User ID certifications or the constant + 0xD1 for User Attribute certifications, followed by a four-octet + number giving the length of the User ID or User Attribute data, and + then the User ID or User Attribute data. + + When a signature is made over a Signature packet (type 0x50), the + hash data starts with the octet 0x88, followed by the four-octet + length of the signature, and then the body of the Signature packet. + (Note that this is an old-style packet header for a Signature packet + with the length-of-length set to zero.) The unhashed subpacket data + of the Signature packet being hashed is not included in the hash, and + the unhashed subpacket data length value is set to zero. + + Once the data body is hashed, then a trailer is hashed. A V3 + signature hashes five octets of the packet body, starting from the + signature type field. This data is the signature type, followed by + the four-octet signature time. A V4 signature hashes the packet body + + + +Callas, et al Standards Track [Page 37] + +RFC 4880 OpenPGP Message Format November 2007 + + + starting from its first field, the version number, through the end + of the hashed subpacket data. Thus, the fields hashed are the + signature version, the signature type, the public-key algorithm, the + hash algorithm, the hashed subpacket length, and the hashed + subpacket body. + + V4 signatures also hash in a final trailer of six octets: the + version of the Signature packet, i.e., 0x04; 0xFF; and a four-octet, + big-endian number that is the length of the hashed data from the + Signature packet (note that this number does not include these final + six octets). + + After all this has been hashed in a single hash context, the + resulting hash field is used in the signature algorithm and placed + at the end of the Signature packet. + +5.2.4.1. Subpacket Hints + + It is certainly possible for a signature to contain conflicting + information in subpackets. For example, a signature may contain + multiple copies of a preference or multiple expiration times. In + most cases, an implementation SHOULD use the last subpacket in the + signature, but MAY use any conflict resolution scheme that makes + more sense. Please note that we are intentionally leaving conflict + resolution to the implementer; most conflicts are simply syntax + errors, and the wishy-washy language here allows a receiver to be + generous in what they accept, while putting pressure on a creator to + be stingy in what they generate. + + Some apparent conflicts may actually make sense -- for example, + suppose a keyholder has a V3 key and a V4 key that share the same + RSA key material. Either of these keys can verify a signature + created by the other, and it may be reasonable for a signature to + contain an issuer subpacket for each key, as a way of explicitly + tying those keys to the signature. + +5.3. Symmetric-Key Encrypted Session Key Packets (Tag 3) + + The Symmetric-Key Encrypted Session Key packet holds the + symmetric-key encryption of a session key used to encrypt a message. + Zero or more Public-Key Encrypted Session Key packets and/or + Symmetric-Key Encrypted Session Key packets may precede a + Symmetrically Encrypted Data packet that holds an encrypted message. + The message is encrypted with a session key, and the session key is + itself encrypted and stored in the Encrypted Session Key packet or + the Symmetric-Key Encrypted Session Key packet. + + + + + +Callas, et al Standards Track [Page 38] + +RFC 4880 OpenPGP Message Format November 2007 + + + If the Symmetrically Encrypted Data packet is preceded by one or + more Symmetric-Key Encrypted Session Key packets, each specifies a + passphrase that may be used to decrypt the message. This allows a + message to be encrypted to a number of public keys, and also to one + or more passphrases. This packet type is new and is not generated + by PGP 2.x or PGP 5.0. + + The body of this packet consists of: + + - A one-octet version number. The only currently defined version + is 4. + + - A one-octet number describing the symmetric algorithm used. + + - A string-to-key (S2K) specifier, length as defined above. + + - Optionally, the encrypted session key itself, which is decrypted + with the string-to-key object. + + If the encrypted session key is not present (which can be detected + on the basis of packet length and S2K specifier size), then the S2K + algorithm applied to the passphrase produces the session key for + decrypting the file, using the symmetric cipher algorithm from the + Symmetric-Key Encrypted Session Key packet. + + If the encrypted session key is present, the result of applying the + S2K algorithm to the passphrase is used to decrypt just that + encrypted session key field, using CFB mode with an IV of all zeros. + The decryption result consists of a one-octet algorithm identifier + that specifies the symmetric-key encryption algorithm used to + encrypt the following Symmetrically Encrypted Data packet, followed + by the session key octets themselves. + + Note: because an all-zero IV is used for this decryption, the S2K + specifier MUST use a salt value, either a Salted S2K or an + Iterated-Salted S2K. The salt value will ensure that the decryption + key is not repeated even if the passphrase is reused. + +5.4. One-Pass Signature Packets (Tag 4) + + The One-Pass Signature packet precedes the signed data and contains + enough information to allow the receiver to begin calculating any + hashes needed to verify the signature. It allows the Signature + packet to be placed at the end of the message, so that the signer + can compute the entire signed message in one pass. + + A One-Pass Signature does not interoperate with PGP 2.6.x or + earlier. + + + +Callas, et al Standards Track [Page 39] + +RFC 4880 OpenPGP Message Format November 2007 + + + The body of this packet consists of: + + - A one-octet version number. The current version is 3. + + - A one-octet signature type. Signature types are described in + Section 5.2.1. + + - A one-octet number describing the hash algorithm used. + + - A one-octet number describing the public-key algorithm used. + + - An eight-octet number holding the Key ID of the signing key. + + - A one-octet number holding a flag showing whether the signature + is nested. A zero value indicates that the next packet is + another One-Pass Signature packet that describes another + signature to be applied to the same message data. + + Note that if a message contains more than one one-pass signature, + then the Signature packets bracket the message; that is, the first + Signature packet after the message corresponds to the last one-pass + packet and the final Signature packet corresponds to the first + one-pass packet. + +5.5. Key Material Packet + + A key material packet contains all the information about a public or + private key. There are four variants of this packet type, and two + major versions. Consequently, this section is complex. + +5.5.1. Key Packet Variants + +5.5.1.1. Public-Key Packet (Tag 6) + + A Public-Key packet starts a series of packets that forms an OpenPGP + key (sometimes called an OpenPGP certificate). + +5.5.1.2. Public-Subkey Packet (Tag 14) + + A Public-Subkey packet (tag 14) has exactly the same format as a + Public-Key packet, but denotes a subkey. One or more subkeys may be + associated with a top-level key. By convention, the top-level key + provides signature services, and the subkeys provide encryption + services. + + Note: in PGP 2.6.x, tag 14 was intended to indicate a comment + packet. This tag was selected for reuse because no previous version + of PGP ever emitted comment packets but they did properly ignore + + + +Callas, et al Standards Track [Page 40] + +RFC 4880 OpenPGP Message Format November 2007 + + + them. Public-Subkey packets are ignored by PGP 2.6.x and do not + cause it to fail, providing a limited degree of backward + compatibility. + +5.5.1.3. Secret-Key Packet (Tag 5) + + A Secret-Key packet contains all the information that is found in a + Public-Key packet, including the public-key material, but also + includes the secret-key material after all the public-key fields. + +5.5.1.4. Secret-Subkey Packet (Tag 7) + + A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + Key packet and has exactly the same format. + +5.5.2. Public-Key Packet Formats + + There are two versions of key-material packets. Version 3 packets + were first generated by PGP 2.6. Version 4 keys first appeared in + PGP 5.0 and are the preferred key version for OpenPGP. + + OpenPGP implementations MUST create keys with version 4 format. V3 + keys are deprecated; an implementation MUST NOT generate a V3 key, + but MAY accept it. + + A version 3 public key or public-subkey packet contains: + + - A one-octet version number (3). + + - A four-octet number denoting the time that the key was created. + + - A two-octet number denoting the time in days that this key is + valid. If this number is zero, then it does not expire. + + - A one-octet number denoting the public-key algorithm of this key. + + - A series of multiprecision integers comprising the key material: + + - a multiprecision integer (MPI) of RSA public modulus n; + + - an MPI of RSA public encryption exponent e. + + V3 keys are deprecated. They contain three weaknesses. First, it is + relatively easy to construct a V3 key that has the same Key ID as any + other key because the Key ID is simply the low 64 bits of the public + modulus. Secondly, because the fingerprint of a V3 key hashes the + key material, but not its length, there is an increased opportunity + for fingerprint collisions. Third, there are weaknesses in the MD5 + + + +Callas, et al Standards Track [Page 41] + +RFC 4880 OpenPGP Message Format November 2007 + + + hash algorithm that make developers prefer other algorithms. See + below for a fuller discussion of Key IDs and fingerprints. + + V2 keys are identical to the deprecated V3 keys except for the + version number. An implementation MUST NOT generate them and MAY + accept or reject them as it sees fit. + + The version 4 format is similar to the version 3 format except for + the absence of a validity period. This has been moved to the + Signature packet. In addition, fingerprints of version 4 keys are + calculated differently from version 3 keys, as described in the + section "Enhanced Key Formats". + + A version 4 packet contains: + + - A one-octet version number (4). + + - A four-octet number denoting the time that the key was created. + + - A one-octet number denoting the public-key algorithm of this key. + + - A series of multiprecision integers comprising the key material. + This algorithm-specific portion is: + + Algorithm-Specific Fields for RSA public keys: + + - multiprecision integer (MPI) of RSA public modulus n; + + - MPI of RSA public encryption exponent e. + + Algorithm-Specific Fields for DSA public keys: + + - MPI of DSA prime p; + + - MPI of DSA group order q (q is a prime divisor of p-1); + + - MPI of DSA group generator g; + + - MPI of DSA public-key value y (= g**x mod p where x + is secret). + + Algorithm-Specific Fields for Elgamal public keys: + + - MPI of Elgamal prime p; + + - MPI of Elgamal group generator g; + + + + + +Callas, et al Standards Track [Page 42] + +RFC 4880 OpenPGP Message Format November 2007 + + + - MPI of Elgamal public key value y (= g**x mod p where x + is secret). + +5.5.3. Secret-Key Packet Formats + + The Secret-Key and Secret-Subkey packets contain all the data of the + Public-Key and Public-Subkey packets, with additional algorithm- + specific secret-key data appended, usually in encrypted form. + + The packet contains: + + - A Public-Key or Public-Subkey packet, as described above. + + - One octet indicating string-to-key usage conventions. Zero + indicates that the secret-key data is not encrypted. 255 or 254 + indicates that a string-to-key specifier is being given. Any + other value is a symmetric-key encryption algorithm identifier. + + - [Optional] If string-to-key usage octet was 255 or 254, a one- + octet symmetric encryption algorithm. + + - [Optional] If string-to-key usage octet was 255 or 254, a + string-to-key specifier. The length of the string-to-key + specifier is implied by its type, as described above. + + - [Optional] If secret data is encrypted (string-to-key usage octet + not zero), an Initial Vector (IV) of the same length as the + cipher's block size. + + - Plain or encrypted multiprecision integers comprising the secret + key data. These algorithm-specific fields are as described + below. + + - If the string-to-key usage octet is zero or 255, then a two-octet + checksum of the plaintext of the algorithm-specific portion (sum + of all octets, mod 65536). If the string-to-key usage octet was + 254, then a 20-octet SHA-1 hash of the plaintext of the + algorithm-specific portion. This checksum or hash is encrypted + together with the algorithm-specific fields (if string-to-key + usage octet is not zero). Note that for all other values, a + two-octet checksum is required. + + Algorithm-Specific Fields for RSA secret keys: + + - multiprecision integer (MPI) of RSA secret exponent d. + + - MPI of RSA secret prime value p. + + + + +Callas, et al Standards Track [Page 43] + +RFC 4880 OpenPGP Message Format November 2007 + + + - MPI of RSA secret prime value q (p < q). + + - MPI of u, the multiplicative inverse of p, mod q. + + Algorithm-Specific Fields for DSA secret keys: + + - MPI of DSA secret exponent x. + + Algorithm-Specific Fields for Elgamal secret keys: + + - MPI of Elgamal secret exponent x. + + Secret MPI values can be encrypted using a passphrase. If a string- + to-key specifier is given, that describes the algorithm for + converting the passphrase to a key, else a simple MD5 hash of the + passphrase is used. Implementations MUST use a string-to-key + specifier; the simple hash is for backward compatibility and is + deprecated, though implementations MAY continue to use existing + private keys in the old format. The cipher for encrypting the MPIs + is specified in the Secret-Key packet. + + Encryption/decryption of the secret data is done in CFB mode using + the key created from the passphrase and the Initial Vector from the + packet. A different mode is used with V3 keys (which are only RSA) + than with other key formats. With V3 keys, the MPI bit count prefix + (i.e., the first two octets) is not encrypted. Only the MPI non- + prefix data is encrypted. Furthermore, the CFB state is + resynchronized at the beginning of each new MPI value, so that the + CFB block boundary is aligned with the start of the MPI data. + + With V4 keys, a simpler method is used. All secret MPI values are + encrypted in CFB mode, including the MPI bitcount prefix. + + The two-octet checksum that follows the algorithm-specific portion is + the algebraic sum, mod 65536, of the plaintext of all the algorithm- + specific octets (including MPI prefix and data). With V3 keys, the + checksum is stored in the clear. With V4 keys, the checksum is + encrypted like the algorithm-specific data. This value is used to + check that the passphrase was correct. However, this checksum is + deprecated; an implementation SHOULD NOT use it, but should rather + use the SHA-1 hash denoted with a usage octet of 254. The reason for + this is that there are some attacks that involve undetectably + modifying the secret key. + + + + + + + + +Callas, et al Standards Track [Page 44] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.6. Compressed Data Packet (Tag 8) + + The Compressed Data packet contains compressed data. Typically, this + packet is found as the contents of an encrypted packet, or following + a Signature or One-Pass Signature packet, and contains a literal data + packet. + + The body of this packet consists of: + + - One octet that gives the algorithm used to compress the packet. + + - Compressed data, which makes up the remainder of the packet. + + A Compressed Data Packet's body contains an block that compresses + some set of packets. See section "Packet Composition" for details on + how messages are formed. + + ZIP-compressed packets are compressed with raw RFC 1951 [RFC1951] + DEFLATE blocks. Note that PGP V2.6 uses 13 bits of compression. If + an implementation uses more bits of compression, PGP V2.6 cannot + decompress it. + + ZLIB-compressed packets are compressed with RFC 1950 [RFC1950] ZLIB- + style blocks. + + BZip2-compressed packets are compressed using the BZip2 [BZ2] + algorithm. + +5.7. Symmetrically Encrypted Data Packet (Tag 9) + + The Symmetrically Encrypted Data packet contains data encrypted with + a symmetric-key algorithm. When it has been decrypted, it contains + other packets (usually a literal data packet or compressed data + packet, but in theory other Symmetrically Encrypted Data packets or + sequences of packets that form whole OpenPGP messages). + + The body of this packet consists of: + + - Encrypted data, the output of the selected symmetric-key cipher + operating in OpenPGP's variant of Cipher Feedback (CFB) mode. + + The symmetric cipher used may be specified in a Public-Key or + Symmetric-Key Encrypted Session Key packet that precedes the + Symmetrically Encrypted Data packet. In that case, the cipher + algorithm octet is prefixed to the session key before it is + encrypted. If no packets of these types precede the encrypted data, + the IDEA algorithm is used with the session key calculated as the MD5 + hash of the passphrase, though this use is deprecated. + + + +Callas, et al Standards Track [Page 45] + +RFC 4880 OpenPGP Message Format November 2007 + + + The data is encrypted in CFB mode, with a CFB shift size equal to the + cipher's block size. The Initial Vector (IV) is specified as all + zeros. Instead of using an IV, OpenPGP prefixes a string of length + equal to the block size of the cipher plus two to the data before it + is encrypted. The first block-size octets (for example, 8 octets for + a 64-bit block length) are random, and the following two octets are + copies of the last two octets of the IV. For example, in an 8-octet + block, octet 9 is a repeat of octet 7, and octet 10 is a repeat of + octet 8. In a cipher of length 16, octet 17 is a repeat of octet 15 + and octet 18 is a repeat of octet 16. As a pedantic clarification, + in both these examples, we consider the first octet to be numbered 1. + + After encrypting the first block-size-plus-two octets, the CFB state + is resynchronized. The last block-size octets of ciphertext are + passed through the cipher and the block boundary is reset. + + The repetition of 16 bits in the random data prefixed to the message + allows the receiver to immediately check whether the session key is + incorrect. See the "Security Considerations" section for hints on + the proper use of this "quick check". + +5.8. Marker Packet (Obsolete Literal Packet) (Tag 10) + + An experimental version of PGP used this packet as the Literal + packet, but no released version of PGP generated Literal packets with + this tag. With PGP 5.x, this packet has been reassigned and is + reserved for use as the Marker packet. + + The body of this packet consists of: + + - The three octets 0x50, 0x47, 0x50 (which spell "PGP" in UTF-8). + + Such a packet MUST be ignored when received. It may be placed at the + beginning of a message that uses features not available in PGP 2.6.x + in order to cause that version to report that newer software is + necessary to process the message. + +5.9. Literal Data Packet (Tag 11) + + A Literal Data packet contains the body of a message; data that is + not to be further interpreted. + + The body of this packet consists of: + + - A one-octet field that describes how the data is formatted. + + + + + + +Callas, et al Standards Track [Page 46] + +RFC 4880 OpenPGP Message Format November 2007 + + + If it is a 'b' (0x62), then the Literal packet contains binary data. + If it is a 't' (0x74), then it contains text data, and thus may need + line ends converted to local form, or other text-mode changes. The + tag 'u' (0x75) means the same as 't', but also indicates that + implementation believes that the literal data contains UTF-8 text. + + Early versions of PGP also defined a value of 'l' as a 'local' mode + for machine-local conversions. RFC 1991 [RFC1991] incorrectly stated + this local mode flag as '1' (ASCII numeral one). Both of these local + modes are deprecated. + + - File name as a string (one-octet length, followed by a file + name). This may be a zero-length string. Commonly, if the + source of the encrypted data is a file, this will be the name of + the encrypted file. An implementation MAY consider the file name + in the Literal packet to be a more authoritative name than the + actual file name. + + If the special name "_CONSOLE" is used, the message is considered to + be "for your eyes only". This advises that the message data is + unusually sensitive, and the receiving program should process it more + carefully, perhaps avoiding storing the received data to disk, for + example. + + - A four-octet number that indicates a date associated with the + literal data. Commonly, the date might be the modification date + of a file, or the time the packet was created, or a zero that + indicates no specific time. + + - The remainder of the packet is literal data. + + Text data is stored with text endings (i.e., network- + normal line endings). These should be converted to native line + endings by the receiving software. + +5.10. Trust Packet (Tag 12) + + The Trust packet is used only within keyrings and is not normally + exported. Trust packets contain data that record the user's + specifications of which key holders are trustworthy introducers, + along with other information that implementing software uses for + trust information. The format of Trust packets is defined by a given + implementation. + + Trust packets SHOULD NOT be emitted to output streams that are + transferred to other users, and they SHOULD be ignored on any input + other than local keyring files. + + + + +Callas, et al Standards Track [Page 47] + +RFC 4880 OpenPGP Message Format November 2007 + + +5.11. User ID Packet (Tag 13) + + A User ID packet consists of UTF-8 text that is intended to represent + the name and email address of the key holder. By convention, it + includes an RFC 2822 [RFC2822] mail name-addr, but there are no + restrictions on its content. The packet length in the header + specifies the length of the User ID. + +5.12. User Attribute Packet (Tag 17) + + The User Attribute packet is a variation of the User ID packet. It + is capable of storing more types of data than the User ID packet, + which is limited to text. Like the User ID packet, a User Attribute + packet may be certified by the key owner ("self-signed") or any other + key owner who cares to certify it. Except as noted, a User Attribute + packet may be used anywhere that a User ID packet may be used. + + While User Attribute packets are not a required part of the OpenPGP + standard, implementations SHOULD provide at least enough + compatibility to properly handle a certification signature on the + User Attribute packet. A simple way to do this is by treating the + User Attribute packet as a User ID packet with opaque contents, but + an implementation may use any method desired. + + The User Attribute packet is made up of one or more attribute + subpackets. Each subpacket consists of a subpacket header and a + body. The header consists of: + + - the subpacket length (1, 2, or 5 octets) + + - the subpacket type (1 octet) + + and is followed by the subpacket specific data. + + The only currently defined subpacket type is 1, signifying an image. + An implementation SHOULD ignore any subpacket of a type that it does + not recognize. Subpacket types 100 through 110 are reserved for + private or experimental use. + +5.12.1. The Image Attribute Subpacket + + The Image Attribute subpacket is used to encode an image, presumably + (but not required to be) that of the key owner. + + The Image Attribute subpacket begins with an image header. The first + two octets of the image header contain the length of the image + header. Note that unlike other multi-octet numerical values in this + document, due to a historical accident this value is encoded as a + + + +Callas, et al Standards Track [Page 48] + +RFC 4880 OpenPGP Message Format November 2007 + + + little-endian number. The image header length is followed by a + single octet for the image header version. The only currently + defined version of the image header is 1, which is a 16-octet image + header. The first three octets of a version 1 image header are thus + 0x10, 0x00, 0x01. + + The fourth octet of a version 1 image header designates the encoding + format of the image. The only currently defined encoding format is + the value 1 to indicate JPEG. Image format types 100 through 110 are + reserved for private or experimental use. The rest of the version 1 + image header is made up of 12 reserved octets, all of which MUST be + set to 0. + + The rest of the image subpacket contains the image itself. As the + only currently defined image type is JPEG, the image is encoded in + the JPEG File Interchange Format (JFIF), a standard file format for + JPEG images [JFIF]. + + An implementation MAY try to determine the type of an image by + examination of the image data if it is unable to handle a particular + version of the image header or if a specified encoding format value + is not recognized. + +5.13. Sym. Encrypted Integrity Protected Data Packet (Tag 18) + + The Symmetrically Encrypted Integrity Protected Data packet is a + variant of the Symmetrically Encrypted Data packet. It is a new + feature created for OpenPGP that addresses the problem of detecting a + modification to encrypted data. It is used in combination with a + Modification Detection Code packet. + + There is a corresponding feature in the features Signature subpacket + that denotes that an implementation can properly use this packet + type. An implementation MUST support decrypting these packets and + SHOULD prefer generating them to the older Symmetrically Encrypted + Data packet when possible. Since this data packet protects against + modification attacks, this standard encourages its proliferation. + While blanket adoption of this data packet would create + interoperability problems, rapid adoption is nevertheless important. + An implementation SHOULD specifically denote support for this packet, + but it MAY infer it from other mechanisms. + + For example, an implementation might infer from the use of a cipher + such as Advanced Encryption Standard (AES) or Twofish that a user + supports this feature. It might place in the unhashed portion of + another user's key signature a Features subpacket. It might also + present a user with an opportunity to regenerate their own self- + signature with a Features subpacket. + + + +Callas, et al Standards Track [Page 49] + +RFC 4880 OpenPGP Message Format November 2007 + + + This packet contains data encrypted with a symmetric-key algorithm + and protected against modification by the SHA-1 hash algorithm. When + it has been decrypted, it will typically contain other packets (often + a Literal Data packet or Compressed Data packet). The last decrypted + packet in this packet's payload MUST be a Modification Detection Code + packet. + + The body of this packet consists of: + + - A one-octet version number. The only currently defined value is + 1. + + - Encrypted data, the output of the selected symmetric-key cipher + operating in Cipher Feedback mode with shift amount equal to the + block size of the cipher (CFB-n where n is the block size). + + The symmetric cipher used MUST be specified in a Public-Key or + Symmetric-Key Encrypted Session Key packet that precedes the + Symmetrically Encrypted Data packet. In either case, the cipher + algorithm octet is prefixed to the session key before it is + encrypted. + + The data is encrypted in CFB mode, with a CFB shift size equal to the + cipher's block size. The Initial Vector (IV) is specified as all + zeros. Instead of using an IV, OpenPGP prefixes an octet string to + the data before it is encrypted. The length of the octet string + equals the block size of the cipher in octets, plus two. The first + octets in the group, of length equal to the block size of the cipher, + are random; the last two octets are each copies of their 2nd + preceding octet. For example, with a cipher whose block size is 128 + bits or 16 octets, the prefix data will contain 16 random octets, + then two more octets, which are copies of the 15th and 16th octets, + respectively. Unlike the Symmetrically Encrypted Data Packet, no + special CFB resynchronization is done after encrypting this prefix + data. See "OpenPGP CFB Mode" below for more details. + + The repetition of 16 bits in the random data prefixed to the message + allows the receiver to immediately check whether the session key is + incorrect. + + The plaintext of the data to be encrypted is passed through the SHA-1 + hash function, and the result of the hash is appended to the + plaintext in a Modification Detection Code packet. The input to the + hash function includes the prefix data described above; it includes + all of the plaintext, and then also includes two octets of values + 0xD3, 0x14. These represent the encoding of a Modification Detection + Code packet tag and length field of 20 octets. + + + + +Callas, et al Standards Track [Page 50] + +RFC 4880 OpenPGP Message Format November 2007 + + + The resulting hash value is stored in a Modification Detection Code + (MDC) packet, which MUST use the two octet encoding just given to + represent its tag and length field. The body of the MDC packet is + the 20-octet output of the SHA-1 hash. + + The Modification Detection Code packet is appended to the plaintext + and encrypted along with the plaintext using the same CFB context. + + During decryption, the plaintext data should be hashed with SHA-1, + including the prefix data as well as the packet tag and length field + of the Modification Detection Code packet. The body of the MDC + packet, upon decryption, is compared with the result of the SHA-1 + hash. + + Any failure of the MDC indicates that the message has been modified + and MUST be treated as a security problem. Failures include a + difference in the hash values, but also the absence of an MDC packet, + or an MDC packet in any position other than the end of the plaintext. + Any failure SHOULD be reported to the user. + + Note: future designs of new versions of this packet should consider + rollback attacks since it will be possible for an attacker to change + the version back to 1. + + NON-NORMATIVE EXPLANATION + + The MDC system, as packets 18 and 19 are called, were created to + provide an integrity mechanism that is less strong than a + signature, yet stronger than bare CFB encryption. + + It is a limitation of CFB encryption that damage to the ciphertext + will corrupt the affected cipher blocks and the block following. + Additionally, if data is removed from the end of a CFB-encrypted + block, that removal is undetectable. (Note also that CBC mode has + a similar limitation, but data removed from the front of the block + is undetectable.) + + The obvious way to protect or authenticate an encrypted block is + to digitally sign it. However, many people do not wish to + habitually sign data, for a large number of reasons beyond the + scope of this document. Suffice it to say that many people + consider properties such as deniability to be as valuable as + integrity. + + OpenPGP addresses this desire to have more security than raw + encryption and yet preserve deniability with the MDC system. An + MDC is intentionally not a MAC. Its name was not selected by + accident. It is analogous to a checksum. + + + +Callas, et al Standards Track [Page 51] + +RFC 4880 OpenPGP Message Format November 2007 + + + Despite the fact that it is a relatively modest system, it has + proved itself in the real world. It is an effective defense to + several attacks that have surfaced since it has been created. It + has met its modest goals admirably. + + Consequently, because it is a modest security system, it has + modest requirements on the hash function(s) it employs. It does + not rely on a hash function being collision-free, it relies on a + hash function being one-way. If a forger, Frank, wishes to send + Alice a (digitally) unsigned message that says, "I've always + secretly loved you, signed Bob", it is far easier for him to + construct a new message than it is to modify anything intercepted + from Bob. (Note also that if Bob wishes to communicate secretly + with Alice, but without authentication or identification and with + a threat model that includes forgers, he has a problem that + transcends mere cryptography.) + + Note also that unlike nearly every other OpenPGP subsystem, there + are no parameters in the MDC system. It hard-defines SHA-1 as its + hash function. This is not an accident. It is an intentional + choice to avoid downgrade and cross-grade attacks while making a + simple, fast system. (A downgrade attack would be an attack that + replaced SHA-256 with SHA-1, for example. A cross-grade attack + would replace SHA-1 with another 160-bit hash, such as RIPE- + MD/160, for example.) + + However, given the present state of hash function cryptanalysis + and cryptography, it may be desirable to upgrade the MDC system to + a new hash function. See Section 13.11 in the "IANA + Considerations" for guidance. + +5.14. Modification Detection Code Packet (Tag 19) + + The Modification Detection Code packet contains a SHA-1 hash of + plaintext data, which is used to detect message modification. It is + only used with a Symmetrically Encrypted Integrity Protected Data + packet. The Modification Detection Code packet MUST be the last + packet in the plaintext data that is encrypted in the Symmetrically + Encrypted Integrity Protected Data packet, and MUST appear in no + other place. + + A Modification Detection Code packet MUST have a length of 20 octets. + + + + + + + + + +Callas, et al Standards Track [Page 52] + +RFC 4880 OpenPGP Message Format November 2007 + + + The body of this packet consists of: + + - A 20-octet SHA-1 hash of the preceding plaintext data of the + Symmetrically Encrypted Integrity Protected Data packet, + including prefix data, the tag octet, and length octet of the + Modification Detection Code packet. + + Note that the Modification Detection Code packet MUST always use a + new format encoding of the packet tag, and a one-octet encoding of + the packet length. The reason for this is that the hashing rules for + modification detection include a one-octet tag and one-octet length + in the data hash. While this is a bit restrictive, it reduces + complexity. + +6. Radix-64 Conversions + + As stated in the introduction, OpenPGP's underlying native + representation for objects is a stream of arbitrary octets, and some + systems desire these objects to be immune to damage caused by + character set translation, data conversions, etc. + + In principle, any printable encoding scheme that met the requirements + of the unsafe channel would suffice, since it would not change the + underlying binary bit streams of the native OpenPGP data structures. + The OpenPGP standard specifies one such printable encoding scheme to + ensure interoperability. + + OpenPGP's Radix-64 encoding is composed of two parts: a base64 + encoding of the binary data and a checksum. The base64 encoding is + identical to the MIME base64 content-transfer-encoding [RFC2045]. + + The checksum is a 24-bit Cyclic Redundancy Check (CRC) converted to + four characters of radix-64 encoding by the same MIME base64 + transformation, preceded by an equal sign (=). The CRC is computed + by using the generator 0x864CFB and an initialization of 0xB704CE. + The accumulation is done on the data before it is converted to + radix-64, rather than on the converted data. A sample implementation + of this algorithm is in the next section. + + The checksum with its leading equal sign MAY appear on the first line + after the base64 encoded data. + + Rationale for CRC-24: The size of 24 bits fits evenly into printable + base64. The nonzero initialization can detect more errors than a + zero initialization. + + + + + + +Callas, et al Standards Track [Page 53] + +RFC 4880 OpenPGP Message Format November 2007 + + +6.1. An Implementation of the CRC-24 in "C" + + #define CRC24_INIT 0xB704CEL + #define CRC24_POLY 0x1864CFBL + + typedef long crc24; + crc24 crc_octets(unsigned char *octets, size_t len) + { + crc24 crc = CRC24_INIT; + int i; + while (len--) { + crc ^= (*octets++) << 16; + for (i = 0; i < 8; i++) { + crc <<= 1; + if (crc & 0x1000000) + crc ^= CRC24_POLY; + } + } + return crc & 0xFFFFFFL; + } + +6.2. Forming ASCII Armor + + When OpenPGP encodes data into ASCII Armor, it puts specific headers + around the Radix-64 encoded data, so OpenPGP can reconstruct the data + later. An OpenPGP implementation MAY use ASCII armor to protect raw + binary data. OpenPGP informs the user what kind of data is encoded + in the ASCII armor through the use of the headers. + + Concatenating the following data creates ASCII Armor: + + - An Armor Header Line, appropriate for the type of data + + - Armor Headers + + - A blank (zero-length, or containing only whitespace) line + + - The ASCII-Armored data + + - An Armor Checksum + + - The Armor Tail, which depends on the Armor Header Line + + An Armor Header Line consists of the appropriate header line text + surrounded by five (5) dashes ('-', 0x2D) on either side of the + header line text. The header line text is chosen based upon the type + of data that is being encoded in Armor, and how it is being encoded. + Header line texts include the following strings: + + + +Callas, et al Standards Track [Page 54] + +RFC 4880 OpenPGP Message Format November 2007 + + + BEGIN PGP MESSAGE + Used for signed, encrypted, or compressed files. + + BEGIN PGP PUBLIC KEY BLOCK + Used for armoring public keys. + + BEGIN PGP PRIVATE KEY BLOCK + Used for armoring private keys. + + BEGIN PGP MESSAGE, PART X/Y + Used for multi-part messages, where the armor is split amongst Y + parts, and this is the Xth part out of Y. + + BEGIN PGP MESSAGE, PART X + Used for multi-part messages, where this is the Xth part of an + unspecified number of parts. Requires the MESSAGE-ID Armor + Header to be used. + + BEGIN PGP SIGNATURE + Used for detached signatures, OpenPGP/MIME signatures, and + cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE + for detached signatures. + + Note that all these Armor Header Lines are to consist of a complete + line. That is to say, there is always a line ending preceding the + starting five dashes, and following the ending five dashes. The + header lines, therefore, MUST start at the beginning of a line, and + MUST NOT have text other than whitespace following them on the same + line. These line endings are considered a part of the Armor Header + Line for the purposes of determining the content they delimit. This + is particularly important when computing a cleartext signature (see + below). + + The Armor Headers are pairs of strings that can give the user or the + receiving OpenPGP implementation some information about how to decode + or use the message. The Armor Headers are a part of the armor, not a + part of the message, and hence are not protected by any signatures + applied to the message. + + The format of an Armor Header is that of a key-value pair. A colon + (':' 0x38) and a single space (0x20) separate the key and value. + OpenPGP should consider improperly formatted Armor Headers to be + corruption of the ASCII Armor. Unknown keys should be reported to + the user, but OpenPGP should continue to process the message. + + Note that some transport methods are sensitive to line length. While + there is a limit of 76 characters for the Radix-64 data (Section + 6.3), there is no limit to the length of Armor Headers. Care should + + + +Callas, et al Standards Track [Page 55] + +RFC 4880 OpenPGP Message Format November 2007 + + + be taken that the Armor Headers are short enough to survive + transport. One way to do this is to repeat an Armor Header key + multiple times with different values for each so that no one line is + overly long. + + Currently defined Armor Header Keys are as follows: + + - "Version", which states the OpenPGP implementation and version + used to encode the message. + + - "Comment", a user-defined comment. OpenPGP defines all text to + be in UTF-8. A comment may be any UTF-8 string. However, the + whole point of armoring is to provide seven-bit-clean data. + Consequently, if a comment has characters that are outside the + US-ASCII range of UTF, they may very well not survive transport. + + - "MessageID", a 32-character string of printable characters. The + string must be the same for all parts of a multi-part message + that uses the "PART X" Armor Header. MessageID strings should be + unique enough that the recipient of the mail can associate all + the parts of a message with each other. A good checksum or + cryptographic hash function is sufficient. + + The MessageID SHOULD NOT appear unless it is in a multi-part + message. If it appears at all, it MUST be computed from the + finished (encrypted, signed, etc.) message in a deterministic + fashion, rather than contain a purely random value. This is to + allow the legitimate recipient to determine that the MessageID + cannot serve as a covert means of leaking cryptographic key + information. + + - "Hash", a comma-separated list of hash algorithms used in this + message. This is used only in cleartext signed messages. + + - "Charset", a description of the character set that the plaintext + is in. Please note that OpenPGP defines text to be in UTF-8. An + implementation will get best results by translating into and out + of UTF-8. However, there are many instances where this is easier + said than done. Also, there are communities of users who have no + need for UTF-8 because they are all happy with a character set + like ISO Latin-5 or a Japanese character set. In such instances, + an implementation MAY override the UTF-8 default by using this + header key. An implementation MAY implement this key and any + translations it cares to; an implementation MAY ignore it and + assume all text is UTF-8. + + + + + + +Callas, et al Standards Track [Page 56] + +RFC 4880 OpenPGP Message Format November 2007 + + + The Armor Tail Line is composed in the same manner as the Armor + Header Line, except the string "BEGIN" is replaced by the string + "END". + +6.3. Encoding Binary in Radix-64 + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating three 8-bit input + groups. These 24 bits are then treated as four concatenated 6-bit + groups, each of which is translated into a single digit in the + Radix-64 alphabet. When encoding a bit stream with the Radix-64 + encoding, the bit stream must be presumed to be ordered with the most + significant bit first. That is, the first bit in the stream will be + the high-order bit in the first 8-bit octet, and the eighth bit will + be the low-order bit in the first 8-bit octet, and so on. + + +--first octet--+-second octet--+--third octet--+ + |7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0|7 6 5 4 3 2 1 0| + +-----------+---+-------+-------+---+-----------+ + |5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0|5 4 3 2 1 0| + +--1.index--+--2.index--+--3.index--+--4.index--+ + + Each 6-bit group is used as an index into an array of 64 printable + characters from the table below. The character referenced by the + index is placed in the output string. + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + The encoded output stream must be represented in lines of no more + than 76 characters each. + + + +Callas, et al Standards Track [Page 57] + +RFC 4880 OpenPGP Message Format November 2007 + + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. There are three possibilities: + + 1. The last data group has 24 bits (3 octets). No special processing + is needed. + + 2. The last data group has 16 bits (2 octets). The first two 6-bit + groups are processed as above. The third (incomplete) data group + has two zero-value bits added to it, and is processed as above. A + pad character (=) is added to the output. + + 3. The last data group has 8 bits (1 octet). The first 6-bit group + is processed as above. The second (incomplete) data group has + four zero-value bits added to it, and is processed as above. Two + pad characters (=) are added to the output. + +6.4. Decoding Radix-64 + + In Radix-64 data, characters other than those in the table, line + breaks, and other white space probably indicate a transmission error, + about which a warning message or even a message rejection might be + appropriate under some circumstances. Decoding software must ignore + all white space. + + Because it is used only for padding at the end of the data, the + occurrence of any "=" characters may be taken as evidence that the + end of the data has been reached (without truncation in transit). No + such assurance is possible, however, when the number of octets + transmitted was a multiple of three and no "=" characters are + present. + + + + + + + + + + + + + + + + + + + + + +Callas, et al Standards Track [Page 58] + +RFC 4880 OpenPGP Message Format November 2007 + + +6.5. Examples of Radix-64 + + Input data: 0x14FB9C03D97E + Hex: 1 4 F B 9 C | 0 3 D 9 7 E + 8-bit: 00010100 11111011 10011100 | 00000011 11011001 11111110 + 6-bit: 000101 001111 101110 011100 | 000000 111101 100111 111110 + Decimal: 5 15 46 28 0 61 37 62 + Output: F P u c A 9 l + + Input data: 0x14FB9C03D9 + Hex: 1 4 F B 9 C | 0 3 D 9 + 8-bit: 00010100 11111011 10011100 | 00000011 11011001 + pad with 00 + 6-bit: 000101 001111 101110 011100 | 000000 111101 100100 + Decimal: 5 15 46 28 0 61 36 + pad with = + Output: F P u c A 9 k = + Input data: 0x14FB9C03 + Hex: 1 4 F B 9 C | 0 3 + 8-bit: 00010100 11111011 10011100 | 00000011 + pad with 0000 + 6-bit: 000101 001111 101110 011100 | 000000 110000 + Decimal: 5 15 46 28 0 48 + pad with = = + Output: F P u c A w = = + +6.6. Example of an ASCII Armored Message + + -----BEGIN PGP MESSAGE----- + Version: OpenPrivacy 0.99 + + yDgBO22WxBHv7O8X7O/jygAEzol56iUKiXmV+XmpCtmpqQUKiQrFqclFqUDBovzS + vBSFjNSiVHsuAA== + =njUN + -----END PGP MESSAGE----- + + Note that this example has extra indenting; an actual armored message + would have no leading whitespace. + +7. Cleartext Signature Framework + + It is desirable to be able to sign a textual octet stream without + ASCII armoring the stream itself, so the signed text is still + readable without special software. In order to bind a signature to + such a cleartext, this framework is used. (Note that this framework + is not intended to be reversible. RFC 3156 [RFC3156] defines another + way to sign cleartext messages for environments that support MIME.) + + + + + +Callas, et al Standards Track [Page 59] + +RFC 4880 OpenPGP Message Format November 2007 + + + The cleartext signed message consists of: + + - The cleartext header '-----BEGIN PGP SIGNED MESSAGE-----' on a + single line, + + - One or more "Hash" Armor Headers, + + - Exactly one empty line not included into the message digest, + + - The dash-escaped cleartext that is included into the message + digest, + + - The ASCII armored signature(s) including the '-----BEGIN PGP + SIGNATURE-----' Armor Header and Armor Tail Lines. + + If the "Hash" Armor Header is given, the specified message digest + algorithm(s) are used for the signature. If there are no such + headers, MD5 is used. If MD5 is the only hash used, then an + implementation MAY omit this header for improved V2.x compatibility. + If more than one message digest is used in the signature, the "Hash" + armor header contains a comma-delimited list of used message digests. + + Current message digest names are described below with the algorithm + IDs. + + An implementation SHOULD add a line break after the cleartext, but + MAY omit it if the cleartext ends with a line break. This is for + visual clarity. + +7.1. Dash-Escaped Text + + The cleartext content of the message must also be dash-escaped. + + Dash-escaped cleartext is the ordinary cleartext where every line + starting with a dash '-' (0x2D) is prefixed by the sequence dash '-' + (0x2D) and space ' ' (0x20). This prevents the parser from + recognizing armor headers of the cleartext itself. An implementation + MAY dash-escape any line, SHOULD dash-escape lines commencing "From" + followed by a space, and MUST dash-escape any line commencing in a + dash. The message digest is computed using the cleartext itself, not + the dash-escaped form. + + As with binary signatures on text documents, a cleartext signature is + calculated on the text using canonical line endings. The + line ending (i.e., the ) before the '-----BEGIN PGP + SIGNATURE-----' line that terminates the signed text is not + considered part of the signed text. + + + + +Callas, et al Standards Track [Page 60] + +RFC 4880 OpenPGP Message Format November 2007 + + + When reversing dash-escaping, an implementation MUST strip the string + "- " if it occurs at the beginning of a line, and SHOULD warn on "-" + and any character other than a space at the beginning of a line. + + Also, any trailing whitespace -- spaces (0x20) and tabs (0x09) -- at + the end of any line is removed when the cleartext signature is + generated. + +8. Regular Expressions + + A regular expression is zero or more branches, separated by '|'. It + matches anything that matches one of the branches. + + A branch is zero or more pieces, concatenated. It matches a match + for the first, followed by a match for the second, etc. + + A piece is an atom possibly followed by '*', '+', or '?'. An atom + followed by '*' matches a sequence of 0 or more matches of the atom. + An atom followed by '+' matches a sequence of 1 or more matches of + the atom. An atom followed by '?' matches a match of the atom, or + the null string. + + An atom is a regular expression in parentheses (matching a match for + the regular expression), a range (see below), '.' (matching any + single character), '^' (matching the null string at the beginning of + the input string), '$' (matching the null string at the end of the + input string), a '\' followed by a single character (matching that + character), or a single character with no other significance + (matching that character). + + A range is a sequence of characters enclosed in '[]'. It normally + matches any single character from the sequence. If the sequence + begins with '^', it matches any single character not from the rest of + the sequence. If two characters in the sequence are separated + by '-', this is shorthand for the full list of ASCII characters + between them (e.g., '[0-9]' matches any decimal digit). To include a + literal ']' in the sequence, make it the first character (following a + possible '^'). To include a literal '-', make it the first or last + character. + +9. Constants + + This section describes the constants used in OpenPGP. + + Note that these tables are not exhaustive lists; an implementation + MAY implement an algorithm not on these lists, so long as the + algorithm numbers are chosen from the private or experimental + algorithm range. + + + +Callas, et al Standards Track [Page 61] + +RFC 4880 OpenPGP Message Format November 2007 + + + See the section "Notes on Algorithms" below for more discussion of + the algorithms. + +9.1. Public-Key Algorithms + + ID Algorithm + -- --------- + 1 - RSA (Encrypt or Sign) [HAC] + 2 - RSA Encrypt-Only [HAC] + 3 - RSA Sign-Only [HAC] + 16 - Elgamal (Encrypt-Only) [ELGAMAL] [HAC] + 17 - DSA (Digital Signature Algorithm) [FIPS186] [HAC] + 18 - Reserved for Elliptic Curve + 19 - Reserved for ECDSA + 20 - Reserved (formerly Elgamal Encrypt or Sign) + 21 - Reserved for Diffie-Hellman (X9.42, + as defined for IETF-S/MIME) + 100 to 110 - Private/Experimental algorithm + + Implementations MUST implement DSA for signatures, and Elgamal for + encryption. Implementations SHOULD implement RSA keys (1). RSA + Encrypt-Only (2) and RSA Sign-Only are deprecated and SHOULD NOT be + generated, but may be interpreted. See Section 13.5. See Section + 13.8 for notes on Elliptic Curve (18), ECDSA (19), Elgamal Encrypt or + Sign (20), and X9.42 (21). Implementations MAY implement any other + algorithm. + +9.2. Symmetric-Key Algorithms + + ID Algorithm + -- --------- + 0 - Plaintext or unencrypted data + 1 - IDEA [IDEA] + 2 - TripleDES (DES-EDE, [SCHNEIER] [HAC] - + 168 bit key derived from 192) + 3 - CAST5 (128 bit key, as per [RFC2144]) + 4 - Blowfish (128 bit key, 16 rounds) [BLOWFISH] + 5 - Reserved + 6 - Reserved + 7 - AES with 128-bit key [AES] + 8 - AES with 192-bit key + 9 - AES with 256-bit key + 10 - Twofish with 256-bit key [TWOFISH] + 100 to 110 - Private/Experimental algorithm + + Implementations MUST implement TripleDES. Implementations SHOULD + implement AES-128 and CAST5. Implementations that interoperate with + + + + +Callas, et al Standards Track [Page 62] + +RFC 4880 OpenPGP Message Format November 2007 + + + PGP 2.6 or earlier need to support IDEA, as that is the only + symmetric cipher those versions use. Implementations MAY implement + any other algorithm. + +9.3. Compression Algorithms + + ID Algorithm + -- --------- + 0 - Uncompressed + 1 - ZIP [RFC1951] + 2 - ZLIB [RFC1950] + 3 - BZip2 [BZ2] + 100 to 110 - Private/Experimental algorithm + + Implementations MUST implement uncompressed data. Implementations + SHOULD implement ZIP. Implementations MAY implement any other + algorithm. + +9.4. Hash Algorithms + + ID Algorithm Text Name + -- --------- --------- + 1 - MD5 [HAC] "MD5" + 2 - SHA-1 [FIPS180] "SHA1" + 3 - RIPE-MD/160 [HAC] "RIPEMD160" + 4 - Reserved + 5 - Reserved + 6 - Reserved + 7 - Reserved + 8 - SHA256 [FIPS180] "SHA256" + 9 - SHA384 [FIPS180] "SHA384" + 10 - SHA512 [FIPS180] "SHA512" + 11 - SHA224 [FIPS180] "SHA224" + 100 to 110 - Private/Experimental algorithm + + Implementations MUST implement SHA-1. Implementations MAY implement + other algorithms. MD5 is deprecated. + +10. IANA Considerations + + OpenPGP is highly parameterized, and consequently there are a number + of considerations for allocating parameters for extensions. This + section describes how IANA should look at extensions to the protocol + as described in this document. + + + + + + + +Callas, et al Standards Track [Page 63] + +RFC 4880 OpenPGP Message Format November 2007 + + +10.1. New String-to-Key Specifier Types + + OpenPGP S2K specifiers contain a mechanism for new algorithms to turn + a string into a key. This specification creates a registry of S2K + specifier types. The registry includes the S2K type, the name of the + S2K, and a reference to the defining specification. The initial + values for this registry can be found in Section 3.7.1. Adding a new + S2K specifier MUST be done through the IETF CONSENSUS method, as + described in [RFC2434]. + +10.2. New Packets + + Major new features of OpenPGP are defined through new packet types. + This specification creates a registry of packet types. The registry + includes the packet type, the name of the packet, and a reference to + the defining specification. The initial values for this registry can + be found in Section 4.3. Adding a new packet type MUST be done + through the IETF CONSENSUS method, as described in [RFC2434]. + +10.2.1. User Attribute Types + + The User Attribute packet permits an extensible mechanism for other + types of certificate identification. This specification creates a + registry of User Attribute types. The registry includes the User + Attribute type, the name of the User Attribute, and a reference to + the defining specification. The initial values for this registry can + be found in Section 5.12. Adding a new User Attribute type MUST be + done through the IETF CONSENSUS method, as described in [RFC2434]. + +10.2.1.1. Image Format Subpacket Types + + Within User Attribute packets, there is an extensible mechanism for + other types of image-based user attributes. This specification + creates a registry of Image Attribute subpacket types. The registry + includes the Image Attribute subpacket type, the name of the Image + Attribute subpacket, and a reference to the defining specification. + The initial values for this registry can be found in Section 5.12.1. + Adding a new Image Attribute subpacket type MUST be done through the + IETF CONSENSUS method, as described in [RFC2434]. + +10.2.2. New Signature Subpackets + + OpenPGP signatures contain a mechanism for signed (or unsigned) data + to be added to them for a variety of purposes in the Signature + subpackets as discussed in Section 5.2.3.1. This specification + creates a registry of Signature subpacket types. The registry + includes the Signature subpacket type, the name of the subpacket, and + a reference to the defining specification. The initial values for + + + +Callas, et al Standards Track [Page 64] + +RFC 4880 OpenPGP Message Format November 2007 + + + this registry can be found in Section 5.2.3.1. Adding a new + Signature subpacket MUST be done through the IETF CONSENSUS method, + as described in [RFC2434]. + +10.2.2.1. Signature Notation Data Subpackets + + OpenPGP signatures further contain a mechanism for extensions in + signatures. These are the Notation Data subpackets, which contain a + key/value pair. Notations contain a user space that is completely + unmanaged and an IETF space. + + This specification creates a registry of Signature Notation Data + types. The registry includes the Signature Notation Data type, the + name of the Signature Notation Data, its allowed values, and a + reference to the defining specification. The initial values for this + registry can be found in Section 5.2.3.16. Adding a new Signature + Notation Data subpacket MUST be done through the EXPERT REVIEW + method, as described in [RFC2434]. + +10.2.2.2. Key Server Preference Extensions + + OpenPGP signatures contain a mechanism for preferences to be + specified about key servers. This specification creates a registry + of key server preferences. The registry includes the key server + preference, the name of the preference, and a reference to the + defining specification. The initial values for this registry can be + found in Section 5.2.3.17. Adding a new key server preference MUST + be done through the IETF CONSENSUS method, as described in [RFC2434]. + +10.2.2.3. Key Flags Extensions + + OpenPGP signatures contain a mechanism for flags to be specified + about key usage. This specification creates a registry of key usage + flags. The registry includes the key flags value, the name of the + flag, and a reference to the defining specification. The initial + values for this registry can be found in Section 5.2.3.21. Adding a + new key usage flag MUST be done through the IETF CONSENSUS method, as + described in [RFC2434]. + +10.2.2.4. Reason for Revocation Extensions + + OpenPGP signatures contain a mechanism for flags to be specified + about why a key was revoked. This specification creates a registry + of "Reason for Revocation" flags. The registry includes the "Reason + for Revocation" flags value, the name of the flag, and a reference to + the defining specification. The initial values for this registry can + be found in Section 5.2.3.23. Adding a new feature flag MUST be done + through the IETF CONSENSUS method, as described in [RFC2434]. + + + +Callas, et al Standards Track [Page 65] + +RFC 4880 OpenPGP Message Format November 2007 + + +10.2.2.5. Implementation Features + + OpenPGP signatures contain a mechanism for flags to be specified + stating which optional features an implementation supports. This + specification creates a registry of feature-implementation flags. + The registry includes the feature-implementation flags value, the + name of the flag, and a reference to the defining specification. The + initial values for this registry can be found in Section 5.2.3.24. + Adding a new feature-implementation flag MUST be done through the + IETF CONSENSUS method, as described in [RFC2434]. + + Also see Section 13.12 for more information about when feature flags + are needed. + +10.2.3. New Packet Versions + + The core OpenPGP packets all have version numbers, and can be revised + by introducing a new version of an existing packet. This + specification creates a registry of packet types. The registry + includes the packet type, the number of the version, and a reference + to the defining specification. The initial values for this registry + can be found in Section 5. Adding a new packet version MUST be done + through the IETF CONSENSUS method, as described in [RFC2434]. + +10.3. New Algorithms + + Section 9 lists the core algorithms that OpenPGP uses. Adding in a + new algorithm is usually simple. For example, adding in a new + symmetric cipher usually would not need anything more than allocating + a constant for that cipher. If that cipher had other than a 64-bit + or 128-bit block size, there might need to be additional + documentation describing how OpenPGP-CFB mode would be adjusted. + Similarly, when DSA was expanded from a maximum of 1024-bit public + keys to 3072-bit public keys, the revision of FIPS 186 contained + enough information itself to allow implementation. Changes to this + document were made mainly for emphasis. + +10.3.1. Public-Key Algorithms + + OpenPGP specifies a number of public-key algorithms. This + specification creates a registry of public-key algorithm identifiers. + The registry includes the algorithm name, its key sizes and + parameters, and a reference to the defining specification. The + initial values for this registry can be found in Section 9. Adding a + new public-key algorithm MUST be done through the IETF CONSENSUS + method, as described in [RFC2434]. + + + + + +Callas, et al Standards Track [Page 66] + +RFC 4880 OpenPGP Message Format November 2007 + + +10.3.2. Symmetric-Key Algorithms + + OpenPGP specifies a number of symmetric-key algorithms. This + specification creates a registry of symmetric-key algorithm + identifiers. The registry includes the algorithm name, its key sizes + and block size, and a reference to the defining specification. The + initial values for this registry can be found in Section 9. Adding a + new symmetric-key algorithm MUST be done through the IETF CONSENSUS + method, as described in [RFC2434]. + +10.3.3. Hash Algorithms + + OpenPGP specifies a number of hash algorithms. This specification + creates a registry of hash algorithm identifiers. The registry + includes the algorithm name, a text representation of that name, its + block size, an OID hash prefix, and a reference to the defining + specification. The initial values for this registry can be found in + Section 9 for the algorithm identifiers and text names, and Section + 5.2.2 for the OIDs and expanded signature prefixes. Adding a new + hash algorithm MUST be done through the IETF CONSENSUS method, as + described in [RFC2434]. + +10.3.4. Compression Algorithms + + OpenPGP specifies a number of compression algorithms. This + specification creates a registry of compression algorithm + identifiers. The registry includes the algorithm name and a + reference to the defining specification. The initial values for this + registry can be found in Section 9.3. Adding a new compression key + algorithm MUST be done through the IETF CONSENSUS method, as + described in [RFC2434]. + +11. Packet Composition + + OpenPGP packets are assembled into sequences in order to create + messages and to transfer keys. Not all possible packet sequences are + meaningful and correct. This section describes the rules for how + packets should be placed into sequences. + +11.1. Transferable Public Keys + + OpenPGP users may transfer public keys. The essential elements of a + transferable public key are as follows: + + - One Public-Key packet + + - Zero or more revocation signatures + + + + +Callas, et al Standards Track [Page 67] + +RFC 4880 OpenPGP Message Format November 2007 + + + - One or more User ID packets + + - After each User ID packet, zero or more Signature packets + (certifications) + + - Zero or more User Attribute packets + + - After each User Attribute packet, zero or more Signature packets + (certifications) + + - Zero or more Subkey packets + + - After each Subkey packet, one Signature packet, plus optionally a + revocation + + The Public-Key packet occurs first. Each of the following User ID + packets provides the identity of the owner of this public key. If + there are multiple User ID packets, this corresponds to multiple + means of identifying the same unique individual user; for example, a + user may have more than one email address, and construct a User ID + for each one. + + Immediately following each User ID packet, there are zero or more + Signature packets. Each Signature packet is calculated on the + immediately preceding User ID packet and the initial Public-Key + packet. The signature serves to certify the corresponding public key + and User ID. In effect, the signer is testifying to his or her + belief that this public key belongs to the user identified by this + User ID. + + Within the same section as the User ID packets, there are zero or + more User Attribute packets. Like the User ID packets, a User + Attribute packet is followed by zero or more Signature packets + calculated on the immediately preceding User Attribute packet and the + initial Public-Key packet. + + User Attribute packets and User ID packets may be freely intermixed + in this section, so long as the signatures that follow them are + maintained on the proper User Attribute or User ID packet. + + After the User ID packet or Attribute packet, there may be zero or + more Subkey packets. In general, subkeys are provided in cases where + the top-level public key is a signature-only key. However, any V4 + key may have subkeys, and the subkeys may be encryption-only keys, + signature-only keys, or general-purpose keys. V3 keys MUST NOT have + subkeys. + + + + + +Callas, et al Standards Track [Page 68] + +RFC 4880 OpenPGP Message Format November 2007 + + + Each Subkey packet MUST be followed by one Signature packet, which + should be a subkey binding signature issued by the top-level key. + For subkeys that can issue signatures, the subkey binding signature + MUST contain an Embedded Signature subpacket with a primary key + binding signature (0x19) issued by the subkey on the top-level key. + + Subkey and Key packets may each be followed by a revocation Signature + packet to indicate that the key is revoked. Revocation signatures + are only accepted if they are issued by the key itself, or by a key + that is authorized to issue revocations via a Revocation Key + subpacket in a self-signature by the top-level key. + + Transferable public-key packet sequences may be concatenated to allow + transferring multiple public keys in one operation. + +11.2. Transferable Secret Keys + + OpenPGP users may transfer secret keys. The format of a transferable + secret key is the same as a transferable public key except that + secret-key and secret-subkey packets are used instead of the public + key and public-subkey packets. Implementations SHOULD include self- + signatures on any user IDs and subkeys, as this allows for a complete + public key to be automatically extracted from the transferable secret + key. Implementations MAY choose to omit the self-signatures, + especially if a transferable public key accompanies the transferable + secret key. + +11.3. OpenPGP Messages + + An OpenPGP message is a packet or sequence of packets that + corresponds to the following grammatical rules (comma represents + sequential composition, and vertical bar separates alternatives): + + OpenPGP Message :- Encrypted Message | Signed Message | + Compressed Message | Literal Message. + + Compressed Message :- Compressed Data Packet. + + Literal Message :- Literal Data Packet. + + ESK :- Public-Key Encrypted Session Key Packet | + Symmetric-Key Encrypted Session Key Packet. + + ESK Sequence :- ESK | ESK Sequence, ESK. + + Encrypted Data :- Symmetrically Encrypted Data Packet | + Symmetrically Encrypted Integrity Protected Data Packet + + + + +Callas, et al Standards Track [Page 69] + +RFC 4880 OpenPGP Message Format November 2007 + + + Encrypted Message :- Encrypted Data | ESK Sequence, Encrypted Data. + + One-Pass Signed Message :- One-Pass Signature Packet, + OpenPGP Message, Corresponding Signature Packet. + + Signed Message :- Signature Packet, OpenPGP Message | + One-Pass Signed Message. + + In addition, decrypting a Symmetrically Encrypted Data packet or a + Symmetrically Encrypted Integrity Protected Data packet as well as + decompressing a Compressed Data packet must yield a valid OpenPGP + Message. + +11.4. Detached Signatures + + Some OpenPGP applications use so-called "detached signatures". For + example, a program bundle may contain a file, and with it a second + file that is a detached signature of the first file. These detached + signatures are simply a Signature packet stored separately from the + data for which they are a signature. + +12. Enhanced Key Formats + +12.1. Key Structures + + The format of an OpenPGP V3 key is as follows. Entries in square + brackets are optional and ellipses indicate repetition. + + RSA Public Key + [Revocation Self Signature] + User ID [Signature ...] + [User ID [Signature ...] ...] + + Each signature certifies the RSA public key and the preceding User + ID. The RSA public key can have many User IDs and each User ID can + have many signatures. V3 keys are deprecated. Implementations MUST + NOT generate new V3 keys, but MAY continue to use existing ones. + + The format of an OpenPGP V4 key that uses multiple public keys is + similar except that the other keys are added to the end as "subkeys" + of the primary key. + + + + + + + + + + +Callas, et al Standards Track [Page 70] + +RFC 4880 OpenPGP Message Format November 2007 + + + Primary-Key + [Revocation Self Signature] + [Direct Key Signature...] + User ID [Signature ...] + [User ID [Signature ...] ...] + [User Attribute [Signature ...] ...] + [[Subkey [Binding-Signature-Revocation] + Primary-Key-Binding-Signature] ...] + + A subkey always has a single signature after it that is issued using + the primary key to tie the two keys together. This binding signature + may be in either V3 or V4 format, but SHOULD be V4. Subkeys that can + issue signatures MUST have a V4 binding signature due to the REQUIRED + embedded primary key binding signature. + + In the above diagram, if the binding signature of a subkey has been + revoked, the revoked key may be removed, leaving only one key. + + In a V4 key, the primary key MUST be a key capable of certification. + The subkeys may be keys of any other type. There may be other + constructions of V4 keys, too. For example, there may be a single- + key RSA key in V4 format, a DSA primary key with an RSA encryption + key, or RSA primary key with an Elgamal subkey, etc. + + It is also possible to have a signature-only subkey. This permits a + primary key that collects certifications (key signatures), but is + used only for certifying subkeys that are used for encryption and + signatures. + +12.2. Key IDs and Fingerprints + + For a V3 key, the eight-octet Key ID consists of the low 64 bits of + the public modulus of the RSA key. + + The fingerprint of a V3 key is formed by hashing the body (but not + the two-octet length) of the MPIs that form the key material (public + modulus n, followed by exponent e) with MD5. Note that both V3 keys + and MD5 are deprecated. + + A V4 fingerprint is the 160-bit SHA-1 hash of the octet 0x99, + followed by the two-octet packet length, followed by the entire + Public-Key packet starting with the version field. The Key ID is the + low-order 64 bits of the fingerprint. Here are the fields of the + hash material, with the example of a DSA key: + + a.1) 0x99 (1 octet) + + a.2) high-order length octet of (b)-(e) (1 octet) + + + +Callas, et al Standards Track [Page 71] + +RFC 4880 OpenPGP Message Format November 2007 + + + a.3) low-order length octet of (b)-(e) (1 octet) + + b) version number = 4 (1 octet); + + c) timestamp of key creation (4 octets); + + d) algorithm (1 octet): 17 = DSA (example); + + e) Algorithm-specific fields. + + Algorithm-Specific Fields for DSA keys (example): + + e.1) MPI of DSA prime p; + + e.2) MPI of DSA group order q (q is a prime divisor of p-1); + + e.3) MPI of DSA group generator g; + + e.4) MPI of DSA public-key value y (= g**x mod p where x is secret). + + Note that it is possible for there to be collisions of Key IDs -- two + different keys with the same Key ID. Note that there is a much + smaller, but still non-zero, probability that two different keys have + the same fingerprint. + + Also note that if V3 and V4 format keys share the same RSA key + material, they will have different Key IDs as well as different + fingerprints. + + Finally, the Key ID and fingerprint of a subkey are calculated in the + same way as for a primary key, including the 0x99 as the first octet + (even though this is not a valid packet ID for a public subkey). + +13. Notes on Algorithms + +13.1. PKCS#1 Encoding in OpenPGP + + This standard makes use of the PKCS#1 functions EME-PKCS1-v1_5 and + EMSA-PKCS1-v1_5. However, the calling conventions of these functions + has changed in the past. To avoid potential confusion and + interoperability problems, we are including local copies in this + document, adapted from those in PKCS#1 v2.1 [RFC3447]. RFC 3447 + should be treated as the ultimate authority on PKCS#1 for OpenPGP. + Nonetheless, we believe that there is value in having a self- + contained document that avoids problems in the future with needed + changes in the conventions. + + + + + +Callas, et al Standards Track [Page 72] + +RFC 4880 OpenPGP Message Format November 2007 + + +13.1.1. EME-PKCS1-v1_5-ENCODE + + Input: + + k = the length in octets of the key modulus + + M = message to be encoded, an octet string of length mLen, where + mLen <= k - 11 + + Output: + + EM = encoded message, an octet string of length k + + Error: "message too long" + + 1. Length checking: If mLen > k - 11, output "message too long" and + stop. + + 2. Generate an octet string PS of length k - mLen - 3 consisting of + pseudo-randomly generated nonzero octets. The length of PS will + be at least eight octets. + + 3. Concatenate PS, the message M, and other padding to form an + encoded message EM of length k octets as + + EM = 0x00 || 0x02 || PS || 0x00 || M. + + 4. Output EM. + +13.1.2. EME-PKCS1-v1_5-DECODE + + Input: + + EM = encoded message, an octet string + + Output: + + M = message, an octet string + + Error: "decryption error" + + To decode an EME-PKCS1_v1_5 message, separate the encoded message EM + into an octet string PS consisting of nonzero octets and a message M + as follows + + EM = 0x00 || 0x02 || PS || 0x00 || M. + + + + + +Callas, et al Standards Track [Page 73] + +RFC 4880 OpenPGP Message Format November 2007 + + + If the first octet of EM does not have hexadecimal value 0x00, if the + second octet of EM does not have hexadecimal value 0x02, if there is + no octet with hexadecimal value 0x00 to separate PS from M, or if the + length of PS is less than 8 octets, output "decryption error" and + stop. See also the security note in Section 14 regarding differences + in reporting between a decryption error and a padding error. + +13.1.3. EMSA-PKCS1-v1_5 + + This encoding method is deterministic and only has an encoding + operation. + + Option: + + Hash - a hash function in which hLen denotes the length in octets of + the hash function output + + Input: + + M = message to be encoded + + mL = intended length in octets of the encoded message, at least tLen + + 11, where tLen is the octet length of the DER encoding T of a + certain value computed during the encoding operation + + Output: + + EM = encoded message, an octet string of length emLen + + Errors: "message too long"; "intended encoded message length too + short" + + Steps: + + 1. Apply the hash function to the message M to produce a hash value + H: + + H = Hash(M). + + If the hash function outputs "message too long," output "message + too long" and stop. + + 2. Using the list in Section 5.2.2, produce an ASN.1 DER value for + the hash function used. Let T be the full hash prefix from + Section 5.2.2, and let tLen be the length in octets of T. + + 3. If emLen < tLen + 11, output "intended encoded message length + too short" and stop. + + + +Callas, et al Standards Track [Page 74] + +RFC 4880 OpenPGP Message Format November 2007 + + + 4. Generate an octet string PS consisting of emLen - tLen - 3 + octets with hexadecimal value 0xFF. The length of PS will be at + least 8 octets. + + 5. Concatenate PS, the hash prefix T, and other padding to form the + encoded message EM as + + EM = 0x00 || 0x01 || PS || 0x00 || T. + + 6. Output EM. + +13.2. Symmetric Algorithm Preferences + + The symmetric algorithm preference is an ordered list of algorithms + that the keyholder accepts. Since it is found on a self-signature, + it is possible that a keyholder may have multiple, different + preferences. For example, Alice may have TripleDES only specified + for "alice@work.com" but CAST5, Blowfish, and TripleDES specified for + "alice@home.org". Note that it is also possible for preferences to + be in a subkey's binding signature. + + Since TripleDES is the MUST-implement algorithm, if it is not + explicitly in the list, it is tacitly at the end. However, it is + good form to place it there explicitly. Note also that if an + implementation does not implement the preference, then it is + implicitly a TripleDES-only implementation. + + An implementation MUST NOT use a symmetric algorithm that is not in + the recipient's preference list. When encrypting to more than one + recipient, the implementation finds a suitable algorithm by taking + the intersection of the preferences of the recipients. Note that the + MUST-implement algorithm, TripleDES, ensures that the intersection is + not null. The implementation may use any mechanism to pick an + algorithm in the intersection. + + If an implementation can decrypt a message that a keyholder doesn't + have in their preferences, the implementation SHOULD decrypt the + message anyway, but MUST warn the keyholder that the protocol has + been violated. For example, suppose that Alice, above, has software + that implements all algorithms in this specification. Nonetheless, + she prefers subsets for work or home. If she is sent a message + encrypted with IDEA, which is not in her preferences, the software + warns her that someone sent her an IDEA-encrypted message, but it + would ideally decrypt it anyway. + + + + + + + +Callas, et al Standards Track [Page 75] + +RFC 4880 OpenPGP Message Format November 2007 + + +13.3. Other Algorithm Preferences + + Other algorithm preferences work similarly to the symmetric algorithm + preference, in that they specify which algorithms the keyholder + accepts. There are two interesting cases that other comments need to + be made about, though, the compression preferences and the hash + preferences. + +13.3.1. Compression Preferences + + Compression has been an integral part of PGP since its first days. + OpenPGP and all previous versions of PGP have offered compression. + In this specification, the default is for messages to be compressed, + although an implementation is not required to do so. Consequently, + the compression preference gives a way for a keyholder to request + that messages not be compressed, presumably because they are using a + minimal implementation that does not include compression. + Additionally, this gives a keyholder a way to state that it can + support alternate algorithms. + + Like the algorithm preferences, an implementation MUST NOT use an + algorithm that is not in the preference vector. If the preferences + are not present, then they are assumed to be [ZIP(1), + Uncompressed(0)]. + + Additionally, an implementation MUST implement this preference to the + degree of recognizing when to send an uncompressed message. A robust + implementation would satisfy this requirement by looking at the + recipient's preference and acting accordingly. A minimal + implementation can satisfy this requirement by never generating a + compressed message, since all implementations can handle messages + that have not been compressed. + +13.3.2. Hash Algorithm Preferences + + Typically, the choice of a hash algorithm is something the signer + does, rather than the verifier, because a signer rarely knows who is + going to be verifying the signature. This preference, though, allows + a protocol based upon digital signatures ease in negotiation. + + Thus, if Alice is authenticating herself to Bob with a signature, it + makes sense for her to use a hash algorithm that Bob's software uses. + This preference allows Bob to state in his key which algorithms Alice + may use. + + Since SHA1 is the MUST-implement hash algorithm, if it is not + explicitly in the list, it is tacitly at the end. However, it is + good form to place it there explicitly. + + + +Callas, et al Standards Track [Page 76] + +RFC 4880 OpenPGP Message Format November 2007 + + +13.4. Plaintext + + Algorithm 0, "plaintext", may only be used to denote secret keys that + are stored in the clear. Implementations MUST NOT use plaintext in + Symmetrically Encrypted Data packets; they must use Literal Data + packets to encode unencrypted or literal data. + +13.5. RSA + + There are algorithm types for RSA Sign-Only, and RSA Encrypt-Only + keys. These types are deprecated. The "key flags" subpacket in a + signature is a much better way to express the same idea, and + generalizes it to all algorithms. An implementation SHOULD NOT + create such a key, but MAY interpret it. + + An implementation SHOULD NOT implement RSA keys of size less than + 1024 bits. + +13.6. DSA + + An implementation SHOULD NOT implement DSA keys of size less than + 1024 bits. It MUST NOT implement a DSA key with a q size of less + than 160 bits. DSA keys MUST also be a multiple of 64 bits, and the + q size MUST be a multiple of 8 bits. The Digital Signature Standard + (DSS) [FIPS186] specifies that DSA be used in one of the following + ways: + + * 1024-bit key, 160-bit q, SHA-1, SHA-224, SHA-256, SHA-384, or + SHA-512 hash + + * 2048-bit key, 224-bit q, SHA-224, SHA-256, SHA-384, or SHA-512 + hash + + * 2048-bit key, 256-bit q, SHA-256, SHA-384, or SHA-512 hash + + * 3072-bit key, 256-bit q, SHA-256, SHA-384, or SHA-512 hash + + The above key and q size pairs were chosen to best balance the + strength of the key with the strength of the hash. Implementations + SHOULD use one of the above key and q size pairs when generating DSA + keys. If DSS compliance is desired, one of the specified SHA hashes + must be used as well. [FIPS186] is the ultimate authority on DSS, + and should be consulted for all questions of DSS compliance. + + Note that earlier versions of this standard only allowed a 160-bit q + with no truncation allowed, so earlier implementations may not be + able to handle signatures with a different q size or a truncated + hash. + + + +Callas, et al Standards Track [Page 77] + +RFC 4880 OpenPGP Message Format November 2007 + + +13.7. Elgamal + + An implementation SHOULD NOT implement Elgamal keys of size less than + 1024 bits. + +13.8. Reserved Algorithm Numbers + + A number of algorithm IDs have been reserved for algorithms that + would be useful to use in an OpenPGP implementation, yet there are + issues that prevent an implementer from actually implementing the + algorithm. These are marked in Section 9.1, "Public-Key Algorithms", + as "reserved for". + + The reserved public-key algorithms, Elliptic Curve (18), ECDSA (19), + and X9.42 (21), do not have the necessary parameters, parameter + order, or semantics defined. + + Previous versions of OpenPGP permitted Elgamal [ELGAMAL] signatures + with a public-key identifier of 20. These are no longer permitted. + An implementation MUST NOT generate such keys. An implementation + MUST NOT generate Elgamal signatures. See [BLEICHENBACHER]. + +13.9. OpenPGP CFB Mode + + OpenPGP does symmetric encryption using a variant of Cipher Feedback + mode (CFB mode). This section describes the procedure it uses in + detail. This mode is what is used for Symmetrically Encrypted Data + Packets; the mechanism used for encrypting secret-key material is + similar, and is described in the sections above. + + In the description below, the value BS is the block size in octets of + the cipher. Most ciphers have a block size of 8 octets. The AES and + Twofish have a block size of 16 octets. Also note that the + description below assumes that the IV and CFB arrays start with an + index of 1 (unlike the C language, which assumes arrays start with a + zero index). + + OpenPGP CFB mode uses an initialization vector (IV) of all zeros, and + prefixes the plaintext with BS+2 octets of random data, such that + octets BS+1 and BS+2 match octets BS-1 and BS. It does a CFB + resynchronization after encrypting those BS+2 octets. + + Thus, for an algorithm that has a block size of 8 octets (64 bits), + the IV is 10 octets long and octets 7 and 8 of the IV are the same as + octets 9 and 10. For an algorithm with a block size of 16 octets + (128 bits), the IV is 18 octets long, and octets 17 and 18 replicate + octets 15 and 16. Those extra two octets are an easy check for a + correct key. + + + +Callas, et al Standards Track [Page 78] + +RFC 4880 OpenPGP Message Format November 2007 + + + Step by step, here is the procedure: + + 1. The feedback register (FR) is set to the IV, which is all zeros. + + 2. FR is encrypted to produce FRE (FR Encrypted). This is the + encryption of an all-zero value. + + 3. FRE is xored with the first BS octets of random data prefixed to + the plaintext to produce C[1] through C[BS], the first BS octets + of ciphertext. + + 4. FR is loaded with C[1] through C[BS]. + + 5. FR is encrypted to produce FRE, the encryption of the first BS + octets of ciphertext. + + 6. The left two octets of FRE get xored with the next two octets of + data that were prefixed to the plaintext. This produces C[BS+1] + and C[BS+2], the next two octets of ciphertext. + + 7. (The resynchronization step) FR is loaded with C[3] through + C[BS+2]. + + 8. FR is encrypted to produce FRE. + + 9. FRE is xored with the first BS octets of the given plaintext, now + that we have finished encrypting the BS+2 octets of prefixed + data. This produces C[BS+3] through C[BS+(BS+2)], the next BS + octets of ciphertext. + + 10. FR is loaded with C[BS+3] to C[BS + (BS+2)] (which is C11-C18 for + an 8-octet block). + + 11. FR is encrypted to produce FRE. + + 12. FRE is xored with the next BS octets of plaintext, to produce + the next BS octets of ciphertext. These are loaded into FR, and + the process is repeated until the plaintext is used up. + +13.10. Private or Experimental Parameters + + S2K specifiers, Signature subpacket types, user attribute types, + image format types, and algorithms described in Section 9 all reserve + the range 100 to 110 for private and experimental use. Packet types + reserve the range 60 to 63 for private and experimental use. These + are intentionally managed with the PRIVATE USE method, as described + in [RFC2434]. + + + + +Callas, et al Standards Track [Page 79] + +RFC 4880 OpenPGP Message Format November 2007 + + + However, implementations need to be careful with these and promote + them to full IANA-managed parameters when they grow beyond the + original, limited system. + +13.11. Extension of the MDC System + + As described in the non-normative explanation in Section 5.13, the + MDC system is uniquely unparameterized in OpenPGP. This was an + intentional decision to avoid cross-grade attacks. If the MDC system + is extended to a stronger hash function, care must be taken to avoid + downgrade and cross-grade attacks. + + One simple way to do this is to create new packets for a new MDC. + For example, instead of the MDC system using packets 18 and 19, a new + MDC could use 20 and 21. This has obvious drawbacks (it uses two + packet numbers for each new hash function in a space that is limited + to a maximum of 60). + + Another simple way to extend the MDC system is to create new versions + of packet 18, and reflect this in packet 19. For example, suppose + that V2 of packet 18 implicitly used SHA-256. This would require + packet 19 to have a length of 32 octets. The change in the version + in packet 18 and the size of packet 19 prevent a downgrade attack. + + There are two drawbacks to this latter approach. The first is that + using the version number of a packet to carry algorithm information + is not tidy from a protocol-design standpoint. It is possible that + there might be several versions of the MDC system in common use, but + this untidiness would reflect untidiness in cryptographic consensus + about hash function security. The second is that different versions + of packet 19 would have to have unique sizes. If there were two + versions each with 256-bit hashes, they could not both have 32-octet + packet 19s without admitting the chance of a cross-grade attack. + + Yet another, complex approach to extend the MDC system would be a + hybrid of the two above -- create a new pair of MDC packets that are + fully parameterized, and yet protected from downgrade and cross- + grade. + + Any change to the MDC system MUST be done through the IETF CONSENSUS + method, as described in [RFC2434]. + +13.12. Meta-Considerations for Expansion + + If OpenPGP is extended in a way that is not backwards-compatible, + meaning that old implementations will not gracefully handle their + + + + + +Callas, et al Standards Track [Page 80] + +RFC 4880 OpenPGP Message Format November 2007 + + + absence of a new feature, the extension proposal can be declared in + the key holder's self-signature as part of the Features signature + subpacket. + + We cannot state definitively what extensions will not be upwards- + compatible, but typically new algorithms are upwards-compatible, + whereas new packets are not. + + If an extension proposal does not update the Features system, it + SHOULD include an explanation of why this is unnecessary. If the + proposal contains neither an extension to the Features system nor an + explanation of why such an extension is unnecessary, the proposal + SHOULD be rejected. + +14. Security Considerations + + * As with any technology involving cryptography, you should check the + current literature to determine if any algorithms used here have + been found to be vulnerable to attack. + + * This specification uses Public-Key Cryptography technologies. It + is assumed that the private key portion of a public-private key + pair is controlled and secured by the proper party or parties. + + * Certain operations in this specification involve the use of random + numbers. An appropriate entropy source should be used to generate + these numbers (see [RFC4086]). + + * The MD5 hash algorithm has been found to have weaknesses, with + collisions found in a number of cases. MD5 is deprecated for use + in OpenPGP. Implementations MUST NOT generate new signatures using + MD5 as a hash function. They MAY continue to consider old + signatures that used MD5 as valid. + + * SHA-224 and SHA-384 require the same work as SHA-256 and SHA-512, + respectively. In general, there are few reasons to use them + outside of DSS compatibility. You need a situation where one needs + more security than smaller hashes, but does not want to have the + full 256-bit or 512-bit data length. + + * Many security protocol designers think that it is a bad idea to use + a single key for both privacy (encryption) and integrity + (signatures). In fact, this was one of the motivating forces + behind the V4 key format with separate signature and encryption + keys. If you as an implementer promote dual-use keys, you should + at least be aware of this controversy. + + + + + +Callas, et al Standards Track [Page 81] + +RFC 4880 OpenPGP Message Format November 2007 + + + * The DSA algorithm will work with any hash, but is sensitive to the + quality of the hash algorithm. Verifiers should be aware that even + if the signer used a strong hash, an attacker could have modified + the signature to use a weak one. Only signatures using acceptably + strong hash algorithms should be accepted as valid. + + * As OpenPGP combines many different asymmetric, symmetric, and hash + algorithms, each with different measures of strength, care should + be taken that the weakest element of an OpenPGP message is still + sufficiently strong for the purpose at hand. While consensus about + the strength of a given algorithm may evolve, NIST Special + Publication 800-57 [SP800-57] recommends the following list of + equivalent strengths: + + Asymmetric | Hash | Symmetric + key size | size | key size + ------------+--------+----------- + 1024 160 80 + 2048 224 112 + 3072 256 128 + 7680 384 192 + 15360 512 256 + + * There is a somewhat-related potential security problem in + signatures. If an attacker can find a message that hashes to the + same hash with a different algorithm, a bogus signature structure + can be constructed that evaluates correctly. + + For example, suppose Alice DSA signs message M using hash algorithm + H. Suppose that Mallet finds a message M' that has the same hash + value as M with H'. Mallet can then construct a signature block + that verifies as Alice's signature of M' with H'. However, this + would also constitute a weakness in either H or H' or both. Should + this ever occur, a revision will have to be made to this document + to revise the allowed hash algorithms. + + * If you are building an authentication system, the recipient may + specify a preferred signing algorithm. However, the signer would + be foolish to use a weak algorithm simply because the recipient + requests it. + + * Some of the encryption algorithms mentioned in this document have + been analyzed less than others. For example, although CAST5 is + presently considered strong, it has been analyzed less than + TripleDES. Other algorithms may have other controversies + surrounding them. + + + + + +Callas, et al Standards Track [Page 82] + +RFC 4880 OpenPGP Message Format November 2007 + + + * In late summer 2002, Jallad, Katz, and Schneier published an + interesting attack on the OpenPGP protocol and some of its + implementations [JKS02]. In this attack, the attacker modifies a + message and sends it to a user who then returns the erroneously + decrypted message to the attacker. The attacker is thus using the + user as a random oracle, and can often decrypt the message. + + Compressing data can ameliorate this attack. The incorrectly + decrypted data nearly always decompresses in ways that defeat the + attack. However, this is not a rigorous fix, and leaves open some + small vulnerabilities. For example, if an implementation does not + compress a message before encryption (perhaps because it knows it + was already compressed), then that message is vulnerable. Because + of this happenstance -- that modification attacks can be thwarted + by decompression errors -- an implementation SHOULD treat a + decompression error as a security problem, not merely a data + problem. + + This attack can be defeated by the use of Modification Detection, + provided that the implementation does not let the user naively + return the data to the attacker. An implementation MUST treat an + MDC failure as a security problem, not merely a data problem. + + In either case, the implementation MAY allow the user access to the + erroneous data, but MUST warn the user as to potential security + problems should that data be returned to the sender. + + While this attack is somewhat obscure, requiring a special set of + circumstances to create it, it is nonetheless quite serious as it + permits someone to trick a user to decrypt a message. + Consequently, it is important that: + + 1. Implementers treat MDC errors and decompression failures as + security problems. + + 2. Implementers implement Modification Detection with all due + speed and encourage its spread. + + 3. Users migrate to implementations that support Modification + Detection with all due speed. + + * PKCS#1 has been found to be vulnerable to attacks in which a system + that reports errors in padding differently from errors in + decryption becomes a random oracle that can leak the private key in + mere millions of queries. Implementations must be aware of this + attack and prevent it from happening. The simplest solution is to + report a single error code for all variants of decryption errors so + as not to leak information to an attacker. + + + +Callas, et al Standards Track [Page 83] + +RFC 4880 OpenPGP Message Format November 2007 + + + * Some technologies mentioned here may be subject to government + control in some countries. + + * In winter 2005, Serge Mister and Robert Zuccherato from Entrust + released a paper describing a way that the "quick check" in OpenPGP + CFB mode can be used with a random oracle to decrypt two octets of + every cipher block [MZ05]. They recommend as prevention not using + the quick check at all. + + Many implementers have taken this advice to heart for any data that + is symmetrically encrypted and for which the session key is + public-key encrypted. In this case, the quick check is not needed + as the public-key encryption of the session key should guarantee + that it is the right session key. In other cases, the + implementation should use the quick check with care. + + On the one hand, there is a danger to using it if there is a random + oracle that can leak information to an attacker. In plainer + language, there is a danger to using the quick check if timing + information about the check can be exposed to an attacker, + particularly via an automated service that allows rapidly repeated + queries. + + On the other hand, it is inconvenient to the user to be informed + that they typed in the wrong passphrase only after a petabyte of + data is decrypted. There are many cases in cryptographic + engineering where the implementer must use care and wisdom, and + this is one. + +15. Implementation Nits + + This section is a collection of comments to help an implementer, + particularly with an eye to backward compatibility. Previous + implementations of PGP are not OpenPGP compliant. Often the + differences are small, but small differences are frequently more + vexing than large differences. Thus, this is a non-comprehensive + list of potential problems and gotchas for a developer who is trying + to be backward-compatible. + + * The IDEA algorithm is patented, and yet it is required for PGP + 2.x interoperability. It is also the de-facto preferred + algorithm for a V3 key with a V3 self-signature (or no self- + signature). + + * When exporting a private key, PGP 2.x generates the header "BEGIN + PGP SECRET KEY BLOCK" instead of "BEGIN PGP PRIVATE KEY BLOCK". + All previous versions ignore the implied data type, and look + directly at the packet data type. + + + +Callas, et al Standards Track [Page 84] + +RFC 4880 OpenPGP Message Format November 2007 + + + * PGP 2.0 through 2.5 generated V2 Public-Key packets. These are + identical to the deprecated V3 keys except for the version + number. An implementation MUST NOT generate them and may accept + or reject them as it sees fit. Some older PGP versions generated + V2 PKESK packets (Tag 1) as well. An implementation may accept + or reject V2 PKESK packets as it sees fit, and MUST NOT generate + them. + + * PGP 2.6.x will not accept key-material packets with versions + greater than 3. + + * There are many ways possible for two keys to have the same key + material, but different fingerprints (and thus Key IDs). Perhaps + the most interesting is an RSA key that has been "upgraded" to V4 + format, but since a V4 fingerprint is constructed by hashing the + key creation time along with other things, two V4 keys created at + different times, yet with the same key material will have + different fingerprints. + + * If an implementation is using zlib to interoperate with PGP 2.x, + then the "windowBits" parameter should be set to -13. + + * The 0x19 back signatures were not required for signing subkeys + until relatively recently. Consequently, there may be keys in + the wild that do not have these back signatures. Implementing + software may handle these keys as it sees fit. + + * OpenPGP does not put limits on the size of public keys. However, + larger keys are not necessarily better keys. Larger keys take + more computation time to use, and this can quickly become + impractical. Different OpenPGP implementations may also use + different upper bounds for public key sizes, and so care should + be taken when choosing sizes to maintain interoperability. As of + 2007 most implementations have an upper bound of 4096 bits. + + * ASCII armor is an optional feature of OpenPGP. The OpenPGP + working group strives for a minimal set of mandatory-to-implement + features, and since there could be useful implementations that + only use binary object formats, this is not a "MUST" feature for + an implementation. For example, an implementation that is using + OpenPGP as a mechanism for file signatures may find ASCII armor + unnecessary. OpenPGP permits an implementation to declare what + features it does and does not support, but ASCII armor is not one + of these. Since most implementations allow binary and armored + objects to be used indiscriminately, an implementation that does + not implement ASCII armor may find itself with compatibility + issues with general-purpose implementations. Moreover, + implementations of OpenPGP-MIME [RFC3156] already have a + + + +Callas, et al Standards Track [Page 85] + +RFC 4880 OpenPGP Message Format November 2007 + + + requirement for ASCII armor so those implementations will + necessarily have support. + +16. References + +16.1. Normative References + + [AES] NIST, FIPS PUB 197, "Advanced Encryption Standard + (AES)," November 2001. + http://csrc.nist.gov/publications/fips/fips197/fips- + 197.{ps,pdf} + + [BLOWFISH] Schneier, B. "Description of a New Variable-Length + Key, 64-Bit Block Cipher (Blowfish)" Fast Software + Encryption, Cambridge Security Workshop Proceedings + (December 1993), Springer-Verlag, 1994, pp191-204 + + + [BZ2] J. Seward, jseward@acm.org, "The Bzip2 and libbzip2 + home page" + + [ELGAMAL] T. Elgamal, "A Public-Key Cryptosystem and a + Signature Scheme Based on Discrete Logarithms," IEEE + Transactions on Information Theory, v. IT-31, n. 4, + 1985, pp. 469-472. + + [FIPS180] Secure Hash Signature Standard (SHS) (FIPS PUB 180- + 2). + + + [FIPS186] Digital Signature Standard (DSS) (FIPS PUB 186-2). + FIPS 186-3 describes keys + greater than 1024 bits. The latest draft is at: + + + [HAC] Alfred Menezes, Paul van Oorschot, and Scott + Vanstone, "Handbook of Applied Cryptography," CRC + Press, 1996. + + + [IDEA] Lai, X, "On the design and security of block + ciphers", ETH Series in Information Processing, J.L. + Massey (editor), Vol. 1, Hartung-Gorre Verlag + Knostanz, Technische Hochschule (Zurich), 1992 + + + + +Callas, et al Standards Track [Page 86] + +RFC 4880 OpenPGP Message Format November 2007 + + + [ISO10646] ISO/IEC 10646-1:1993. International Standard -- + Information technology -- Universal Multiple-Octet + Coded Character Set (UCS) -- Part 1: Architecture + and Basic Multilingual Plane. + + [JFIF] JPEG File Interchange Format (Version 1.02). Eric + Hamilton, C-Cube Microsystems, Milpitas, CA, + September 1, 1992. + + [RFC1950] Deutsch, P. and J-L. Gailly, "ZLIB Compressed Data + Format Specification version 3.3", RFC 1950, May + 1996. + + [RFC1951] Deutsch, P., "DEFLATE Compressed Data Format + Specification version 1.3", RFC 1951, May 1996. + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet + Mail Extensions (MIME) Part One: Format of Internet + Message Bodies", RFC 2045, November 1996 + + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RFC2144] Adams, C., "The CAST-128 Encryption Algorithm", RFC + 2144, May 1997. + + [RFC2434] Narten, T. and H. Alvestrand, "Guidelines for + Writing an IANA Considerations Section in RFCs", BCP + 26, RFC 2434, October 1998. + + [RFC2822] Resnick, P., "Internet Message Format", RFC 2822, + April 2001. + + [RFC3156] Elkins, M., Del Torto, D., Levien, R., and T. + Roessler, "MIME Security with OpenPGP", RFC 3156, + August 2001. + + [RFC3447] Jonsson, J. and B. Kaliski, "Public-Key Cryptography + Standards (PKCS) #1: RSA Cryptography Specifications + Version 2.1", RFC 3447, February 2003. + + [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, November 2003. + + [RFC4086] Eastlake, D., 3rd, Schiller, J., and S. Crocker, + "Randomness Requirements for Security", BCP 106, RFC + 4086, June 2005. + + + + +Callas, et al Standards Track [Page 87] + +RFC 4880 OpenPGP Message Format November 2007 + + + [SCHNEIER] Schneier, B., "Applied Cryptography Second Edition: + protocols, algorithms, and source code in C", 1996. + + [TWOFISH] B. Schneier, J. Kelsey, D. Whiting, D. Wagner, C. + Hall, and N. Ferguson, "The Twofish Encryption + Algorithm", John Wiley & Sons, 1999. + +16.2. Informative References + + [BLEICHENBACHER] Bleichenbacher, Daniel, "Generating Elgamal + signatures without knowing the secret key," + Eurocrypt 96. Note that the version in the + proceedings has an error. A revised version is + available at the time of writing from + + + [JKS02] Kahil Jallad, Jonathan Katz, Bruce Schneier + "Implementation of Chosen-Ciphertext Attacks against + PGP and GnuPG" http://www.counterpane.com/pgp- + attack.html + + [MAURER] Ueli Maurer, "Modelling a Public-Key + Infrastructure", Proc. 1996 European Symposium on + Research in Computer Security (ESORICS' 96), Lecture + Notes in Computer Science, Springer-Verlag, vol. + 1146, pp. 325-350, Sep 1996. + + [MZ05] Serge Mister, Robert Zuccherato, "An Attack on CFB + Mode Encryption As Used By OpenPGP," IACR ePrint + Archive: Report 2005/033, 8 Feb 2005 + http://eprint.iacr.org/2005/033 + + [REGEX] Jeffrey Friedl, "Mastering Regular Expressions," + O'Reilly, ISBN 0-596-00289-0. + + [RFC1423] Balenson, D., "Privacy Enhancement for Internet + Electronic Mail: Part III: Algorithms, Modes, and + Identifiers", RFC 1423, February 1993. + + [RFC1991] Atkins, D., Stallings, W., and P. Zimmermann, "PGP + Message Exchange Formats", RFC 1991, August 1996. + + [RFC2440] Callas, J., Donnerhacke, L., Finney, H., and R. + Thayer, "OpenPGP Message Format", RFC 2440, November + 1998. + + + + + +Callas, et al Standards Track [Page 88] + +RFC 4880 OpenPGP Message Format November 2007 + + + [SP800-57] NIST Special Publication 800-57, Recommendation on + Key Management + + + +Acknowledgements + + This memo also draws on much previous work from a number of other + authors, including: Derek Atkins, Charles Breed, Dave Del Torto, Marc + Dyksterhouse, Gail Haspert, Gene Hoffman, Paul Hoffman, Ben Laurie, + Raph Levien, Colin Plumb, Will Price, David Shaw, William Stallings, + Mark Weaver, and Philip R. Zimmermann. + +Authors' Addresses + + The working group can be contacted via the current chair: + + Derek Atkins + IHTFP Consulting, Inc. + 4 Farragut Ave + Somerville, MA 02144 USA + + EMail: derek@ihtfp.com + Tel: +1 617 623 3745 + + The principal authors of this document are as follows: + + Jon Callas + EMail: jon@callas.org + + Lutz Donnerhacke + IKS GmbH + Wildenbruchstr. 15 + 07745 Jena, Germany + EMail: lutz@iks-jena.de + + Hal Finney + EMail: hal@finney.org + + David Shaw + EMail: dshaw@jabberwocky.com + + Rodney Thayer + EMail: rodney@canola-jones.com + + + + + +Callas, et al Standards Track [Page 89] + +RFC 4880 OpenPGP Message Format November 2007 + + +Full Copyright Statement + + Copyright (C) The IETF Trust (2007). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND + THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF + THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + + + + + + + + + + + + +Callas, et al Standards Track [Page 90] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4954.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4954.txt new file mode 100644 index 00000000..668d7383 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc4954.txt @@ -0,0 +1,1123 @@ + + + + + + +Network Working Group R. Siemborski, Ed. +Request for Comments: 4954 Google, Inc. +Obsoletes: 2554 A. Melnikov, Ed. +Updates: 3463 Isode Limited +Category: Standards Track July 2007 + + + SMTP Service Extension for Authentication + +Status of This Memo + + This document specifies an Internet standards track protocol for the + Internet community, and requests discussion and suggestions for + improvements. Please refer to the current edition of the "Internet + Official Protocol Standards" (STD 1) for the standardization state + and status of this protocol. Distribution of this memo is unlimited. + +Copyright Notice + + Copyright (C) The IETF Trust (2007). + +Abstract + + This document defines a Simple Mail Transport Protocol (SMTP) + extension whereby an SMTP client may indicate an authentication + mechanism to the server, perform an authentication protocol exchange, + and optionally negotiate a security layer for subsequent protocol + interactions during this session. This extension includes a profile + of the Simple Authentication and Security Layer (SASL) for SMTP. + + This document obsoletes RFC 2554. + + + + + + + + + + + + + + + + + + + + +Siemborski & Melnikov Standards Track [Page 1] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +Table of Contents + + 1. Introduction ....................................................2 + 2. How to Read This Document .......................................2 + 3. The Authentication Service Extension ............................3 + 4. The AUTH Command ................................................3 + 4.1. Examples ...................................................7 + 5. The AUTH Parameter to the MAIL FROM command .....................9 + 5.1. Examples ..................................................10 + 6. Status Codes ...................................................11 + 7. Additional requirements on servers .............................12 + 8. Formal Syntax ..................................................13 + 9. Security Considerations ........................................14 + 10. IANA Considerations ...........................................15 + 11. Normative References ..........................................15 + 12. Informative References ........................................16 + 13. Acknowledgments ...............................................17 + 14. Additional Requirements When Using SASL PLAIN over TLS ........17 + 15. Changes since RFC 2554 ........................................18 + +1. Introduction + + This document defines a Simple Mail Transport Protocol (SMTP) + extension whereby an SMTP client may indicate an authentication + mechanism to the server, perform an authentication protocol exchange, + optionally negotiate a security layer for subsequent protocol + interactions during this session and, during a mail transaction, + optionally specify a mailbox associated with the identity that + submitted the message to the mail delivery system. + + This extension includes a profile of the Simple Authentication and + Security Layer (SASL) for SMTP. + + When compared to RFC 2554, this document deprecates use of the 538 + response code, adds a new Enhanced Status Code, adds a requirement to + support SASLprep profile for preparing authorization identities, + recommends use of RFC 3848 transmission types in the Received trace + header field, and clarifies interaction with SMTP PIPELINING + [PIPELINING] extension. + +2. How to Read This Document + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [KEYWORDS]. + + In examples, "C:" and "S:" indicate lines sent by the client and + server, respectively. + + + +Siemborski & Melnikov Standards Track [Page 2] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +3. The Authentication Service Extension + + 1. The name of this [SMTP] service extension is "Authentication". + + 2. The EHLO keyword value associated with this extension is "AUTH". + + 3. The AUTH EHLO keyword contains as a parameter a space-separated + list of the names of available [SASL] mechanisms. The list of + available mechanisms MAY change after a successful STARTTLS + command [SMTP-TLS]. + + 4. A new [SMTP] verb "AUTH" is defined. + + 5. An optional parameter using the keyword "AUTH" is added to the + MAIL FROM command, and extends the maximum line length of the + MAIL FROM command by 500 characters. + + 6. This extension is appropriate for the submission protocol + [SUBMIT]. + +4. The AUTH Command + + AUTH mechanism [initial-response] + + Arguments: + mechanism: A string identifying a [SASL] authentication + mechanism. + + initial-response: An optional initial client response. If + present, this response MUST be encoded as described in Section + 4 of [BASE64] or contain a single character "=". + + Restrictions: + After an AUTH command has been successfully completed, no more + AUTH commands may be issued in the same session. After a + successful AUTH command completes, a server MUST reject any + further AUTH commands with a 503 reply. + + The AUTH command is not permitted during a mail transaction. + An AUTH command issued during a mail transaction MUST be + rejected with a 503 reply. + + Discussion: + The AUTH command initiates a [SASL] authentication exchange + between the client and the server. The client identifies the + SASL mechanism to use with the first parameter of the AUTH + command. If the server supports the requested authentication + mechanism, it performs the SASL exchange to authenticate the + + + +Siemborski & Melnikov Standards Track [Page 3] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + user. Optionally, it also negotiates a security layer for + subsequent protocol interactions during this session. If the + requested authentication mechanism is invalid (e.g., is not + supported or requires an encryption layer), the server rejects + the AUTH command with a 504 reply. If the server supports the + [ESMTP-CODES] extension, it SHOULD return a 5.5.4 enhanced + response code. + + The SASL authentication exchange consists of a series of + server challenges and client responses that are specific to + the chosen [SASL] mechanism. + + A server challenge is sent as a 334 reply with the text part + containing the [BASE64] encoded string supplied by the SASL + mechanism. This challenge MUST NOT contain any text other + than the BASE64 encoded challenge. + + A client response consists of a line containing a [BASE64] + encoded string. If the client wishes to cancel the + authentication exchange, it issues a line with a single "*". + If the server receives such a response, it MUST reject the + AUTH command by sending a 501 reply. + + The optional initial response argument to the AUTH command is + used to save a round-trip when using authentication mechanisms + that support an initial client response. If the initial + response argument is omitted and the chosen mechanism requires + an initial client response, the server MUST proceed as defined + in Section 5.1 of [SASL]. In SMTP, a server challenge that + contains no data is defined as a 334 reply with no text part. + Note that there is still a space following the reply code, so + the complete response line is "334 ". + + Note that the AUTH command is still subject to the line length + limitations defined in [SMTP]. If use of the initial response + argument would cause the AUTH command to exceed this length, + the client MUST NOT use the initial response parameter (and + instead proceed as defined in Section 5.1 of [SASL]). + + If the client is transmitting an initial response of zero + length, it MUST instead transmit the response as a single + equals sign ("="). This indicates that the response is + present, but contains no data. + + If the client uses an initial-response argument to the AUTH + command with a SASL mechanism in which the client does not + begin the authentication exchange, the server MUST reject the + + + + +Siemborski & Melnikov Standards Track [Page 4] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + AUTH command with a 501 reply. Servers using the enhanced + status codes extension [ESMTP-CODES] SHOULD return an enhanced + status code of 5.7.0 in this case. + + If the server cannot [BASE64] decode any client response, it + MUST reject the AUTH command with a 501 reply (and an enhanced + status code of 5.5.2). If the client cannot BASE64 decode any + of the server's challenges, it MUST cancel the authentication + using the "*" response. In particular, servers and clients + MUST reject (and not ignore) any character not explicitly + allowed by the BASE64 alphabet, and MUST reject any sequence + of BASE64 characters that contains the pad character ('=') + anywhere other than the end of the string (e.g., "=AAA" and + "AAA=BBB" are not allowed). + + Note that these [BASE64] strings can be much longer than + normal SMTP commands. Clients and servers MUST be able to + handle the maximum encoded size of challenges and responses + generated by their supported authentication mechanisms. This + requirement is independent of any line length limitations the + client or server may have in other parts of its protocol + implementation. (At the time of writing of this document, + 12288 octets is considered to be a sufficient line length + limit for handling of deployed authentication mechanisms.) + If, during an authentication exchange, the server receives a + line that is longer than the server's authentication buffer, + the server fails the AUTH command with the 500 reply. Servers + using the enhanced status codes extension [ESMTP-CODES] SHOULD + return an enhanced status code of 5.5.6 in this case. + + The authorization identity generated by this [SASL] exchange + is a "simple username" (in the sense defined in [SASLprep]), + and both client and server SHOULD (*) use the [SASLprep] + profile of the [StringPrep] algorithm to prepare these names + for transmission or comparison. If preparation of the + authorization identity fails or results in an empty string + (unless it was transmitted as the empty string), the server + MUST fail the authentication. + + (*) Note: Future revision of this specification may change this + requirement to MUST. Currently, the SHOULD is used in order to + avoid breaking the majority of existing implementations. + + If the server is unable to authenticate the client, it SHOULD reject + the AUTH command with a 535 reply unless a more specific error code + is appropriate. Should the client successfully complete the + exchange, the SMTP server issues a 235 reply. (Note that the SMTP + protocol doesn't support the SASL feature of returning additional + + + +Siemborski & Melnikov Standards Track [Page 5] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + data with a successful outcome.) These status codes, along with + others defined by this extension, are discussed in Section 6 of this + document. + + If a security layer is negotiated during the SASL exchange, it takes + effect for the client on the octet immediately following the CRLF + that concludes the last response generated by the client. For the + server, it takes effect immediately following the CRLF of its success + reply. + + When a security layer takes effect, the SMTP protocol is reset to the + initial state (the state in SMTP after a server issues a 220 service + ready greeting). The server MUST discard any knowledge obtained from + the client, such as the EHLO argument, which was not obtained from + the SASL negotiation itself. Likewise, the client MUST discard any + knowledge obtained from the server, such as the list of SMTP service + extensions, which was not obtained from the SASL negotiation itself. + (Note that a client MAY compare the advertised SASL mechanisms before + and after authentication in order to detect an active down- + negotiation attack). + + The client SHOULD send an EHLO command as the first command after a + successful SASL negotiation that results in the enabling of a + security layer. + + When an entity (whether it is the client or the server end) is + sending data, and both [TLS] and SASL security layers are in effect, + the TLS encoding MUST be applied after the SASL encoding, regardless + of the order in which the layers were negotiated. + + The service name specified by this protocol's profile of SASL is + "smtp". This service name is also to be used for the [SUBMIT] + protocol. + + If an AUTH command fails, the client MAY proceed without + authentication. Alternatively, the client MAY try another + authentication mechanism or present different credentials by issuing + another AUTH + + Note: A server implementation MUST implement a configuration in which + it does NOT permit any plaintext password mechanisms, unless either + the STARTTLS [SMTP-TLS] command has been negotiated or some other + mechanism that protects the session from password snooping has been + provided. Server sites SHOULD NOT use any configuration which + permits a plaintext password mechanism without such a protection + mechanism against password snooping. + + + + + +Siemborski & Melnikov Standards Track [Page 6] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + To ensure interoperability, client and server implementations of this + extension MUST implement the [PLAIN] SASL mechanism running over TLS + [TLS] [SMTP-TLS]. See also Section 15 for additional requirements on + implementations of [PLAIN] over [TLS]. + + Note that many existing client and server implementations implement + CRAM-MD5 [CRAM-MD5] SASL mechanism. In order to ensure + interoperability with deployed software, new implementations MAY + implement it; however, implementations should be aware that this SASL + mechanism doesn't provide any server authentication. Note that at + the time of writing of this document the SASL Working Group is + working on several replacement SASL mechanisms that provide server + authentication and other features. + + When the AUTH command is used together with the [PIPELINING] + extension, it MUST be the last command in a pipelined group of + commands. The only exception to this rule is when the AUTH command + contains an initial response for a SASL mechanism that allows the + client to send data first, the SASL mechanism is known to complete in + one round-trip, and a security layer is not negotiated by the client. + Two examples of such SASL mechanisms are PLAIN [PLAIN] and EXTERNAL + [SASL]. + +4.1. Examples + + Here is an example of a client attempting AUTH using the [PLAIN] SASL + mechanism under a TLS layer, and making use of the initial client + response: + + S: 220-smtp.example.com ESMTP Server + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250-AUTH GSSAPI DIGEST-MD5 + S: 250-ENHANCEDSTATUSCODES + S: 250 STARTTLS + C: STARTTLS + S: 220 Ready to start TLS + ... TLS negotiation proceeds, further commands + protected by TLS layer ... + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250 AUTH GSSAPI DIGEST-MD5 PLAIN + C: AUTH PLAIN dGVzdAB0ZXN0ADEyMzQ= + S: 235 2.7.0 Authentication successful + + Here is another client that is attempting AUTH PLAIN under a TLS + layer, this time without the initial response. Parts of the + negotiation before the TLS layer was established have been omitted: + + + +Siemborski & Melnikov Standards Track [Page 7] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + ... TLS negotiation proceeds, further commands + protected by TLS layer ... + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250 AUTH GSSAPI DIGEST-MD5 PLAIN + C: AUTH PLAIN + (note: there is a single space following the 334 + on the following line) + S: 334 + C: dGVzdAB0ZXN0ADEyMzQ= + S: 235 2.7.0 Authentication successful + + Here is an example using CRAM-MD5 [CRAM-MD5], a mechanism in which + the client does not begin the authentication exchange, and includes a + server challenge: + + S: 220-smtp.example.com ESMTP Server + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250-AUTH DIGEST-MD5 CRAM-MD5 + S: 250-ENHANCEDSTATUSCODES + S: 250 STARTTLS + C: AUTH CRAM-MD5 + S: 334 PDQxOTI5NDIzNDEuMTI4Mjg0NzJAc291cmNlZm91ci5hbmRyZXcuY211LmVk + dT4= + C: cmpzMyBlYzNhNTlmZWQzOTVhYmExZWM2MzY3YzRmNGI0MWFjMA== + S: 235 2.7.0 Authentication successful + + Here is an example of a client attempting AUTH EXTERNAL under TLS, + using the derived authorization ID (and thus a zero-length initial + client response). + + S: 220-smtp.example.com ESMTP Server + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250-AUTH GSSAPI DIGEST-MD5 + S: 250-ENHANCEDSTATUSCODES + S: 250 STARTTLS + C: STARTTLS + S: 220 Ready to start TLS + ... TLS negotiation proceeds, further commands + protected by TLS layer ... + C: EHLO client.example.com + S: 250-smtp.example.com Hello client.example.com + S: 250 AUTH EXTERNAL GSSAPI DIGEST-MD5 PLAIN + C: AUTH EXTERNAL = + S: 235 2.7.0 Authentication successful + + + + +Siemborski & Melnikov Standards Track [Page 8] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +5. The AUTH Parameter to the MAIL FROM command + + AUTH=mailbox + + Arguments: + A (see Section 4.1.2 of [SMTP]) that is associated + with the identity that submitted the message to the delivery + system, or the two character sequence "<>" indicating such an + identity is unknown or insufficiently authenticated. To comply + with restrictions imposed on ESMTP parameters, the is + encoded inside an xtext. The syntax of an xtext is described in + Section 4 of [ESMTP-DSN]. + + Note: + For the purposes of this discussion, "authenticated identity" + refers to the identity (if any) derived from the authorization + identity of previous AUTH command, while the terms "authorized + identity" and "supplied " refer to the sender identity + that is being associated with a particular message. Note that + one authenticated identity may be able to identify messages as + being sent by any number of authorized identities within a + single session. For example, this may be the case when an SMTP + server (one authenticated identity) is processing its queue + (many messages with distinct authorized identities). + + Discussion: + The optional AUTH parameter to the MAIL FROM command allows + cooperating agents in a trusted environment to communicate the + authorization identity associated with individual messages. + + If the server trusts the authenticated identity of the client to + assert that the message was originally submitted by the supplied + , then the server SHOULD supply the same in + an AUTH parameter when relaying the message to any other server + which supports the AUTH extension. + + For this reason, servers that advertise support for this + extension MUST support the AUTH parameter to the MAIL FROM + command even when the client has not authenticated itself to the + server. + + A MAIL FROM parameter of AUTH=<> indicates that the original + submitter of the message is not known. The server MUST NOT + treat the message as having been originally submitted by the + authenticated identity that resulted from the AUTH command. + + + + + + +Siemborski & Melnikov Standards Track [Page 9] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + If the AUTH parameter to the MAIL FROM command is not supplied, + the client has authenticated, and the server believes the + message is an original submission, the server MAY generate a + from the user's authenticated identity for use in an + AUTH parameter when relaying the message to any server which + supports the AUTH extension. The generated is + implementation specific, but it MUST conform to the syntax of + [SMTP]. If the implementation cannot generate a valid + , it MUST transmit AUTH=<> when relaying this message. + + If the server does not sufficiently trust the authenticated + identity of the client, or if the client is not authenticated, + then the server MUST behave as if the AUTH=<> parameter was + supplied. The server MAY, however, write the value of any + supplied AUTH parameter to a log file. + + If an AUTH=<> parameter was supplied, either explicitly or due + to the requirement in the previous paragraph, then the server + MUST supply the AUTH=<> parameter when relaying the message to + any server which it has authenticated to using the AUTH + extension. + + A server MAY treat expansion of a mailing list as a new + submission, setting the AUTH parameter to the mailing list + address or mailing list administration address when relaying the + message to list subscribers. + + Note that an implementation which is hard-coded to treat all + clients as being insufficiently trusted is compliant with this + specification. In that case, the implementation does nothing + more than parse and discard syntactically valid AUTH parameters + to the MAIL FROM command, and supply AUTH=<> parameters to any + servers that it authenticates to. + +5.1. Examples + + An example where the original identity of the sender is trusted and + known: + + C: MAIL FROM: AUTH=e+3Dmc2@example.com + S: 250 OK + + One example where the identity of the sender is not trusted or is + otherwise being suppressed by the client: + + C: MAIL FROM: AUTH=<> + S: 250 OK + + + + +Siemborski & Melnikov Standards Track [Page 10] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +6. Status Codes + + The following error codes may be used to indicate various success or + failure conditions. Servers that return enhanced status codes + [ESMTP-CODES] SHOULD use the enhanced codes suggested here. + + 235 2.7.0 Authentication Succeeded + + This response to the AUTH command indicates that the authentication + was successful. + + 432 4.7.12 A password transition is needed + + This response to the AUTH command indicates that the user needs to + transition to the selected authentication mechanism. This is + typically done by authenticating once using the [PLAIN] + authentication mechanism. The selected mechanism SHOULD then work + for authentications in subsequent sessions. + + 454 4.7.0 Temporary authentication failure + + This response to the AUTH command indicates that the authentication + failed due to a temporary server failure. The client SHOULD NOT + prompt the user for another password in this case, and should instead + notify the user of server failure. + + 534 5.7.9 Authentication mechanism is too weak + + This response to the AUTH command indicates that the selected + authentication mechanism is weaker than server policy permits for + that user. The client SHOULD retry with a new authentication + mechanism. + + 535 5.7.8 Authentication credentials invalid + + This response to the AUTH command indicates that the authentication + failed due to invalid or insufficient authentication credentials. In + this case, the client SHOULD ask the user to supply new credentials + (such as by presenting a password dialog box). + + 500 5.5.6 Authentication Exchange line is too long + + This response to the AUTH command indicates that the authentication + failed due to the client sending a [BASE64] response that is longer + than the maximum buffer size available for the currently selected + SASL mechanism. + + + + + +Siemborski & Melnikov Standards Track [Page 11] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + 530 5.7.0 Authentication required + + This response SHOULD be returned by any command other than AUTH, + EHLO, HELO, NOOP, RSET, or QUIT when server policy requires + authentication in order to perform the requested action and + authentication is not currently in force. + + 538 5.7.11 Encryption required for requested authentication + mechanism + + This response to the AUTH command indicates that the selected + authentication mechanism may only be used when the underlying SMTP + connection is encrypted. Note that this response code is documented + here for historical purposes only. Modern implementations SHOULD NOT + advertise mechanisms that are not permitted due to lack of + encryption, unless an encryption layer of sufficient strength is + currently being employed. + + This document adds several new enhanced status codes to the list + defined in [ENHANCED]: + + The following 3 Enhanced Status Codes were defined above: + + 5.7.8 Authentication credentials invalid + 5.7.9 Authentication mechanism is too weak + 5.7.11 Encryption required for requested authentication mechanism + + X.5.6 Authentication Exchange line is too long + + This enhanced status code SHOULD be returned when the server fails + the AUTH command due to the client sending a [BASE64] response which + is longer than the maximum buffer size available for the currently + selected SASL mechanism. This is useful for both permanent and + persistent transient errors. + +7. Additional Requirements on Servers + + As described in Section 4.4 of [SMTP], an SMTP server that receives a + message for delivery or further processing MUST insert the + "Received:" header field at the beginning of the message content. + This document places additional requirements on the content of a + generated "Received:" header field. Upon successful authentication, + a server SHOULD use the "ESMTPA" or the "ESMTPSA" [SMTP-TT] (when + appropriate) keyword in the "with" clause of the Received header + field. + + + + + + +Siemborski & Melnikov Standards Track [Page 12] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +8. Formal Syntax + + The following syntax specification uses the Augmented Backus-Naur + Form notation as specified in [ABNF]. Non-terminals referenced but + not defined below are as defined by [ABNF] or [SASL]. The non- + terminal is defined in [SMTP]. + + Except as noted otherwise, all alphabetic characters are case- + insensitive. The use of upper or lower case characters to define + token strings is for editorial clarity only. Implementations MUST + accept these strings in a case-insensitive fashion. + + hexchar = "+" HEXDIG HEXDIG + + xchar = %x21-2A / %x2C-3C / %x3E-7E + ;; US-ASCII except for "+", "=", SP, and CTL + + xtext = *(xchar / hexchar) + ;; non-US-ASCII is only allowed as hexchar + + auth-command = "AUTH" SP sasl-mech [SP initial-response] + *(CRLF [base64]) [CRLF cancel-response] + CRLF + ;; is defined in [SASL] + + auth-param = "AUTH=" xtext + ;; Parameter to the MAIL FROM command. + ;; This non-terminal complies with + ;; syntax defined by esmtp-param [SMTP]. + ;; + ;; The decoded form of the xtext MUST be + ;; either a or the two + ;; characters "<>" + + base64 = base64-terminal / + ( 1*(4base64-char) [base64-terminal] ) + + base64-char = ALPHA / DIGIT / "+" / "/" + ;; Case-sensitive + + base64-terminal = (2base64-char "==") / (3base64-char "=") + + continue-req = "334" SP [base64] CRLF + ;; Intermediate response to the AUTH + ;; command. + ;; This non-terminal complies with + ;; syntax defined by Reply-line [SMTP]. + + + + +Siemborski & Melnikov Standards Track [Page 13] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + initial-response= base64 / "=" + + cancel-response = "*" + +9. Security Considerations + + Security issues are discussed throughout this memo. + + If a client uses this extension to get an encrypted tunnel through an + insecure network to a cooperating server, it needs to be configured + to never send mail to that server when the connection is not mutually + authenticated and encrypted. Otherwise, an attacker could steal the + client's mail by hijacking the [SMTP] connection and either + pretending the server does not support the Authentication extension + or causing all AUTH commands to fail. + + Before the [SASL] negotiation has begun, any protocol interactions + are performed in the clear and may be modified by an active attacker. + For this reason, clients and servers MUST discard any knowledge + obtained prior to the start of the SASL negotiation upon the + establishment of a security layer. + + This mechanism does not protect the TCP port, so an active attacker + may redirect a relay connection attempt (i.e., a connection between + two Mail Transfer Agents (MTAs)) to the submission port [SUBMIT]. + The AUTH=<> parameter prevents such an attack from causing a relayed + message and, in the absence of other envelope authentication, from + picking up the authentication of the relay client. + + A message submission client may require the user to authenticate + whenever a suitable [SASL] mechanism is advertised. Therefore, it + may not be desirable for a submission server [SUBMIT] to advertise a + SASL mechanism when use of that mechanism grants the clients no + benefits over anonymous submission. + + Servers MAY implement a policy whereby the connection is dropped + after a number of failed authentication attempts. If they do so, + they SHOULD NOT drop the connection until at least 3 attempts to + authenticate have failed. + + If an implementation supports SASL mechanisms that are vulnerable to + passive eavesdropping attacks (such as [PLAIN]), then the + implementation MUST support at least one configuration where these + SASL mechanisms are not advertised or used without the presence of an + external security layer such as [TLS]. + + + + + + +Siemborski & Melnikov Standards Track [Page 14] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + This extension is not intended to replace or be used instead of end- + to-end message signature and encryption systems such as [S/MIME] or + [PGP]. This extension addresses a different problem than end-to-end + systems; it has the following key differences: + + 1. It is generally useful only within a trusted enclave. + + 2. It protects the entire envelope of a message, not just the + message's body. + + 3. It authenticates the message submission, not authorship of the + message content. + + 4. When mutual authentication is used along with a security layer, + it can give the sender some assurance that the message was + successfully delivered to the next hop. + + Additional security considerations are mentioned in the [SASL] + specification. Additional security considerations specific to a + particular SASL mechanism are described in the relevant + specification. Additional security considerations for [PLAIN] over + [TLS] are mentioned in Section 15 of this document. + +10. IANA Considerations + + IANA updated the entry for the "smtp" SASL protocol name to point at + this document. + + IANA updated the registration of the Authentication SMTP service + extension as defined in Section 3 of this document. This registry is + currently located at . + +11. Normative References + + [ABNF] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", RFC 4234, October 2005. + + [BASE64] Josefsson, S., "The Base16, Base32, and Base64 Data + Encodings", RFC 4648, October 2006. + + [ESMTP-CODES] Freed, N., "SMTP Service Extension for Returning + Enhanced Error Codes", RFC 2034, October 1996. + + [ENHANCED] Vaudreuil, G., "Enhanced Mail System Status Codes", RFC + 3463, January 2003. + + + + + +Siemborski & Melnikov Standards Track [Page 15] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + [ESMTP-DSN] Moore, K., "Simple Mail Transfer Protocol (SMTP) + Service Extension Delivery Status Notifications + (DSNs)", RFC 3461, January 2003. + + [KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [SASL] Melnikov, A. and K. Zeilenga, "Simple Authentication + and Security Layer (SASL)", RFC 4422, June 2006. + + [SASLprep] Zeilenga, K., "SASLprep: Stringprep Profile for User + Names and Passwords", RFC 4013, February 2005. + + [SMTP] Klensin, J., "Simple Mail Transfer Protocol", RFC 2821, + April 2001. + + [SMTP-TLS] Hoffman, P., "SMTP Service Extension for Secure SMTP + over Transport Layer Security", RFC 3207, February + 2002. + + [StringPrep] Hoffman, P. and M. Blanchet, "Preparation of + Internationalized Strings ("stringprep")", RFC 3454, + December 2002. + + [SUBMIT] Gellens, R. and J. Klensin, "Message Submission for + Mail", RFC 4409, April 2006. + + [SMTP-TT] Newman, C., "ESMTP and LMTP Transmission Types + Registration", RFC 3848, July 2004. + + [PLAIN] Zeilenga, K., Ed., "The PLAIN Simple Authentication and + Security Layer (SASL) Mechanism", RFC 4616, August + 2006. + + [X509] Housley, R., Polk, W., Ford, W., and D. Solo, "Internet + X.509 Public Key Infrastructure Certificate and + Certificate Revocation List (CRL) Profile", RFC 3280, + April 2002. + +12. Informative References + + [PGP] Elkins, M., "MIME Security with Pretty Good Privacy + (PGP)", RFC 2015, October 1996. + + [S/MIME] Ramsdell, B., Ed., "Secure/Multipurpose Internet Mail + Extensions (S/MIME) Version 3.1 Message Specification", + RFC 3851, July 2004. + + + + +Siemborski & Melnikov Standards Track [Page 16] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + [TLS] Dierks, T. and E. Rescorla, "The Transport Layer + Security (TLS) Protocol Version 1.1", RFC 4346, April + 2006. + + [PIPELINING] Freed, N., "SMTP Service Extension for Command + Pipelining", STD 60, RFC 2920, September 2000. + + [CRAM-MD5] Klensin, J., Catoe, R., and P. Krumviede, "IMAP/POP + AUTHorize Extension for Simple Challenge/Response", RFC + 2195, September 1997. + +13. Acknowledgments + + The editors would like to acknowledge the contributions of John Myers + and other contributors to RFC 2554, on which this document draws from + heavily. + + The editors would also like to thank Ken Murchison, Mark Crispin, + Chris Newman, David Wilson, Dave Cridland, Frank Ellermann, Ned + Freed, John Klensin, Tony Finch, Abhijit Menon-Sen, Philip Guenther, + Sam Hartman, Russ Housley, Cullen Jennings, and Lisa Dusseault for + the time they devoted to reviewing of this document and/or for the + comments received. + +14. Additional Requirements When Using SASL PLAIN over TLS + + This section is normative for SMTP implementations that support SASL + [PLAIN] over [TLS]. + + If an SMTP client is willing to use SASL PLAIN over TLS to + authenticate to the SMTP server, the client verifies the server + certificate according to the rules of [X509]. If the server has not + provided any certificate, or if the certificate verification fails, + the client MUST NOT attempt to authenticate using the SASL PLAIN + mechanism. + + After a successful [TLS] negotiation, the client MUST check its + understanding of the server hostname against the server's identity as + presented in the server Certificate message, in order to prevent + man-in-the-middle attacks. If the match fails, the client MUST NOT + attempt to authenticate using the SASL PLAIN mechanism. Matching is + performed according to the following rules: + + The client MUST use the server hostname it used to open the + connection as the value to compare against the server name as + expressed in the server certificate. The client MUST NOT use + + + + + +Siemborski & Melnikov Standards Track [Page 17] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + any form of the server hostname derived from an insecure remote + source (e.g., insecure DNS lookup). CNAME canonicalization is + not done. + + If a subjectAltName extension of type dNSName is present in the + certificate, it SHOULD be used as the source of the server's + identity. + + Matching is case-insensitive. + + A "*" wildcard character MAY be used as the leftmost name + component in the certificate. For example, *.example.com would + match a.example.com, foo.example.com, etc., but would not match + example.com. + + If the certificate contains multiple names (e.g., more than one + dNSName field), then a match with any one of the fields is + considered acceptable. + +15. Changes since RFC 2554 + + 1. Clarified that servers MUST support the use of the AUTH=mailbox + parameter to MAIL FROM, even when the client is not + authenticated. + + 2. Clarified the initial-client-send requirements, and give + additional examples. + + 3. Updated references to newer versions of various specifications. + + 4. Required SASL PLAIN (over TLS) as mandatory-to-implement. + + 5. Clarified that the mechanism list can change. + + 6. Deprecated the use of the 538 response code. + + 7. Added the use of the SASLprep profile for preparing authorization + identities. + + 8. Substantial cleanup of response codes and indicated suggested + enhanced response codes. Also indicated what response codes + should result in a client prompting the user for new credentials. + + 9. Updated ABNF section to use RFC 4234. + + 10. Clarified interaction with SMTP PIPELINING extension. + + 11. Added a reference to RFC 3848. + + + +Siemborski & Melnikov Standards Track [Page 18] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + + 12. Added a new Enhanced Status Code for "authentication line too + long" case. + + 13. Other general editorial clarifications. + +Editors' Addresses + + Robert Siemborski + Google, Inc. + 1600 Ampitheatre Parkway + Mountain View, CA 94043, USA + + Phone: +1 650 623 6925 + EMail: robsiemb@google.com + + + Alexey Melnikov + Isode Limited + 5 Castle Business Village, 36 Station Road, + Hampton, Middlesex, TW12 2BX, UK + + EMail: Alexey.Melnikov@isode.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Siemborski & Melnikov Standards Track [Page 19] + +RFC 4954 SMTP Service Extension for Authentication July 2007 + + +Full Copyright Statement + + Copyright (C) The IETF Trust (2007). + + This document is subject to the rights, licenses and restrictions + contained in BCP 78, and except as set forth therein, the authors + retain all their rights. + + This document and the information contained herein are provided on an + "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS + OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY, THE IETF TRUST AND + THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF + THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED + WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +Intellectual Property + + The IETF takes no position regarding the validity or scope of any + Intellectual Property Rights or other rights that might be claimed to + pertain to the implementation or use of the technology described in + this document or the extent to which any license under such rights + might or might not be available; nor does it represent that it has + made any independent effort to identify any such rights. Information + on the procedures with respect to rights in RFC documents can be + found in BCP 78 and BCP 79. + + Copies of IPR disclosures made to the IETF Secretariat and any + assurances of licenses to be made available, or the result of an + attempt made to obtain a general license or permission for the use of + such proprietary rights by implementers or users of this + specification can be obtained from the IETF on-line IPR repository at + http://www.ietf.org/ipr. + + The IETF invites any interested party to bring to its attention any + copyrights, patents or patent applications, or other proprietary + rights that may cover technology that may be required to implement + this standard. Please address the information to the IETF at + ietf-ipr@ietf.org. + +Acknowledgement + + Funding for the RFC Editor function is currently provided by the + Internet Society. + + + + + + + +Siemborski & Melnikov Standards Track [Page 20] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/rfc5751.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc5751.txt new file mode 100644 index 00000000..8d1dd218 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/rfc5751.txt @@ -0,0 +1,2523 @@ + + + + + + +Internet Engineering Task Force (IETF) B. Ramsdell +Request for Comments: 5751 Brute Squad Labs +Obsoletes: 3851 S. Turner +Category: Standards Track IECA +ISSN: 2070-1721 January 2010 + + + Secure/Multipurpose Internet Mail Extensions (S/MIME) Version 3.2 + Message Specification + +Abstract + + This document defines Secure/Multipurpose Internet Mail Extensions + (S/MIME) version 3.2. S/MIME provides a consistent way to send and + receive secure MIME data. Digital signatures provide authentication, + message integrity, and non-repudiation with proof of origin. + Encryption provides data confidentiality. Compression can be used to + reduce data size. This document obsoletes RFC 3851. + +Status of This Memo + + This is an Internet Standards Track document. + + This document is a product of the Internet Engineering Task Force + (IETF). It represents the consensus of the IETF community. It has + received public review and has been approved for publication by + the Internet Engineering Steering Group (IESG). Further + information on Internet Standards is available in Section 2 of + RFC 5741. + + Information about the current status of this document, any + errata, and how to provide feedback on it may be obtained at + http://www.rfc-editor.org/info/rfc5751. + + + + + + + + + + + + + + + + + + +Ramsdell & Turner Standards Track [Page 1] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +Copyright Notice + + Copyright (c) 2010 IETF Trust and the persons identified as the + document authors. All rights reserved. + + This document is subject to BCP 78 and the IETF Trust's Legal + Provisions Relating to IETF Documents + (http://trustee.ietf.org/license-info) in effect on the date of + publication of this document. Please review these documents + carefully, as they describe your rights and restrictions with respect + to this document. Code Components extracted from this document must + include Simplified BSD License text as described in Section 4.e of + the Trust Legal Provisions and are provided without warranty as + described in the Simplified BSD License. + + This document may contain material from IETF Documents or IETF + Contributions published or made publicly available before November + 10, 2008. The person(s) controlling the copyright in some of this + material may not have granted the IETF Trust the right to allow + modifications of such material outside the IETF Standards Process. + Without obtaining an adequate license from the person(s) controlling + the copyright in such materials, this document may not be modified + outside the IETF Standards Process, and derivative works of it may + not be created outside the IETF Standards Process, except to format + it for publication as an RFC or to translate it into languages other + than English. + + + + + + + + + + + + + + + + + + + + + + + + + +Ramsdell & Turner Standards Track [Page 2] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +Table of Contents + + 1. Introduction ....................................................4 + 1.1. Specification Overview .....................................4 + 1.2. Definitions ................................................5 + 1.3. Conventions Used in This Document ..........................6 + 1.4. Compatibility with Prior Practice of S/MIME ................7 + 1.5. Changes from S/MIME v3 to S/MIME v3.1 ......................7 + 1.6. Changes since S/MIME v3.1 ..................................7 + 2. CMS Options .....................................................9 + 2.1. DigestAlgorithmIdentifier ..................................9 + 2.2. SignatureAlgorithmIdentifier ...............................9 + 2.3. KeyEncryptionAlgorithmIdentifier ..........................10 + 2.4. General Syntax ............................................11 + 2.5. Attributes and the SignerInfo Type ........................12 + 2.6. SignerIdentifier SignerInfo Type ..........................16 + 2.7. ContentEncryptionAlgorithmIdentifier ......................16 + 3. Creating S/MIME Messages .......................................18 + 3.1. Preparing the MIME Entity for Signing, Enveloping, + or Compressing ............................................19 + 3.2. The application/pkcs7-mime Media Type .....................23 + 3.3. Creating an Enveloped-Only Message ........................25 + 3.4. Creating a Signed-Only Message ............................26 + 3.5. Creating a Compressed-Only Message ........................30 + 3.6. Multiple Operations .......................................30 + 3.7. Creating a Certificate Management Message .................31 + 3.8. Registration Requests .....................................32 + 3.9. Identifying an S/MIME Message .............................32 + 4. Certificate Processing .........................................32 + 4.1. Key Pair Generation .......................................33 + 4.2. Signature Generation ......................................33 + 4.3. Signature Verification ....................................34 + 4.4. Encryption ................................................34 + 4.5. Decryption ................................................34 + 5. IANA Considerations ............................................34 + 5.1. Media Type for application/pkcs7-mime .....................34 + 5.2. Media Type for application/pkcs7-signature ................35 + 6. Security Considerations ........................................36 + 7. References .....................................................38 + 7.1. Reference Conventions .....................................38 + 7.2. Normative References ......................................39 + 7.3. Informative References ....................................41 + Appendix A. ASN.1 Module ..........................................43 + Appendix B. Moving S/MIME v2 Message Specification to Historic + Status ................................................45 + Appendix C. Acknowledgments .......................................45 + + + + + +Ramsdell & Turner Standards Track [Page 3] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +1. Introduction + + S/MIME (Secure/Multipurpose Internet Mail Extensions) provides a + consistent way to send and receive secure MIME data. Based on the + popular Internet MIME standard, S/MIME provides the following + cryptographic security services for electronic messaging + applications: authentication, message integrity and non-repudiation + of origin (using digital signatures), and data confidentiality (using + encryption). As a supplementary service, S/MIME provides for message + compression. + + S/MIME can be used by traditional mail user agents (MUAs) to add + cryptographic security services to mail that is sent, and to + interpret cryptographic security services in mail that is received. + However, S/MIME is not restricted to mail; it can be used with any + transport mechanism that transports MIME data, such as HTTP or SIP. + As such, S/MIME takes advantage of the object-based features of MIME + and allows secure messages to be exchanged in mixed-transport + systems. + + Further, S/MIME can be used in automated message transfer agents that + use cryptographic security services that do not require any human + intervention, such as the signing of software-generated documents and + the encryption of FAX messages sent over the Internet. + +1.1. Specification Overview + + This document describes a protocol for adding cryptographic signature + and encryption services to MIME data. The MIME standard [MIME-SPEC] + provides a general structure for the content of Internet messages and + allows extensions for new content-type-based applications. + + This specification defines how to create a MIME body part that has + been cryptographically enhanced according to the Cryptographic + Message Syntax (CMS) RFC 5652 [CMS], which is derived from PKCS #7 + [PKCS-7]. This specification also defines the application/pkcs7-mime + media type that can be used to transport those body parts. + + This document also discusses how to use the multipart/signed media + type defined in [MIME-SECURE] to transport S/MIME signed messages. + multipart/signed is used in conjunction with the application/pkcs7- + signature media type, which is used to transport a detached S/MIME + signature. + + + + + + + + +Ramsdell & Turner Standards Track [Page 4] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + In order to create S/MIME messages, an S/MIME agent MUST follow the + specifications in this document, as well as the specifications listed + in the Cryptographic Message Syntax document [CMS], [CMSALG], + [RSAPSS], [RSAOAEP], and [CMS-SHA2]. + + Throughout this specification, there are requirements and + recommendations made for how receiving agents handle incoming + messages. There are separate requirements and recommendations for + how sending agents create outgoing messages. In general, the best + strategy is to "be liberal in what you receive and conservative in + what you send". Most of the requirements are placed on the handling + of incoming messages, while the recommendations are mostly on the + creation of outgoing messages. + + The separation for requirements on receiving agents and sending + agents also derives from the likelihood that there will be S/MIME + systems that involve software other than traditional Internet mail + clients. S/MIME can be used with any system that transports MIME + data. An automated process that sends an encrypted message might not + be able to receive an encrypted message at all, for example. Thus, + the requirements and recommendations for the two types of agents are + listed separately when appropriate. + +1.2. Definitions + + For the purposes of this specification, the following definitions + apply. + + ASN.1: Abstract Syntax Notation One, as defined in ITU-T + Recommendation X.680 [X.680]. + + BER: Basic Encoding Rules for ASN.1, as defined in ITU- + T Recommendation X.690 [X.690]. + + Certificate: A type that binds an entity's name to a public key + with a digital signature. + + DER: Distinguished Encoding Rules for ASN.1, as defined + in ITU-T Recommendation X.690 [X.690]. + + 7-bit data: Text data with lines less than 998 characters + long, where none of the characters have the 8th + bit set, and there are no NULL characters. + and occur only as part of a end-of- + line delimiter. + + + + + + +Ramsdell & Turner Standards Track [Page 5] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + 8-bit data: Text data with lines less than 998 characters, and + where none of the characters are NULL characters. + and occur only as part of a + end-of-line delimiter. + + Binary data: Arbitrary data. + + Transfer encoding: A reversible transformation made on data so 8-bit + or binary data can be sent via a channel that only + transmits 7-bit data. + + Receiving agent: Software that interprets and processes S/MIME CMS + objects, MIME body parts that contain CMS content + types, or both. + + Sending agent: Software that creates S/MIME CMS content types, + MIME body parts that contain CMS content types, or + both. + + S/MIME agent: User software that is a receiving agent, a sending + agent, or both. + +1.3. Conventions Used in This Document + + The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", + "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this + document are to be interpreted as described in [MUSTSHOULD]. + + We define some additional terms here: + + SHOULD+ This term means the same as SHOULD. However, the authors + expect that a requirement marked as SHOULD+ will be + promoted at some future time to be a MUST. + + SHOULD- This term means the same as SHOULD. However, the authors + expect that a requirement marked as SHOULD- will be demoted + to a MAY in a future version of this document. + + MUST- This term means the same as MUST. However, the authors + expect that this requirement will no longer be a MUST in a + future document. Although its status will be determined at + a later time, it is reasonable to expect that if a future + revision of a document alters the status of a MUST- + requirement, it will remain at least a SHOULD or a SHOULD-. + + + + + + + +Ramsdell & Turner Standards Track [Page 6] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +1.4. Compatibility with Prior Practice of S/MIME + + S/MIME version 3.2 agents ought to attempt to have the greatest + interoperability possible with agents for prior versions of S/MIME. + S/MIME version 2 is described in RFC 2311 through RFC 2315 inclusive + [SMIMEv2], S/MIME version 3 is described in RFC 2630 through RFC 2634 + inclusive and RFC 5035 [SMIMEv3], and S/MIME version 3.1 is described + in RFC 3850, RFC 3851, RFC 3852, RFC 2634, and RFC 5035 [SMIMEv3.1]. + RFC 2311 also has historical information about the development of + S/MIME. + +1.5. Changes from S/MIME v3 to S/MIME v3.1 + + The RSA public key algorithm was changed to a MUST implement key + wrapping algorithm, and the Diffie-Hellman (DH) algorithm changed to + a SHOULD implement. + + The AES symmetric encryption algorithm has been included as a SHOULD + implement. + + The RSA public key algorithm was changed to a MUST implement + signature algorithm. + + Ambiguous language about the use of "empty" SignedData messages to + transmit certificates was clarified to reflect that transmission of + Certificate Revocation Lists is also allowed. + + The use of binary encoding for some MIME entities is now explicitly + discussed. + + Header protection through the use of the message/rfc822 media type + has been added. + + Use of the CompressedData CMS type is allowed, along with required + media type and file extension additions. + +1.6. Changes since S/MIME v3.1 + + Editorial changes, e.g., replaced "MIME type" with "media type", + content-type with Content-Type. + + Moved "Conventions Used in This Document" to Section 1.3. Added + definitions for SHOULD+, SHOULD-, and MUST-. + + Section 1.1 and Appendix A: Added references to RFCs for RSASSA-PSS, + RSAES-OAEP, and SHA2 CMS algorithms. Added CMS Multiple Signers + Clarification to CMS reference. + + + + +Ramsdell & Turner Standards Track [Page 7] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Section 1.2: Updated references to ASN.1 to X.680 and BER and DER to + X.690. + + Section 1.4: Added references to S/MIME MSG 3.1 RFCs. + + Section 2.1 (digest algorithm): SHA-256 added as MUST, SHA-1 and MD5 + made SHOULD-. + + Section 2.2 (signature algorithms): RSA with SHA-256 added as MUST, + and DSA with SHA-256 added as SHOULD+, RSA with SHA-1, DSA with + SHA-1, and RSA with MD5 changed to SHOULD-, and RSASSA-PSS with + SHA-256 added as SHOULD+. Also added note about what S/MIME v3.1 + clients support. + + Section 2.3 (key encryption): DH changed to SHOULD-, and RSAES-OAEP + added as SHOULD+. Elaborated requirements for key wrap algorithm. + + Section 2.5.1: Added requirement that receiving agents MUST support + both GeneralizedTime and UTCTime. + + Section 2.5.2: Replaced reference "sha1WithRSAEncryption" with + "sha256WithRSAEncryption", "DES-3EDE-CBC" with "AES-128 CBC", and + deleted the RC5 example. + + Section 2.5.2.1: Deleted entire section (discussed deprecated RC2). + + Section 2.7, 2.7.1, Appendix A: references to RC2/40 removed. + + Section 2.7 (content encryption): AES-128 CBC added as MUST, AES-192 + and AES-256 CBC SHOULD+, tripleDES now SHOULD-. + + Section 2.7.1: Updated pointers from 2.7.2.1 through 2.7.2.4 to + 2.7.1.1 to 2.7.1.2. + + Section 3.1.1: Removed text about MIME character sets. + + Section 3.2.2 and 3.6: Replaced "encrypted" with "enveloped". Update + OID example to use AES-128 CBC oid. + + Section 3.4.3.2: Replace micalg parameter for SHA-1 with sha-1. + + Section 4: Updated reference to CERT v3.2. + + Section 4.1: Updated RSA and DSA key size discussion. Moved last + four sentences to security considerations. Updated reference to + randomness requirements for security. + + + + + +Ramsdell & Turner Standards Track [Page 8] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Section 5: Added IANA registration templates to update media type + registry to point to this document as opposed to RFC 2311. + + Section 6: Updated security considerations. + + Section 7: Moved references from Appendix B to this section. Updated + references. Added informational references to SMIMEv2, SMIMEv3, and + SMIMEv3.1. + + Appendix B: Added Appendix B to move S/MIME v2 to Historic status. + +2. CMS Options + + CMS allows for a wide variety of options in content, attributes, and + algorithm support. This section puts forth a number of support + requirements and recommendations in order to achieve a base level of + interoperability among all S/MIME implementations. [CMSALG] and + [CMS-SHA2] provides additional details regarding the use of the + cryptographic algorithms. [ESS] provides additional details + regarding the use of additional attributes. + +2.1. DigestAlgorithmIdentifier + + Sending and receiving agents MUST support SHA-256 [CMS-SHA2] and + SHOULD- support SHA-1 [CMSALG]. Receiving agents SHOULD- support MD5 + [CMSALG] for the purpose of providing backward compatibility with + MD5-digested S/MIME v2 SignedData objects. + +2.2. SignatureAlgorithmIdentifier + + Receiving agents: + + - MUST support RSA with SHA-256. + + - SHOULD+ support DSA with SHA-256. + + - SHOULD+ support RSASSA-PSS with SHA-256. + + - SHOULD- support RSA with SHA-1. + + - SHOULD- support DSA with SHA-1. + + - SHOULD- support RSA with MD5. + + + + + + + + +Ramsdell & Turner Standards Track [Page 9] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Sending agents: + + - MUST support RSA with SHA-256. + + - SHOULD+ support DSA with SHA-256. + + - SHOULD+ support RSASSA-PSS with SHA-256. + + - SHOULD- support RSA with SHA-1 or DSA with SHA-1. + + - SHOULD- support RSA with MD5. + + See Section 4.1 for information on key size and algorithm references. + + Note that S/MIME v3.1 clients support verifying id-dsa-with-sha1 and + rsaEncryption and might not implement sha256withRSAEncryption. Note + that S/MIME v3 clients might only implement signing or signature + verification using id-dsa-with-sha1, and might also use id-dsa as an + AlgorithmIdentifier in this field. Receiving clients SHOULD + recognize id-dsa as equivalent to id-dsa-with-sha1, and sending + clients MUST use id-dsa-with-sha1 if using that algorithm. Also note + that S/MIME v2 clients are only required to verify digital signatures + using the rsaEncryption algorithm with SHA-1 or MD5, and might not + implement id-dsa-with-sha1 or id-dsa at all. + +2.3. KeyEncryptionAlgorithmIdentifier + + Receiving and sending agents: + + - MUST support RSA Encryption, as specified in [CMSALG]. + + - SHOULD+ support RSAES-OAEP, as specified in [RSAOAEP]. + + - SHOULD- support DH ephemeral-static mode, as specified in + [CMSALG] and [SP800-57]. + + When DH ephemeral-static is used, a key wrap algorithm is also + specified in the KeyEncryptionAlgorithmIdentifier [CMS]. The + underlying encryption functions for the key wrap and content + encryption algorithm ([CMSALG] and [CMSAES]) and the key sizes for + the two algorithms MUST be the same (e.g., AES-128 key wrap algorithm + with AES-128 content encryption algorithm). As AES-128 CBC is the + mandatory-to-implement content encryption algorithm, the AES-128 key + wrap algorithm MUST also be supported when DH ephemeral-static is + used. + + + + + + +Ramsdell & Turner Standards Track [Page 10] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Note that S/MIME v3.1 clients might only implement key encryption and + decryption using the rsaEncryption algorithm. Note that S/MIME v3 + clients might only implement key encryption and decryption using the + Diffie-Hellman algorithm. Also note that S/MIME v2 clients are only + capable of decrypting content-encryption keys using the rsaEncryption + algorithm. + +2.4. General Syntax + + There are several CMS content types. Of these, only the Data, + SignedData, EnvelopedData, and CompressedData content types are + currently used for S/MIME. + +2.4.1. Data Content Type + + Sending agents MUST use the id-data content type identifier to + identify the "inner" MIME message content. For example, when + applying a digital signature to MIME data, the CMS SignedData + encapContentInfo eContentType MUST include the id-data object + identifier and the media type MUST be stored in the SignedData + encapContentInfo eContent OCTET STRING (unless the sending agent is + using multipart/signed, in which case the eContent is absent, per + Section 3.4.3 of this document). As another example, when applying + encryption to MIME data, the CMS EnvelopedData encryptedContentInfo + contentType MUST include the id-data object identifier and the + encrypted MIME content MUST be stored in the EnvelopedData + encryptedContentInfo encryptedContent OCTET STRING. + +2.4.2. SignedData Content Type + + Sending agents MUST use the SignedData content type to apply a + digital signature to a message or, in a degenerate case where there + is no signature information, to convey certificates. Applying a + signature to a message provides authentication, message integrity, + and non-repudiation of origin. + +2.4.3. EnvelopedData Content Type + + This content type is used to apply data confidentiality to a message. + A sender needs to have access to a public key for each intended + message recipient to use this service. + +2.4.4. CompressedData Content Type + + This content type is used to apply data compression to a message. + This content type does not provide authentication, message integrity, + non-repudiation, or data confidentiality, and is only used to reduce + the message's size. + + + +Ramsdell & Turner Standards Track [Page 11] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + See Section 3.6 for further guidance on the use of this type in + conjunction with other CMS types. + +2.5. Attributes and the SignerInfo Type + + The SignerInfo type allows the inclusion of unsigned and signed + attributes along with a signature. + + Receiving agents MUST be able to handle zero or one instance of each + of the signed attributes listed here. Sending agents SHOULD generate + one instance of each of the following signed attributes in each + S/MIME message: + + - Signing Time (section (Section 2.5.1 in this document) + + - SMIME Capabilities (section (Section 2.5.2 in this document) + + - Encryption Key Preference (section (Section 2.5.3 in this + document) + + - Message Digest (section (Section 11.2 in [CMS]) + + - Content Type (section (Section 11.1 in [CMS]) + + Further, receiving agents SHOULD be able to handle zero or one + instance of the signingCertificate and signingCertificatev2 signed + attributes, as defined in Section 5 of RFC 2634 [ESS] and Section 3 + of RFC 5035 [ESS]. + + Sending agents SHOULD generate one instance of the signingCertificate + or signingCertificatev2 signed attribute in each SignerInfo + structure. + + Additional attributes and values for these attributes might be + defined in the future. Receiving agents SHOULD handle attributes or + values that they do not recognize in a graceful manner. + + Interactive sending agents that include signed attributes that are + not listed here SHOULD display those attributes to the user, so that + the user is aware of all of the data being signed. + +2.5.1. Signing Time Attribute + + The signing-time attribute is used to convey the time that a message + was signed. The time of signing will most likely be created by a + message originator and therefore is only as trustworthy as the + originator. + + + + +Ramsdell & Turner Standards Track [Page 12] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Sending agents MUST encode signing time through the year 2049 as + UTCTime; signing times in 2050 or later MUST be encoded as + GeneralizedTime. When the UTCTime CHOICE is used, S/MIME agents MUST + interpret the year field (YY) as follows: + + If YY is greater than or equal to 50, the year is interpreted as + 19YY; if YY is less than 50, the year is interpreted as 20YY. + + Receiving agents MUST be able to process signing-time attributes that + are encoded in either UTCTime or GeneralizedTime. + +2.5.2. SMIME Capabilities Attribute + + The SMIMECapabilities attribute includes signature algorithms (such + as "sha256WithRSAEncryption"), symmetric algorithms (such as "AES-128 + CBC"), and key encipherment algorithms (such as "rsaEncryption"). + There are also several identifiers that indicate support for other + optional features such as binary encoding and compression. The + SMIMECapabilities were designed to be flexible and extensible so + that, in the future, a means of identifying other capabilities and + preferences such as certificates can be added in a way that will not + cause current clients to break. + + If present, the SMIMECapabilities attribute MUST be a + SignedAttribute; it MUST NOT be an UnsignedAttribute. CMS defines + SignedAttributes as a SET OF Attribute. The SignedAttributes in a + signerInfo MUST NOT include multiple instances of the + SMIMECapabilities attribute. CMS defines the ASN.1 syntax for + Attribute to include attrValues SET OF AttributeValue. A + SMIMECapabilities attribute MUST only include a single instance of + AttributeValue. There MUST NOT be zero or multiple instances of + AttributeValue present in the attrValues SET OF AttributeValue. + + The semantics of the SMIMECapabilities attribute specify a partial + list as to what the client announcing the SMIMECapabilities can + support. A client does not have to list every capability it + supports, and need not list all its capabilities so that the + capabilities list doesn't get too long. In an SMIMECapabilities + attribute, the object identifiers (OIDs) are listed in order of their + preference, but SHOULD be separated logically along the lines of + their categories (signature algorithms, symmetric algorithms, key + encipherment algorithms, etc.). + + The structure of the SMIMECapabilities attribute is to facilitate + simple table lookups and binary comparisons in order to determine + matches. For instance, the DER-encoding for the SMIMECapability for + AES-128 CBC MUST be identically encoded regardless of the + implementation. Because of the requirement for identical encoding, + + + +Ramsdell & Turner Standards Track [Page 13] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + individuals documenting algorithms to be used in the + SMIMECapabilities attribute SHOULD explicitly document the correct + byte sequence for the common cases. + + For any capability, the associated parameters for the OID MUST + specify all of the parameters necessary to differentiate between two + instances of the same algorithm. + + The OIDs that correspond to algorithms SHOULD use the same OID as the + actual algorithm, except in the case where the algorithm usage is + ambiguous from the OID. For instance, in an earlier specification, + rsaEncryption was ambiguous because it could refer to either a + signature algorithm or a key encipherment algorithm. In the event + that an OID is ambiguous, it needs to be arbitrated by the maintainer + of the registered SMIMECapabilities list as to which type of + algorithm will use the OID, and a new OID MUST be allocated under the + smimeCapabilities OID to satisfy the other use of the OID. + + The registered SMIMECapabilities list specifies the parameters for + OIDs that need them, most notably key lengths in the case of + variable-length symmetric ciphers. In the event that there are no + differentiating parameters for a particular OID, the parameters MUST + be omitted, and MUST NOT be encoded as NULL. Additional values for + the SMIMECapabilities attribute might be defined in the future. + Receiving agents MUST handle a SMIMECapabilities object that has + values that it does not recognize in a graceful manner. + + Section 2.7.1 explains a strategy for caching capabilities. + +2.5.3. Encryption Key Preference Attribute + + The encryption key preference attribute allows the signer to + unambiguously describe which of the signer's certificates has the + signer's preferred encryption key. This attribute is designed to + enhance behavior for interoperating with those clients that use + separate keys for encryption and signing. This attribute is used to + convey to anyone viewing the attribute which of the listed + certificates is appropriate for encrypting a session key for future + encrypted messages. + + If present, the SMIMEEncryptionKeyPreference attribute MUST be a + SignedAttribute; it MUST NOT be an UnsignedAttribute. CMS defines + SignedAttributes as a SET OF Attribute. The SignedAttributes in a + signerInfo MUST NOT include multiple instances of the + SMIMEEncryptionKeyPreference attribute. CMS defines the ASN.1 syntax + for Attribute to include attrValues SET OF AttributeValue. A + SMIMEEncryptionKeyPreference attribute MUST only include a single + + + + +Ramsdell & Turner Standards Track [Page 14] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + instance of AttributeValue. There MUST NOT be zero or multiple + instances of AttributeValue present in the attrValues SET OF + AttributeValue. + + The sending agent SHOULD include the referenced certificate in the + set of certificates included in the signed message if this attribute + is used. The certificate MAY be omitted if it has been previously + made available to the receiving agent. Sending agents SHOULD use + this attribute if the commonly used or preferred encryption + certificate is not the same as the certificate used to sign the + message. + + Receiving agents SHOULD store the preference data if the signature on + the message is valid and the signing time is greater than the + currently stored value. (As with the SMIMECapabilities, the clock + skew SHOULD be checked and the data not used if the skew is too + great.) Receiving agents SHOULD respect the sender's encryption key + preference attribute if possible. This, however, represents only a + preference and the receiving agent can use any certificate in + replying to the sender that is valid. + + Section 2.7.1 explains a strategy for caching preference data. + +2.5.3.1. Selection of Recipient Key Management Certificate + + In order to determine the key management certificate to be used when + sending a future CMS EnvelopedData message for a particular + recipient, the following steps SHOULD be followed: + + - If an SMIMEEncryptionKeyPreference attribute is found in a + SignedData object received from the desired recipient, this + identifies the X.509 certificate that SHOULD be used as the X.509 + key management certificate for the recipient. + + - If an SMIMEEncryptionKeyPreference attribute is not found in a + SignedData object received from the desired recipient, the set of + X.509 certificates SHOULD be searched for a X.509 certificate with + the same subject name as the signer of a X.509 certificate that can + be used for key management. + + - Or use some other method of determining the user's key management + key. If a X.509 key management certificate is not found, then + encryption cannot be done with the signer of the message. If + multiple X.509 key management certificates are found, the S/MIME + agent can make an arbitrary choice between them. + + + + + + +Ramsdell & Turner Standards Track [Page 15] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +2.6. SignerIdentifier SignerInfo Type + + S/MIME v3.2 implementations MUST support both issuerAndSerialNumber + and subjectKeyIdentifier. Messages that use the subjectKeyIdentifier + choice cannot be read by S/MIME v2 clients. + + It is important to understand that some certificates use a value for + subjectKeyIdentifier that is not suitable for uniquely identifying a + certificate. Implementations MUST be prepared for multiple + certificates for potentially different entities to have the same + value for subjectKeyIdentifier, and MUST be prepared to try each + matching certificate during signature verification before indicating + an error condition. + +2.7. ContentEncryptionAlgorithmIdentifier + + Sending and receiving agents: + + - MUST support encryption and decryption with AES-128 CBC + [CMSAES]. + + - SHOULD+ support encryption and decryption with AES-192 CBC and + AES-256 CBC [CMSAES]. + + - SHOULD- support encryption and decryption with DES EDE3 CBC, + hereinafter called "tripleDES" [CMSALG]. + +2.7.1. Deciding Which Encryption Method to Use + + When a sending agent creates an encrypted message, it has to decide + which type of encryption to use. The decision process involves using + information garnered from the capabilities lists included in messages + received from the recipient, as well as out-of-band information such + as private agreements, user preferences, legal restrictions, and so + on. + + Section 2.5.2 defines a method by which a sending agent can + optionally announce, among other things, its decrypting capabilities + in its order of preference. The following method for processing and + remembering the encryption capabilities attribute in incoming signed + messages SHOULD be used. + + - If the receiving agent has not yet created a list of + capabilities for the sender's public key, then, after verifying + the signature on the incoming message and checking the + timestamp, the receiving agent SHOULD create a new list + containing at least the signing time and the symmetric + capabilities. + + + +Ramsdell & Turner Standards Track [Page 16] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + - If such a list already exists, the receiving agent SHOULD verify + that the signing time in the incoming message is greater than + the signing time stored in the list and that the signature is + valid. If so, the receiving agent SHOULD update both the + signing time and capabilities in the list. Values of the + signing time that lie far in the future (that is, a greater + discrepancy than any reasonable clock skew), or a capabilities + list in messages whose signature could not be verified, MUST NOT + be accepted. + + The list of capabilities SHOULD be stored for future use in creating + messages. + + Before sending a message, the sending agent MUST decide whether it is + willing to use weak encryption for the particular data in the + message. If the sending agent decides that weak encryption is + unacceptable for this data, then the sending agent MUST NOT use a + weak algorithm. The decision to use or not use weak encryption + overrides any other decision in this section about which encryption + algorithm to use. + + Sections 2.7.1.1 through 2.7.1.2 describe the decisions a sending + agent SHOULD use in deciding which type of encryption will be applied + to a message. These rules are ordered, so the sending agent SHOULD + make its decision in the order given. + +2.7.1.1. Rule 1: Known Capabilities + + If the sending agent has received a set of capabilities from the + recipient for the message the agent is about to encrypt, then the + sending agent SHOULD use that information by selecting the first + capability in the list (that is, the capability most preferred by the + intended recipient) that the sending agent knows how to encrypt. The + sending agent SHOULD use one of the capabilities in the list if the + agent reasonably expects the recipient to be able to decrypt the + message. + +2.7.1.2. Rule 2: Unknown Capabilities, Unknown Version of S/MIME + + If the following two conditions are met: + + - the sending agent has no knowledge of the encryption + capabilities of the recipient, and + + - the sending agent has no knowledge of the version of S/MIME of + the recipient, + + + + + +Ramsdell & Turner Standards Track [Page 17] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + then the sending agent SHOULD use AES-128 because it is a stronger + algorithm and is required by S/MIME v3.2. If the sending agent + chooses not to use AES-128 in this step, it SHOULD use tripleDES. + +2.7.2. Choosing Weak Encryption + + All algorithms that use 40-bit keys are considered by many to be weak + encryption. A sending agent that is controlled by a human SHOULD + allow a human sender to determine the risks of sending data using a + weak encryption algorithm before sending the data, and possibly allow + the human to use a stronger encryption method such as tripleDES or + AES. + +2.7.3. Multiple Recipients + + If a sending agent is composing an encrypted message to a group of + recipients where the encryption capabilities of some of the + recipients do not overlap, the sending agent is forced to send more + than one message. Please note that if the sending agent chooses to + send a message encrypted with a strong algorithm, and then send the + same message encrypted with a weak algorithm, someone watching the + communications channel could learn the contents of the strongly + encrypted message simply by decrypting the weakly encrypted message. + +3. Creating S/MIME Messages + + This section describes the S/MIME message formats and how they are + created. S/MIME messages are a combination of MIME bodies and CMS + content types. Several media types as well as several CMS content + types are used. The data to be secured is always a canonical MIME + entity. The MIME entity and other data, such as certificates and + algorithm identifiers, are given to CMS processing facilities that + produce a CMS object. Finally, the CMS object is wrapped in MIME. + The Enhanced Security Services for S/MIME [ESS] document provides + descriptions of how nested, secured S/MIME messages are formatted. + ESS provides a description of how a triple-wrapped S/MIME message is + formatted using multipart/signed and application/pkcs7-mime for the + signatures. + + S/MIME provides one format for enveloped-only data, several formats + for signed-only data, and several formats for signed and enveloped + data. Several formats are required to accommodate several + environments, in particular for signed messages. The criteria for + choosing among these formats are also described. + + The reader of this section is expected to understand MIME as + described in [MIME-SPEC] and [MIME-SECURE]. + + + + +Ramsdell & Turner Standards Track [Page 18] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.1. Preparing the MIME Entity for Signing, Enveloping, or Compressing + + S/MIME is used to secure MIME entities. A MIME entity can be a sub- + part, sub-parts of a message, or the whole message with all its sub- + parts. A MIME entity that is the whole message includes only the + MIME message headers and MIME body, and does not include the RFC-822 + header. Note that S/MIME can also be used to secure MIME entities + used in applications other than Internet mail. If protection of the + RFC-822 header is required, the use of the message/rfc822 media type + is explained later in this section. + + The MIME entity that is secured and described in this section can be + thought of as the "inside" MIME entity. That is, it is the + "innermost" object in what is possibly a larger MIME message. + Processing "outside" MIME entities into CMS content types is + described in Sections 3.2, 3.4, and elsewhere. + + The procedure for preparing a MIME entity is given in [MIME-SPEC]. + The same procedure is used here with some additional restrictions + when signing. The description of the procedures from [MIME-SPEC] is + repeated here, but it is suggested that the reader refer to that + document for the exact procedure. This section also describes + additional requirements. + + A single procedure is used for creating MIME entities that are to + have any combination of signing, enveloping, and compressing applied. + Some additional steps are recommended to defend against known + corruptions that can occur during mail transport that are of + particular importance for clear-signing using the multipart/signed + format. It is recommended that these additional steps be performed + on enveloped messages, or signed and enveloped messages, so that the + message can be forwarded to any environment without modification. + + These steps are descriptive rather than prescriptive. The + implementer is free to use any procedure as long as the result is the + same. + + Step 1. The MIME entity is prepared according to the local + conventions. + + Step 2. The leaf parts of the MIME entity are converted to canonical + form. + + Step 3. Appropriate transfer encoding is applied to the leaves of + the MIME entity. + + + + + + +Ramsdell & Turner Standards Track [Page 19] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + When an S/MIME message is received, the security services on the + message are processed, and the result is the MIME entity. That MIME + entity is typically passed to a MIME-capable user agent where it is + further decoded and presented to the user or receiving application. + + In order to protect outer, non-content-related message header fields + (for instance, the "Subject", "To", "From", and "Cc" fields), the + sending client MAY wrap a full MIME message in a message/rfc822 + wrapper in order to apply S/MIME security services to these header + fields. It is up to the receiving client to decide how to present + this "inner" header along with the unprotected "outer" header. + + When an S/MIME message is received, if the top-level protected MIME + entity has a Content-Type of message/rfc822, it can be assumed that + the intent was to provide header protection. This entity SHOULD be + presented as the top-level message, taking into account header + merging issues as previously discussed. + +3.1.1. Canonicalization + + Each MIME entity MUST be converted to a canonical form that is + uniquely and unambiguously representable in the environment where the + signature is created and the environment where the signature will be + verified. MIME entities MUST be canonicalized for enveloping and + compressing as well as signing. + + The exact details of canonicalization depend on the actual media type + and subtype of an entity, and are not described here. Instead, the + standard for the particular media type SHOULD be consulted. For + example, canonicalization of type text/plain is different from + canonicalization of audio/basic. Other than text types, most types + have only one representation regardless of computing platform or + environment that can be considered their canonical representation. + In general, canonicalization will be performed by the non-security + part of the sending agent rather than the S/MIME implementation. + + The most common and important canonicalization is for text, which is + often represented differently in different environments. MIME + entities of major type "text" MUST have both their line endings and + character set canonicalized. The line ending MUST be the pair of + characters , and the charset SHOULD be a registered charset + [CHARSETS]. The details of the canonicalization are specified in + [MIME-SPEC]. + + Note that some charsets such as ISO-2022 have multiple + representations for the same characters. When preparing such text + for signing, the canonical representation specified for the charset + MUST be used. + + + +Ramsdell & Turner Standards Track [Page 20] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.1.2. Transfer Encoding + + When generating any of the secured MIME entities below, except the + signing using the multipart/signed format, no transfer encoding is + required at all. S/MIME implementations MUST be able to deal with + binary MIME objects. If no Content-Transfer-Encoding header field is + present, the transfer encoding is presumed to be 7BIT. + + S/MIME implementations SHOULD however use transfer encoding described + in Section 3.1.3 for all MIME entities they secure. The reason for + securing only 7-bit MIME entities, even for enveloped data that are + not exposed to the transport, is that it allows the MIME entity to be + handled in any environment without changing it. For example, a + trusted gateway might remove the envelope, but not the signature, of + a message, and then forward the signed message on to the end + recipient so that they can verify the signatures directly. If the + transport internal to the site is not 8-bit clean, such as on a wide- + area network with a single mail gateway, verifying the signature will + not be possible unless the original MIME entity was only 7-bit data. + + S/MIME implementations that "know" that all intended recipients are + capable of handling inner (all but the outermost) binary MIME objects + SHOULD use binary encoding as opposed to a 7-bit-safe transfer + encoding for the inner entities. The use of a 7-bit-safe encoding + (such as base64) would unnecessarily expand the message size. + Implementations MAY "know" that recipient implementations are capable + of handling inner binary MIME entities either by interpreting the id- + cap-preferBinaryInside SMIMECapabilities attribute, by prior + agreement, or by other means. + + If one or more intended recipients are unable to handle inner binary + MIME objects, or if this capability is unknown for any of the + intended recipients, S/MIME implementations SHOULD use transfer + encoding described in Section 3.1.3 for all MIME entities they + secure. + +3.1.3. Transfer Encoding for Signing Using multipart/signed + + If a multipart/signed entity is ever to be transmitted over the + standard Internet SMTP infrastructure or other transport that is + constrained to 7-bit text, it MUST have transfer encoding applied so + that it is represented as 7-bit text. MIME entities that are 7-bit + data already need no transfer encoding. Entities such as 8-bit text + and binary data can be encoded with quoted-printable or base-64 + transfer encoding. + + + + + + +Ramsdell & Turner Standards Track [Page 21] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + The primary reason for the 7-bit requirement is that the Internet + mail transport infrastructure cannot guarantee transport of 8-bit or + binary data. Even though many segments of the transport + infrastructure now handle 8-bit and even binary data, it is sometimes + not possible to know whether the transport path is 8-bit clean. If a + mail message with 8-bit data were to encounter a message transfer + agent that cannot transmit 8-bit or binary data, the agent has three + options, none of which are acceptable for a clear-signed message: + + - The agent could change the transfer encoding; this would + invalidate the signature. + + - The agent could transmit the data anyway, which would most likely + result in the 8th bit being corrupted; this too would invalidate + the signature. + + - The agent could return the message to the sender. + + [MIME-SECURE] prohibits an agent from changing the transfer encoding + of the first part of a multipart/signed message. If a compliant + agent that cannot transmit 8-bit or binary data encounters a + multipart/signed message with 8-bit or binary data in the first part, + it would have to return the message to the sender as undeliverable. + +3.1.4. Sample Canonical MIME Entity + + This example shows a multipart/mixed message with full transfer + encoding. This message contains a text part and an attachment. The + sample message text includes characters that are not US-ASCII and + thus need to be transfer encoded. Though not shown here, the end of + each line is . The line ending of the MIME headers, the + text, and the transfer encoded parts, all MUST be . + + Note that this example is not of an S/MIME message. + + Content-Type: multipart/mixed; boundary=bar + + --bar + Content-Type: text/plain; charset=iso-8859-1 + Content-Transfer-Encoding: quoted-printable + + =A1Hola Michael! + + How do you like the new S/MIME specification? + + It's generally a good idea to encode lines that begin with + From=20because some mail transport agents will insert a greater- + than (>) sign, thus invalidating the signature. + + + +Ramsdell & Turner Standards Track [Page 22] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Also, in some cases it might be desirable to encode any =20 + trailing whitespace that occurs on lines in order to ensure =20 + that the message signature is not invalidated when passing =20 + a gateway that modifies such whitespace (like BITNET). =20 + + --bar + Content-Type: image/jpeg + Content-Transfer-Encoding: base64 + + iQCVAwUBMJrRF2N9oWBghPDJAQE9UQQAtl7LuRVndBjrk4EqYBIb3h5QXIX/LC// + jJV5bNvkZIGPIcEmI5iFd9boEgvpirHtIREEqLQRkYNoBActFBZmh9GC3C041WGq + uMbrbxc+nIs1TIKlA08rVi9ig/2Yh7LFrK5Ein57U/W72vgSxLhe/zhdfolT9Brn + HOxEa44b+EI= + + --bar-- + +3.2. The application/pkcs7-mime Media Type + + The application/pkcs7-mime media type is used to carry CMS content + types including EnvelopedData, SignedData, and CompressedData. The + details of constructing these entities are described in subsequent + sections. This section describes the general characteristics of the + application/pkcs7-mime media type. + + The carried CMS object always contains a MIME entity that is prepared + as described in Section 3.1 if the eContentType is id-data. Other + contents MAY be carried when the eContentType contains different + values. See [ESS] for an example of this with signed receipts. + + Since CMS content types are binary data, in most cases base-64 + transfer encoding is appropriate, in particular, when used with SMTP + transport. The transfer encoding used depends on the transport + through which the object is to be sent, and is not a characteristic + of the media type. + + Note that this discussion refers to the transfer encoding of the CMS + object or "outside" MIME entity. It is completely distinct from, and + unrelated to, the transfer encoding of the MIME entity secured by the + CMS object, the "inside" object, which is described in Section 3.1. + + Because there are several types of application/pkcs7-mime objects, a + sending agent SHOULD do as much as possible to help a receiving agent + know about the contents of the object without forcing the receiving + agent to decode the ASN.1 for the object. The Content-Type header + field of all application/pkcs7-mime objects SHOULD include the + optional "smime-type" parameter, as described in the following + sections. + + + + +Ramsdell & Turner Standards Track [Page 23] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.2.1. The name and filename Parameters + + For the application/pkcs7-mime, sending agents SHOULD emit the + optional "name" parameter to the Content-Type field for compatibility + with older systems. Sending agents SHOULD also emit the optional + Content-Disposition field [CONTDISP] with the "filename" parameter. + If a sending agent emits the above parameters, the value of the + parameters SHOULD be a file name with the appropriate extension: + + Media Type File Extension + application/pkcs7-mime (SignedData, EnvelopedData) .p7m + application/pkcs7-mime (degenerate SignedData .p7c + certificate management message) + application/pkcs7-mime (CompressedData) .p7z + application/pkcs7-signature (SignedData) .p7s + + In addition, the file name SHOULD be limited to eight characters + followed by a three-letter extension. The eight-character filename + base can be any distinct name; the use of the filename base "smime" + SHOULD be used to indicate that the MIME entity is associated with + S/MIME. + + Including a file name serves two purposes. It facilitates easier use + of S/MIME objects as files on disk. It also can convey type + information across gateways. When a MIME entity of type + application/pkcs7-mime (for example) arrives at a gateway that has no + special knowledge of S/MIME, it will default the entity's media type + to application/octet-stream and treat it as a generic attachment, + thus losing the type information. However, the suggested filename + for an attachment is often carried across a gateway. This often + allows the receiving systems to determine the appropriate application + to hand the attachment off to, in this case, a stand-alone S/MIME + processing application. Note that this mechanism is provided as a + convenience for implementations in certain environments. A proper + S/MIME implementation MUST use the media types and MUST NOT rely on + the file extensions. + +3.2.2. The smime-type Parameter + + The application/pkcs7-mime content type defines the optional "smime- + type" parameter. The intent of this parameter is to convey details + about the security applied (signed or enveloped) along with + information about the contained content. This specification defines + the following smime-types. + + + + + + + +Ramsdell & Turner Standards Track [Page 24] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Name CMS Type Inner Content + enveloped-data EnvelopedData id-data + signed-data SignedData id-data + certs-only SignedData none + compressed-data CompressedData id-data + + In order for consistency to be obtained with future specifications, + the following guidelines SHOULD be followed when assigning a new + smime-type parameter. + + 1. If both signing and encryption can be applied to the content, + then two values for smime-type SHOULD be assigned "signed-*" + and "enveloped-*". If one operation can be assigned, then this + can be omitted. Thus, since "certs-only" can only be signed, + "signed-" is omitted. + + 2. A common string for a content OID SHOULD be assigned. We use + "data" for the id-data content OID when MIME is the inner + content. + + 3. If no common string is assigned, then the common string of + "OID." is recommended (for example, + "OID.2.16.840.1.101.3.4.1.2" would be AES-128 CBC). + + It is explicitly intended that this field be a suitable hint for mail + client applications to indicate whether a message is "signed" or + "enveloped" without having to tunnel into the CMS payload. + +3.3. Creating an Enveloped-Only Message + + This section describes the format for enveloping a MIME entity + without signing it. It is important to note that sending enveloped + but not signed messages does not provide for data integrity. It is + possible to replace ciphertext in such a way that the processed + message will still be valid, but the meaning can be altered. + + Step 1. The MIME entity to be enveloped is prepared according to + Section 3.1. + + Step 2. The MIME entity and other required data is processed into a + CMS object of type EnvelopedData. In addition to encrypting + a copy of the content-encryption key for each recipient, a + copy of the content-encryption key SHOULD be encrypted for + the originator and included in the EnvelopedData (see [CMS], + Section 6). + + Step 3. The EnvelopedData object is wrapped in a CMS ContentInfo + object. + + + +Ramsdell & Turner Standards Track [Page 25] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Step 4. The ContentInfo object is inserted into an + application/pkcs7-mime MIME entity. + + The smime-type parameter for enveloped-only messages is "enveloped- + data". The file extension for this type of message is ".p7m". + + A sample message would be: + + Content-Type: application/pkcs7-mime; smime-type=enveloped-data; + name=smime.p7m + Content-Transfer-Encoding: base64 + Content-Disposition: attachment; filename=smime.p7m + + rfvbnj756tbBghyHhHUujhJhjH77n8HHGT9HG4VQpfyF467GhIGfHfYT6 + 7n8HHGghyHhHUujhJh4VQpfyF467GhIGfHfYGTrfvbnjT6jH7756tbB9H + f8HHGTrfvhJhjH776tbB9HG4VQbnj7567GhIGfHfYT6ghyHhHUujpfyF4 + 0GhIGfHfQbnj756YT64V + +3.4. Creating a Signed-Only Message + + There are two formats for signed messages defined for S/MIME: + + - application/pkcs7-mime with SignedData. + + - multipart/signed. + + In general, the multipart/signed form is preferred for sending, and + receiving agents MUST be able to handle both. + +3.4.1. Choosing a Format for Signed-Only Messages + + There are no hard-and-fast rules as to when a particular signed-only + format is chosen. It depends on the capabilities of all the + receivers and the relative importance of receivers with S/MIME + facilities being able to verify the signature versus the importance + of receivers without S/MIME software being able to view the message. + + Messages signed using the multipart/signed format can always be + viewed by the receiver whether or not they have S/MIME software. + They can also be viewed whether they are using a MIME-native user + agent or they have messages translated by a gateway. In this + context, "be viewed" means the ability to process the message + essentially as if it were not a signed message, including any other + MIME structure the message might have. + + + + + + + +Ramsdell & Turner Standards Track [Page 26] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Messages signed using the SignedData format cannot be viewed by a + recipient unless they have S/MIME facilities. However, the + SignedData format protects the message content from being changed by + benign intermediate agents. Such agents might do line wrapping or + content-transfer encoding changes that would break the signature. + +3.4.2. Signing Using application/pkcs7-mime with SignedData + + This signing format uses the application/pkcs7-mime media type. The + steps to create this format are: + + Step 1. The MIME entity is prepared according to Section 3.1. + + Step 2. The MIME entity and other required data are processed into a + CMS object of type SignedData. + + Step 3. The SignedData object is wrapped in a CMS ContentInfo + object. + + Step 4. The ContentInfo object is inserted into an + application/pkcs7-mime MIME entity. + + The smime-type parameter for messages using application/pkcs7-mime + with SignedData is "signed-data". The file extension for this type + of message is ".p7m". + + A sample message would be: + + Content-Type: application/pkcs7-mime; smime-type=signed-data; + name=smime.p7m + Content-Transfer-Encoding: base64 + Content-Disposition: attachment; filename=smime.p7m + + 567GhIGfHfYT6ghyHhHUujpfyF4f8HHGTrfvhJhjH776tbB9HG4VQbnj7 + 77n8HHGT9HG4VQpfyF467GhIGfHfYT6rfvbnj756tbBghyHhHUujhJhjH + HUujhJh4VQpfyF467GhIGfHfYGTrfvbnjT6jH7756tbB9H7n8HHGghyHh + 6YT64V0GhIGfHfQbnj75 + +3.4.3. Signing Using the multipart/signed Format + + This format is a clear-signing format. Recipients without any S/MIME + or CMS processing facilities are able to view the message. It makes + use of the multipart/signed media type described in [MIME-SECURE]. + The multipart/signed media type has two parts. The first part + contains the MIME entity that is signed; the second part contains the + "detached signature" CMS SignedData object in which the + encapContentInfo eContent field is absent. + + + + +Ramsdell & Turner Standards Track [Page 27] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.4.3.1. The application/pkcs7-signature Media Type + + This media type always contains a CMS ContentInfo containing a single + CMS object of type SignedData. The SignedData encapContentInfo + eContent field MUST be absent. The signerInfos field contains the + signatures for the MIME entity. + + The file extension for signed-only messages using application/pkcs7- + signature is ".p7s". + +3.4.3.2. Creating a multipart/signed Message + + Step 1. The MIME entity to be signed is prepared according to + Section 3.1, taking special care for clear-signing. + + Step 2. The MIME entity is presented to CMS processing in order to + obtain an object of type SignedData in which the + encapContentInfo eContent field is absent. + + Step 3. The MIME entity is inserted into the first part of a + multipart/signed message with no processing other than that + described in Section 3.1. + + Step 4. Transfer encoding is applied to the "detached signature" CMS + SignedData object, and it is inserted into a MIME entity of + type application/pkcs7-signature. + + Step 5. The MIME entity of the application/pkcs7-signature is + inserted into the second part of the multipart/signed + entity. + + The multipart/signed Content-Type has two required parameters: the + protocol parameter and the micalg parameter. + + The protocol parameter MUST be "application/pkcs7-signature". Note + that quotation marks are required around the protocol parameter + because MIME requires that the "/" character in the parameter value + MUST be quoted. + + The micalg parameter allows for one-pass processing when the + signature is being verified. The value of the micalg parameter is + dependent on the message digest algorithm(s) used in the calculation + of the Message Integrity Check. If multiple message digest + algorithms are used, they MUST be separated by commas per [MIME- + SECURE]. The values to be placed in the micalg parameter SHOULD be + from the following: + + + + + +Ramsdell & Turner Standards Track [Page 28] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Algorithm Value Used + + MD5 md5 + SHA-1 sha-1 + SHA-224 sha-224 + SHA-256 sha-256 + SHA-384 sha-384 + SHA-512 sha-512 + Any other (defined separately in algorithm profile or "unknown" + if not defined) + + (Historical note: some early implementations of S/MIME emitted and + expected "rsa-md5", "rsa-sha1", and "sha1" for the micalg parameter.) + Receiving agents SHOULD be able to recover gracefully from a micalg + parameter value that they do not recognize. Future names for this + parameter will be consistent with the IANA "Hash Function Textual + Names" registry. + +3.4.3.3. Sample multipart/signed Message + + Content-Type: multipart/signed; + protocol="application/pkcs7-signature"; + micalg=sha1; boundary=boundary42 + + --boundary42 + Content-Type: text/plain + + This is a clear-signed message. + + --boundary42 + Content-Type: application/pkcs7-signature; name=smime.p7s + Content-Transfer-Encoding: base64 + Content-Disposition: attachment; filename=smime.p7s + + ghyHhHUujhJhjH77n8HHGTrfvbnj756tbB9HG4VQpfyF467GhIGfHfYT6 + 4VQpfyF467GhIGfHfYT6jH77n8HHGghyHhHUujhJh756tbB9HGTrfvbnj + n8HHGTrfvhJhjH776tbB9HG4VQbnj7567GhIGfHfYT6ghyHhHUujpfyF4 + 7GhIGfHfYT64VQbnj756 + + --boundary42-- + + The content that is digested (the first part of the multipart/signed) + consists of the bytes: + + 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 70 6c 61 69 + 6e 0d 0a 0d 0a 54 68 69 73 20 69 73 20 61 20 63 6c 65 61 72 2d 73 69 + 67 6e 65 64 20 6d 65 73 73 61 67 65 2e 0d 0a + + + + +Ramsdell & Turner Standards Track [Page 29] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.5. Creating a Compressed-Only Message + + This section describes the format for compressing a MIME entity. + Please note that versions of S/MIME prior to version 3.1 did not + specify any use of CompressedData, and will not recognize it. The + use of a capability to indicate the ability to receive CompressedData + is described in [CMSCOMPR] and is the preferred method for + compatibility. + + Step 1. The MIME entity to be compressed is prepared according to + Section 3.1. + + Step 2. The MIME entity and other required data are processed into a + CMS object of type CompressedData. + + Step 3. The CompressedData object is wrapped in a CMS ContentInfo + object. + + Step 4. The ContentInfo object is inserted into an + application/pkcs7-mime MIME entity. + + The smime-type parameter for compressed-only messages is "compressed- + data". The file extension for this type of message is ".p7z". + + A sample message would be: + + Content-Type: application/pkcs7-mime; smime-type=compressed-data; + name=smime.p7z + Content-Transfer-Encoding: base64 + Content-Disposition: attachment; filename=smime.p7z + + rfvbnj756tbBghyHhHUujhJhjH77n8HHGT9HG4VQpfyF467GhIGfHfYT6 + 7n8HHGghyHhHUujhJh4VQpfyF467GhIGfHfYGTrfvbnjT6jH7756tbB9H + f8HHGTrfvhJhjH776tbB9HG4VQbnj7567GhIGfHfYT6ghyHhHUujpfyF4 + 0GhIGfHfQbnj756YT64V + +3.6. Multiple Operations + + The signed-only, enveloped-only, and compressed-only MIME formats can + be nested. This works because these formats are all MIME entities + that encapsulate other MIME entities. + + An S/MIME implementation MUST be able to receive and process + arbitrarily nested S/MIME within reasonable resource limits of the + recipient computer. + + + + + + +Ramsdell & Turner Standards Track [Page 30] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + It is possible to apply any of the signing, encrypting, and + compressing operations in any order. It is up to the implementer and + the user to choose. When signing first, the signatories are then + securely obscured by the enveloping. When enveloping first the + signatories are exposed, but it is possible to verify signatures + without removing the enveloping. This can be useful in an + environment where automatic signature verification is desired, as no + private key material is required to verify a signature. + + There are security ramifications to choosing whether to sign first or + encrypt first. A recipient of a message that is encrypted and then + signed can validate that the encrypted block was unaltered, but + cannot determine any relationship between the signer and the + unencrypted contents of the message. A recipient of a message that + is signed then encrypted can assume that the signed message itself + has not been altered, but that a careful attacker could have changed + the unauthenticated portions of the encrypted message. + + When using compression, keep the following guidelines in mind: + + - Compression of binary encoded encrypted data is discouraged, + since it will not yield significant compression. Base64 + encrypted data could very well benefit, however. + + - If a lossy compression algorithm is used with signing, you will + need to compress first, then sign. + +3.7. Creating a Certificate Management Message + + The certificate management message or MIME entity is used to + transport certificates and/or Certificate Revocation Lists, such as + in response to a registration request. + + Step 1. The certificates and/or Certificate Revocation Lists are + made available to the CMS generating process that creates a + CMS object of type SignedData. The SignedData + encapContentInfo eContent field MUST be absent and + signerInfos field MUST be empty. + + Step 2. The SignedData object is wrapped in a CMS ContentInfo + object. + + Step 3. The ContentInfo object is enclosed in an + application/pkcs7-mime MIME entity. + + The smime-type parameter for a certificate management message is + "certs-only". The file extension for this type of message is ".p7c". + + + + +Ramsdell & Turner Standards Track [Page 31] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +3.8. Registration Requests + + A sending agent that signs messages MUST have a certificate for the + signature so that a receiving agent can verify the signature. There + are many ways of getting certificates, such as through an exchange + with a certification authority, through a hardware token or diskette, + and so on. + + S/MIME v2 [SMIMEv2] specified a method for "registering" public keys + with certificate authorities using an application/pkcs10 body part. + Since that time, the IETF PKIX Working Group has developed other + methods for requesting certificates. However, S/MIME v3.2 does not + require a particular certificate request mechanism. + +3.9. Identifying an S/MIME Message + + Because S/MIME takes into account interoperation in non-MIME + environments, several different mechanisms are employed to carry the + type information, and it becomes a bit difficult to identify S/MIME + messages. The following table lists criteria for determining whether + or not a message is an S/MIME message. A message is considered an + S/MIME message if it matches any of the criteria listed below. + + The file suffix in the table below comes from the "name" parameter in + the Content-Type header field, or the "filename" parameter on the + Content-Disposition header field. These parameters that give the + file suffix are not listed below as part of the parameter section. + + Media type: application/pkcs7-mime + parameters: any + file suffix: any + + Media type: multipart/signed + parameters: protocol="application/pkcs7-signature" + file suffix: any + + Media type: application/octet-stream + parameters: any + file suffix: p7m, p7s, p7c, p7z + +4. Certificate Processing + + A receiving agent MUST provide some certificate retrieval mechanism + in order to gain access to certificates for recipients of digital + envelopes. This specification does not cover how S/MIME agents + handle certificates, only what they do after a certificate has been + validated or rejected. S/MIME certificate issues are covered in + [CERT32]. + + + +Ramsdell & Turner Standards Track [Page 32] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + At a minimum, for initial S/MIME deployment, a user agent could + automatically generate a message to an intended recipient requesting + that recipient's certificate in a signed return message. Receiving + and sending agents SHOULD also provide a mechanism to allow a user to + "store and protect" certificates for correspondents in such a way so + as to guarantee their later retrieval. + +4.1. Key Pair Generation + + All generated key pairs MUST be generated from a good source of non- + deterministic random input [RANDOM] and the private key MUST be + protected in a secure fashion. + + An S/MIME user agent MUST NOT generate asymmetric keys less than 512 + bits for use with the RSA or DSA signature algorithms. + + For 512-bit RSA with SHA-1 see [CMSALG] and [FIPS186-2] without + Change Notice 1, for 512-bit RSA with SHA-256 see [CMS-SHA2] and + [FIPS186-2] without Change Notice 1, and for 1024-bit through + 2048-bit RSA with SHA-256 see [CMS-SHA2] and [FIPS186-2] with Change + Notice 1. The first reference provides the signature algorithm's + object identifier, and the second provides the signature algorithm's + definition. + + For 512-bit DSA with SHA-1 see [CMSALG] and [FIPS186-2] without + Change Notice 1, for 512-bit DSA with SHA-256 see [CMS-SHA2] and + [FIPS186-2] without Change Notice 1, for 1024-bit DSA with SHA-1 see + [CMSALG] and [FIPS186-2] with Change Notice 1, for 1024-bit and above + DSA with SHA-256 see [CMS-SHA2] and [FIPS186-3]. The first reference + provides the signature algorithm's object identifier and the second + provides the signature algorithm's definition. + + For RSASSA-PSS with SHA-256, see [RSAPSS]. For 1024-bit DH, see + [CMSALG]. For 1024-bit and larger DH, see [SP800-56A]; regardless, + use the KDF, which is from X9.42, specified in [CMSALG]. For RSAES- + OAEP, see [RSAOAEP]. + +4.2. Signature Generation + + The following are the requirements for an S/MIME agent generated RSA, + RSASSA-PSS, and DSA signatures: + + key size <= 1023 : SHOULD NOT (see Security Considerations) + 1024 <= key size <= 2048 : SHOULD (see Security Considerations) + 2048 < key size : MAY (see Security Considerations) + + + + + + +Ramsdell & Turner Standards Track [Page 33] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +4.3. Signature Verification + + The following are the requirements for S/MIME receiving agents during + signature verification of RSA, RSASSA-PSS, and DSA signatures: + + key size <= 1023 : MAY (see Security Considerations) + 1024 <= key size <= 2048 : MUST (see Security Considerations) + 2048 < key size : MAY (see Security Considerations) + +4.4. Encryption + + The following are the requirements for an S/MIME agent when + establishing keys for content encryption using the RSA, RSA-OAEP, and + DH algorithms: + + key size <= 1023 : SHOULD NOT (see Security Considerations) + 1024 <= key size <= 2048 : SHOULD (see Security Considerations) + 2048 < key size : MAY (see Security Considerations) + +4.5. Decryption + + The following are the requirements for an S/MIME agent when + establishing keys for content decryption using the RSA, RSAES-OAEP, + and DH algorithms: + + key size <= 1023 : MAY (see Security Considerations) + 1024 <= key size <= 2048 : MUST (see Security Considerations) + 2048 < key size : MAY (see Security Considerations) + +5. IANA Considerations + + The following information updates the media type registration for + application/pkcs7-mime and application/pkcs7-signature to refer to + this document as opposed to RFC 2311. + + Note that other documents can define additional MIME media types for + S/MIME. + +5.1. Media Type for application/pkcs7-mime + + Type name: application + + Subtype Name: pkcs7-mime + + Required Parameters: NONE + + + + + + +Ramsdell & Turner Standards Track [Page 34] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Optional Parameters: smime-type/signed-data + smime-type/enveloped-data + smime-type/compressed-data + smime-type/certs-only + name + + Encoding Considerations: See Section 3 of this document + + Security Considerations: See Section 6 of this document + + Interoperability Considerations: See Sections 1-6 of this document + + Published Specification: RFC 2311, RFC 2633, and this document + + Applications that use this media type: Security applications + + Additional information: NONE + + Person & email to contact for further information: + S/MIME working group chairs smime-chairs@tools.ietf.org + + Intended usage: COMMON + + Restrictions on usage: NONE + + Author: Sean Turner + + Change Controller: S/MIME working group delegated from the IESG + +5.2. Media Type for application/pkcs7-signature + + Type name: application + + Subtype Name: pkcs7-signature + + Required Parameters: NONE + + Optional Parameters: NONE + + Encoding Considerations: See Section 3 of this document + + Security Considerations: See Section 6 of this document + + Interoperability Considerations: See Sections 1-6 of this document + + Published Specification: RFC 2311, RFC 2633, and this document + + Applications that use this media type: Security applications + + + +Ramsdell & Turner Standards Track [Page 35] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + Additional information: NONE + + Person & email to contact for further information: + S/MIME working group chairs smime-chairs@tools.ietf.org + + Intended usage: COMMON + + Restrictions on usage: NONE + + Author: Sean Turner + + Change Controller: S/MIME working group delegated from the IESG + +6. Security Considerations + + Cryptographic algorithms will be broken or weakened over time. + Implementers and users need to check that the cryptographic + algorithms listed in this document continue to provide the expected + level of security. The IETF from time to time may issue documents + dealing with the current state of the art. For example: + + - The Million Message Attack described in RFC 3218 [MMA]. + + - The Diffie-Hellman "small-subgroup" attacks described in RFC + 2785 [DHSUB]. + + - The attacks against hash algorithms described in RFC 4270 [HASH- + ATTACK]. + + This specification uses Public-Key Cryptography technologies. It is + assumed that the private key is protected to ensure that it is not + accessed or altered by unauthorized parties. + + It is impossible for most people or software to estimate the value of + a message's content. Further, it is impossible for most people or + software to estimate the actual cost of recovering an encrypted + message content that is encrypted with a key of a particular size. + Further, it is quite difficult to determine the cost of a failed + decryption if a recipient cannot process a message's content. Thus, + choosing between different key sizes (or choosing whether to just use + plaintext) is also impossible for most people or software. However, + decisions based on these criteria are made all the time, and + therefore this specification gives a framework for using those + estimates in choosing algorithms. + + The choice of 2048 bits as the RSA asymmetric key size in this + specification is based on the desire to provide at least 100 bits of + security. The key sizes that must be supported to conform to this + + + +Ramsdell & Turner Standards Track [Page 36] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + specification seem appropriate for the Internet based on [STRENGTH]. + Of course, there are environments, such as financial and medical + systems, that may select different key sizes. For this reason, an + implementation MAY support key sizes beyond those recommended in this + specification. + + Receiving agents that validate signatures and sending agents that + encrypt messages need to be cautious of cryptographic processing + usage when validating signatures and encrypting messages using keys + larger than those mandated in this specification. An attacker could + send certificates with keys that would result in excessive + cryptographic processing, for example, keys larger than those + mandated in this specification, which could swamp the processing + element. Agents that use such keys without first validating the + certificate to a trust anchor are advised to have some sort of + cryptographic resource management system to prevent such attacks. + + Using weak cryptography in S/MIME offers little actual security over + sending plaintext. However, other features of S/MIME, such as the + specification of AES and the ability to announce stronger + cryptographic capabilities to parties with whom you communicate, + allow senders to create messages that use strong encryption. Using + weak cryptography is never recommended unless the only alternative is + no cryptography. + + RSA and DSA keys of less than 1024 bits are now considered by many + experts to be cryptographically insecure (due to advances in + computing power), and should no longer be used to protect messages. + Such keys were previously considered secure, so processing previously + received signed and encrypted mail will often result in the use of + weak keys. Implementations that wish to support previous versions of + S/MIME or process old messages need to consider the security risks + that result from smaller key sizes (e.g., spoofed messages) versus + the costs of denial of service. If an implementation supports + verification of digital signatures generated with RSA and DSA keys of + less than 1024 bits, it MUST warn the user. Implementers should + consider providing different warnings for newly received messages and + previously stored messages. Server implementations (e.g., secure + mail list servers) where user warnings are not appropriate SHOULD + reject messages with weak signatures. + + Implementers SHOULD be aware that multiple active key pairs can be + associated with a single individual. For example, one key pair can + be used to support confidentiality, while a different key pair can be + used for digital signatures. + + + + + + +Ramsdell & Turner Standards Track [Page 37] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + If a sending agent is sending the same message using different + strengths of cryptography, an attacker watching the communications + channel might be able to determine the contents of the strongly + encrypted message by decrypting the weakly encrypted version. In + other words, a sender SHOULD NOT send a copy of a message using + weaker cryptography than they would use for the original of the + message. + + Modification of the ciphertext can go undetected if authentication is + not also used, which is the case when sending EnvelopedData without + wrapping it in SignedData or enclosing SignedData within it. + + If an implementation is concerned about compliance with National + Institute of Standards and Technology (NIST) key size + recommendations, then see [SP800-57]. + + If messaging environments make use of the fact that a message is + signed to change the behavior of message processing (examples would + be running rules or UI display hints), without first verifying that + the message is actually signed and knowing the state of the + signature, this can lead to incorrect handling of the message. + Visual indicators on messages may need to have the signature + validation code checked periodically if the indicator is supposed to + give information on the current status of a message. + +7. References + +7.1. Reference Conventions + + [CMS] refers to [RFC5652]. + + [ESS] refers to [RFC2634] and [RFC5035]. + + [MIME] refers to [RFC2045], [RFC2046], [RFC2047], [RFC2049], + [RFC4288], and [RFC4289]. + + [SMIMEv2] refers to [RFC2311], [RFC2312], [RFC2313], [RFC2314], and + [RFC2315]. + + [SMIMEv3] refers to [RFC2630], [RFC2631], [RFC2632], [RFC2633], + [RFC2634], and [RFC5035]. + + [SMIMv3.1] refers to [RFC2634], [RFC3850], [RFC3851], [RFC3852], and + [RFC5035]. + + + + + + + +Ramsdell & Turner Standards Track [Page 38] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +7.2. Normative References + + [CERT32] Ramsdell, B. and S. Turner, "Secure/Multipurpose + Internet Mail Extensions (S/MIME) Version 3.2 + Certificate Handling", RFC 5750, January 2010. + + [CHARSETS] Character sets assigned by IANA. See + http://www.iana.org/assignments/character-sets. + + [CMSAES] Schaad, J., "Use of the Advanced Encryption Standard + (AES) Encryption Algorithm in Cryptographic Message + Syntax (CMS)", RFC 3565, July 2003. + + [CMSALG] Housley, R., "Cryptographic Message Syntax (CMS) + Algorithms", RFC 3370, August 2002. + + [CMSCOMPR] Gutmann, P., "Compressed Data Content Type for + Cryptographic Message Syntax (CMS)", RFC 3274, June + 2002. + + [CMS-SHA2] Turner, S., "Using SHA2 Algorithms with Cryptographic + Message Syntax", RFC 5754, January 2010. + + [CONTDISP] Troost, R., Dorner, S., and K. Moore, Ed., + "Communicating Presentation Information in Internet + Messages: The Content-Disposition Header Field", RFC + 2183, August 1997. + + [FIPS186-2] National Institute of Standards and Technology (NIST), + "Digital Signature Standard (DSS)", FIPS Publication + 186-2, January 2000. [With Change Notice 1]. + + [FIPS186-3] National Institute of Standards and Technology (NIST), + FIPS Publication 186-3: Digital Signature Standard, + June 2009. + + [MIME-SECURE] Galvin, J., Murphy, S., Crocker, S., and N. Freed, + "Security Multiparts for MIME: Multipart/Signed and + Multipart/Encrypted", RFC 1847, October 1995. + + [MUSTSHOULD] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + + [RANDOM] Eastlake, D., 3rd, Schiller, J., and S. Crocker, + "Randomness Requirements for Security", BCP 106, RFC + 4086, June 2005. + + + + + +Ramsdell & Turner Standards Track [Page 39] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + [RFC2045] Freed, N. and N. Borenstein, "Multipurpose Internet + Mail Extensions (MIME) Part One: Format of Internet + Message Bodies", RFC 2045, November 1996. + + [RFC2046] Freed, N. and N. Borenstein, "Multipurpose Internet + Mail Extensions (MIME) Part Two: Media Types", RFC + 2046, November 1996. + + [RFC2047] Moore, K., "MIME (Multipurpose Internet Mail + Extensions) Part Three: Message Header Extensions for + Non-ASCII Text", RFC 2047, November 1996. + + [RFC2049] Freed, N. and N. Borenstein, "Multipurpose Internet + Mail Extensions (MIME) Part Five: Conformance Criteria + and Examples", RFC 2049, November 1996. + + [RFC2634] Hoffman, P. Ed., "Enhanced Security Services for + S/MIME", RFC 2634, June 1999. + + [RFC4288] Freed, N. and J. Klensin, "Media Type Specifications + and Registration Procedures", BCP 13, RFC 4288, + December 2005. + + [RFC4289] Freed, N. and J. Klensin, "Multipurpose Internet Mail + Extensions (MIME) Part Four: Registration Procedures", + BCP 13, RFC 4289, December 2005. + + [RFC5035] Schaad, J., "Enhanced Security Services (ESS) Update: + Adding CertID Algorithm Agility", RFC 5035, August + 2007. + + [RFC5652] Housley, R., "Cryptographic Message Syntax (CMS)", RFC + 5652, September 2009. + + [RSAOAEP] Housley, R. "Use of the RSAES-OAEP Key Transport + Algorithm in the Cryptographic Message Syntax (CMS)", + RFC 3560, July 2003. + + [RSAPSS] Schaad, J., "Use of the RSASSA-PSS Signature Algorithm + in Cryptographic Message Syntax (CMS)", RFC 4056, June + 2005. + + [SP800-56A] National Institute of Standards and Technology (NIST), + Special Publication 800-56A: Recommendation Pair-Wise + Key Establishment Schemes Using Discrete Logarithm + Cryptography (Revised), March 2007. + + + + + +Ramsdell & Turner Standards Track [Page 40] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + [X.680] ITU-T Recommendation X.680 (2002) | ISO/IEC + 8824-1:2002. Information Technology - Abstract Syntax + Notation One (ASN.1): Specification of basic notation. + + [X.690] ITU-T Recommendation X.690 (2002) | ISO/IEC + 8825-1:2002. Information Technology - ASN.1 encoding + rules: Specification of Basic Encoding Rules (BER), + Canonical Encoding Rules (CER) and Distinguished + Encoding Rules (DER). + +7.3. Informative References + + [DHSUB] Zuccherato, R., "Methods for Avoiding the "Small- + Subgroup" Attacks on the Diffie-Hellman Key Agreement + Method for S/MIME", RFC 2785, March 2000. + + [HASH-ATTACK] Hoffman, P. and B. Schneier, "Attacks on Cryptographic + Hashes in Internet Protocols", RFC 4270, November 2005. + + [MMA] Rescorla, E., "Preventing the Million Message Attack on + Cryptographic Message Syntax", RFC 3218, January 2002. + + [PKCS-7] Kaliski, B., "PKCS #7: Cryptographic Message Syntax + Version 1.5", RFC 2315, March 1998. + + [RFC2311] Dusse, S., Hoffman, P., Ramsdell, B., Lundblade, L., + and L. Repka, "S/MIME Version 2 Message Specification", + RFC 2311, March 1998. + + [RFC2312] Dusse, S., Hoffman, P., Ramsdell, B., and J. + Weinstein, "S/MIME Version 2 Certificate Handling", RFC + 2312, March 1998. + + [RFC2313] Kaliski, B., "PKCS #1: RSA Encryption Version 1.5", RFC + 2313, March 1998. + + [RFC2314] Kaliski, B., "PKCS #10: Certification Request Syntax + Version 1.5", RFC 2314, March 1998. + + [RFC2315] Kaliski, B., "PKCS #7: Certification Message Syntax + Version 1.5", RFC 2315, March 1998. + + [RFC2630] Housley, R., "Cryptographic Message Syntax", RFC 2630, + June 1999. + + [RFC2631] Rescorla, E., "Diffie-Hellman Key Agreement Method", + RFC 2631, June 1999. + + + + +Ramsdell & Turner Standards Track [Page 41] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + [RFC2632] Ramsdell, B., Ed., "S/MIME Version 3 Certificate + Handling", RFC 2632, June 1999. + + [RFC2633] Ramsdell, B., Ed., "S/MIME Version 3 Message + Specification", RFC 2633, June 1999. + + [RFC3850] Ramsdell, B., Ed., "Secure/Multipurpose Internet Mail + Extensions (S/MIME) Version 3.1 Certificate Handling", + RFC 3850, July 2004. + + [RFC3851] Ramsdell, B., Ed., "Secure/Multipurpose Internet Mail + Extensions (S/MIME) Version 3.1 Message Specification", + RFC 3851, July 2004. + + [RFC3852] Housley, R., "Cryptographic Message Syntax (CMS)", RFC + 3852, July 2004. + + [SP800-57] National Institute of Standards and Technology (NIST), + Special Publication 800-57: Recommendation for Key + Management, August 2005. + + [STRENGTH] Orman, H., and P. Hoffman, "Determining Strengths For + Public Keys Used For Exchanging Symmetric Keys", BCP + 86, RFC 3766, April 2004. + + + + + + + + + + + + + + + + + + + + + + + + + + + +Ramsdell & Turner Standards Track [Page 42] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +Appendix A. ASN.1 Module + + Note: The ASN.1 module contained herein is unchanged from RFC 3851 + [SMIMEv3.1] with the exception of a change to the prefersBinaryInside + ASN.1 comment. This module uses the 1988 version of ASN.1. + + SecureMimeMessageV3dot1 + + { iso(1) member-body(2) us(840) rsadsi(113549) + pkcs(1) pkcs-9(9) smime(16) modules(0) msg-v3dot1(21) } + + DEFINITIONS IMPLICIT TAGS ::= + + BEGIN + + IMPORTS + + -- Cryptographic Message Syntax [CMS] + SubjectKeyIdentifier, IssuerAndSerialNumber, + RecipientKeyIdentifier + FROM CryptographicMessageSyntax + { iso(1) member-body(2) us(840) rsadsi(113549) + pkcs(1) pkcs-9(9) smime(16) modules(0) cms-2001(14) }; + + -- id-aa is the arc with all new authenticated and unauthenticated + -- attributes produced by the S/MIME Working Group + + id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) + rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)} + + -- S/MIME Capabilities provides a method of broadcasting the + -- symmetric capabilities understood. Algorithms SHOULD be ordered + -- by preference and grouped by type + + smimeCapabilities OBJECT IDENTIFIER ::= {iso(1) member-body(2) + us(840) rsadsi(113549) pkcs(1) pkcs-9(9) 15} + + SMIMECapability ::= SEQUENCE { + capabilityID OBJECT IDENTIFIER, + parameters ANY DEFINED BY capabilityID OPTIONAL } + + SMIMECapabilities ::= SEQUENCE OF SMIMECapability + + -- Encryption Key Preference provides a method of broadcasting the + -- preferred encryption certificate. + + id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11} + + + + +Ramsdell & Turner Standards Track [Page 43] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + + SMIMEEncryptionKeyPreference ::= CHOICE { + issuerAndSerialNumber [0] IssuerAndSerialNumber, + receipentKeyId [1] RecipientKeyIdentifier, + subjectAltKeyIdentifier [2] SubjectKeyIdentifier + } + + -- receipentKeyId is spelt incorrectly, but kept for historical + -- reasons. + + id-smime OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) + rsadsi(113549) pkcs(1) pkcs9(9) 16 } + + id-cap OBJECT IDENTIFIER ::= { id-smime 11 } + + -- The preferBinaryInside OID indicates an ability to receive + -- messages with binary encoding inside the CMS wrapper. + -- The preferBinaryInside attribute's value field is ABSENT. + + id-cap-preferBinaryInside OBJECT IDENTIFIER ::= { id-cap 1 } + + -- The following list OIDs to be used with S/MIME V3 + + -- Signature Algorithms Not Found in [CMSALG], [CMS-SHA2], [RSAPSS], + -- and [RSAOAEP] + + -- + -- md2WithRSAEncryption OBJECT IDENTIFIER ::= + -- {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-1(1) + -- 2} + + -- + -- Other Signed Attributes + -- + -- signingTime OBJECT IDENTIFIER ::= + -- {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) + -- 5} + -- See [CMS] for a description of how to encode the attribute + -- value. + + SMIMECapabilitiesParametersForRC2CBC ::= INTEGER + -- (RC2 Key Length (number of bits)) + + END + + + + + + + + +Ramsdell & Turner Standards Track [Page 44] + +RFC 5751 S/MIME 3.2 Message Specification January 2010 + + +Appendix B. Moving S/MIME v2 Message Specification to Historic Status + + The S/MIME v3 [SMIMEv3], v3.1 [SMIMEv3.1], and v3.2 (this document) + are backwards compatible with the S/MIME v2 Message Specification + [SMIMEv2], with the exception of the algorithms (dropped RC2/40 + requirement and added DSA and RSASSA-PSS requirements). Therefore, + it is recommended that RFC 2311 [SMIMEv2] be moved to Historic + status. + +Appendix C. Acknowledgments + + Many thanks go out to the other authors of the S/MIME version 2 + Message Specification RFC: Steve Dusse, Paul Hoffman, Laurence + Lundblade, and Lisa Repka. Without v2, there wouldn't be a v3, v3.1, + or v3.2. + + A number of the members of the S/MIME Working Group have also worked + very hard and contributed to this document. Any list of people is + doomed to omission, and for that I apologize. In alphabetical order, + the following people stand out in my mind because they made direct + contributions to this document: + + Tony Capel, Piers Chivers, Dave Crocker, Bill Flanigan, Peter + Gutmann, Alfred Hoenes, Paul Hoffman, Russ Housley, William Ottaway, + John Pawling, and Jim Schaad. + +Authors' Addresses + + Blake Ramsdell + Brute Squad Labs, Inc. + + EMail: blaker@gmail.com + + + Sean Turner + IECA, Inc. + 3057 Nutley Street, Suite 106 + Fairfax, VA 22031 + USA + + EMail: turners@ieca.com + + + + + + + + + + +Ramsdell & Turner Standards Track [Page 45] + diff --git a/vendor/swiftmailer/swiftmailer/notes/rfc/whats_where.txt b/vendor/swiftmailer/swiftmailer/notes/rfc/whats_where.txt new file mode 100644 index 00000000..201a5f72 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/rfc/whats_where.txt @@ -0,0 +1,90 @@ +RFC 1854: +--------- +PIPELINING extension + +RFC 2222: +--------- +SASL + +RFC 4505: +--------- +ANYNONYMOUS SASL + +RFC 4616: +--------- +PLAIN SASL + +RFC 2487: +--------- +STARTTLS extension + +RFC 2554 & 4954: +---------------- +AUTH extension + +RFC 2821: +--------- +SMTP protocol + +RFC 2822: +--------- +General message structure (focusing on important headers) + +RFC 2045: +--------- +Quoted Printable Encoding +Base 64 Encoding +Detailed message structure + +RFC 2046: +--------- +Media types (for subparts) + +RFC 2047: +--------- +Header Encoding + +RFC 2183: +--------- +The Content-Disposition header + +RFC 2231: +--------- +Encoded Text header/attribute extensions + +RFC 2234: +--------- +ABNF definitions + +RFC 3676: +--------- +Flowed formatting/delsp parameters + +RFC 2015: +--------- +Original Mime Security with OpenPGP + +RFC 2440: +--------- +Original OpenPGP message format + +RFC 3156: +--------- +Current (30/01/2009) Mime Security with OpenPGP + +RFC 4880: +--------- +Current (30/01/2009) OpenPGP Message format revision (fun, it's exactly original *2 --sorry) + +RFC 5751: +-------- +Secure/Multipurpose Internet Mail Extensions (S/MIME) Version 3.2 + +RFC 4870: +--------- +DomainKeys (historic), but still used by a few people. + +RFX 4871: +--------- +DKIM + diff --git a/vendor/swiftmailer/swiftmailer/notes/smtp.txt b/vendor/swiftmailer/swiftmailer/notes/smtp.txt new file mode 100644 index 00000000..3f8047a9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/notes/smtp.txt @@ -0,0 +1,48 @@ +General Notes +-------------- + * MX is NOT required, but an A record, or CNAME to a MX MUST be present at the least. + * EHLO should be tried, then fall back to HELO + * The 250 return code from RCPT TO is not actually clear-cut. A 251 may be + returned if the message was forwarded to another address. This could be a + useful indicator to end-users that an address should be updated. + * RCPT TO can accpet just "postmaster" without a domain name + * Server MUST not close connection before: + - QUIT and returning 221 response + - Forced requirement, and only after returning a 421 response + - Clients expriencing a forced connection closure, without prior warning should + just treat it like a 451 closure regardless + * ALWAYS use blocking sockets for the initial connection (this should prevent + Exim4's whining about sync). + +Response codes +-------------- + * From RFC2821, 4.2. + - In particular, the 220, 221, 251, 421, and 551 reply codes + are associated with message text that must be parsed and interpreted + by machines. + +Error Codes +------------ + * Numeric 5yz = Error + - 550/RCPT TO = Relay denied + - 500 = Unknown command + * Numeric 2yz = Normal + * Numeric 4yz = Temporary failure?? + + + + + + + + + + + + tests/unit + + + tests/acceptance + + + tests/bug + + + tests/smoke + + + + + + + diff --git a/vendor/swiftmailer/swiftmailer/tests/IdenticalBinaryConstraint.php b/vendor/swiftmailer/swiftmailer/tests/IdenticalBinaryConstraint.php new file mode 100644 index 00000000..95251b4d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/IdenticalBinaryConstraint.php @@ -0,0 +1,60 @@ +value = $value; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function matches($other) + { + $aHex = $this->asHexString($this->value); + $bHex = $this->asHexString($other); + + return $aHex === $bHex; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'indentical binary'; + } + + /** + * Get the given string of bytes as a stirng of Hexadecimal sequences. + * + * @param string $binary + * + * @return string + */ + private function asHexString($binary) + { + $hex = ''; + + $bytes = unpack('H*', $binary); + + foreach ($bytes as &$byte) { + $byte = strtoupper($byte); + } + + return implode('', $bytes); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/StreamCollector.php b/vendor/swiftmailer/swiftmailer/tests/StreamCollector.php new file mode 100644 index 00000000..7f079d98 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/StreamCollector.php @@ -0,0 +1,11 @@ +content .= $arg; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/SwiftMailerSmokeTestCase.php b/vendor/swiftmailer/swiftmailer/tests/SwiftMailerSmokeTestCase.php new file mode 100644 index 00000000..6ff53432 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/SwiftMailerSmokeTestCase.php @@ -0,0 +1,46 @@ +markTestSkipped( + 'Smoke tests are skipped if tests/smoke.conf.php is not edited' + ); + } + } + + protected function _getMailer() + { + switch (SWIFT_SMOKE_TRANSPORT_TYPE) { + case 'smtp': + $transport = Swift_DependencyContainer::getInstance()->lookup('transport.smtp') + ->setHost(SWIFT_SMOKE_SMTP_HOST) + ->setPort(SWIFT_SMOKE_SMTP_PORT) + ->setUsername(SWIFT_SMOKE_SMTP_USER) + ->setPassword(SWIFT_SMOKE_SMTP_PASS) + ->setEncryption(SWIFT_SMOKE_SMTP_ENCRYPTION) + ; + break; + case 'sendmail': + $transport = Swift_DependencyContainer::getInstance()->lookup('transport.sendmail') + ->setCommand(SWIFT_SMOKE_SENDMAIL_COMMAND) + ; + break; + case 'mail': + case 'nativemail': + $transport = Swift_DependencyContainer::getInstance()->lookup('transport.mail'); + break; + default: + throw new Exception('Undefined transport [' . SWIFT_SMOKE_TRANSPORT_TYPE . ']'); + } + + return new Swift_Mailer($transport); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/SwiftMailerTestCase.php b/vendor/swiftmailer/swiftmailer/tests/SwiftMailerTestCase.php new file mode 100644 index 00000000..365c56a8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/SwiftMailerTestCase.php @@ -0,0 +1,33 @@ + \ No newline at end of file diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/CA.srl b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/CA.srl new file mode 100644 index 00000000..dd9818ab --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/CA.srl @@ -0,0 +1 @@ +D42DA34CF90FA0DE diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.crt b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.crt new file mode 100644 index 00000000..695f8142 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.crt @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDazCCAlOgAwIBAgIJAKJCGQYLxWT1MA0GCSqGSIb3DQEBBQUAMEwxFzAVBgNV +BAMMDlN3aWZ0bWFpbGVyIENBMRQwEgYDVQQKDAtTd2lmdG1haWxlcjEOMAwGA1UE +BwwFUGFyaXMxCzAJBgNVBAYTAkZSMB4XDTEzMTEyNzA4MzkxMFoXDTE3MTEyNjA4 +MzkxMFowTDEXMBUGA1UEAwwOU3dpZnRtYWlsZXIgQ0ExFDASBgNVBAoMC1N3aWZ0 +bWFpbGVyMQ4wDAYDVQQHDAVQYXJpczELMAkGA1UEBhMCRlIwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC7RLdHE3OWo9aZwv1xA/cYyPui/gegxpTqClRp +gGcVQ+jxIfnJQDQndyoAvFDiqOiZ+gAjZGJeUHDp9C/2IZp05MLh+omt9N8pBykm +3nj/3ZwPXOAO0uyDPAOHhISITAxEuZCqDnq7iYujywtwfQ7bpW1hCK9PfNZYMStM +kw7LsGr5BqcKkPuOWTvxE3+NqK8HxydYolsoApEGhgonyImVh1Pg1Kjkt5ojvwAX +zOdjfw5poY5NArwuLORUH+XocetRo8DC6S42HkU/MoqcYxa9EuRuwuQh7GtE6baR +PgrDsEYaY4Asy43sK81V51F/8Q1bHZKN/goQdxQwzv+/nOLTAgMBAAGjUDBOMB0G +A1UdDgQWBBRHgqkl543tKhsVAvcx1I0JFU7JuDAfBgNVHSMEGDAWgBRHgqkl543t +KhsVAvcx1I0JFU7JuDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAz +OJiEQcygKGkkXXDiXGBvP/cSznj3nG9FolON0yHUBgdvLfNnctRMStGzPke0siLt +RJvjqiL0Uw+blmLJU8lgMyLJ9ctXkiLJ/WflabN7VzmwYRWe5HzafGQJAg5uFjae +VtAAHQgvbmdXB6brWvcMQmB8di7wjVedeigZvkt1z2V0FtBy8ybJaT5H6bX9Bf5C +dS9r4mLhk/0ThthpRhRxsmupSL6e49nJaIk9q0UTEQVnorJXPcs4SPTIY51bCp6u +cOebhNgndSxCiy0zSD7vRjNiyB/YNGZ9Uv/3DNTLleMZ9kZgfoKVpwYKrRL0IFT/ +cfS2OV1wxRxq668qaOfK +-----END CERTIFICATE----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.key b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.key new file mode 100644 index 00000000..df674708 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/ca.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAu0S3RxNzlqPWmcL9cQP3GMj7ov4HoMaU6gpUaYBnFUPo8SH5 +yUA0J3cqALxQ4qjomfoAI2RiXlBw6fQv9iGadOTC4fqJrfTfKQcpJt54/92cD1zg +DtLsgzwDh4SEiEwMRLmQqg56u4mLo8sLcH0O26VtYQivT3zWWDErTJMOy7Bq+Qan +CpD7jlk78RN/jaivB8cnWKJbKAKRBoYKJ8iJlYdT4NSo5LeaI78AF8znY38OaaGO +TQK8LizkVB/l6HHrUaPAwukuNh5FPzKKnGMWvRLkbsLkIexrROm2kT4Kw7BGGmOA +LMuN7CvNVedRf/ENWx2Sjf4KEHcUMM7/v5zi0wIDAQABAoIBAGyaWkvu/O7Uz2TW +z1JWgVuvWzfYaKYV5FCicvfITn/npVUKZikPge+NTR+mFqaMXHDHqoLb+axGrGUR +hysPq9q0vEx/lo763tyVWYlAJh4E8Dd8njganK0zBbz23kGJEOheUYY95XGTQBda +bqTq8c3x7zAB8GGBvXDh+wFqm38GLyMF6T+YEzWJZqXfg31f1ldRvf6+VFwlLfz6 +cvTR7oUpYIsUeGE47kBs13SN7Oju6a355o/7wy9tOCRiu+r/ikXFh8rFGLfeTiwv +R1dhYjcEYGxZUD8u64U+Cj4qR1P0gHJL0kbh22VMMqgALOc8FpndkjNdg1Nun2X8 +BWpsPwECgYEA7C9PfTOIZfxGBlCl05rmWex++/h5E5PbH1Cw/NGjIH1HjmAkO3+5 +WyMXhySOJ8yWyCBQ/nxqc0w7+TO4C7wQcEdZdUak25KJ74v0sfmWWrVw6kcnLU6k +oawW/L2F2w7ET3zDoxKh4fOF34pfHpSbZk7XJ68YOfHpYVnP4efkQVMCgYEAyvrM +KA7xjnsKumWh206ag3QEI0M/9uPHWmrh2164p7w1MtawccZTxYYJ5o5SsjTwbxkf +0cAamp4qLInmRUxU1gk76tPYC3Ndp6Yf1C+dt0q/vtzyJetCDrdz8HHT1SpKbW0l +g6z1I5FMwa6oWvWsfS++W51vsxUheNsOJ4uxKIECgYBwM7GRiw+7U3N4wItm0Wmp +Qp642Tu7vzwTzmOmV3klkB6UVrwfv/ewgiVFQGqAIcNn42JW44g2qfq70oQWnws4 +K80l15+t6Bm7QUPH4Qg6o4O26IKGFZxEadqpyudyP7um/2B5cfqRuvzYS4YQowyI +N+AirB3YOUJjyyTk7yMSnQKBgGNLpSvDg6+ryWe96Bwcq8G6s3t8noHsk81LlAl4 +oOSNUYj5NX+zAbATDizXWuUKuMPgioxVaa5RyVfYbelgme/KvKD32Sxg12P4BIIM +eR79VifMdjjOiZYhcHojdPlGovo89qkfpxwrLF1jT8CPhj4HaRvwPIBiyekRYC9A +Sv4BAoGAXCIC1xxAJP15osUuQjcM8KdsL1qw+LiPB2+cJJ2VMAZGV7CR2K0aCsis +OwRaYM0jZKUpxzp1uwtfrfqbhdYsv+jIBkfwoShYZuo6MhbUrj0sffkhJC3WrT2z +xafCFLFv1idzGvvNxatlp1DNKrndG2NS3syVAox9MnL5OMsvGM8= +-----END RSA PRIVATE KEY----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/create-cert.sh b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/create-cert.sh new file mode 100644 index 00000000..16314a27 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/create-cert.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +openssl genrsa -out CA.key 2048 +openssl req -x509 -new -nodes -key CA.key -days 1460 -subj '/CN=Swiftmailer CA/O=Swiftmailer/L=Paris/C=FR' -out CA.crt +openssl x509 -in CA.crt -clrtrust -out CA.crt + +openssl genrsa -out sign.key 2048 +openssl req -new -key sign.key -subj '/CN=Swiftmailer-User/O=Swiftmailer/L=Paris/C=FR' -out sign.csr +openssl x509 -req -in sign.csr -CA CA.crt -CAkey CA.key -out sign.crt -days 1460 -addtrust emailProtection +openssl x509 -in sign.crt -clrtrust -out sign.crt + +rm sign.csr + +openssl genrsa -out encrypt.key 2048 +openssl req -new -key encrypt.key -subj '/CN=Swiftmailer-User/O=Swiftmailer/L=Paris/C=FR' -out encrypt.csr +openssl x509 -req -in encrypt.csr -CA CA.crt -CAkey CA.key -CAcreateserial -out encrypt.crt -days 1460 -addtrust emailProtection +openssl x509 -in encrypt.crt -clrtrust -out encrypt.crt + +rm encrypt.csr + +openssl genrsa -out encrypt2.key 2048 +openssl req -new -key encrypt2.key -subj '/CN=Swiftmailer-User2/O=Swiftmailer/L=Paris/C=FR' -out encrypt2.csr +openssl x509 -req -in encrypt2.csr -CA CA.crt -CAkey CA.key -CAcreateserial -out encrypt2.crt -days 1460 -addtrust emailProtection +openssl x509 -in encrypt2.crt -clrtrust -out encrypt2.crt + +rm encrypt2.csr diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.crt b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.crt new file mode 100644 index 00000000..7435855c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFjCCAf4CCQDULaNM+Q+g3TANBgkqhkiG9w0BAQUFADBMMRcwFQYDVQQDDA5T +d2lmdG1haWxlciBDQTEUMBIGA1UECgwLU3dpZnRtYWlsZXIxDjAMBgNVBAcMBVBh +cmlzMQswCQYDVQQGEwJGUjAeFw0xMzExMjcwODM5MTFaFw0xNzExMjYwODM5MTFa +ME4xGTAXBgNVBAMMEFN3aWZ0bWFpbGVyLVVzZXIxFDASBgNVBAoMC1N3aWZ0bWFp +bGVyMQ4wDAYDVQQHDAVQYXJpczELMAkGA1UEBhMCRlIwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCcNO+fVZBT2znmVwXXZ08n3G5WA1kyvqh9z4RBBZOD +V46Gc1X9MMXr9+wzZBFkAckKaa6KsTkeUr4pC8XUBpQnakxH/kW9CaDPdOE+7wNo +FkPfc6pjWWgpAVxdkrtk7pb4/aGQ++HUkqVu0cMpIcj/7ht7H+3QLZHybn+oMr2+ +FDnn8vPmHxVioinSrxKTlUITuLWS9ZZUTrDa0dG8UAv55A/Tba4T4McCPDpJSA4m +9jrW321NGQUntQoItOJxagaueSvh6PveGV826gTXoU5X+YJ3I2OZUEQ2l6yByAzf +nT+QlxPj5ikotFwL72HsenYtetynOO/k43FblAF/V/l7AgMBAAEwDQYJKoZIhvcN +AQEFBQADggEBAJ048Sdb9Sw5OJM5L00OtGHgcT1B/phqdzSjkM/s64cg3Q20VN+F +fZIIkOnxgyYWcpOWXcdNw2tm5OWhWPGsBcYgMac7uK/ukgoOJSjICg+TTS5kRo96 +iHtmImqkWc6WjNODh7uMnQ6DsZsscdl7Bkx5pKhgGnEdHr5GW8sztgXgyPQO5LUs +YzCmR1RK1WoNMxwbPrGLgYdcpJw69ns5hJbZbMWwrdufiMjYWvTfBPABkk1JRCcY +K6rRTAx4fApsw1kEIY8grGxyAzfRXLArpro7thJr0SIquZ8GpXkQT/mgRR8JD9Hp +z9yhr98EnKzITE/yclGN4pUsuk9S3jiyzUU= +-----END CERTIFICATE----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.key b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.key new file mode 100644 index 00000000..aa620ca6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAnDTvn1WQU9s55lcF12dPJ9xuVgNZMr6ofc+EQQWTg1eOhnNV +/TDF6/fsM2QRZAHJCmmuirE5HlK+KQvF1AaUJ2pMR/5FvQmgz3ThPu8DaBZD33Oq +Y1loKQFcXZK7ZO6W+P2hkPvh1JKlbtHDKSHI/+4bex/t0C2R8m5/qDK9vhQ55/Lz +5h8VYqIp0q8Sk5VCE7i1kvWWVE6w2tHRvFAL+eQP022uE+DHAjw6SUgOJvY61t9t +TRkFJ7UKCLTicWoGrnkr4ej73hlfNuoE16FOV/mCdyNjmVBENpesgcgM350/kJcT +4+YpKLRcC+9h7Hp2LXrcpzjv5ONxW5QBf1f5ewIDAQABAoIBADmuMm2botfUM+Ui +bT3FIC2P8A5C3kUmsgEDB8sazAXL5w0uuanswKkJu2aepO1Q23PE4nbESlswIpf1 +iO9qHnsPfWt4MThEveTdO++JQrDEx/tTMq/M6/F4VysWa6wxjf4Taf2nhRSBsiTh +wDcICri2q98jQyWELkhfFTR+yCHPsn6iNtzE2OpNv9ojKiSqck/sVjC39Z+uU/HD +N4v0CPf9pDGkO+modaVGKf2TpvZT7Hpq/jsPzkk1h7BY7aWdZiIY4YkBkWYqZk8f +0dsxKkOR2glfuEYNtcywG+4UGx3i1AY0mMu96hH5M1ACFmFrTCoodmWDnWy9wUpm +leLmG8ECgYEAywWdryqcvLyhcmqHbnmUhCL9Vl4/5w5fr/5/FNvqArxSGwd2CxcN +Jtkvu22cxWAUoe155eMc6GlPIdNRG8KdWg4sg0TN3Jb2jiHQ3QkHXUJlWU6onjP1 +g2n5h052JxVNGBEb7hr3U7ZMW6wnuYnGdYwCB9P3r5oGxxtfVRB8ygUCgYEAxPfy +tAd3SNT8Sv/cciw76GYKbztUjJRXkLo6GOBGq/AQxP1NDWMuL2AES11YIahidMsF +TMmM+zhkNHsd5P69p87FTMWx0cLoH0M9iQNK7Q6C1luTjLf5DTFuk+nHGErM4Drs ++6Ly1Z4KLXfXgBDD8Ce6U9+W3RrCc36poGZvjX8CgYEAna0P6WJr9r19mhIYevmc +Gf/ex7xNXxMvx80dP8MIfPVrwyhJSpWtljVpt+SKtFRJ0fVRDfUUl4Bqf/fR74B3 +muCVO6ItTBxHAt5Ki9CeUpTlh7XqiWwLSvP8Y1TRuMr3ZDCtg4CYBAD6Ttxmwde6 +NcL2NMQwgsZaazrcEIHMmU0CgYEAl/Mn2tZ/oUIdt8YWzEVvmeNOXW0J1sGBo/bm +ZtZt7qpuZWl7jb5bnNSXu4QxPxXljnAokIpUJmHke9AWydfze4c6EfXZLhcMd0Gq +MQ7HOIWfTbqr4zzx9smRoq4Ql57s2nba521XpJAdDeKL7xH/9j7PsXCls8C3Dd5D +AajEmgUCgYAGEdn6tYxIdX7jF39E3x7zHQf8jHIoQ7+cLTLtd944mSGgeqMfbiww +CoUa+AAUqjdAD5ViAyJrA+gmDtWpkFnJZtToXYwfUF2o3zRo4k1DeBrVbFqwSQkE +omrfiBGtviYIPdqQLE34LYpWEooNPraqO9qTyc+9w5038u2OFS+WmQ== +-----END RSA PRIVATE KEY----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.crt b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.crt new file mode 100644 index 00000000..69081656 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFzCCAf8CCQDULaNM+Q+g3jANBgkqhkiG9w0BAQUFADBMMRcwFQYDVQQDDA5T +d2lmdG1haWxlciBDQTEUMBIGA1UECgwLU3dpZnRtYWlsZXIxDjAMBgNVBAcMBVBh +cmlzMQswCQYDVQQGEwJGUjAeFw0xMzExMjcwODM5MTJaFw0xNzExMjYwODM5MTJa +ME8xGjAYBgNVBAMMEVN3aWZ0bWFpbGVyLVVzZXIyMRQwEgYDVQQKDAtTd2lmdG1h +aWxlcjEOMAwGA1UEBwwFUGFyaXMxCzAJBgNVBAYTAkZSMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAw4AoYVYss2sa1BWJAJpK6gVemjXrp1mVXVpb1/z6 +SH15AGsp3kiNXsMpgvsdofbqC/5HXrw2G8gWqo+uh6GuK67+Tvp7tO2aD4+8CZzU +K1cffj7Pbx95DUPwXckv79PT5ZcuyeFaVo92aug11+gS/P8n0WXSlzZxNuZ1f3G2 +r/IgwfNKZlarEf1Ih781L2SwmyveW/dtsV2pdrd4IZwsV5SOF2zBFIXSuhPN0c+m +mtwSJe+Ow1udLX4KJkAX8sGVFJ5P5q4s2nS9vLkkj7X6YRQscbyJO9L7e1TksRqL +DLxZwiko6gUhp4/bIs1wDj5tzkQBi4qXviRq3i7A9b2d0QIDAQABMA0GCSqGSIb3 +DQEBBQUAA4IBAQAj8iARhPB2DA3YfT5mJJrgU156Sm0Z3mekAECsr+VqFZtU/9Dz +pPFYEf0hg61cjvwhLtOmaTB+50hu1KNNlu8QlxAfPJqNxtH85W0CYiZHJwW9eSTr +z1swaHpRHLDUgo3oAXdh5syMbdl0MWos0Z14WP5yYu4IwJXs+j2JRW70BICyrNjm +d+AjCzoYjKMdJkSj4uxQEOuW2/5veAoDyU+kHDdfT7SmbyoKu+Pw4Xg/XDuKoWYg +w5/sRiw5vxsmOr9+anspDHdP9rUe1JEfwAJqZB3fwdqEyxu54Xw/GedG4wZBEJf0 +ZcS1eh31emcjYUHQa1IA93jcFSmXzJ+ftJrY +-----END CERTIFICATE----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.key b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.key new file mode 100644 index 00000000..e322a8f4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/encrypt2.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAw4AoYVYss2sa1BWJAJpK6gVemjXrp1mVXVpb1/z6SH15AGsp +3kiNXsMpgvsdofbqC/5HXrw2G8gWqo+uh6GuK67+Tvp7tO2aD4+8CZzUK1cffj7P +bx95DUPwXckv79PT5ZcuyeFaVo92aug11+gS/P8n0WXSlzZxNuZ1f3G2r/IgwfNK +ZlarEf1Ih781L2SwmyveW/dtsV2pdrd4IZwsV5SOF2zBFIXSuhPN0c+mmtwSJe+O +w1udLX4KJkAX8sGVFJ5P5q4s2nS9vLkkj7X6YRQscbyJO9L7e1TksRqLDLxZwiko +6gUhp4/bIs1wDj5tzkQBi4qXviRq3i7A9b2d0QIDAQABAoIBAH8RvK1PmqxfkEeL +W8oVf13OcafgJjRW6NuNkKa5mmAlldFs1gDRvXl7dm7ZE3CjkYqMEw2DXdP+4KSp +0TH9J7zi+A6ThnaZ/QniTcEdu1YUQbcH0kIS/dZec0wyKUNDtrXC5zl2jQY4Jyrj +laOpBzaEDfhvq0p3q2yYrIRSgACpSEVEsfPoHrxtlLhfMkVNe8P0nkQkzdwou5MQ +MZKV4JUopLHLgPH6IXQCqA1wzlU32yZ86w88GFcBVLkwlLJCKbuAo7yxMCD+nzvA +xm5NuF1kzpP0gk+kZRXF+rFEV4av/2kSS+n8IeUBQZrxovLBuQHVDvJXoqcEjmlh +ZUltznUCgYEA4inwieePfb7kh7L/ma5OLLn+uCNwzVw9LayzXT1dyPravOnkHl6h +MgaoTspqDyU8k8pStedRrr5dVYbseni/A4WSMGvi4innqSXBQGp64TyeJy/e+LrS +ypSWQ6RSJkCxI5t8s4mOpR7FMcdE34I5qeA4G5RS1HIacn7Hxc7uXtcCgYEA3Uqn +E7EDfNfYdZm6AikvE6x64oihWI0x47rlkLu6lf6ihiF1dbfaEN+IAaIxQ/unGYwU +130F0TUwarXnVkeBIRlij4fXhExyd7USSQH1VpqmIqDwsS2ojrzQVMo5UcH+A22G +bbHPtwJNmw8a7yzTPWo2/vnjgV2OaXEQ9vCVG5cCgYEAu1kEoihJDGBijSqxY4wp +xBE7OSxamDNtlnV2i6l3FDMBmfaieqnnHDq5l7NDklJFUSQLyhXZ60hUprHDGV0G +1pMCW8wzQSh3d/4HjSXnrsd5N3sHWMHiNeBKbbQkPP3f/2AhN9SebpgDwE2S9xe4 +TsmnkOkYiFYRJIFzWaAmhDcCgYEAwxRCgZt0xaPKULG6RpljxOYyVm24PsYKCwYB +xjuYWw5k2/W3BJWVCXblAPuojpPUVTMmVGkErc9D5W6Ch471iOZF+t334cs6xci8 +W9v8GeKvPqu+Q5NKmrpctcKoESkA8qik7yLnSCAhpeYFCn/roKJ35QMJyktddhqU +p/yilfUCgYBxZ6YmFjYH6l5SxQdcfa5JQ2To8lZCfRJwB65EyWj4pKH4TaWFS7vb +50WOGTBwJgyhTKLCO3lOmXIUyIwC+OO9xzaeRCBjqEhpup/Ih3MsfMEd6BZRVK5E +IxtmIWba5HQ52k8FKHeRrRB7PSVSADUN2pUFkLudH+j/01kSZyJoLA== +-----END RSA PRIVATE KEY----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.crt b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.crt new file mode 100644 index 00000000..15fd65d2 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFjCCAf4CCQDULaNM+Q+g3DANBgkqhkiG9w0BAQUFADBMMRcwFQYDVQQDDA5T +d2lmdG1haWxlciBDQTEUMBIGA1UECgwLU3dpZnRtYWlsZXIxDjAMBgNVBAcMBVBh +cmlzMQswCQYDVQQGEwJGUjAeFw0xMzExMjcwODM5MTBaFw0xNzExMjYwODM5MTBa +ME4xGTAXBgNVBAMMEFN3aWZ0bWFpbGVyLVVzZXIxFDASBgNVBAoMC1N3aWZ0bWFp +bGVyMQ4wDAYDVQQHDAVQYXJpczELMAkGA1UEBhMCRlIwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCTe8ZouyjVGgqlljhaswYqLj7icMoHq+Qg13CE+zJg +tl2/UzyPhAd3WWOIvlQ0lu+E/n0bXrS6+q28DrQ3UgJ9BskzzLz15qUO12b92AvG +vLJ+9kKuiM5KXDljOAsXc7/A9UUGwEFA1D0mkeMmkHuiQavAMkzBLha22hGpg/hz +VbE6W9MGna0szd8yh38IY1M5uR+OZ0dG3KbVZb7H3N0OLOP8j8n+4YtAGAW+Onz/ +2CGPfZ1kaDMvY/WTZwyGeA4FwCPy1D8tfeswqKnWDB9Sfl8hns5VxnoJ3dqKQHeX +iC4OMfQ0U4CcuM5sVYJZRNNwP7/TeUh3HegnOnuZ1hy9AgMBAAEwDQYJKoZIhvcN +AQEFBQADggEBAAEPjGt98GIK6ecAEat52aG+8UP7TuZaxoH3cbZdhFTafrP8187F +Rk5G3LCPTeA/QIzbHppA4fPAiS07OVSwVCknpTJbtKKn0gmtTZxThacFHF2NlzTH +XxM5bIbkK3jzIF+WattyTSj34UHHfaNAmvmS7Jyq6MhjSDbcQ+/dZ9eo2tF/AmrC ++MBhyH8aUYwKhTOQQh8yC11niziHhGO99FQ4tpuD9AKlun5snHq4uK9AOFe8VhoR +q2CqX5g5v8OAtdlvzhp50IqD4BNOP+JrUxjGLHDG76BZZIK2Ai1eBz+GhRlIQru/ +8EhQzd94mdFEPblGbmuD2QXWLFFKLiYOwOc= +-----END CERTIFICATE----- diff --git a/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.key b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.key new file mode 100644 index 00000000..b3d3c535 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/_samples/smime/sign.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAk3vGaLso1RoKpZY4WrMGKi4+4nDKB6vkINdwhPsyYLZdv1M8 +j4QHd1ljiL5UNJbvhP59G160uvqtvA60N1ICfQbJM8y89ealDtdm/dgLxryyfvZC +rojOSlw5YzgLF3O/wPVFBsBBQNQ9JpHjJpB7okGrwDJMwS4WttoRqYP4c1WxOlvT +Bp2tLM3fMod/CGNTObkfjmdHRtym1WW+x9zdDizj/I/J/uGLQBgFvjp8/9ghj32d +ZGgzL2P1k2cMhngOBcAj8tQ/LX3rMKip1gwfUn5fIZ7OVcZ6Cd3aikB3l4guDjH0 +NFOAnLjObFWCWUTTcD+/03lIdx3oJzp7mdYcvQIDAQABAoIBAH2vrw/T6GFrlwU0 +twP8q1VJIghCDLpq77hZQafilzU6VTxWyDaaUu6QPDXt1b8Xnjnd02p+1FDAj0zD +zyuR9VLtdIxzf9mj3KiAQ2IzOx3787YlUgCB0CQo4jM/MJyk5RahL1kogLOp7A8x +pr5XxTUq+B6L/0Nmbq8XupOXRyWp53amZ5N8sgWDv4oKh9fqgAhxbSG6KUkTmhYs +DLinWg86Q28pSn+eivf4dehR56YwtTBVguXW3WKO70+GW1RotSrS6e6SSxfKYksZ +a7/J1hCmJkEE3+4C8BpcI0MelgaK66ocN0pOqDF9ByxphARqyD7tYCfoS2P8gi81 +XoiZJaECgYEAwqx4AnDX63AANsfKuKVsEQfMSAG47SnKOVwHB7prTAgchTRcDph1 +EVOPtJ+4ssanosXzLcN/dCRlvqLEqnKYAOizy3C56CyRguCpO1AGbRpJjRmHTRgA +w8iArhM07HgJ3XLFn99V/0bsPCMxW8dje1ZMjKjoQtDrXRQMtWaVY+UCgYEAwfGi +f0If6z7wJj9gQUkGimWDAg/bxDkvEeh3nSD/PQyNiW0XDclcb3roNPQsal2ZoMwt +f1bwkclw7yUCIZBvXWEkZapjKCdseTp6nglScxr8GAzfN9p5KQl+OS3GzC6xZf6C +BsZQ5ucsHTHsCAi3WbwGK829z9c7x0qRwgwu9/kCgYEAsqwEwYi8Q/RZ3e1lXC9H +jiHwFi6ugc2XMyoJscghbnkLZB54V1UKLUraXFcz97FobnbsCJajxf8Z+uv9QMtI +Q51QV2ow1q0BKHP2HuAF5eD4nK5Phix/lzHRGPO74UUTGNKcG22pylBXxaIvTSMl +ZTABth/YfGqvepBKUbvDZRkCgYB5ykbUCW9H6D8glZ3ZgYU09ag+bD0CzTIs2cH7 +j1QZPz/GdBYNF00PyKv3TPpzVRH7cxyDIdJyioB7/M6Iy03T4wPbQBOCjLdGrZ2A +jrQTCngSlkq6pVx+k7KLL57ua8gFF70JihIV3kfKkaX6KZcSJ8vsSAgRc8TbUo2T +wNjh6QKBgDyxw4bG2ULs+LVaHcnp7nizLgRGXJsCkDICjla6y0eCgAnG8fSt8CcG +s5DIfJeVs/NXe/NVNuVrfwsUx0gBOirtFwQStvi5wJnY/maGAyjmgafisNFgAroT +aM5f+wyGPQeGCs7bj7JWY7Nx9lkyuUV7DdKBTZNMOe51K3+PTEL3 +-----END RSA PRIVATE KEY----- diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance.conf.php.default b/vendor/swiftmailer/swiftmailer/tests/acceptance.conf.php.default new file mode 100644 index 00000000..68902d84 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance.conf.php.default @@ -0,0 +1,44 @@ +markTestSkipped( + 'Cannot run test without a writable directory to use ('. + 'define SWIFT_TMP_DIR in tests/config.php if you wish to run this test)' + ); + } + + $this->_tmpDir = SWIFT_TMP_DIR; + $this->_testFile = $this->_tmpDir.'/swift-test-file'.__CLASS__; + file_put_contents($this->_testFile, 'abcdefghijklm'); + } + + public function tearDown() + { + unlink($this->_testFile); + } + + public function testFileDataCanBeRead() + { + $file = $this->_createFileStream($this->_testFile); + $str = ''; + while (false !== $bytes = $file->read(8192)) { + $str .= $bytes; + } + $this->assertEquals('abcdefghijklm', $str); + } + + public function testFileDataCanBeReadSequentially() + { + $file = $this->_createFileStream($this->_testFile); + $this->assertEquals('abcde', $file->read(5)); + $this->assertEquals('fghijklm', $file->read(8)); + $this->assertFalse($file->read(1)); + } + + public function testFilenameIsReturned() + { + $file = $this->_createFileStream($this->_testFile); + $this->assertEquals($this->_testFile, $file->getPath()); + } + + public function testFileCanBeWrittenTo() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $file->write('foobar'); + $this->assertEquals('foobar', $file->read(8192)); + } + + public function testReadingFromThenWritingToFile() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $file->write('foobar'); + $this->assertEquals('foobar', $file->read(8192)); + $file->write('zipbutton'); + $this->assertEquals('zipbutton', $file->read(8192)); + } + + public function testWritingToFileWithCanonicalization() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $file->addFilter($this->_createFilter(array("\r\n", "\r"), "\n"), 'allToLF'); + $file->write("foo\r\nbar\r"); + $file->write("\nzip\r\ntest\r"); + $file->flushBuffers(); + $this->assertEquals("foo\nbar\nzip\ntest\n", file_get_contents($this->_testFile)); + } + + public function testBindingOtherStreamsMirrorsWriteOperations() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->at(0)) + ->method('write') + ->with('x'); + $is2->expects($this->at(1)) + ->method('write') + ->with('y'); + + $file->bind($is1); + $file->bind($is2); + + $file->write('x'); + $file->write('y'); + } + + public function testBindingOtherStreamsMirrorsFlushOperations() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->once()) + ->method('flushBuffers'); + $is2->expects($this->once()) + ->method('flushBuffers'); + + $file->bind($is1); + $file->bind($is2); + + $file->flushBuffers(); + } + + public function testUnbindingStreamPreventsFurtherWrites() + { + $file = $this->_createFileStream( + $this->_testFile, true + ); + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->once()) + ->method('write') + ->with('x'); + + $file->bind($is1); + $file->bind($is2); + + $file->write('x'); + + $file->unbind($is2); + + $file->write('y'); + } + + // -- Creation methods + + private function _createFilter($search, $replace) + { + return new Swift_StreamFilters_StringReplacementFilter($search, $replace); + } + + private function _createMockInputStream() + { + return $this->getMock('Swift_InputByteStream'); + } + + private function _createFileStream($file, $writable = false) + { + return new Swift_ByteStream_FileByteStream($file, $writable); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/CharacterReaderFactory/SimpleCharacterReaderFactoryAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/CharacterReaderFactory/SimpleCharacterReaderFactoryAcceptanceTest.php new file mode 100644 index 00000000..9853e88f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/CharacterReaderFactory/SimpleCharacterReaderFactoryAcceptanceTest.php @@ -0,0 +1,179 @@ +_factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + } + + public function testCreatingUtf8Reader() + { + foreach (array('utf8', 'utf-8', 'UTF-8', 'UTF8') as $utf8) { + $reader = $this->_factory->getReaderFor($utf8); + $this->assertInstanceof($this->_prefix.'Utf8Reader', $reader); + } + } + + public function testCreatingIso8859XReaders() + { + $charsets = array(); + foreach (range(1, 16) as $number) { + foreach (array('iso', 'iec') as $body) { + $charsets[] = $body.'-8859-'.$number; + $charsets[] = $body.'8859-'.$number; + $charsets[] = strtoupper($body).'-8859-'.$number; + $charsets[] = strtoupper($body).'8859-'.$number; + } + } + + foreach ($charsets as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingWindows125XReaders() + { + $charsets = array(); + foreach (range(0, 8) as $number) { + $charsets[] = 'windows-125'.$number; + $charsets[] = 'windows125'.$number; + $charsets[] = 'WINDOWS-125'.$number; + $charsets[] = 'WINDOWS125'.$number; + } + + foreach ($charsets as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingCodePageReaders() + { + $charsets = array(); + foreach (range(0, 8) as $number) { + $charsets[] = 'cp-125'.$number; + $charsets[] = 'cp125'.$number; + $charsets[] = 'CP-125'.$number; + $charsets[] = 'CP125'.$number; + } + + foreach (array(437, 737, 850, 855, 857, 858, 860, + 861, 863, 865, 866, 869,) as $number) { + $charsets[] = 'cp-'.$number; + $charsets[] = 'cp'.$number; + $charsets[] = 'CP-'.$number; + $charsets[] = 'CP'.$number; + } + + foreach ($charsets as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingAnsiReader() + { + foreach (array('ansi', 'ANSI') as $ansi) { + $reader = $this->_factory->getReaderFor($ansi); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingMacintoshReader() + { + foreach (array('macintosh', 'MACINTOSH') as $mac) { + $reader = $this->_factory->getReaderFor($mac); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingKOIReaders() + { + $charsets = array(); + foreach (array('7', '8-r', '8-u', '8u', '8r') as $end) { + $charsets[] = 'koi-'.$end; + $charsets[] = 'koi'.$end; + $charsets[] = 'KOI-'.$end; + $charsets[] = 'KOI'.$end; + } + + foreach ($charsets as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingIsciiReaders() + { + foreach (array('iscii', 'ISCII', 'viscii', 'VISCII') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingMIKReader() + { + foreach (array('mik', 'MIK') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingCorkReader() + { + foreach (array('cork', 'CORK', 't1', 'T1') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(1, $reader->getInitialByteSize()); + } + } + + public function testCreatingUcs2Reader() + { + foreach (array('ucs-2', 'UCS-2', 'ucs2', 'UCS2') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(2, $reader->getInitialByteSize()); + } + } + + public function testCreatingUtf16Reader() + { + foreach (array('utf-16', 'UTF-16', 'utf16', 'UTF16') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(2, $reader->getInitialByteSize()); + } + } + + public function testCreatingUcs4Reader() + { + foreach (array('ucs-4', 'UCS-4', 'ucs4', 'UCS4') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(4, $reader->getInitialByteSize()); + } + } + + public function testCreatingUtf32Reader() + { + foreach (array('utf-32', 'UTF-32', 'utf32', 'UTF32') as $charset) { + $reader = $this->_factory->getReaderFor($charset); + $this->assertInstanceof($this->_prefix.'GenericFixedWidthReader', $reader); + $this->assertEquals(4, $reader->getInitialByteSize()); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/DependencyContainerAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/DependencyContainerAcceptanceTest.php new file mode 100644 index 00000000..8caf6f54 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/DependencyContainerAcceptanceTest.php @@ -0,0 +1,20 @@ +listItems() as $itemName) { + try { + $di->lookup($itemName); + } catch (Swift_DependencyException $e) { + $this->fail($e->getMessage()); + } + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EmbeddedFileAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EmbeddedFileAcceptanceTest.php new file mode 100644 index 00000000..fc5a8147 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EmbeddedFileAcceptanceTest.php @@ -0,0 +1,12 @@ +_samplesDir = realpath(__DIR__.'/../../../_samples/charsets'); + $this->_encoder = new Swift_Encoder_Base64Encoder(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + $encodedText = $this->_encoder->encodeString($text); + + $this->assertEquals( + base64_decode($encodedText), $text, + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/QpEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/QpEncoderAcceptanceTest.php new file mode 100644 index 00000000..736dccbe --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/QpEncoderAcceptanceTest.php @@ -0,0 +1,50 @@ +_samplesDir = realpath(__DIR__.'/../../../_samples/charsets'); + $this->_factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $encoding = $encodingDir; + $charStream = new Swift_CharacterStream_ArrayCharacterStream( + $this->_factory, $encoding); + $encoder = new Swift_Encoder_QpEncoder($charStream); + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + $encodedText = $encoder->encodeString($text); + + $this->assertEquals( + quoted_printable_decode($encodedText), $text, + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/Rfc2231EncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/Rfc2231EncoderAcceptanceTest.php new file mode 100644 index 00000000..043ddf8c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Encoder/Rfc2231EncoderAcceptanceTest.php @@ -0,0 +1,50 @@ +_samplesDir = realpath(__DIR__.'/../../../_samples/charsets'); + $this->_factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $encoding = $encodingDir; + $charStream = new Swift_CharacterStream_ArrayCharacterStream( + $this->_factory, $encoding); + $encoder = new Swift_Encoder_Rfc2231Encoder($charStream); + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + $encodedText = $encoder->encodeString($text); + + $this->assertEquals( + urldecode(implode('', explode("\r\n", $encodedText))), $text, + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EncodingAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EncodingAcceptanceTest.php new file mode 100644 index 00000000..6a4d05d3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/EncodingAcceptanceTest.php @@ -0,0 +1,30 @@ +assertEquals('7bit', $encoder->getName()); + } + + public function testGet8BitEncodingReturns8BitEncoder() + { + $encoder = Swift_Encoding::get8BitEncoding(); + $this->assertEquals('8bit', $encoder->getName()); + } + + public function testGetQpEncodingReturnsQpEncoder() + { + $encoder = Swift_Encoding::getQpEncoding(); + $this->assertEquals('quoted-printable', $encoder->getName()); + } + + public function testGetBase64EncodingReturnsBase64Encoder() + { + $encoder = Swift_Encoding::getBase64Encoding(); + $this->assertEquals('base64', $encoder->getName()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/ArrayKeyCacheAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/ArrayKeyCacheAcceptanceTest.php new file mode 100644 index 00000000..6b06e2ee --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/ArrayKeyCacheAcceptanceTest.php @@ -0,0 +1,173 @@ +_cache = new Swift_KeyCache_ArrayKeyCache( + new Swift_KeyCache_SimpleKeyCacheInputStream() + ); + } + + public function testStringDataCanBeSetAndFetched() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeOverwritten() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'foo', 'whatever', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('whatever', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeAppended() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'foo', 'ing', Swift_KeyCache::MODE_APPEND + ); + $this->assertEquals('testing', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testHasKeyReturnValue() + { + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyIsWellPartitioned() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key2, 'foo', 'ing', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $this->_cache->getString($this->_key2, 'foo')); + } + + public function testItemKeyIsWellPartitioned() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'bar', 'ing', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $this->_cache->getString($this->_key1, 'bar')); + } + + public function testByteStreamCanBeImported() + { + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write('abcdef'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('abcdef', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamCanBeAppended() + { + $os1 = new Swift_ByteStream_ArrayByteStream(); + $os1->write('abcdef'); + + $os2 = new Swift_ByteStream_ArrayByteStream(); + $os2->write('xyzuvw'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os1, Swift_KeyCache::MODE_APPEND + ); + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os2, Swift_KeyCache::MODE_APPEND + ); + + $this->assertEquals('abcdefxyzuvw', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamAndStringCanBeAppended() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_APPEND + ); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write('abcdef'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_APPEND + ); + $this->assertEquals('testabcdef', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testDataCanBeExportedToByteStream() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + + $is = new Swift_ByteStream_ArrayByteStream(); + + $this->_cache->exportToByteStream($this->_key1, 'foo', $is); + + $string = ''; + while (false !== $bytes = $is->read(8192)) { + $string .= $bytes; + } + + $this->assertEquals('test', $string); + } + + public function testKeyCanBeCleared() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + $this->_cache->clearKey($this->_key1, 'foo'); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyCanBeCleared() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'bar', 'xyz', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'bar')); + $this->_cache->clearAll($this->_key1); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'bar')); + } + + public function testKeyCacheInputStream() + { + $is = $this->_cache->getInputByteStream($this->_key1, 'foo'); + $is->write('abc'); + $is->write('xyz'); + $this->assertEquals('abcxyz', $this->_cache->getString($this->_key1, 'foo')); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/DiskKeyCacheAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/DiskKeyCacheAcceptanceTest.php new file mode 100644 index 00000000..392edde8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/KeyCache/DiskKeyCacheAcceptanceTest.php @@ -0,0 +1,183 @@ +markTestSkipped( + 'Cannot run test without a writable directory to use ('. + 'define SWIFT_TMP_DIR in tests/config.php if you wish to run this test)' + ); + } + + $this->_key1 = uniqid(microtime(true), true); + $this->_key2 = uniqid(microtime(true), true); + $this->_cache = new Swift_KeyCache_DiskKeyCache( + new Swift_KeyCache_SimpleKeyCacheInputStream(), + SWIFT_TMP_DIR + ); + } + + public function testStringDataCanBeSetAndFetched() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeOverwritten() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'foo', 'whatever', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('whatever', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeAppended() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'foo', 'ing', Swift_KeyCache::MODE_APPEND + ); + $this->assertEquals('testing', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testHasKeyReturnValue() + { + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyIsWellPartitioned() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key2, 'foo', 'ing', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $this->_cache->getString($this->_key2, 'foo')); + } + + public function testItemKeyIsWellPartitioned() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'bar', 'ing', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $this->_cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $this->_cache->getString($this->_key1, 'bar')); + } + + public function testByteStreamCanBeImported() + { + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write('abcdef'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('abcdef', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamCanBeAppended() + { + $os1 = new Swift_ByteStream_ArrayByteStream(); + $os1->write('abcdef'); + + $os2 = new Swift_ByteStream_ArrayByteStream(); + $os2->write('xyzuvw'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os1, Swift_KeyCache::MODE_APPEND + ); + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os2, Swift_KeyCache::MODE_APPEND + ); + + $this->assertEquals('abcdefxyzuvw', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamAndStringCanBeAppended() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_APPEND + ); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write('abcdef'); + + $this->_cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_APPEND + ); + $this->assertEquals('testabcdef', $this->_cache->getString($this->_key1, 'foo')); + } + + public function testDataCanBeExportedToByteStream() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + + $is = new Swift_ByteStream_ArrayByteStream(); + + $this->_cache->exportToByteStream($this->_key1, 'foo', $is); + + $string = ''; + while (false !== $bytes = $is->read(8192)) { + $string .= $bytes; + } + + $this->assertEquals('test', $string); + } + + public function testKeyCanBeCleared() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + $this->_cache->clearKey($this->_key1, 'foo'); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyCanBeCleared() + { + $this->_cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->_cache->setString( + $this->_key1, 'bar', 'xyz', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'foo')); + $this->assertTrue($this->_cache->hasKey($this->_key1, 'bar')); + $this->_cache->clearAll($this->_key1); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'foo')); + $this->assertFalse($this->_cache->hasKey($this->_key1, 'bar')); + } + + public function testKeyCacheInputStream() + { + $is = $this->_cache->getInputByteStream($this->_key1, 'foo'); + $is->write('abc'); + $is->write('xyz'); + $this->assertEquals('abcxyz', $this->_cache->getString($this->_key1, 'foo')); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MessageAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MessageAcceptanceTest.php new file mode 100644 index 00000000..04062e1f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MessageAcceptanceTest.php @@ -0,0 +1,57 @@ +_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = $message->getDate(); + $boundary = $message->getBoundary(); + + $message->addPart('foo', 'text/plain', 'iso-8859-1'); + $message->addPart('test foo', 'text/html', 'iso-8859-1'); + + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'test foo'. + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + // -- Private helpers + + protected function _createMessage() + { + Swift_DependencyContainer::getInstance() + ->register('properties.charset')->asValue(null); + + return Swift_Message::newInstance(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/AttachmentAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/AttachmentAcceptanceTest.php new file mode 100644 index 00000000..e925367e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/AttachmentAcceptanceTest.php @@ -0,0 +1,125 @@ +_cache = new Swift_KeyCache_ArrayKeyCache( + new Swift_KeyCache_SimpleKeyCacheInputStream() + ); + $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + $this->_contentEncoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + + $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $paramEncoder = new Swift_Encoder_Rfc2231Encoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $this->_grammar = new Swift_Mime_Grammar(); + $this->_headers = new Swift_Mime_SimpleHeaderSet( + new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $this->_grammar) + ); + } + + public function testDispositionIsSetInHeader() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setDisposition('inline'); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline'."\r\n", + $attachment->toString() + ); + } + + public function testDispositionIsAttachmentByDefault() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment'."\r\n", + $attachment->toString() + ); + } + + public function testFilenameIsSetInHeader() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf'."\r\n", + $attachment->toString() + ); + } + + public function testSizeIsSetInHeader() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setSize(12340); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; size=12340'."\r\n", + $attachment->toString() + ); + } + + public function testMultipleParametersInHeader() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setSize(12340); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf; size=12340'."\r\n", + $attachment->toString() + ); + } + + public function testEndToEnd() + { + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setSize(12340); + $attachment->setBody('abcd'); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf; size=12340'."\r\n". + "\r\n". + base64_encode('abcd'), + $attachment->toString() + ); + } + + // -- Private helpers + + protected function _createAttachment() + { + $entity = new Swift_Mime_Attachment( + $this->_headers, + $this->_contentEncoder, + $this->_cache, + $this->_grammar + ); + + return $entity; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/Base64ContentEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/Base64ContentEncoderAcceptanceTest.php new file mode 100644 index 00000000..2a5c562b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/Base64ContentEncoderAcceptanceTest.php @@ -0,0 +1,56 @@ +_samplesDir = realpath(__DIR__.'/../../../../_samples/charsets'); + $this->_encoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write($text); + + $is = new Swift_ByteStream_ArrayByteStream(); + + $this->_encoder->encodeByteStream($os, $is); + + $encoded = ''; + while (false !== $bytes = $is->read(8192)) { + $encoded .= $bytes; + } + + $this->assertEquals( + base64_decode($encoded), $text, + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/NativeQpContentEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/NativeQpContentEncoderAcceptanceTest.php new file mode 100644 index 00000000..e8313da1 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/NativeQpContentEncoderAcceptanceTest.php @@ -0,0 +1,86 @@ +_samplesDir = realpath(__DIR__.'/../../../../_samples/charsets'); + $this->_encoder = new Swift_Mime_ContentEncoder_NativeQpContentEncoder(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write($text); + + $is = new Swift_ByteStream_ArrayByteStream(); + $this->_encoder->encodeByteStream($os, $is); + + $encoded = ''; + while (false !== $bytes = $is->read(8192)) { + $encoded .= $bytes; + } + + $this->assertEquals( + quoted_printable_decode($encoded), + // CR and LF are converted to CRLF + preg_replace('~\r(?!\n)|(?_createEncoderFromContainer(); + $this->assertSame('=C3=A4=C3=B6=C3=BC=C3=9F', $encoder->encodeString('äöüß')); + } + + /** + * @expectedException RuntimeException + */ + public function testCharsetChangeNotImplemented() + { + $this->_encoder->charsetChanged('utf-8'); + $this->_encoder->charsetChanged('charset'); + $this->_encoder->encodeString('foo'); + } + + public function testGetName() + { + $this->assertSame('quoted-printable', $this->_encoder->getName()); + } + + private function _createEncoderFromContainer() + { + return Swift_DependencyContainer::getInstance() + ->lookup('mime.nativeqpcontentencoder') + ; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/PlainContentEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/PlainContentEncoderAcceptanceTest.php new file mode 100644 index 00000000..1541b7ea --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/PlainContentEncoderAcceptanceTest.php @@ -0,0 +1,88 @@ +_samplesDir = realpath(__DIR__.'/../../../../_samples/charsets'); + $this->_encoder = new Swift_Mime_ContentEncoder_PlainContentEncoder('8bit'); + } + + public function testEncodingAndDecodingSamplesString() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + $encodedText = $this->_encoder->encodeString($text); + + $this->assertEquals( + $encodedText, $text, + '%s: Encoded string should be identical to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } + + public function testEncodingAndDecodingSamplesByteStream() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write($text); + + $is = new Swift_ByteStream_ArrayByteStream(); + + $this->_encoder->encodeByteStream($os, $is); + + $encoded = ''; + while (false !== $bytes = $is->read(8192)) { + $encoded .= $bytes; + } + + $this->assertEquals( + $encoded, $text, + '%s: Encoded string should be identical to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/QpContentEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/QpContentEncoderAcceptanceTest.php new file mode 100644 index 00000000..501dbfa8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/ContentEncoder/QpContentEncoderAcceptanceTest.php @@ -0,0 +1,157 @@ +_samplesDir = realpath(__DIR__.'/../../../../_samples/charsets'); + $this->_factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + } + + public function testEncodingAndDecodingSamples() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $encoding = $encodingDir; + $charStream = new Swift_CharacterStream_NgCharacterStream( + $this->_factory, $encoding); + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write($text); + + $is = new Swift_ByteStream_ArrayByteStream(); + $encoder->encodeByteStream($os, $is); + + $encoded = ''; + while (false !== $bytes = $is->read(8192)) { + $encoded .= $bytes; + } + + $this->assertEquals( + quoted_printable_decode($encoded), $text, + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } + + public function testEncodingAndDecodingSamplesFromDiConfiguredInstance() + { + $sampleFp = opendir($this->_samplesDir); + while (false !== $encodingDir = readdir($sampleFp)) { + if (substr($encodingDir, 0, 1) == '.') { + continue; + } + + $encoding = $encodingDir; + $encoder = $this->_createEncoderFromContainer(); + + $sampleDir = $this->_samplesDir.'/'.$encodingDir; + + if (is_dir($sampleDir)) { + $fileFp = opendir($sampleDir); + while (false !== $sampleFile = readdir($fileFp)) { + if (substr($sampleFile, 0, 1) == '.') { + continue; + } + + $text = file_get_contents($sampleDir.'/'.$sampleFile); + + $os = new Swift_ByteStream_ArrayByteStream(); + $os->write($text); + + $is = new Swift_ByteStream_ArrayByteStream(); + $encoder->encodeByteStream($os, $is); + + $encoded = ''; + while (false !== $bytes = $is->read(8192)) { + $encoded .= $bytes; + } + + $this->assertEquals( + str_replace("\r\n", "\n", quoted_printable_decode($encoded)), str_replace("\r\n", "\n", $text), + '%s: Encoded string should decode back to original string for sample '. + $sampleDir.'/'.$sampleFile + ); + } + closedir($fileFp); + } + } + closedir($sampleFp); + } + + public function testEncodingLFTextWithDiConfiguredInstance() + { + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a\r\nb\r\nc", $encoder->encodeString("a\nb\nc")); + } + + public function testEncodingCRTextWithDiConfiguredInstance() + { + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a\r\nb\r\nc", $encoder->encodeString("a\rb\rc")); + } + + public function testEncodingLFCRTextWithDiConfiguredInstance() + { + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a\r\n\r\nb\r\n\r\nc", $encoder->encodeString("a\n\rb\n\rc")); + } + + public function testEncodingCRLFTextWithDiConfiguredInstance() + { + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a\r\nb\r\nc", $encoder->encodeString("a\r\nb\r\nc")); + } + + public function testEncodingDotStuffingWithDiConfiguredInstance() + { + // Enable DotEscaping + Swift_Preferences::getInstance()->setQPDotEscape(true); + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a=2E\r\n=2E\r\n=2Eb\r\nc", $encoder->encodeString("a.\r\n.\r\n.b\r\nc")); + // Return to default + Swift_Preferences::getInstance()->setQPDotEscape(false); + $encoder = $this->_createEncoderFromContainer(); + $this->assertEquals("a.\r\n.\r\n.b\r\nc", $encoder->encodeString("a.\r\n.\r\n.b\r\nc")); + } + + public function testDotStuffingEncodingAndDecodingSamplesFromDiConfiguredInstance() + { + // Enable DotEscaping + Swift_Preferences::getInstance()->setQPDotEscape(true); + $this->testEncodingAndDecodingSamplesFromDiConfiguredInstance(); + // Disable DotStuffing to continue + Swift_Preferences::getInstance()->setQPDotEscape(false); + } + + private function _createEncoderFromContainer() + { + return Swift_DependencyContainer::getInstance() + ->lookup('mime.qpcontentencoder') + ; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/EmbeddedFileAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/EmbeddedFileAcceptanceTest.php new file mode 100644 index 00000000..75f3c84c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/EmbeddedFileAcceptanceTest.php @@ -0,0 +1,137 @@ +_cache = new Swift_KeyCache_ArrayKeyCache( + new Swift_KeyCache_SimpleKeyCacheInputStream() + ); + $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + $this->_contentEncoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + + $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $paramEncoder = new Swift_Encoder_Rfc2231Encoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $this->_grammar = new Swift_Mime_Grammar(); + $this->_headers = new Swift_Mime_SimpleHeaderSet( + new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $this->_grammar) + ); + } + + public function testContentIdIsSetInHeader() + { + $file = $this->_createEmbeddedFile(); + $file->setContentType('application/pdf'); + $file->setId('foo@bar'); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline'."\r\n". + 'Content-ID: '."\r\n", + $file->toString() + ); + } + + public function testDispositionIsSetInHeader() + { + $file = $this->_createEmbeddedFile(); + $id = $file->getId(); + $file->setContentType('application/pdf'); + $file->setDisposition('attachment'); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment'."\r\n". + 'Content-ID: <'.$id.'>'."\r\n", + $file->toString() + ); + } + + public function testFilenameIsSetInHeader() + { + $file = $this->_createEmbeddedFile(); + $id = $file->getId(); + $file->setContentType('application/pdf'); + $file->setFilename('foo.pdf'); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=foo.pdf'."\r\n". + 'Content-ID: <'.$id.'>'."\r\n", + $file->toString() + ); + } + + public function testSizeIsSetInHeader() + { + $file = $this->_createEmbeddedFile(); + $id = $file->getId(); + $file->setContentType('application/pdf'); + $file->setSize(12340); + $this->assertEquals( + 'Content-Type: application/pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; size=12340'."\r\n". + 'Content-ID: <'.$id.'>'."\r\n", + $file->toString() + ); + } + + public function testMultipleParametersInHeader() + { + $file = $this->_createEmbeddedFile(); + $id = $file->getId(); + $file->setContentType('application/pdf'); + $file->setFilename('foo.pdf'); + $file->setSize(12340); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=foo.pdf; size=12340'."\r\n". + 'Content-ID: <'.$id.'>'."\r\n", + $file->toString() + ); + } + + public function testEndToEnd() + { + $file = $this->_createEmbeddedFile(); + $id = $file->getId(); + $file->setContentType('application/pdf'); + $file->setFilename('foo.pdf'); + $file->setSize(12340); + $file->setBody('abcd'); + $this->assertEquals( + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=foo.pdf; size=12340'."\r\n". + 'Content-ID: <'.$id.'>'."\r\n". + "\r\n". + base64_encode('abcd'), + $file->toString() + ); + } + + // -- Private helpers + + protected function _createEmbeddedFile() + { + $entity = new Swift_Mime_EmbeddedFile( + $this->_headers, + $this->_contentEncoder, + $this->_cache, + $this->_grammar + ); + + return $entity; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/HeaderEncoder/Base64HeaderEncoderAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/HeaderEncoder/Base64HeaderEncoderAcceptanceTest.php new file mode 100644 index 00000000..95675279 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/HeaderEncoder/Base64HeaderEncoderAcceptanceTest.php @@ -0,0 +1,32 @@ +_encoder = new Swift_Mime_HeaderEncoder_Base64HeaderEncoder(); + } + + public function testEncodingJIS() + { + if (function_exists('mb_convert_encoding')) { + // base64_encode and split cannot handle long JIS text to fold + $subject = "長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い長い件名"; + + $encodedWrapperLength = strlen('=?iso-2022-jp?'.$this->_encoder->getName().'??='); + + $old = mb_internal_encoding(); + mb_internal_encoding('utf-8'); + $newstring = mb_encode_mimeheader($subject, 'iso-2022-jp', 'B', "\r\n"); + mb_internal_encoding($old); + + $encoded = $this->_encoder->encodeString($subject, 0, 75 - $encodedWrapperLength, 'iso-2022-jp'); + $this->assertEquals( + $encoded, $newstring, + 'Encoded string should decode back to original string for sample ' + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/MimePartAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/MimePartAcceptanceTest.php new file mode 100644 index 00000000..8232fe63 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/MimePartAcceptanceTest.php @@ -0,0 +1,129 @@ +_cache = new Swift_KeyCache_ArrayKeyCache( + new Swift_KeyCache_SimpleKeyCacheInputStream() + ); + $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + $this->_contentEncoder = new Swift_Mime_ContentEncoder_QpContentEncoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'), + new Swift_StreamFilters_ByteArrayReplacementFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ) + ); + + $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $paramEncoder = new Swift_Encoder_Rfc2231Encoder( + new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8') + ); + $this->_grammar = new Swift_Mime_Grammar(); + $this->_headers = new Swift_Mime_SimpleHeaderSet( + new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $this->_grammar) + ); + } + + public function testCharsetIsSetInHeader() + { + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('utf-8'); + $part->setBody('foobar'); + $this->assertEquals( + 'Content-Type: text/plain; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foobar', + $part->toString() + ); + } + + public function testFormatIsSetInHeaders() + { + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setFormat('flowed'); + $part->setBody('> foobar'); + $this->assertEquals( + 'Content-Type: text/plain; format=flowed'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + '> foobar', + $part->toString() + ); + } + + public function testDelSpIsSetInHeaders() + { + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setDelSp(true); + $part->setBody('foobar'); + $this->assertEquals( + 'Content-Type: text/plain; delsp=yes'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foobar', + $part->toString() + ); + } + + public function testAll3ParamsInHeaders() + { + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('utf-8'); + $part->setFormat('fixed'); + $part->setDelSp(true); + $part->setBody('foobar'); + $this->assertEquals( + 'Content-Type: text/plain; charset=utf-8; format=fixed; delsp=yes'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foobar', + $part->toString() + ); + } + + public function testBodyIsCanonicalized() + { + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('utf-8'); + $part->setBody("foobar\r\rtest\ning\r"); + $this->assertEquals( + 'Content-Type: text/plain; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + "foobar\r\n". + "\r\n". + "test\r\n". + "ing\r\n", + $part->toString() + ); + } + + // -- Private helpers + + protected function _createMimePart() + { + $entity = new Swift_Mime_MimePart( + $this->_headers, + $this->_contentEncoder, + $this->_cache, + $this->_grammar + ); + + return $entity; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/SimpleMessageAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/SimpleMessageAcceptanceTest.php new file mode 100644 index 00000000..16760471 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Mime/SimpleMessageAcceptanceTest.php @@ -0,0 +1,1251 @@ +setCharset(null); //TODO: Test with the charset defined + } + + public function testBasicHeaders() + { + /* -- RFC 2822, 3.6. + */ + + $message = $this->_createMessage(); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString(), + '%s: Only required headers, and non-empty headers should be displayed' + ); + } + + public function testSubjectIsDisplayedIfSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testDateCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $id = $message->getId(); + $message->setDate(1234); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', 1234)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMessageIdCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setId('foo@bar'); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: '."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testContentTypeCanBeChanged() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setContentType('text/html'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/html'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testCharsetCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setContentType('text/html'); + $message->setCharset('iso-8859-1'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testFormatCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFormat('flowed'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain; format=flowed'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testEncoderCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setContentType('text/html'); + $message->setEncoder( + new Swift_Mime_ContentEncoder_PlainContentEncoder('7bit') + ); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/html'."\r\n". + 'Content-Transfer-Encoding: 7bit'."\r\n", + $message->toString() + ); + } + + public function testFromAddressCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom('chris.corbyn@swiftmailer.org'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: chris.corbyn@swiftmailer.org'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testFromAddressCanBeSetWithName() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris Corbyn')); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMultipleFromAddressesCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org', + )); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn , mark@swiftmailer.org'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testReturnPathAddressCanBeSet() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testEmptyReturnPathHeaderCanBeUsed() + { + $message = $this->_createMessage(); + $message->setReturnPath(''); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Return-Path: <>'."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testSenderCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setSender('chris.corbyn@swiftmailer.org'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Sender: chris.corbyn@swiftmailer.org'."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testSenderCanBeSetWithName() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setSender(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Sender: Chris '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testReplyToCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array('chris@w3style.co.uk' => 'Myself')); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMultipleReplyAddressCanBeUsed() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testToAddressCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo('mark@swiftmailer.org'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMultipleToAddressesCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo(array( + 'mark@swiftmailer.org', 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org, Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testCcAddressCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo(array( + 'mark@swiftmailer.org', 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $message->setCc('john@some-site.com'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org, Chris Corbyn '."\r\n". + 'Cc: john@some-site.com'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMultipleCcAddressesCanBeSet() + { + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo(array( + 'mark@swiftmailer.org', 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $message->setCc(array( + 'john@some-site.com' => 'John West', + 'fred@another-site.co.uk' => 'Big Fred', + )); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org, Chris Corbyn '."\r\n". + 'Cc: John West , Big Fred '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testBccAddressCanBeSet() + { + //Obviously Transports need to setBcc(array()) and send to each Bcc recipient + // separately in accordance with RFC 2822/2821 + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo(array( + 'mark@swiftmailer.org', 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $message->setCc(array( + 'john@some-site.com' => 'John West', + 'fred@another-site.co.uk' => 'Big Fred', + )); + $message->setBcc('x@alphabet.tld'); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org, Chris Corbyn '."\r\n". + 'Cc: John West , Big Fred '."\r\n". + 'Bcc: x@alphabet.tld'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testMultipleBccAddressesCanBeSet() + { + //Obviously Transports need to setBcc(array()) and send to each Bcc recipient + // separately in accordance with RFC 2822/2821 + $message = $this->_createMessage(); + $message->setSubject('just a test subject'); + $message->setFrom(array('chris.corbyn@swiftmailer.org' => 'Chris')); + $message->setReplyTo(array( + 'chris@w3style.co.uk' => 'Myself', + 'my.other@address.com' => 'Me', + )); + $message->setTo(array( + 'mark@swiftmailer.org', 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $message->setCc(array( + 'john@some-site.com' => 'John West', + 'fred@another-site.co.uk' => 'Big Fred', + )); + $message->setBcc(array('x@alphabet.tld', 'a@alphabet.tld' => 'A')); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris '."\r\n". + 'Reply-To: Myself , Me '."\r\n". + 'To: mark@swiftmailer.org, Chris Corbyn '."\r\n". + 'Cc: John West , Big Fred '."\r\n". + 'Bcc: x@alphabet.tld, A '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString() + ); + } + + public function testStringBodyIsAppended() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setBody( + 'just a test body'."\r\n". + 'with a new line' + ); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'just a test body'."\r\n". + 'with a new line', + $message->toString() + ); + } + + public function testStringBodyIsEncoded() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setBody( + 'Just s'.pack('C*', 0xC2, 0x01, 0x01).'me multi-'."\r\n". + 'line message!' + ); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'Just s=C2=01=01me multi-'."\r\n". + 'line message!', + $message->toString() + ); + } + + public function testChildrenCanBeAttached() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = $message->getDate(); + $boundary = $message->getBoundary(); + + $part1 = $this->_createMimePart(); + $part1->setContentType('text/plain'); + $part1->setCharset('iso-8859-1'); + $part1->setBody('foo'); + + $message->attach($part1); + + $part2 = $this->_createMimePart(); + $part2->setContentType('text/html'); + $part2->setCharset('iso-8859-1'); + $part2->setBody('test foo'); + + $message->attach($part2); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'test foo'. + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + public function testAttachmentsBeingAttached() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('iso-8859-1'); + $part->setBody('foo'); + + $message->attach($part); + + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setBody(''); + + $message->attach($attachment); + + $this->assertRegExp( + '~^'. + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString() + ); + } + + public function testAttachmentsAndEmbeddedFilesBeingAttached() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('iso-8859-1'); + $part->setBody('foo'); + + $message->attach($part); + + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setBody(''); + + $message->attach($attachment); + + $file = $this->_createEmbeddedFile(); + $file->setContentType('image/jpeg'); + $file->setFilename('myimage.jpg'); + $file->setBody(''); + + $message->attach($file); + + $cid = $file->getId(); + + $this->assertRegExp( + '~^'. + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\2'."\r\n". + 'Content-Type: image/jpeg; name=myimage.jpg'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=myimage.jpg'."\r\n". + 'Content-ID: <'.$cid.'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--\\2--'."\r\n". + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString() + ); + } + + public function testComplexEmbeddingOfContent() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setBody(''); + + $message->attach($attachment); + + $file = $this->_createEmbeddedFile(); + $file->setContentType('image/jpeg'); + $file->setFilename('myimage.jpg'); + $file->setBody(''); + + $part = $this->_createMimePart(); + $part->setContentType('text/html'); + $part->setCharset('iso-8859-1'); + $part->setBody('foo '); + + $message->attach($part); + + $cid = $file->getId(); + + $this->assertRegExp( + '~^'. + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo './/=3D is just = in QP + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: image/jpeg; name=myimage.jpg'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=myimage.jpg'."\r\n". + 'Content-ID: <'.$cid.'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString() + ); + } + + public function testAttachingAndDetachingContent() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $part = $this->_createMimePart(); + $part->setContentType('text/plain'); + $part->setCharset('iso-8859-1'); + $part->setBody('foo'); + + $message->attach($part); + + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setBody(''); + + $message->attach($attachment); + + $file = $this->_createEmbeddedFile(); + $file->setContentType('image/jpeg'); + $file->setFilename('myimage.jpg'); + $file->setBody(''); + + $message->attach($file); + + $cid = $file->getId(); + + $message->detach($attachment); + + $this->assertRegExp( + '~^'. + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: image/jpeg; name=myimage.jpg'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=myimage.jpg'."\r\n". + 'Content-ID: <'.$cid.'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString(), + '%s: Attachment should have been detached' + ); + } + + public function testBoundaryDoesNotAppearAfterAllPartsAreDetached() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = $message->getDate(); + $boundary = $message->getBoundary(); + + $part1 = $this->_createMimePart(); + $part1->setContentType('text/plain'); + $part1->setCharset('iso-8859-1'); + $part1->setBody('foo'); + + $message->attach($part1); + + $part2 = $this->_createMimePart(); + $part2->setContentType('text/html'); + $part2->setCharset('iso-8859-1'); + $part2->setBody('test foo'); + + $message->attach($part2); + + $message->detach($part1); + $message->detach($part2); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n", + $message->toString(), + '%s: Message should be restored to orignal state after parts are detached' + ); + } + + public function testCharsetFormatOrDelSpAreNotShownWhenBoundaryIsSet() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setCharset('utf-8'); + $message->setFormat('flowed'); + $message->setDelSp(true); + + $id = $message->getId(); + $date = $message->getDate(); + $boundary = $message->getBoundary(); + + $part1 = $this->_createMimePart(); + $part1->setContentType('text/plain'); + $part1->setCharset('iso-8859-1'); + $part1->setBody('foo'); + + $message->attach($part1); + + $part2 = $this->_createMimePart(); + $part2->setContentType('text/html'); + $part2->setCharset('iso-8859-1'); + $part2->setBody('test foo'); + + $message->attach($part2); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'test foo'. + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + public function testBodyCanBeSetWithAttachments() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setContentType('text/html'); + $message->setCharset('iso-8859-1'); + $message->setBody('foo'); + + $id = $message->getId(); + $date = date('r', $message->getDate()); + $boundary = $message->getBoundary(); + + $attachment = $this->_createAttachment(); + $attachment->setContentType('application/pdf'); + $attachment->setFilename('foo.pdf'); + $attachment->setBody(''); + + $message->attach($attachment); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=iso-8859-1'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: application/pdf; name=foo.pdf'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=foo.pdf'."\r\n". + "\r\n". + base64_encode(''). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + public function testHtmlPartAlwaysAppearsLast() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + + $id = $message->getId(); + $date = date('r', $message->getDate()); + $boundary = $message->getBoundary(); + + $part1 = $this->_createMimePart(); + $part1->setContentType('text/html'); + $part1->setBody('foo'); + + $part2 = $this->_createMimePart(); + $part2->setContentType('text/plain'); + $part2->setBody('bar'); + + $message->attach($part1); + $message->attach($part2); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'bar'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + public function testBodyBecomesPartIfOtherPartsAttached() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setContentType('text/html'); + $message->setBody('foo'); + + $id = $message->getId(); + $date = date('r', $message->getDate()); + $boundary = $message->getBoundary(); + + $part2 = $this->_createMimePart(); + $part2->setContentType('text/plain'); + $part2->setBody('bar'); + + $message->attach($part2); + + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'bar'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'foo'. + "\r\n\r\n". + '--'.$boundary.'--'."\r\n", + $message->toString() + ); + } + + public function testBodyIsCanonicalized() + { + $message = $this->_createMessage(); + $message->setReturnPath('chris@w3style.co.uk'); + $message->setSubject('just a test subject'); + $message->setFrom(array( + 'chris.corbyn@swiftmailer.org' => 'Chris Corbyn',)); + $message->setBody( + 'just a test body'."\n". + 'with a new line' + ); + $id = $message->getId(); + $date = $message->getDate(); + $this->assertEquals( + 'Return-Path: '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.date('r', $date)."\r\n". + 'Subject: just a test subject'."\r\n". + 'From: Chris Corbyn '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: text/plain'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'just a test body'."\r\n". + 'with a new line', + $message->toString() + ); + } + + // -- Private helpers + + protected function _createMessage() + { + return new Swift_Message(); + } + + protected function _createMimePart() + { + return new Swift_MimePart(); + } + + protected function _createAttachment() + { + return new Swift_Attachment(); + } + + protected function _createEmbeddedFile() + { + return new Swift_EmbeddedFile(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MimePartAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MimePartAcceptanceTest.php new file mode 100644 index 00000000..f42405df --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/MimePartAcceptanceTest.php @@ -0,0 +1,15 @@ +register('properties.charset')->asValue(null); + + return Swift_MimePart::newInstance(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/AbstractStreamBufferAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/AbstractStreamBufferAcceptanceTest.php new file mode 100644 index 00000000..465f2c18 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/AbstractStreamBufferAcceptanceTest.php @@ -0,0 +1,134 @@ +markTestSkipped( + 'Will fail on travis-ci if not skipped due to travis blocking '. + 'socket mailing tcp connections.' + ); + } + + $this->_buffer = new Swift_Transport_StreamBuffer( + $this->getMock('Swift_ReplacementFilterFactory') + ); + } + + public function testReadLine() + { + $this->_initializeBuffer(); + + $line = $this->_buffer->readLine(0); + $this->assertRegExp('/^[0-9]{3}.*?\r\n$/D', $line); + $seq = $this->_buffer->write("QUIT\r\n"); + $this->assertTrue((bool) $seq); + $line = $this->_buffer->readLine($seq); + $this->assertRegExp('/^[0-9]{3}.*?\r\n$/D', $line); + $this->_buffer->terminate(); + } + + public function testWrite() + { + $this->_initializeBuffer(); + + $line = $this->_buffer->readLine(0); + $this->assertRegExp('/^[0-9]{3}.*?\r\n$/D', $line); + + $seq = $this->_buffer->write("HELO foo\r\n"); + $this->assertTrue((bool) $seq); + $line = $this->_buffer->readLine($seq); + $this->assertRegExp('/^[0-9]{3}.*?\r\n$/D', $line); + + $seq = $this->_buffer->write("QUIT\r\n"); + $this->assertTrue((bool) $seq); + $line = $this->_buffer->readLine($seq); + $this->assertRegExp('/^[0-9]{3}.*?\r\n$/D', $line); + $this->_buffer->terminate(); + } + + public function testBindingOtherStreamsMirrorsWriteOperations() + { + $this->_initializeBuffer(); + + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->at(0)) + ->method('write') + ->with('x'); + $is2->expects($this->at(1)) + ->method('write') + ->with('y'); + + $this->_buffer->bind($is1); + $this->_buffer->bind($is2); + + $this->_buffer->write('x'); + $this->_buffer->write('y'); + } + + public function testBindingOtherStreamsMirrorsFlushOperations() + { + $this->_initializeBuffer(); + + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->once()) + ->method('flushBuffers'); + $is2->expects($this->once()) + ->method('flushBuffers'); + + $this->_buffer->bind($is1); + $this->_buffer->bind($is2); + + $this->_buffer->flushBuffers(); + } + + public function testUnbindingStreamPreventsFurtherWrites() + { + $this->_initializeBuffer(); + + $is1 = $this->_createMockInputStream(); + $is2 = $this->_createMockInputStream(); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->once()) + ->method('write') + ->with('x'); + + $this->_buffer->bind($is1); + $this->_buffer->bind($is2); + + $this->_buffer->write('x'); + + $this->_buffer->unbind($is2); + + $this->_buffer->write('y'); + } + + // -- Creation Methods + + private function _createMockInputStream() + { + return $this->getMock('Swift_InputByteStream'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/BasicSocketAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/BasicSocketAcceptanceTest.php new file mode 100644 index 00000000..8f6e453a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/BasicSocketAcceptanceTest.php @@ -0,0 +1,34 @@ +markTestSkipped( + 'Cannot run test without an SMTP host to connect to (define '. + 'SWIFT_SMTP_HOST in tests/acceptance.conf.php if you wish to run this test)' + ); + } + parent::setUp(); + } + + protected function _initializeBuffer() + { + $parts = explode(':', SWIFT_SMTP_HOST); + $host = $parts[0]; + $port = isset($parts[1]) ? $parts[1] : 25; + + $this->_buffer->initialize(array( + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + 'host' => $host, + 'port' => $port, + 'protocol' => 'tcp', + 'blocking' => 1, + 'timeout' => 15, + )); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/ProcessAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/ProcessAcceptanceTest.php new file mode 100644 index 00000000..b4e88a7a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/ProcessAcceptanceTest.php @@ -0,0 +1,27 @@ +markTestSkipped( + 'Cannot run test without a path to sendmail (define '. + 'SWIFT_SENDMAIL_PATH in tests/acceptance.conf.php if you wish to run this test)' + ); + } + + parent::setUp(); + } + + protected function _initializeBuffer() + { + $this->_buffer->initialize(array( + 'type' => Swift_Transport_IoBuffer::TYPE_PROCESS, + 'command' => SWIFT_SENDMAIL_PATH.' -bs', + )); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SocketTimeoutTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SocketTimeoutTest.php new file mode 100644 index 00000000..0522c081 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SocketTimeoutTest.php @@ -0,0 +1,65 @@ +markTestSkipped( + 'Cannot run test without an SMTP host to connect to (define '. + 'SWIFT_SMTP_HOST in tests/acceptance.conf.php if you wish to run this test)' + ); + } + + $serverStarted = false; + for ($i = 0; $i<5; ++$i) { + $this->_randomHighPort = rand(50000,65000); + $this->_server = stream_socket_server('tcp://127.0.0.1:'.$this->_randomHighPort); + if ($this->_server) { + $serverStarted = true; + } + } + + $this->_buffer = new Swift_Transport_StreamBuffer( + $this->getMock('Swift_ReplacementFilterFactory') + ); + } + + protected function _initializeBuffer() + { + $host = '127.0.0.1'; + $port = $this->_randomHighPort; + + $this->_buffer->initialize(array( + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + 'host' => $host, + 'port' => $port, + 'protocol' => 'tcp', + 'blocking' => 1, + 'timeout' => 1, + )); + } + + public function testTimeoutException() + { + $this->_initializeBuffer(); + $e = null; + try { + $line = $this->_buffer->readLine(0); + } catch (Exception $e) { + } + $this->assertInstanceof('Swift_IoException', $e, 'IO Exception Not Thrown On Connection Timeout'); + $this->assertRegExp('/Connection to .* Timed Out/', $e->getMessage()); + } + + public function tearDown() + { + if ($this->_server) { + stream_socket_shutdown($this->_server, STREAM_SHUT_RDWR); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SslSocketAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SslSocketAcceptanceTest.php new file mode 100644 index 00000000..d2d2a38e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/SslSocketAcceptanceTest.php @@ -0,0 +1,41 @@ +markTestSkipped( + 'SSL is not configured for your system. It is not possible to run this test' + ); + } + if (!defined('SWIFT_SSL_HOST')) { + $this->markTestSkipped( + 'Cannot run test without an SSL enabled SMTP host to connect to (define '. + 'SWIFT_SSL_HOST in tests/acceptance.conf.php if you wish to run this test)' + ); + } + + parent::setUp(); + } + + protected function _initializeBuffer() + { + $parts = explode(':', SWIFT_SSL_HOST); + $host = $parts[0]; + $port = isset($parts[1]) ? $parts[1] : 25; + + $this->_buffer->initialize(array( + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + 'host' => $host, + 'port' => $port, + 'protocol' => 'ssl', + 'blocking' => 1, + 'timeout' => 15, + )); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/TlsSocketAcceptanceTest.php b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/TlsSocketAcceptanceTest.php new file mode 100644 index 00000000..314fffe2 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/acceptance/Swift/Transport/StreamBuffer/TlsSocketAcceptanceTest.php @@ -0,0 +1,40 @@ +markTestSkipped( + 'TLS is not configured for your system. It is not possible to run this test' + ); + } + if (!defined('SWIFT_TLS_HOST')) { + $this->markTestSkipped( + 'Cannot run test without a TLS enabled SMTP host to connect to (define '. + 'SWIFT_TLS_HOST in tests/acceptance.conf.php if you wish to run this test)' + ); + } + parent::setUp(); + } + + protected function _initializeBuffer() + { + $parts = explode(':', SWIFT_TLS_HOST); + $host = $parts[0]; + $port = isset($parts[1]) ? $parts[1] : 25; + + $this->_buffer->initialize(array( + 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, + 'host' => $host, + 'port' => $port, + 'protocol' => 'tls', + 'blocking' => 1, + 'timeout' => 15, + )); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bootstrap.php b/vendor/swiftmailer/swiftmailer/tests/bootstrap.php new file mode 100644 index 00000000..55538bbc --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bootstrap.php @@ -0,0 +1,18 @@ +allowMockingNonExistentMethods(false); + +if (is_file(__DIR__.'/acceptance.conf.php')) { + require_once __DIR__.'/acceptance.conf.php'; +} +if (is_file(__DIR__.'/smoke.conf.php')) { + require_once __DIR__.'/smoke.conf.php'; +} +require_once __DIR__.'/StreamCollector.php'; +require_once __DIR__.'/IdenticalBinaryConstraint.php'; +require_once __DIR__.'/SwiftMailerTestCase.php'; +require_once __DIR__.'/SwiftMailerSmokeTestCase.php'; diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug111Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug111Test.php new file mode 100644 index 00000000..ba29ba87 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug111Test.php @@ -0,0 +1,42 @@ + array( + 'email1@example.com', + 'email2@example.com', + 'email3@example.com', + 'email4@example.com', + 'email5@example.com', + ), + 'sub' => array( + '-name-' => array( + 'email1', + '"email2"', + 'email3\\', + 'email4', + 'email5', + ), + '-url-' => array( + 'http://google.com', + 'http://yahoo.com', + 'http://hotmail.com', + 'http://aol.com', + 'http://facebook.com', + ), + ), + ); + $json = json_encode($complicated_header); + + $message = new Swift_Message(); + $headers = $message->getHeaders(); + $headers->addTextHeader('X-SMTPAPI', $json); + $header = $headers->get('X-SMTPAPI'); + + $this->assertEquals('Swift_Mime_Headers_UnstructuredHeader', get_class($header)); + $this->assertEquals($json, $header->getFieldBody()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug118Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug118Test.php new file mode 100644 index 00000000..bd10c716 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug118Test.php @@ -0,0 +1,20 @@ +_message = new Swift_Message(); + } + + public function testCallingGenerateIdChangesTheMessageId() + { + $currentId = $this->_message->getId(); + $this->_message->generateId(); + $newId = $this->_message->getId(); + + $this->assertNotEquals($currentId, $newId); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug206Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug206Test.php new file mode 100644 index 00000000..fdfa5302 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug206Test.php @@ -0,0 +1,38 @@ +_factory = new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $grammar); + } + + public function testMailboxHeaderEncoding() + { + $this->_testHeaderIsFullyEncoded('email@example.org', 'Family Name, Name', ' "Family Name, Name" '); + $this->_testHeaderIsFullyEncoded('email@example.org', 'Family Namé, Name', ' Family =?utf-8?Q?Nam=C3=A9=2C?= Name'); + $this->_testHeaderIsFullyEncoded('email@example.org', 'Family Namé , Name', ' Family =?utf-8?Q?Nam=C3=A9_=2C?= Name'); + $this->_testHeaderIsFullyEncoded('email@example.org', 'Family Namé ;Name', ' Family =?utf-8?Q?Nam=C3=A9_=3BName?= '); + } + + private function _testHeaderIsFullyEncoded($email, $name, $expected) + { + $mailboxHeader = $this->_factory->createMailboxHeader('To', array( + $email => $name, + )); + + $headerBody = substr($mailboxHeader->toString(), 3, strlen($expected)); + + $this->assertEquals($expected, $headerBody); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug274Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug274Test.php new file mode 100644 index 00000000..d305d02e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug274Test.php @@ -0,0 +1,21 @@ +setExpectedException('Swift_IoException', 'The path cannot be empty'); + $message->attach(Swift_Attachment::fromPath('')); + } + + public function testNonEmptyFileNameAsAttachement() + { + $message = new Swift_Message(); + try { + $message->attach(Swift_Attachment::fromPath(__FILE__)); + } catch (Exception $e) { + $this->fail('Path should not be empty'); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug34Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug34Test.php new file mode 100644 index 00000000..6a0f33d5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug34Test.php @@ -0,0 +1,75 @@ +setCharset('utf-8'); + } + + public function testEmbeddedFilesWithMultipartDataCreateMultipartRelatedContentAsAnAlternative() + { + $message = Swift_Message::newInstance(); + $message->setCharset('utf-8'); + $message->setSubject('test subject'); + $message->addPart('plain part', 'text/plain'); + + $image = Swift_Image::newInstance('', 'image.gif', 'image/gif'); + $cid = $message->embed($image); + + $message->setBody('', 'text/html'); + + $message->setTo(array('user@domain.tld' => 'User')); + + $message->setFrom(array('other@domain.tld' => 'Other')); + $message->setSender(array('other@domain.tld' => 'Other')); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + $cidVal = $image->getId(); + + $this->assertRegExp( + '~^'. + 'Sender: Other '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: test subject'."\r\n". + 'From: Other '."\r\n". + 'To: User '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/plain; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'plain part'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/html; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + ''. + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: image/gif; name=image.gif'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=image.gif'."\r\n". + 'Content-ID: <'.$cidVal.'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString() + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug35Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug35Test.php new file mode 100644 index 00000000..e07ee8f0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug35Test.php @@ -0,0 +1,73 @@ +setCharset('utf-8'); + } + + public function testHTMLPartAppearsLastEvenWhenAttachmentsAdded() + { + $message = Swift_Message::newInstance(); + $message->setCharset('utf-8'); + $message->setSubject('test subject'); + $message->addPart('plain part', 'text/plain'); + + $attachment = Swift_Attachment::newInstance('', 'image.gif', 'image/gif'); + $message->attach($attachment); + + $message->setBody('HTML part', 'text/html'); + + $message->setTo(array('user@domain.tld' => 'User')); + + $message->setFrom(array('other@domain.tld' => 'Other')); + $message->setSender(array('other@domain.tld' => 'Other')); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $this->assertRegExp( + '~^'. + 'Sender: Other '."\r\n". + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: test subject'."\r\n". + 'From: Other '."\r\n". + 'To: User '."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: multipart/alternative;'."\r\n". + ' boundary="(.*?)"'."\r\n". + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/plain; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'plain part'. + "\r\n\r\n". + '--\\1'."\r\n". + 'Content-Type: text/html; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'HTML part'. + "\r\n\r\n". + '--\\1--'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: image/gif; name=image.gif'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename=image.gif'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $message->toString() + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug38Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug38Test.php new file mode 100644 index 00000000..e2815168 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug38Test.php @@ -0,0 +1,194 @@ +_attFileName = 'data.txt'; + $this->_attFileType = 'text/plain'; + $this->_attFile = __DIR__.'/../../_samples/files/data.txt'; + Swift_Preferences::getInstance()->setCharset('utf-8'); + } + + public function testWritingMessageToByteStreamProducesCorrectStructure() + { + $message = new Swift_Message(); + $message->setSubject('test subject'); + $message->setTo('user@domain.tld'); + $message->setCc('other@domain.tld'); + $message->setFrom('user@domain.tld'); + + $image = new Swift_Image('', 'image.gif', 'image/gif'); + + $cid = $message->embed($image); + $message->setBody('HTML part', 'text/html'); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + $imgId = $image->getId(); + + $stream = new Swift_ByteStream_ArrayByteStream(); + + $message->toByteStream($stream); + + $this->assertPatternInStream( + '~^'. + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: test subject'."\r\n". + 'From: user@domain.tld'."\r\n". + 'To: user@domain.tld'."\r\n". + 'Cc: other@domain.tld'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'HTML part'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: image/gif; name=image.gif'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=image.gif'."\r\n". + 'Content-ID: <'.preg_quote($imgId, '~').'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D', + $stream + ); + } + + public function testWritingMessageToByteStreamTwiceProducesCorrectStructure() + { + $message = new Swift_Message(); + $message->setSubject('test subject'); + $message->setTo('user@domain.tld'); + $message->setCc('other@domain.tld'); + $message->setFrom('user@domain.tld'); + + $image = new Swift_Image('', 'image.gif', 'image/gif'); + + $cid = $message->embed($image); + $message->setBody('HTML part', 'text/html'); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + $imgId = $image->getId(); + + $pattern = '~^'. + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: test subject'."\r\n". + 'From: user@domain.tld'."\r\n". + 'To: user@domain.tld'."\r\n". + 'Cc: other@domain.tld'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/related;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'HTML part'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: image/gif; name=image.gif'."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: inline; filename=image.gif'."\r\n". + 'Content-ID: <'.preg_quote($imgId, '~').'>'."\r\n". + "\r\n". + preg_quote(base64_encode(''), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D' + ; + + $streamA = new Swift_ByteStream_ArrayByteStream(); + $streamB = new Swift_ByteStream_ArrayByteStream(); + + $message->toByteStream($streamA); + $message->toByteStream($streamB); + + $this->assertPatternInStream($pattern, $streamA); + $this->assertPatternInStream($pattern, $streamB); + } + + public function testWritingMessageToByteStreamTwiceUsingAFileAttachment() + { + $message = new Swift_Message(); + $message->setSubject('test subject'); + $message->setTo('user@domain.tld'); + $message->setCc('other@domain.tld'); + $message->setFrom('user@domain.tld'); + + $attachment = Swift_Attachment::fromPath($this->_attFile); + + $message->attach($attachment); + + $message->setBody('HTML part', 'text/html'); + + $id = $message->getId(); + $date = preg_quote(date('r', $message->getDate()), '~'); + $boundary = $message->getBoundary(); + + $streamA = new Swift_ByteStream_ArrayByteStream(); + $streamB = new Swift_ByteStream_ArrayByteStream(); + + $pattern = '~^'. + 'Message-ID: <'.$id.'>'."\r\n". + 'Date: '.$date."\r\n". + 'Subject: test subject'."\r\n". + 'From: user@domain.tld'."\r\n". + 'To: user@domain.tld'."\r\n". + 'Cc: other@domain.tld'."\r\n". + 'MIME-Version: 1.0'."\r\n". + 'Content-Type: multipart/mixed;'."\r\n". + ' boundary="'.$boundary.'"'."\r\n". + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: text/html; charset=utf-8'."\r\n". + 'Content-Transfer-Encoding: quoted-printable'."\r\n". + "\r\n". + 'HTML part'. + "\r\n\r\n". + '--'.$boundary."\r\n". + 'Content-Type: '.$this->_attFileType.'; name='.$this->_attFileName."\r\n". + 'Content-Transfer-Encoding: base64'."\r\n". + 'Content-Disposition: attachment; filename='.$this->_attFileName."\r\n". + "\r\n". + preg_quote(base64_encode(file_get_contents($this->_attFile)), '~'). + "\r\n\r\n". + '--'.$boundary.'--'."\r\n". + '$~D' + ; + + $message->toByteStream($streamA); + $message->toByteStream($streamB); + + $this->assertPatternInStream($pattern, $streamA); + $this->assertPatternInStream($pattern, $streamB); + } + + // -- Helpers + + public function assertPatternInStream($pattern, $stream, $message = '%s') + { + $string = ''; + while (false !== $bytes = $stream->read(8192)) { + $string .= $bytes; + } + $this->assertRegExp($pattern, $string, $message); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug518Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug518Test.php new file mode 100644 index 00000000..b83984fe --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug518Test.php @@ -0,0 +1,38 @@ +setTo('foo@bar.com'); + + $that = $this; + $messageValidation = function ($m) use ($that) { + //the getTo should return the same value as we put in + $that->assertEquals('foo@bar.com', key($m->getTo()), 'The message has changed after it was put to the memory queue'); + + return true; + }; + + $transport = m::mock('Swift_Transport'); + $transport->shouldReceive('isStarted')->andReturn(true); + $transport->shouldReceive('send') + ->with(m::on($messageValidation), $failedRecipients) + ->andReturn(1); + + $memorySpool = new Swift_MemorySpool(); + $memorySpool->queueMessage($message); + + /* + * The message is queued in memory. + * Lets change the message + */ + $message->setTo('other@value.com'); + + $memorySpool->flushQueue($transport, $failedRecipients); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug51Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug51Test.php new file mode 100644 index 00000000..b9c33b09 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug51Test.php @@ -0,0 +1,121 @@ +markTestSkipped( + 'Cannot run test without a writable directory to use ('. + 'define SWIFT_TMP_DIR in tests/config.php if you wish to run this test)' + ); + } + + $this->_attachmentFile = SWIFT_TMP_DIR.'/attach.rand.bin'; + file_put_contents($this->_attachmentFile, ''); + + $this->_outputFile = SWIFT_TMP_DIR.'/attach.out.bin'; + file_put_contents($this->_outputFile, ''); + } + + public function tearDown() + { + unlink($this->_attachmentFile); + unlink($this->_outputFile); + } + + public function testAttachmentsDoNotGetTruncatedUsingToByteStream() + { + //Run 100 times with 10KB attachments + for ($i = 0; $i < 10; ++$i) { + $message = $this->_createMessageWithRandomAttachment( + 10000, $this->_attachmentFile + ); + + file_put_contents($this->_outputFile, ''); + $message->toByteStream( + new Swift_ByteStream_FileByteStream($this->_outputFile, true) + ); + + $emailSource = file_get_contents($this->_outputFile); + + $this->assertAttachmentFromSourceMatches( + file_get_contents($this->_attachmentFile), + $emailSource + ); + } + } + + public function testAttachmentsDoNotGetTruncatedUsingToString() + { + //Run 100 times with 10KB attachments + for ($i = 0; $i < 10; ++$i) { + $message = $this->_createMessageWithRandomAttachment( + 10000, $this->_attachmentFile + ); + + $emailSource = $message->toString(); + + $this->assertAttachmentFromSourceMatches( + file_get_contents($this->_attachmentFile), + $emailSource + ); + } + } + + // -- Custom Assertions + + public function assertAttachmentFromSourceMatches($attachmentData, $source) + { + $encHeader = 'Content-Transfer-Encoding: base64'; + $base64declaration = strpos($source, $encHeader); + + $attachmentDataStart = strpos($source, "\r\n\r\n", $base64declaration); + $attachmentDataEnd = strpos($source, "\r\n--", $attachmentDataStart); + + if (false === $attachmentDataEnd) { + $attachmentBase64 = trim(substr($source, $attachmentDataStart)); + } else { + $attachmentBase64 = trim(substr( + $source, $attachmentDataStart, + $attachmentDataEnd - $attachmentDataStart + )); + } + + $this->assertIdenticalBinary($attachmentData, base64_decode($attachmentBase64)); + } + + // -- Creation Methods + + private function _fillFileWithRandomBytes($byteCount, $file) + { + // I was going to use dd with if=/dev/random but this way seems more + // cross platform even if a hella expensive!! + + file_put_contents($file, ''); + $fp = fopen($file, 'wb'); + for ($i = 0; $i < $byteCount; ++$i) { + $byteVal = rand(0, 255); + fwrite($fp, pack('i', $byteVal)); + } + fclose($fp); + } + + private function _createMessageWithRandomAttachment($size, $attachmentPath) + { + $this->_fillFileWithRandomBytes($size, $attachmentPath); + + $message = Swift_Message::newInstance() + ->setSubject('test') + ->setBody('test') + ->setFrom('a@b.c') + ->setTo('d@e.f') + ->attach(Swift_Attachment::fromPath($attachmentPath)) + ; + + return $message; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug71Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug71Test.php new file mode 100644 index 00000000..4b804537 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug71Test.php @@ -0,0 +1,20 @@ +_message = new Swift_Message('test'); + } + + public function testCallingToStringAfterSettingNewBodyReflectsChanges() + { + $this->_message->setBody('BODY1'); + $this->assertRegExp('/BODY1/', $this->_message->toString()); + + $this->_message->setBody('BODY2'); + $this->assertRegExp('/BODY2/', $this->_message->toString()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug76Test.php b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug76Test.php new file mode 100644 index 00000000..c2b12cb4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/bug/Swift/Bug76Test.php @@ -0,0 +1,82 @@ +markTestSkipped( + 'Cannot run test without a writable directory to use ('. + 'define SWIFT_TMP_DIR in tests/config.php if you wish to run this test)' + ); + } + + $this->_inputFile = SWIFT_TMP_DIR.'/in.bin'; + file_put_contents($this->_inputFile, ''); + + $this->_outputFile = SWIFT_TMP_DIR.'/out.bin'; + file_put_contents($this->_outputFile, ''); + + $this->_encoder = $this->_createEncoder(); + } + + public function tearDown() + { + unlink($this->_inputFile); + unlink($this->_outputFile); + } + + public function testBase64EncodedLineLengthNeverExceeds76CharactersEvenIfArgsDo() + { + $this->_fillFileWithRandomBytes(1000, $this->_inputFile); + + $os = $this->_createStream($this->_inputFile); + $is = $this->_createStream($this->_outputFile); + + $this->_encoder->encodeByteStream($os, $is, 0, 80); //Exceeds 76 + + $this->assertMaxLineLength(76, $this->_outputFile, + '%s: Line length should not exceed 76 characters' + ); + } + + // -- Custom Assertions + + public function assertMaxLineLength($length, $filePath, $message = '%s') + { + $lines = file($filePath); + foreach ($lines as $line) { + $this->assertTrue((strlen(trim($line)) <= 76), $message); + } + } + + // -- Creation Methods + + private function _fillFileWithRandomBytes($byteCount, $file) + { + // I was going to use dd with if=/dev/random but this way seems more + // cross platform even if a hella expensive!! + + file_put_contents($file, ''); + $fp = fopen($file, 'wb'); + for ($i = 0; $i < $byteCount; ++$i) { + $byteVal = rand(0, 255); + fwrite($fp, pack('i', $byteVal)); + } + fclose($fp); + } + + private function _createEncoder() + { + return new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + } + + private function _createStream($file) + { + return new Swift_ByteStream_FileByteStream($file, true); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/fixtures/EsmtpTransportFixture.php b/vendor/swiftmailer/swiftmailer/tests/fixtures/EsmtpTransportFixture.php new file mode 100644 index 00000000..d56d88d3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/fixtures/EsmtpTransportFixture.php @@ -0,0 +1,10 @@ +level = $level; + $this->string = $string; + $this->contentType = $contentType; + } + + public function getNestingLevel() + { + return $this->level; + } + + public function toString() + { + return $this->string; + } + + public function getContentType() + { + return $this->contentType; + } + + // These methods are here to account for the implemented interfaces + public function getId() {} + public function getHeaders() {} + public function getBody() {} + public function setBody($body, $contentType = null) {} + public function toByteStream(Swift_InputByteStream $is) {} + public function charsetChanged($charset) {} + public function encoderChanged(Swift_Mime_ContentEncoder $encoder) {} + public function getChildren() {} + public function setChildren(array $children) {} +} diff --git a/vendor/swiftmailer/swiftmailer/tests/smoke.conf.php.default b/vendor/swiftmailer/swiftmailer/tests/smoke.conf.php.default new file mode 100644 index 00000000..0de2763f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/smoke.conf.php.default @@ -0,0 +1,63 @@ +_attFile = __DIR__.'/../../../_samples/files/textfile.zip'; + } + + public function testAttachmentSending() + { + $mailer = $this->_getMailer(); + $message = Swift_Message::newInstance() + ->setSubject('[Swift Mailer] AttachmentSmokeTest') + ->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Swift Mailer')) + ->setTo(SWIFT_SMOKE_EMAIL_ADDRESS) + ->setBody('This message should contain an attached ZIP file (named "textfile.zip").'.PHP_EOL. + 'When unzipped, the archive should produce a text file which reads:'.PHP_EOL. + '"This is part of a Swift Mailer v4 smoke test."' + ) + ->attach(Swift_Attachment::fromPath($this->_attFile)) + ; + $this->assertEquals(1, $mailer->send($message), + '%s: The smoke test should send a single message' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/BasicSmokeTest.php b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/BasicSmokeTest.php new file mode 100644 index 00000000..c7501d46 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/BasicSmokeTest.php @@ -0,0 +1,23 @@ +_getMailer(); + $message = Swift_Message::newInstance() + ->setSubject('[Swift Mailer] BasicSmokeTest') + ->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Swift Mailer')) + ->setTo(SWIFT_SMOKE_EMAIL_ADDRESS) + ->setBody('One, two, three, four, five...'.PHP_EOL. + 'six, seven, eight...' + ) + ; + $this->assertEquals(1, $mailer->send($message), + '%s: The smoke test should send a single message' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/HtmlWithAttachmentSmokeTest.php b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/HtmlWithAttachmentSmokeTest.php new file mode 100644 index 00000000..a589752b --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/HtmlWithAttachmentSmokeTest.php @@ -0,0 +1,29 @@ +_attFile = __DIR__.'/../../../_samples/files/textfile.zip'; + } + + public function testAttachmentSending() + { + $mailer = $this->_getMailer(); + $message = Swift_Message::newInstance('[Swift Mailer] HtmlWithAttachmentSmokeTest') + ->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Swift Mailer')) + ->setTo(SWIFT_SMOKE_EMAIL_ADDRESS) + ->attach(Swift_Attachment::fromPath($this->_attFile)) + ->setBody('

This HTML-formatted message should contain an attached ZIP file (named "textfile.zip").'.PHP_EOL. + 'When unzipped, the archive should produce a text file which reads:

'.PHP_EOL. + '

This is part of a Swift Mailer v4 smoke test.

', 'text/html' + ) + ; + $this->assertEquals(1, $mailer->send($message), + '%s: The smoke test should send a single message' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/InternationalSmokeTest.php b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/InternationalSmokeTest.php new file mode 100644 index 00000000..e7c695e4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/smoke/Swift/Smoke/InternationalSmokeTest.php @@ -0,0 +1,37 @@ +_attFile = __DIR__.'/../../../_samples/files/textfile.zip'; + } + + public function testAttachmentSending() + { + $mailer = $this->_getMailer(); + $message = Swift_Message::newInstance() + ->setCharset('utf-8') + ->setSubject('[Swift Mailer] InternationalSmokeTest (διεθνής)') + ->setFrom(array(SWIFT_SMOKE_EMAIL_ADDRESS => 'Χριστοφορου (Swift Mailer)')) + ->setTo(SWIFT_SMOKE_EMAIL_ADDRESS) + ->setBody('This message should contain an attached ZIP file (named "κείμενο, εδάφιο, θέμα.zip").'.PHP_EOL. + 'When unzipped, the archive should produce a text file which reads:'.PHP_EOL. + '"This is part of a Swift Mailer v4 smoke test."'.PHP_EOL. + PHP_EOL. + 'Following is some arbitrary Greek text:'.PHP_EOL. + 'Δεν βρέθηκαν λέξεις.' + ) + ->attach(Swift_Attachment::fromPath($this->_attFile) + ->setContentType('application/zip') + ->setFilename('κείμενο, εδάφιο, θέμα.zip') + ) + ; + $this->assertEquals(1, $mailer->send($message), + '%s: The smoke test should send a single message' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/ByteStream/ArrayByteStreamTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/ByteStream/ArrayByteStreamTest.php new file mode 100644 index 00000000..01934849 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/ByteStream/ArrayByteStreamTest.php @@ -0,0 +1,204 @@ +_createArrayStream($input); + $output = array(); + while (false !== $bytes = $bs->read(1)) { + $output[] = $bytes; + } + $this->assertEquals($input, $output, + '%s: Bytes read from stream should be the same as bytes in constructor' + ); + } + + public function testReadingMultipleBytesFromBaseInput() + { + $input = array('a', 'b', 'c', 'd'); + $bs = $this->_createArrayStream($input); + $output = array(); + while (false !== $bytes = $bs->read(2)) { + $output[] = $bytes; + } + $this->assertEquals(array('ab', 'cd'), $output, + '%s: Bytes read from stream should be in pairs' + ); + } + + public function testReadingOddOffsetOnLastByte() + { + $input = array('a', 'b', 'c', 'd', 'e'); + $bs = $this->_createArrayStream($input); + $output = array(); + while (false !== $bytes = $bs->read(2)) { + $output[] = $bytes; + } + $this->assertEquals(array('ab', 'cd', 'e'), $output, + '%s: Bytes read from stream should be in pairs except final read' + ); + } + + public function testSettingPointerPartway() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + $bs->setReadPointer(1); + $this->assertEquals('b', $bs->read(1), + '%s: Byte should be second byte since pointer as at offset 1' + ); + } + + public function testResettingPointerAfterExhaustion() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + + while (false !== $bs->read(1)); + + $bs->setReadPointer(0); + $this->assertEquals('a', $bs->read(1), + '%s: Byte should be first byte since pointer as at offset 0' + ); + } + + public function testPointerNeverSetsBelowZero() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + + $bs->setReadPointer(-1); + $this->assertEquals('a', $bs->read(1), + '%s: Byte should be first byte since pointer should be at offset 0' + ); + } + + public function testPointerNeverSetsAboveStackSize() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + + $bs->setReadPointer(3); + $this->assertSame(false, $bs->read(1), + '%s: Stream should be at end and thus return false' + ); + } + + public function testBytesCanBeWrittenToStream() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + + $bs->write('de'); + + $output = array(); + while (false !== $bytes = $bs->read(1)) { + $output[] = $bytes; + } + $this->assertEquals(array('a', 'b', 'c', 'd', 'e'), $output, + '%s: Bytes read from stream should be from initial stack + written' + ); + } + + public function testContentsCanBeFlushed() + { + $input = array('a', 'b', 'c'); + $bs = $this->_createArrayStream($input); + + $bs->flushBuffers(); + + $this->assertSame(false, $bs->read(1), + '%s: Contents have been flushed so read() should return false' + ); + } + + public function testConstructorCanTakeStringArgument() + { + $bs = $this->_createArrayStream('abc'); + $output = array(); + while (false !== $bytes = $bs->read(1)) { + $output[] = $bytes; + } + $this->assertEquals(array('a', 'b', 'c'), $output, + '%s: Bytes read from stream should be the same as bytes in constructor' + ); + } + + public function testBindingOtherStreamsMirrorsWriteOperations() + { + $bs = $this->_createArrayStream(''); + $is1 = $this->getMock('Swift_InputByteStream'); + $is2 = $this->getMock('Swift_InputByteStream'); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->at(0)) + ->method('write') + ->with('x'); + $is2->expects($this->at(1)) + ->method('write') + ->with('y'); + + $bs->bind($is1); + $bs->bind($is2); + + $bs->write('x'); + $bs->write('y'); + } + + public function testBindingOtherStreamsMirrorsFlushOperations() + { + $bs = $this->_createArrayStream(''); + $is1 = $this->getMock('Swift_InputByteStream'); + $is2 = $this->getMock('Swift_InputByteStream'); + + $is1->expects($this->once()) + ->method('flushBuffers'); + $is2->expects($this->once()) + ->method('flushBuffers'); + + $bs->bind($is1); + $bs->bind($is2); + + $bs->flushBuffers(); + } + + public function testUnbindingStreamPreventsFurtherWrites() + { + $bs = $this->_createArrayStream(''); + $is1 = $this->getMock('Swift_InputByteStream'); + $is2 = $this->getMock('Swift_InputByteStream'); + + $is1->expects($this->at(0)) + ->method('write') + ->with('x'); + $is1->expects($this->at(1)) + ->method('write') + ->with('y'); + $is2->expects($this->once()) + ->method('write') + ->with('x'); + + $bs->bind($is1); + $bs->bind($is2); + + $bs->write('x'); + + $bs->unbind($is2); + + $bs->write('y'); + } + + // -- Creation Methods + + private function _createArrayStream($input) + { + return new Swift_ByteStream_ArrayByteStream($input); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/GenericFixedWidthReaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/GenericFixedWidthReaderTest.php new file mode 100644 index 00000000..3f7a46cf --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/GenericFixedWidthReaderTest.php @@ -0,0 +1,43 @@ +assertSame(1, $reader->getInitialByteSize()); + + $reader = new Swift_CharacterReader_GenericFixedWidthReader(4); + $this->assertSame(4, $reader->getInitialByteSize()); + } + + public function testValidationValueIsBasedOnOctetCount() + { + $reader = new Swift_CharacterReader_GenericFixedWidthReader(4); + + $this->assertSame( + 1, $reader->validateByteSequence(array(0x01, 0x02, 0x03), 3) + ); //3 octets + + $this->assertSame( + 2, $reader->validateByteSequence(array(0x01, 0x0A), 2) + ); //2 octets + + $this->assertSame( + 3, $reader->validateByteSequence(array(0xFE), 1) + ); //1 octet + + $this->assertSame( + 0, $reader->validateByteSequence(array(0xFE, 0x03, 0x67, 0x9A), 4) + ); //All 4 octets + } + + public function testValidationFailsIfTooManyOctets() + { + $reader = new Swift_CharacterReader_GenericFixedWidthReader(6); + + $this->assertSame(-1, $reader->validateByteSequence( + array(0xFE, 0x03, 0x67, 0x9A, 0x10, 0x09, 0x85), 7 + )); //7 octets + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/UsAsciiReaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/UsAsciiReaderTest.php new file mode 100644 index 00000000..41f8f703 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/UsAsciiReaderTest.php @@ -0,0 +1,52 @@ +read($size); ) { + $c .= $bytes; + $size = $v->validateCharacter($c); + if (-1 == $size) { + throw new Exception( ... invalid char .. ); + } elseif (0 == $size) { + return $c; //next character in $os + } + } + + */ + + private $_reader; + + public function setUp() + { + $this->_reader = new Swift_CharacterReader_UsAsciiReader(); + } + + public function testAllValidAsciiCharactersReturnZero() + { + for ($ordinal = 0x00; $ordinal <= 0x7F; ++$ordinal) { + $this->assertSame( + 0, $this->_reader->validateByteSequence(array($ordinal), 1) + ); + } + } + + public function testMultipleBytesAreInvalid() + { + for ($ordinal = 0x00; $ordinal <= 0x7F; $ordinal += 2) { + $this->assertSame( + -1, $this->_reader->validateByteSequence(array($ordinal, $ordinal + 1), 2) + ); + } + } + + public function testBytesAboveAsciiRangeAreInvalid() + { + for ($ordinal = 0x80; $ordinal <= 0xFF; ++$ordinal) { + $this->assertSame( + -1, $this->_reader->validateByteSequence(array($ordinal), 1) + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/Utf8ReaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/Utf8ReaderTest.php new file mode 100644 index 00000000..9e9e0a5d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterReader/Utf8ReaderTest.php @@ -0,0 +1,65 @@ +_reader = new Swift_CharacterReader_Utf8Reader(); + } + + public function testLeading7BitOctetCausesReturnZero() + { + for ($ordinal = 0x00; $ordinal <= 0x7F; ++$ordinal) { + $this->assertSame( + 0, $this->_reader->validateByteSequence(array($ordinal), 1) + ); + } + } + + public function testLeadingByteOf2OctetCharCausesReturn1() + { + for ($octet = 0xC0; $octet <= 0xDF; ++$octet) { + $this->assertSame( + 1, $this->_reader->validateByteSequence(array($octet), 1) + ); + } + } + + public function testLeadingByteOf3OctetCharCausesReturn2() + { + for ($octet = 0xE0; $octet <= 0xEF; ++$octet) { + $this->assertSame( + 2, $this->_reader->validateByteSequence(array($octet), 1) + ); + } + } + + public function testLeadingByteOf4OctetCharCausesReturn3() + { + for ($octet = 0xF0; $octet <= 0xF7; ++$octet) { + $this->assertSame( + 3, $this->_reader->validateByteSequence(array($octet), 1) + ); + } + } + + public function testLeadingByteOf5OctetCharCausesReturn4() + { + for ($octet = 0xF8; $octet <= 0xFB; ++$octet) { + $this->assertSame( + 4, $this->_reader->validateByteSequence(array($octet),1) + ); + } + } + + public function testLeadingByteOf6OctetCharCausesReturn5() + { + for ($octet = 0xFC; $octet <= 0xFD; ++$octet) { + $this->assertSame( + 5, $this->_reader->validateByteSequence(array($octet),1) + ); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterStream/ArrayCharacterStreamTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterStream/ArrayCharacterStreamTest.php new file mode 100644 index 00000000..e22e496f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/CharacterStream/ArrayCharacterStreamTest.php @@ -0,0 +1,360 @@ +_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importString(pack('C*', + 0xD0, 0x94, + 0xD0, 0xB6, + 0xD0, 0xBE, + 0xD1, 0x8D, + 0xD0, 0xBB, + 0xD0, 0xB0 + ) + ); + } + + public function testCharactersWrittenUseValidator() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $stream->write(pack('C*', + 0xD0, 0xBB, + 0xD1, 0x8E, + 0xD0, 0xB1, + 0xD1, 0x8B, + 0xD1, 0x85 + ) + ); + } + + public function testReadCharactersAreInTact() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + //String + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + //Stream + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $stream->write(pack('C*', + 0xD0, 0xBB, + 0xD1, 0x8E, + 0xD0, 0xB1, + 0xD1, 0x8B, + 0xD1, 0x85 + ) + ); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0x94), $stream->read(1)); + $this->assertIdenticalBinary( + pack('C*', 0xD0, 0xB6, 0xD0, 0xBE), $stream->read(2) + ); + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xBB), $stream->read(1)); + $this->assertIdenticalBinary( + pack('C*', 0xD1, 0x8E, 0xD0, 0xB1, 0xD1, 0x8B), $stream->read(3) + ); + $this->assertIdenticalBinary(pack('C*', 0xD1, 0x85), $stream->read(1)); + + $this->assertSame(false, $stream->read(1)); + } + + public function testCharactersCanBeReadAsByteArrays() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + //String + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + //Stream + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $stream->write(pack('C*', + 0xD0, 0xBB, + 0xD1, 0x8E, + 0xD0, 0xB1, + 0xD1, 0x8B, + 0xD1, 0x85 + ) + ); + + $this->assertEquals(array(0xD0, 0x94), $stream->readBytes(1)); + $this->assertEquals(array(0xD0, 0xB6, 0xD0, 0xBE), $stream->readBytes(2)); + $this->assertEquals(array(0xD0, 0xBB), $stream->readBytes(1)); + $this->assertEquals( + array(0xD1, 0x8E, 0xD0, 0xB1, 0xD1, 0x8B), $stream->readBytes(3) + ); + $this->assertEquals(array(0xD1, 0x85), $stream->readBytes(1)); + + $this->assertSame(false, $stream->readBytes(1)); + } + + public function testRequestingLargeCharCountPastEndOfStream() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE), + $stream->read(100) + ); + + $this->assertSame(false, $stream->read(1)); + } + + public function testRequestingByteArrayCountPastEndOfStream() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $this->assertEquals(array(0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE), + $stream->readBytes(100) + ); + + $this->assertSame(false, $stream->readBytes(1)); + } + + public function testPointerOffsetCanBeSet() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0x94), $stream->read(1)); + + $stream->setPointer(0); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0x94), $stream->read(1)); + + $stream->setPointer(2); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xBE), $stream->read(1)); + } + + public function testContentsCanBeFlushed() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importString(pack('C*', 0xD0, 0x94, 0xD0, 0xB6, 0xD0, 0xBE)); + + $stream->flushContents(); + + $this->assertSame(false, $stream->read(1)); + } + + public function testByteStreamCanBeImportingUsesValidator() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + $os = $this->_getByteStream(); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $os->shouldReceive('setReadPointer') + ->between(0, 1) + ->with(0); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0x94)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xB6)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xBE)); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importByteStream($os); + } + + public function testImportingStreamProducesCorrectCharArray() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + $os = $this->_getByteStream(); + + $stream = new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8'); + + $os->shouldReceive('setReadPointer') + ->between(0, 1) + ->with(0); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0x94)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xB6)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xD0)); + $os->shouldReceive('read')->once()->andReturn(pack('C*', 0xBE)); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0), 1)->andReturn(1); + + $stream->importByteStream($os); + + $this->assertIdenticalBinary(pack('C*', 0xD0, 0x94), $stream->read(1)); + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xB6), $stream->read(1)); + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xBE), $stream->read(1)); + + $this->assertSame(false, $stream->read(1)); + } + + public function testAlgorithmWithFixedWidthCharsets() + { + $reader = $this->_getReader(); + $factory = $this->_getFactory($reader); + + $reader->shouldReceive('getInitialByteSize') + ->zeroOrMoreTimes() + ->andReturn(2); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD1, 0x8D), 2); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0, 0xBB), 2); + $reader->shouldReceive('validateByteSequence')->once()->with(array(0xD0, 0xB0), 2); + + $stream = new Swift_CharacterStream_ArrayCharacterStream( + $factory, 'utf-8' + ); + $stream->importString(pack('C*', 0xD1, 0x8D, 0xD0, 0xBB, 0xD0, 0xB0)); + + $this->assertIdenticalBinary(pack('C*', 0xD1, 0x8D), $stream->read(1)); + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xBB), $stream->read(1)); + $this->assertIdenticalBinary(pack('C*', 0xD0, 0xB0), $stream->read(1)); + + $this->assertSame(false, $stream->read(1)); + } + + // -- Creation methods + + private function _getReader() + { + return $this->getMockery('Swift_CharacterReader'); + } + + private function _getFactory($reader) + { + $factory = $this->getMockery('Swift_CharacterReaderFactory'); + $factory->shouldReceive('getReaderFor') + ->zeroOrMoreTimes() + ->with('utf-8') + ->andReturn($reader); + + return $factory; + } + + private function _getByteStream() + { + return $this->getMockery('Swift_OutputByteStream'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/DependencyContainerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/DependencyContainerTest.php new file mode 100644 index 00000000..bc4a79bc --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/DependencyContainerTest.php @@ -0,0 +1,174 @@ +arg1 = $arg1; + $this->arg2 = $arg2; + } +} + +class Swift_DependencyContainerTest extends \PHPUnit_Framework_TestCase +{ + private $_container; + + public function setUp() + { + $this->_container = new Swift_DependencyContainer(); + } + + public function testRegisterAndLookupValue() + { + $this->_container->register('foo')->asValue('bar'); + $this->assertEquals('bar', $this->_container->lookup('foo')); + } + + public function testHasReturnsTrueForRegisteredValue() + { + $this->_container->register('foo')->asValue('bar'); + $this->assertTrue($this->_container->has('foo')); + } + + public function testHasReturnsFalseForUnregisteredValue() + { + $this->assertFalse($this->_container->has('foo')); + } + + public function testRegisterAndLookupNewInstance() + { + $this->_container->register('one')->asNewInstanceOf('One'); + $this->assertInstanceof('One', $this->_container->lookup('one')); + } + + public function testHasReturnsTrueForRegisteredInstance() + { + $this->_container->register('one')->asNewInstanceOf('One'); + $this->assertTrue($this->_container->has('one')); + } + + public function testNewInstanceIsAlwaysNew() + { + $this->_container->register('one')->asNewInstanceOf('One'); + $a = $this->_container->lookup('one'); + $b = $this->_container->lookup('one'); + $this->assertEquals($a, $b); + } + + public function testRegisterAndLookupSharedInstance() + { + $this->_container->register('one')->asSharedInstanceOf('One'); + $this->assertInstanceof('One', $this->_container->lookup('one')); + } + + public function testHasReturnsTrueForSharedInstance() + { + $this->_container->register('one')->asSharedInstanceOf('One'); + $this->assertTrue($this->_container->has('one')); + } + + public function testMultipleSharedInstancesAreSameInstance() + { + $this->_container->register('one')->asSharedInstanceOf('One'); + $a = $this->_container->lookup('one'); + $b = $this->_container->lookup('one'); + $this->assertEquals($a, $b); + } + + public function testNewInstanceWithDependencies() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('one')->asNewInstanceOf('One') + ->withDependencies(array('foo')); + $obj = $this->_container->lookup('one'); + $this->assertSame('FOO', $obj->arg1); + } + + public function testNewInstanceWithMultipleDependencies() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('bar')->asValue(42); + $this->_container->register('one')->asNewInstanceOf('One') + ->withDependencies(array('foo', 'bar')); + $obj = $this->_container->lookup('one'); + $this->assertSame('FOO', $obj->arg1); + $this->assertSame(42, $obj->arg2); + } + + public function testNewInstanceWithInjectedObjects() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('one')->asNewInstanceOf('One'); + $this->_container->register('two')->asNewInstanceOf('One') + ->withDependencies(array('one', 'foo')); + $obj = $this->_container->lookup('two'); + $this->assertEquals($this->_container->lookup('one'), $obj->arg1); + $this->assertSame('FOO', $obj->arg2); + } + + public function testNewInstanceWithAddConstructorValue() + { + $this->_container->register('one')->asNewInstanceOf('One') + ->addConstructorValue('x') + ->addConstructorValue(99); + $obj = $this->_container->lookup('one'); + $this->assertSame('x', $obj->arg1); + $this->assertSame(99, $obj->arg2); + } + + public function testNewInstanceWithAddConstructorLookup() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('bar')->asValue(42); + $this->_container->register('one')->asNewInstanceOf('One') + ->addConstructorLookup('foo') + ->addConstructorLookup('bar'); + + $obj = $this->_container->lookup('one'); + $this->assertSame('FOO', $obj->arg1); + $this->assertSame(42, $obj->arg2); + } + + public function testResolvedDependenciesCanBeLookedUp() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('one')->asNewInstanceOf('One'); + $this->_container->register('two')->asNewInstanceOf('One') + ->withDependencies(array('one', 'foo')); + $deps = $this->_container->createDependenciesFor('two'); + $this->assertEquals( + array($this->_container->lookup('one'), 'FOO'), $deps + ); + } + + public function testArrayOfDependenciesCanBeSpecified() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('one')->asNewInstanceOf('One'); + $this->_container->register('two')->asNewInstanceOf('One') + ->withDependencies(array(array('one', 'foo'), 'foo')); + + $obj = $this->_container->lookup('two'); + $this->assertEquals(array($this->_container->lookup('one'), 'FOO'), $obj->arg1); + $this->assertSame('FOO', $obj->arg2); + } + + public function testAliasCanBeSet() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('bar')->asAliasOf('foo'); + + $this->assertSame('FOO', $this->_container->lookup('bar')); + } + + public function testAliasOfAliasCanBeSet() + { + $this->_container->register('foo')->asValue('FOO'); + $this->_container->register('bar')->asAliasOf('foo'); + $this->_container->register('zip')->asAliasOf('bar'); + $this->_container->register('button')->asAliasOf('zip'); + + $this->assertSame('FOO', $this->_container->lookup('button')); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Base64EncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Base64EncoderTest.php new file mode 100644 index 00000000..be588c1d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Base64EncoderTest.php @@ -0,0 +1,173 @@ +_encoder = new Swift_Encoder_Base64Encoder(); + } + + /* + There's really no point in testing the entire base64 encoding to the + level QP encoding has been tested. base64_encode() has been in PHP for + years. + */ + + public function testInputOutputRatioIs3to4Bytes() + { + /* + RFC 2045, 6.8 + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + */ + + $this->assertEquals( + 'MTIz', $this->_encoder->encodeString('123'), + '%s: 3 bytes of input should yield 4 bytes of output' + ); + $this->assertEquals( + 'MTIzNDU2', $this->_encoder->encodeString('123456'), + '%s: 6 bytes in input should yield 8 bytes of output' + ); + $this->assertEquals( + 'MTIzNDU2Nzg5', $this->_encoder->encodeString('123456789'), + '%s: 9 bytes in input should yield 12 bytes of output' + ); + } + + public function testPadLength() + { + /* + RFC 2045, 6.8 + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a body. When fewer than 24 input bits + are available in an input group, zero bits are added (on the right) + to form an integral number of 6-bit groups. Padding at the end of + the data is performed using the "=" character. Since all base64 + input is an integral number of octets, only the following cases can + arise: (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded output will be + an integral multiple of 4 characters with no "=" padding, (2) the + final quantum of encoding input is exactly 8 bits; here, the final + unit of encoded output will be two characters followed by two "=" + padding characters, or (3) the final quantum of encoding input is + exactly 16 bits; here, the final unit of encoded output will be three + characters followed by one "=" padding character. + */ + + for ($i = 0; $i < 30; ++$i) { + $input = pack('C', rand(0, 255)); + $this->assertRegExp( + '~^[a-zA-Z0-9/\+]{2}==$~', $this->_encoder->encodeString($input), + '%s: A single byte should have 2 bytes of padding' + ); + } + + for ($i = 0; $i < 30; ++$i) { + $input = pack('C*', rand(0, 255), rand(0, 255)); + $this->assertRegExp( + '~^[a-zA-Z0-9/\+]{3}=$~', $this->_encoder->encodeString($input), + '%s: Two bytes should have 1 byte of padding' + ); + } + + for ($i = 0; $i < 30; ++$i) { + $input = pack('C*', rand(0, 255), rand(0, 255), rand(0, 255)); + $this->assertRegExp( + '~^[a-zA-Z0-9/\+]{4}$~', $this->_encoder->encodeString($input), + '%s: Three bytes should have no padding' + ); + } + } + + public function testMaximumLineLengthIs76Characters() + { + /* + The encoded output stream must be represented in lines of no more + than 76 characters each. All line breaks or other characters not + found in Table 1 must be ignored by decoding software. + */ + + $input = + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + + $output = + 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQk'.//38 + 'NERUZHSElKS0xNTk9QUVJTVFVWV1hZWjEyMzQ1'."\r\n".//76 * + 'Njc4OTBhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3'.//38 + 'h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFla'."\r\n".//76 * + 'MTIzNDU2Nzg5MEFCQ0RFRkdISUpLTE1OT1BRUl'.//38 + 'NUVVZXWFla'; //48 + + $this->assertEquals( + $output, $this->_encoder->encodeString($input), + '%s: Lines should be no more than 76 characters' + ); + } + + public function testMaximumLineLengthCanBeSpecified() + { + $input = + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + + $output = + 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQk'.//38 + 'NERUZHSElKS0'."\r\n".//50 * + 'xNTk9QUVJTVFVWV1hZWjEyMzQ1Njc4OTBhYmNk'.//38 + 'ZWZnaGlqa2xt'."\r\n".//50 * + 'bm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1'.//38 + 'BRUlNUVVZXWF'."\r\n".//50 * + 'laMTIzNDU2Nzg5MEFCQ0RFRkdISUpLTE1OT1BR'.//38 + 'UlNUVVZXWFla'; //50 * + + $this->assertEquals( + $output, $this->_encoder->encodeString($input, 0, 50), + '%s: Lines should be no more than 100 characters' + ); + } + + public function testFirstLineLengthCanBeDifferent() + { + $input = + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'abcdefghijklmnopqrstuvwxyz'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + '1234567890'. + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + + $output = + 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQk'.//38 + 'NERUZHSElKS0xNTk9QU'."\r\n".//57 * + 'VJTVFVWV1hZWjEyMzQ1Njc4OTBhYmNkZWZnaGl'.//38 + 'qa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLT'."\r\n".//76 * + 'E1OT1BRUlNUVVZXWFlaMTIzNDU2Nzg5MEFCQ0R'.//38 + 'FRkdISUpLTE1OT1BRUlNUVVZXWFla'; //67 + + $this->assertEquals( + $output, $this->_encoder->encodeString($input, 19), + '%s: First line offset is 19 so first line should be 57 chars long' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/QpEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/QpEncoderTest.php new file mode 100644 index 00000000..adf485d7 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/QpEncoderTest.php @@ -0,0 +1,381 @@ +_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($char); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->atLeast()->times(1) + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + + $this->assertIdenticalBinary($char, $encoder->encodeString($char)); + } + } + + public function testWhiteSpaceAtLineEndingIsEncoded() + { + /* -- RFC 2045, 6.7 -- + (3) (White Space) Octets with values of 9 and 32 MAY be + represented as US-ASCII TAB (HT) and SPACE characters, + respectively, but MUST NOT be so represented at the end + of an encoded line. Any TAB (HT) or SPACE characters + on an encoded line MUST thus be followed on that line + by a printable character. In particular, an "=" at the + end of an encoded line, indicating a soft line break + (see rule #5) may follow one or more TAB (HT) or SPACE + characters. It follows that an octet with decimal + value 9 or 32 appearing at the end of an encoded line + must be represented according to Rule #1. This rule is + necessary because some MTAs (Message Transport Agents, + programs which transport messages from one user to + another, or perform a portion of such transfers) are + known to pad lines of text with SPACEs, and others are + known to remove "white space" characters from the end + of a line. Therefore, when decoding a Quoted-Printable + body, any trailing white space on a line must be + deleted, as it will necessarily have been added by + intermediate transport agents. + */ + + $HT = chr(0x09); //9 + $SPACE = chr(0x20); //32 + + //HT + $string = 'a'.$HT.$HT."\r\n".'b'; + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x09)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x09)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals( + 'a'.$HT.'=09'."\r\n".'b', + $encoder->encodeString($string) + ); + + //SPACE + $string = 'a'.$SPACE.$SPACE."\r\n".'b'; + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x20)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x20)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals( + 'a'.$SPACE.'=20'."\r\n".'b', + $encoder->encodeString($string) + ); + } + + public function testCRLFIsLeftAlone() + { + /* + (4) (Line Breaks) A line break in a text body, represented + as a CRLF sequence in the text canonical form, must be + represented by a (RFC 822) line break, which is also a + CRLF sequence, in the Quoted-Printable encoding. Since + the canonical representation of media types other than + text do not generally include the representation of + line breaks as CRLF sequences, no hard line breaks + (i.e. line breaks that are intended to be meaningful + and to be displayed to the user) can occur in the + quoted-printable encoding of such types. Sequences + like "=0D", "=0A", "=0A=0D" and "=0D=0A" will routinely + appear in non-text data represented in quoted- + printable, of course. + + Note that many implementations may elect to encode the + local representation of various content types directly + rather than converting to canonical form first, + encoding, and then converting back to local + representation. In particular, this may apply to plain + text material on systems that use newline conventions + other than a CRLF terminator sequence. Such an + implementation optimization is permissible, but only + when the combined canonicalization-encoding step is + equivalent to performing the three steps separately. + */ + + $string = 'a'."\r\n".'b'."\r\n".'c'."\r\n"; + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('c'))); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes')->once()->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals($string, $encoder->encodeString($string)); + } + + public function testLinesLongerThan76CharactersAreSoftBroken() + { + /* + (5) (Soft Line Breaks) The Quoted-Printable encoding + REQUIRES that encoded lines be no more than 76 + characters long. If longer lines are to be encoded + with the Quoted-Printable encoding, "soft" line breaks + must be used. An equal sign as the last character on a + encoded line indicates such a non-significant ("soft") + line break in the encoded text. + */ + + $input = str_repeat('a', 140); + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($input); + + $output = ''; + for ($i = 0; $i < 140; ++$i) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + + if (75 == $i) { + $output .= "=\r\n"; + } + $output .= 'a'; + } + + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals($output, $encoder->encodeString($input)); + } + + public function testMaxLineLengthCanBeSpecified() + { + $input = str_repeat('a', 100); + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($input); + + $output = ''; + for ($i = 0; $i < 100; ++$i) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + + if (53 == $i) { + $output .= "=\r\n"; + } + $output .= 'a'; + } + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals($output, $encoder->encodeString($input, 0, 54)); + } + + public function testBytesBelowPermittedRangeAreEncoded() + { + /* + According to Rule (1 & 2) + */ + + foreach (range(0, 32) as $ordinal) { + $char = chr($ordinal); + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($char); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->atLeast()->times(1) + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + + $this->assertEquals( + sprintf('=%02X', $ordinal), $encoder->encodeString($char) + ); + } + } + + public function testDecimalByte61IsEncoded() + { + /* + According to Rule (1 & 2) + */ + + $char = '='; + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($char); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(61)); + $charStream->shouldReceive('readBytes') + ->atLeast()->times(1) + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + + $this->assertEquals('=3D', $encoder->encodeString('=')); + } + + public function testBytesAbovePermittedRangeAreEncoded() + { + /* + According to Rule (1 & 2) + */ + + foreach (range(127, 255) as $ordinal) { + $char = chr($ordinal); + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($char); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->atLeast()->times(1) + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + + $this->assertEquals( + sprintf('=%02X', $ordinal), $encoder->encodeString($char) + ); + } + } + + public function testFirstLineLengthCanBeDifferent() + { + $input = str_repeat('a', 140); + + $charStream = $this->_createCharStream(); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($input); + + $output = ''; + for ($i = 0; $i < 140; ++$i) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + + if (53 == $i || 53 + 75 == $i) { + $output .= "=\r\n"; + } + $output .= 'a'; + } + + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(false); + + $encoder = new Swift_Encoder_QpEncoder($charStream); + $this->assertEquals( + $output, $encoder->encodeString($input, 22), + '%s: First line should start at offset 22 so can only have max length 54' + ); + } + + // -- Creation methods + + private function _createCharStream() + { + return $this->getMockery('Swift_CharacterStream')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Rfc2231EncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Rfc2231EncoderTest.php new file mode 100644 index 00000000..28eae6f8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/Rfc2231EncoderTest.php @@ -0,0 +1,141 @@ +getMockery('Swift_CharacterStream'); + + $string = ''; + foreach (range(0x00, 0x7F) as $octet) { + $char = pack('C', $octet); + $string .= $char; + $charStream->shouldReceive('read') + ->once() + ->andReturn($char); + } + + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + $charStream->shouldReceive('read') + ->atLeast()->times(1) + ->andReturn(false); + + $encoder = new Swift_Encoder_Rfc2231Encoder($charStream); + $encoded = $encoder->encodeString($string); + + foreach (explode("\r\n", $encoded) as $line) { + $this->assertRegExp($this->_rfc2045Token, $line, + '%s: Encoder should always return a valid RFC 2045 token.'); + } + } + + public function testEncodingNonAsciiCharactersProducesValidToken() + { + $charStream = $this->getMockery('Swift_CharacterStream'); + + $string = ''; + foreach (range(0x80, 0xFF) as $octet) { + $char = pack('C', $octet); + $string .= $char; + $charStream->shouldReceive('read') + ->once() + ->andReturn($char); + } + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + $charStream->shouldReceive('read') + ->atLeast()->times(1) + ->andReturn(false); + $encoder = new Swift_Encoder_Rfc2231Encoder($charStream); + + $encoded = $encoder->encodeString($string); + + foreach (explode("\r\n", $encoded) as $line) { + $this->assertRegExp($this->_rfc2045Token, $line, + '%s: Encoder should always return a valid RFC 2045 token.'); + } + } + + public function testMaximumLineLengthCanBeSet() + { + $charStream = $this->getMockery('Swift_CharacterStream'); + + $string = ''; + for ($x = 0; $x < 200; ++$x) { + $char = 'a'; + $string .= $char; + $charStream->shouldReceive('read') + ->once() + ->andReturn($char); + } + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + $charStream->shouldReceive('read') + ->atLeast()->times(1) + ->andReturn(false); + $encoder = new Swift_Encoder_Rfc2231Encoder($charStream); + + $encoded = $encoder->encodeString($string, 0, 75); + + $this->assertEquals( + str_repeat('a', 75)."\r\n". + str_repeat('a', 75)."\r\n". + str_repeat('a', 50), + $encoded, + '%s: Lines should be wrapped at each 75 characters' + ); + } + + public function testFirstLineCanHaveShorterLength() + { + $charStream = $this->getMockery('Swift_CharacterStream'); + + $string = ''; + for ($x = 0; $x < 200; ++$x) { + $char = 'a'; + $string .= $char; + $charStream->shouldReceive('read') + ->once() + ->andReturn($char); + } + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importString') + ->once() + ->with($string); + $charStream->shouldReceive('read') + ->atLeast()->times(1) + ->andReturn(false); + $encoder = new Swift_Encoder_Rfc2231Encoder($charStream); + $encoded = $encoder->encodeString($string, 25, 75); + + $this->assertEquals( + str_repeat('a', 50)."\r\n". + str_repeat('a', 75)."\r\n". + str_repeat('a', 75), + $encoded, + '%s: First line should be 25 bytes shorter than the others.' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/CommandEventTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/CommandEventTest.php new file mode 100644 index 00000000..7e598025 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/CommandEventTest.php @@ -0,0 +1,36 @@ +_createEvent($this->_createTransport(), "FOO\r\n"); + $this->assertEquals("FOO\r\n", $evt->getCommand()); + } + + public function testSuccessCodesCanBeFetchedViaGetter() + { + $evt = $this->_createEvent($this->_createTransport(), "FOO\r\n", array(250)); + $this->assertEquals(array(250), $evt->getSuccessCodes()); + } + + public function testSourceIsBuffer() + { + $transport = $this->_createTransport(); + $evt = $this->_createEvent($transport, "FOO\r\n"); + $ref = $evt->getSource(); + $this->assertEquals($transport, $ref); + } + + // -- Creation Methods + + private function _createEvent(Swift_Transport $source, $command, $successCodes = array()) + { + return new Swift_Events_CommandEvent($source, $command, $successCodes); + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/EventObjectTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/EventObjectTest.php new file mode 100644 index 00000000..62a91be5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/EventObjectTest.php @@ -0,0 +1,34 @@ +_createEvent($source); + $ref = $evt->getSource(); + $this->assertEquals($source, $ref); + } + + public function testEventDoesNotHaveCancelledBubbleWhenNew() + { + $source = new stdClass(); + $evt = $this->_createEvent($source); + $this->assertFalse($evt->bubbleCancelled()); + } + + public function testBubbleCanBeCancelledInEvent() + { + $source = new stdClass(); + $evt = $this->_createEvent($source); + $evt->cancelBubble(); + $this->assertTrue($evt->bubbleCancelled()); + } + + // -- Creation Methods + + private function _createEvent($source) + { + return new Swift_Events_EventObject($source); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/ResponseEventTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/ResponseEventTest.php new file mode 100644 index 00000000..e0f3e362 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/ResponseEventTest.php @@ -0,0 +1,40 @@ +_createEvent($this->_createTransport(), "250 Ok\r\n", true); + $this->assertEquals("250 Ok\r\n", $evt->getResponse(), + '%s: Response should be available via getResponse()' + ); + } + + public function testResultCanBeFetchedViaGetter() + { + $evt = $this->_createEvent($this->_createTransport(), "250 Ok\r\n", false); + $this->assertFalse($evt->isValid(), + '%s: Result should be checkable via isValid()' + ); + } + + public function testSourceIsBuffer() + { + $transport = $this->_createTransport(); + $evt = $this->_createEvent($transport, "250 Ok\r\n", true); + $ref = $evt->getSource(); + $this->assertEquals($transport, $ref); + } + + // -- Creation Methods + + private function _createEvent(Swift_Transport $source, $response, $result) + { + return new Swift_Events_ResponseEvent($source, $response, $result); + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SendEventTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SendEventTest.php new file mode 100644 index 00000000..80038700 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SendEventTest.php @@ -0,0 +1,99 @@ +_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + + $ref = $evt->getMessage(); + $this->assertEquals($message, $ref, + '%s: Message should be returned from getMessage()' + ); + } + + public function testTransportCanBeFetchViaGetter() + { + $message = $this->_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + + $ref = $evt->getTransport(); + $this->assertEquals($transport, $ref, + '%s: Transport should be returned from getTransport()' + ); + } + + public function testTransportCanBeFetchViaGetSource() + { + $message = $this->_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + + $ref = $evt->getSource(); + $this->assertEquals($transport, $ref, + '%s: Transport should be returned from getSource()' + ); + } + + public function testResultCanBeSetAndGet() + { + $message = $this->_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + + $evt->setResult( + Swift_Events_SendEvent::RESULT_SUCCESS | Swift_Events_SendEvent::RESULT_TENTATIVE + ); + + $this->assertTrue((bool) ($evt->getResult() & Swift_Events_SendEvent::RESULT_SUCCESS)); + $this->assertTrue((bool) ($evt->getResult() & Swift_Events_SendEvent::RESULT_TENTATIVE)); + } + + public function testFailedRecipientsCanBeSetAndGet() + { + $message = $this->_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + + $evt->setFailedRecipients(array('foo@bar', 'zip@button')); + + $this->assertEquals(array('foo@bar', 'zip@button'), $evt->getFailedRecipients(), + '%s: FailedRecipients should be returned from getter' + ); + } + + public function testFailedRecipientsGetsPickedUpCorrectly() + { + $message = $this->_createMessage(); + $transport = $this->_createTransport(); + + $evt = $this->_createEvent($transport, $message); + $this->assertEquals(array(), $evt->getFailedRecipients()); + } + + // -- Creation Methods + + private function _createEvent(Swift_Transport $source, + Swift_Mime_Message $message) + { + return new Swift_Events_SendEvent($source, $message); + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } + + private function _createMessage() + { + return $this->getMock('Swift_Mime_Message'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SimpleEventDispatcherTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SimpleEventDispatcherTest.php new file mode 100644 index 00000000..52ae07c6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/SimpleEventDispatcherTest.php @@ -0,0 +1,135 @@ +_dispatcher = new Swift_Events_SimpleEventDispatcher(); + } + + public function testSendEventCanBeCreated() + { + $transport = $this->getMock('Swift_Transport'); + $message = $this->getMock('Swift_Mime_Message'); + $evt = $this->_dispatcher->createSendEvent($transport, $message); + $this->assertInstanceof('Swift_Events_SendEvent', $evt); + $this->assertSame($message, $evt->getMessage()); + $this->assertSame($transport, $evt->getTransport()); + } + + public function testCommandEventCanBeCreated() + { + $buf = $this->getMock('Swift_Transport'); + $evt = $this->_dispatcher->createCommandEvent($buf, "FOO\r\n", array(250)); + $this->assertInstanceof('Swift_Events_CommandEvent', $evt); + $this->assertSame($buf, $evt->getSource()); + $this->assertEquals("FOO\r\n", $evt->getCommand()); + $this->assertEquals(array(250), $evt->getSuccessCodes()); + } + + public function testResponseEventCanBeCreated() + { + $buf = $this->getMock('Swift_Transport'); + $evt = $this->_dispatcher->createResponseEvent($buf, "250 Ok\r\n", true); + $this->assertInstanceof('Swift_Events_ResponseEvent', $evt); + $this->assertSame($buf, $evt->getSource()); + $this->assertEquals("250 Ok\r\n", $evt->getResponse()); + $this->assertTrue($evt->isValid()); + } + + public function testTransportChangeEventCanBeCreated() + { + $transport = $this->getMock('Swift_Transport'); + $evt = $this->_dispatcher->createTransportChangeEvent($transport); + $this->assertInstanceof('Swift_Events_TransportChangeEvent', $evt); + $this->assertSame($transport, $evt->getSource()); + } + + public function testTransportExceptionEventCanBeCreated() + { + $transport = $this->getMock('Swift_Transport'); + $ex = new Swift_TransportException(''); + $evt = $this->_dispatcher->createTransportExceptionEvent($transport, $ex); + $this->assertInstanceof('Swift_Events_TransportExceptionEvent', $evt); + $this->assertSame($transport, $evt->getSource()); + $this->assertSame($ex, $evt->getException()); + } + + public function testListenersAreNotifiedOfDispatchedEvent() + { + $transport = $this->getMock('Swift_Transport'); + + $evt = $this->_dispatcher->createTransportChangeEvent($transport); + + $listenerA = $this->getMock('Swift_Events_TransportChangeListener'); + $listenerB = $this->getMock('Swift_Events_TransportChangeListener'); + + $this->_dispatcher->bindEventListener($listenerA); + $this->_dispatcher->bindEventListener($listenerB); + + $listenerA->expects($this->once()) + ->method('transportStarted') + ->with($evt); + $listenerB->expects($this->once()) + ->method('transportStarted') + ->with($evt); + + $this->_dispatcher->dispatchEvent($evt, 'transportStarted'); + } + + public function testListenersAreOnlyCalledIfImplementingCorrectInterface() + { + $transport = $this->getMock('Swift_Transport'); + $message = $this->getMock('Swift_Mime_Message'); + + $evt = $this->_dispatcher->createSendEvent($transport, $message); + + $targetListener = $this->getMock('Swift_Events_SendListener'); + $otherListener = $this->getMock('Swift_Events_TransportChangeListener'); + + $this->_dispatcher->bindEventListener($targetListener); + $this->_dispatcher->bindEventListener($otherListener); + + $targetListener->expects($this->once()) + ->method('sendPerformed') + ->with($evt); + $otherListener->expects($this->never()) + ->method('sendPerformed'); + + $this->_dispatcher->dispatchEvent($evt, 'sendPerformed'); + } + + public function testListenersCanCancelBubblingOfEvent() + { + $transport = $this->getMock('Swift_Transport'); + $message = $this->getMock('Swift_Mime_Message'); + + $evt = $this->_dispatcher->createSendEvent($transport, $message); + + $listenerA = $this->getMock('Swift_Events_SendListener'); + $listenerB = $this->getMock('Swift_Events_SendListener'); + + $this->_dispatcher->bindEventListener($listenerA); + $this->_dispatcher->bindEventListener($listenerB); + + $listenerA->expects($this->once()) + ->method('sendPerformed') + ->with($evt) + ->will($this->returnCallback(function ($object) { + $object->cancelBubble(true); + })); + $listenerB->expects($this->never()) + ->method('sendPerformed'); + + $this->_dispatcher->dispatchEvent($evt, 'sendPerformed'); + + $this->assertTrue($evt->bubbleCancelled()); + } + + private function _createDispatcher(array $map) + { + return new Swift_Events_SimpleEventDispatcher($map); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportChangeEventTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportChangeEventTest.php new file mode 100644 index 00000000..40bec834 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportChangeEventTest.php @@ -0,0 +1,32 @@ +_createTransport(); + $evt = $this->_createEvent($transport); + $ref = $evt->getTransport(); + $this->assertEquals($transport, $ref); + } + + public function testSourceIsTransport() + { + $transport = $this->_createTransport(); + $evt = $this->_createEvent($transport); + $ref = $evt->getSource(); + $this->assertEquals($transport, $ref); + } + + // -- Creation Methods + + private function _createEvent(Swift_Transport $source) + { + return new Swift_Events_TransportChangeEvent($source); + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportExceptionEventTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportExceptionEventTest.php new file mode 100644 index 00000000..86c636b5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Events/TransportExceptionEventTest.php @@ -0,0 +1,43 @@ +_createException(); + $transport = $this->_createTransport(); + $evt = $this->_createEvent($transport, $ex); + $ref = $evt->getException(); + $this->assertEquals($ex, $ref, + '%s: Exception should be available via getException()' + ); + } + + public function testSourceIsTransport() + { + $ex = $this->_createException(); + $transport = $this->_createTransport(); + $evt = $this->_createEvent($transport, $ex); + $ref = $evt->getSource(); + $this->assertEquals($transport, $ref, + '%s: Transport should be available via getSource()' + ); + } + + // -- Creation Methods + + private function _createEvent(Swift_Transport $transport, Swift_TransportException $ex) + { + return new Swift_Events_TransportExceptionEvent($transport, $ex); + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } + + private function _createException() + { + return new Swift_TransportException(''); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/ArrayKeyCacheTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/ArrayKeyCacheTest.php new file mode 100644 index 00000000..36512cff --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/ArrayKeyCacheTest.php @@ -0,0 +1,242 @@ +_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('test', $cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeOverwritten() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $cache->setString( + $this->_key1, 'foo', 'whatever', Swift_KeyCache::MODE_WRITE + ); + + $this->assertEquals('whatever', $cache->getString($this->_key1, 'foo')); + } + + public function testStringDataCanBeAppended() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $cache->setString( + $this->_key1, 'foo', 'ing', Swift_KeyCache::MODE_APPEND + ); + + $this->assertEquals('testing', $cache->getString($this->_key1, 'foo')); + } + + public function testHasKeyReturnValue() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + + $this->assertTrue($cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyIsWellPartitioned() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $cache->setString( + $this->_key2, 'foo', 'ing', Swift_KeyCache::MODE_WRITE + ); + + $this->assertEquals('test', $cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $cache->getString($this->_key2, 'foo')); + } + + public function testItemKeyIsWellPartitioned() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $cache->setString( + $this->_key1, 'bar', 'ing', Swift_KeyCache::MODE_WRITE + ); + + $this->assertEquals('test', $cache->getString($this->_key1, 'foo')); + $this->assertEquals('ing', $cache->getString($this->_key1, 'bar')); + } + + public function testByteStreamCanBeImported() + { + $os = $this->_createOutputStream(); + $os->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('abc')); + $os->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('def')); + $os->expects($this->at(2)) + ->method('read') + ->will($this->returnValue(false)); + + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + $cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_WRITE + ); + $this->assertEquals('abcdef', $cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamCanBeAppended() + { + $os1 = $this->_createOutputStream(); + $os1->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('abc')); + $os1->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('def')); + $os1->expects($this->at(2)) + ->method('read') + ->will($this->returnValue(false)); + + $os2 = $this->_createOutputStream(); + $os2->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('xyz')); + $os2->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('uvw')); + $os2->expects($this->at(2)) + ->method('read') + ->will($this->returnValue(false)); + + $is = $this->_createKeyCacheInputStream(true); + + $cache = $this->_createCache($is); + + $cache->importFromByteStream( + $this->_key1, 'foo', $os1, Swift_KeyCache::MODE_APPEND + ); + $cache->importFromByteStream( + $this->_key1, 'foo', $os2, Swift_KeyCache::MODE_APPEND + ); + + $this->assertEquals('abcdefxyzuvw', $cache->getString($this->_key1, 'foo')); + } + + public function testByteStreamAndStringCanBeAppended() + { + $os = $this->_createOutputStream(); + $os->expects($this->at(0)) + ->method('read') + ->will($this->returnValue('abc')); + $os->expects($this->at(1)) + ->method('read') + ->will($this->returnValue('def')); + $os->expects($this->at(2)) + ->method('read') + ->will($this->returnValue(false)); + + $is = $this->_createKeyCacheInputStream(true); + + $cache = $this->_createCache($is); + + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_APPEND + ); + $cache->importFromByteStream( + $this->_key1, 'foo', $os, Swift_KeyCache::MODE_APPEND + ); + $this->assertEquals('testabcdef', $cache->getString($this->_key1, 'foo')); + } + + public function testDataCanBeExportedToByteStream() + { + //See acceptance test for more detail + $is = $this->_createInputStream(); + $is->expects($this->atLeastOnce()) + ->method('write'); + + $kcis = $this->_createKeyCacheInputStream(true); + + $cache = $this->_createCache($kcis); + + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + + $cache->exportToByteStream($this->_key1, 'foo', $is); + } + + public function testKeyCanBeCleared() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($cache->hasKey($this->_key1, 'foo')); + $cache->clearKey($this->_key1, 'foo'); + $this->assertFalse($cache->hasKey($this->_key1, 'foo')); + } + + public function testNsKeyCanBeCleared() + { + $is = $this->_createKeyCacheInputStream(); + $cache = $this->_createCache($is); + + $cache->setString( + $this->_key1, 'foo', 'test', Swift_KeyCache::MODE_WRITE + ); + $cache->setString( + $this->_key1, 'bar', 'xyz', Swift_KeyCache::MODE_WRITE + ); + $this->assertTrue($cache->hasKey($this->_key1, 'foo')); + $this->assertTrue($cache->hasKey($this->_key1, 'bar')); + $cache->clearAll($this->_key1); + $this->assertFalse($cache->hasKey($this->_key1, 'foo')); + $this->assertFalse($cache->hasKey($this->_key1, 'bar')); + } + + // -- Creation methods + + private function _createCache($is) + { + return new Swift_KeyCache_ArrayKeyCache($is); + } + + private function _createKeyCacheInputStream() + { + return $this->getMock('Swift_KeyCache_KeyCacheInputStream'); + } + + private function _createOutputStream() + { + return $this->getMock('Swift_OutputByteStream'); + } + + private function _createInputStream() + { + return $this->getMock('Swift_InputByteStream'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/SimpleKeyCacheInputStreamTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/SimpleKeyCacheInputStreamTest.php new file mode 100644 index 00000000..691c1e79 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/KeyCache/SimpleKeyCacheInputStreamTest.php @@ -0,0 +1,73 @@ +getMock('Swift_KeyCache'); + $cache->expects($this->at(0)) + ->method('setString') + ->with($this->_nsKey, 'foo', 'a', Swift_KeyCache::MODE_APPEND); + $cache->expects($this->at(1)) + ->method('setString') + ->with($this->_nsKey, 'foo', 'b', Swift_KeyCache::MODE_APPEND); + $cache->expects($this->at(2)) + ->method('setString') + ->with($this->_nsKey, 'foo', 'c', Swift_KeyCache::MODE_APPEND); + + $stream = new Swift_KeyCache_SimpleKeyCacheInputStream(); + $stream->setKeyCache($cache); + $stream->setNsKey($this->_nsKey); + $stream->setItemKey('foo'); + + $stream->write('a'); + $stream->write('b'); + $stream->write('c'); + } + + public function testFlushContentClearsKey() + { + $cache = $this->getMock('Swift_KeyCache'); + $cache->expects($this->once()) + ->method('clearKey') + ->with($this->_nsKey, 'foo'); + + $stream = new Swift_KeyCache_SimpleKeyCacheInputStream(); + $stream->setKeyCache($cache); + $stream->setNsKey($this->_nsKey); + $stream->setItemKey('foo'); + + $stream->flushBuffers(); + } + + public function testClonedStreamStillReferencesSameCache() + { + $cache = $this->getMock('Swift_KeyCache'); + $cache->expects($this->at(0)) + ->method('setString') + ->with($this->_nsKey, 'foo', 'a', Swift_KeyCache::MODE_APPEND); + $cache->expects($this->at(1)) + ->method('setString') + ->with($this->_nsKey, 'foo', 'b', Swift_KeyCache::MODE_APPEND); + $cache->expects($this->at(2)) + ->method('setString') + ->with('test', 'bar', 'x', Swift_KeyCache::MODE_APPEND); + + $stream = new Swift_KeyCache_SimpleKeyCacheInputStream(); + $stream->setKeyCache($cache); + $stream->setNsKey($this->_nsKey); + $stream->setItemKey('foo'); + + $stream->write('a'); + $stream->write('b'); + + $newStream = clone $stream; + $newStream->setKeyCache($cache); + $newStream->setNsKey('test'); + $newStream->setItemKey('bar'); + + $newStream->write('x'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mailer/ArrayRecipientIteratorTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mailer/ArrayRecipientIteratorTest.php new file mode 100644 index 00000000..ff0bce4f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mailer/ArrayRecipientIteratorTest.php @@ -0,0 +1,42 @@ +assertFalse($it->hasNext()); + } + + public function testHasNextReturnsTrueIfItemsLeft() + { + $it = new Swift_Mailer_ArrayRecipientIterator(array('foo@bar' => 'Foo')); + $this->assertTrue($it->hasNext()); + } + + public function testReadingToEndOfListCausesHasNextToReturnFalse() + { + $it = new Swift_Mailer_ArrayRecipientIterator(array('foo@bar' => 'Foo')); + $this->assertTrue($it->hasNext()); + $it->nextRecipient(); + $this->assertFalse($it->hasNext()); + } + + public function testReturnedValueHasPreservedKeyValuePair() + { + $it = new Swift_Mailer_ArrayRecipientIterator(array('foo@bar' => 'Foo')); + $this->assertEquals(array('foo@bar' => 'Foo'), $it->nextRecipient()); + } + + public function testIteratorMovesNextAfterEachIteration() + { + $it = new Swift_Mailer_ArrayRecipientIterator(array( + 'foo@bar' => 'Foo', + 'zip@button' => 'Zip thing', + 'test@test' => null, + )); + $this->assertEquals(array('foo@bar' => 'Foo'), $it->nextRecipient()); + $this->assertEquals(array('zip@button' => 'Zip thing'), $it->nextRecipient()); + $this->assertEquals(array('test@test' => null), $it->nextRecipient()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MailerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MailerTest.php new file mode 100644 index 00000000..db0b35a0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MailerTest.php @@ -0,0 +1,152 @@ +_createTransport(); + $message = $this->_createMessage(); + + $started = false; + $transport->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$started) { + return $started; + }); + $transport->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$started) { + $started = true; + + return; + }); + + $mailer = $this->_createMailer($transport); + $mailer->send($message); + } + + public function testTransportIsOnlyStartedOnce() + { + $transport = $this->_createTransport(); + $message = $this->_createMessage(); + + $started = false; + $transport->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$started) { + return $started; + }); + $transport->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$started) { + $started = true; + + return; + }); + + $mailer = $this->_createMailer($transport); + for ($i = 0; $i < 10; ++$i) { + $mailer->send($message); + } + } + + public function testMessageIsPassedToTransport() + { + $transport = $this->_createTransport(); + $message = $this->_createMessage(); + $transport->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()); + + $mailer = $this->_createMailer($transport); + $mailer->send($message); + } + + public function testSendReturnsCountFromTransport() + { + $transport = $this->_createTransport(); + $message = $this->_createMessage(); + $transport->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturn(57); + + $mailer = $this->_createMailer($transport); + $this->assertEquals(57, $mailer->send($message)); + } + + public function testFailedRecipientReferenceIsPassedToTransport() + { + $failures = array(); + + $transport = $this->_createTransport(); + $message = $this->_createMessage(); + $transport->shouldReceive('send') + ->once() + ->with($message, $failures) + ->andReturn(57); + + $mailer = $this->_createMailer($transport); + $mailer->send($message, $failures); + } + + public function testSendRecordsRfcComplianceExceptionAsEntireSendFailure() + { + $failures = array(); + + $rfcException = new Swift_RfcComplianceException('test'); + $transport = $this->_createTransport(); + $message = $this->_createMessage(); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo&invalid' => 'Foo', 'bar@valid.tld' => 'Bar')); + $transport->shouldReceive('send') + ->once() + ->with($message, $failures) + ->andThrow($rfcException); + + $mailer = $this->_createMailer($transport); + $this->assertEquals(0, $mailer->send($message, $failures), '%s: Should return 0'); + $this->assertEquals(array('foo&invalid', 'bar@valid.tld'), $failures, '%s: Failures should contain all addresses since the entire message failed to compile'); + } + + public function testRegisterPluginDelegatesToTransport() + { + $plugin = $this->_createPlugin(); + $transport = $this->_createTransport(); + $mailer = $this->_createMailer($transport); + + $transport->shouldReceive('registerPlugin') + ->once() + ->with($plugin); + + $mailer->registerPlugin($plugin); + } + + // -- Creation methods + + private function _createPlugin() + { + return $this->getMockery('Swift_Events_EventListener')->shouldIgnoreMissing(); + } + + private function _createTransport() + { + return $this->getMockery('Swift_Transport')->shouldIgnoreMissing(); + } + + private function _createMessage() + { + return $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + } + + private function _createIterator() + { + return $this->getMockery('Swift_Mailer_RecipientIterator')->shouldIgnoreMissing(); + } + + private function _createMailer(Swift_Transport $transport) + { + return new Swift_Mailer($transport); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MessageTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MessageTest.php new file mode 100644 index 00000000..d4afcd7c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/MessageTest.php @@ -0,0 +1,128 @@ +_recursiveObjectCloningCheck($message1, $message2, $message1_clone); + } + + public function testCloningWithSigners() + { + $message1 = new Swift_Message('subj', 'body', 'ctype'); + $signer = new Swift_Signers_DKIMSigner(dirname(dirname(__DIR__)).'/_samples/dkim/dkim.test.priv', 'test.example', 'example'); + $message1->attachSigner($signer); + $message2 = new Swift_Message('subj', 'body', 'ctype'); + $signer = new Swift_Signers_DKIMSigner(dirname(dirname(__DIR__)).'/_samples/dkim/dkim.test.priv', 'test.example', 'example'); + $message2->attachSigner($signer); + $message1_clone = clone $message1; + + $this->_recursiveObjectCloningCheck($message1, $message2, $message1_clone); + } + + public function testBodySwap() + { + $message1 = new Swift_Message('Test'); + $html = Swift_MimePart::newInstance('', 'text/html'); + $html->getHeaders()->addTextHeader('X-Test-Remove', 'Test-Value'); + $html->getHeaders()->addTextHeader('X-Test-Alter', 'Test-Value'); + $message1->attach($html); + $source = $message1->toString(); + $message2 = clone $message1; + $message2->setSubject('Message2'); + foreach ($message2->getChildren() as $child) { + $child->setBody('Test'); + $child->getHeaders()->removeAll('X-Test-Remove'); + $child->getHeaders()->get('X-Test-Alter')->setValue('Altered'); + } + $final = $message1->toString(); + if ($source != $final) { + $this->fail("Difference although object cloned \n [".$source."]\n[".$final."]\n"); + } + $final = $message2->toString(); + if ($final == $source) { + $this->fail('Two body matches although they should differ'."\n [".$source."]\n[".$final."]\n"); + } + $id_1 = $message1->getId(); + $id_2 = $message2->getId(); + $this->assertNotEquals($id_1, $id_2, 'Message Ids are the same'); + } + + // -- Private helpers + protected function _recursiveObjectCloningCheck($obj1, $obj2, $obj1_clone) + { + $obj1_properties = (array) $obj1; + $obj2_properties = (array) $obj2; + $obj1_clone_properties = (array) $obj1_clone; + + foreach ($obj1_properties as $property => $value) { + if (is_object($value)) { + $obj1_value = $obj1_properties[$property]; + $obj2_value = $obj2_properties[$property]; + $obj1_clone_value = $obj1_clone_properties[$property]; + + if ($obj1_value !== $obj2_value) { + // two separetely instanciated objects property not referencing same object + $this->assertFalse( + // but object's clone does - not everything copied + $obj1_value === $obj1_clone_value, + "Property `$property` cloning error: source and cloned objects property is referencing same object" + ); + } else { + // two separetely instanciated objects have same reference + $this->assertFalse( + // but object's clone doesn't - overdone making copies + $obj1_value !== $obj1_clone_value, + "Property `$property` not properly cloned: it should reference same object as cloning source (overdone copping)" + ); + } + // recurse + $this->_recursiveObjectCloningCheck($obj1_value, $obj2_value, $obj1_clone_value); + } elseif (is_array($value)) { + $obj1_value = $obj1_properties[$property]; + $obj2_value = $obj2_properties[$property]; + $obj1_clone_value = $obj1_clone_properties[$property]; + + return $this->_recursiveArrayCloningCheck($obj1_value, $obj2_value, $obj1_clone_value); + } + } + } + + protected function _recursiveArrayCloningCheck($array1, $array2, $array1_clone) + { + foreach ($array1 as $key => $value) { + if (is_object($value)) { + $arr1_value = $array1[$key]; + $arr2_value = $array2[$key]; + $arr1_clone_value = $array1_clone[$key]; + if ($arr1_value !== $arr2_value) { + // two separetely instanciated objects property not referencing same object + $this->assertFalse( + // but object's clone does - not everything copied + $arr1_value === $arr1_clone_value, + "Key `$key` cloning error: source and cloned objects property is referencing same object" + ); + } else { + // two separetely instanciated objects have same reference + $this->assertFalse( + // but object's clone doesn't - overdone making copies + $arr1_value !== $arr1_clone_value, + "Key `$key` not properly cloned: it should reference same object as cloning source (overdone copping)" + ); + } + // recurse + $this->_recursiveObjectCloningCheck($arr1_value, $arr2_value, $arr1_clone_value); + } elseif (is_array($value)) { + $arr1_value = $array1[$key]; + $arr2_value = $array2[$key]; + $arr1_clone_value = $array1_clone[$key]; + + return $this->_recursiveArrayCloningCheck($obj1_value, $obj2_value, $obj1_clone_value); + } + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AbstractMimeEntityTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AbstractMimeEntityTest.php new file mode 100644 index 00000000..de928bc9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AbstractMimeEntityTest.php @@ -0,0 +1,1052 @@ +_createHeaderSet(); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $this->assertSame($headers, $entity->getHeaders()); + } + + public function testContentTypeIsReturnedFromHeader() + { + $ctype = $this->_createHeader('Content-Type', 'image/jpeg-test'); + $headers = $this->_createHeaderSet(array('Content-Type' => $ctype)); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $this->assertEquals('image/jpeg-test', $entity->getContentType()); + } + + public function testContentTypeIsSetInHeader() + { + $ctype = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $headers = $this->_createHeaderSet(array('Content-Type' => $ctype)); + + $ctype->shouldReceive('setFieldBodyModel') + ->once() + ->with('image/jpeg'); + $ctype->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes() + ->with(\Mockery::not('image/jpeg')); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setContentType('image/jpeg'); + } + + public function testContentTypeHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addParameterizedHeader') + ->once() + ->with('Content-Type', 'image/jpeg'); + $headers->shouldReceive('addParameterizedHeader') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setContentType('image/jpeg'); + } + + public function testContentTypeCanBeSetViaSetBody() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addParameterizedHeader') + ->once() + ->with('Content-Type', 'text/html'); + $headers->shouldReceive('addParameterizedHeader') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBody('foo', 'text/html'); + } + + public function testGetEncoderFromConstructor() + { + $encoder = $this->_createEncoder('base64'); + $entity = $this->_createEntity($this->_createHeaderSet(), $encoder, + $this->_createCache() + ); + $this->assertSame($encoder, $entity->getEncoder()); + } + + public function testSetAndGetEncoder() + { + $encoder = $this->_createEncoder('base64'); + $headers = $this->_createHeaderSet(); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setEncoder($encoder); + $this->assertSame($encoder, $entity->getEncoder()); + } + + public function testSettingEncoderUpdatesTransferEncoding() + { + $encoder = $this->_createEncoder('base64'); + $encoding = $this->_createHeader( + 'Content-Transfer-Encoding', '8bit', array(), false + ); + $headers = $this->_createHeaderSet(array( + 'Content-Transfer-Encoding' => $encoding, + )); + $encoding->shouldReceive('setFieldBodyModel') + ->once() + ->with('base64'); + $encoding->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setEncoder($encoder); + } + + public function testSettingEncoderAddsEncodingHeaderIfNonePresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addTextHeader') + ->once() + ->with('Content-Transfer-Encoding', 'something'); + $headers->shouldReceive('addTextHeader') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setEncoder($this->_createEncoder('something')); + } + + public function testIdIsReturnedFromHeader() + { + /* -- RFC 2045, 7. + In constructing a high-level user agent, it may be desirable to allow + one body to make reference to another. Accordingly, bodies may be + labelled using the "Content-ID" header field, which is syntactically + identical to the "Message-ID" header field + */ + + $cid = $this->_createHeader('Content-ID', 'zip@button'); + $headers = $this->_createHeaderSet(array('Content-ID' => $cid)); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $this->assertEquals('zip@button', $entity->getId()); + } + + public function testIdIsSetInHeader() + { + $cid = $this->_createHeader('Content-ID', 'zip@button', array(), false); + $headers = $this->_createHeaderSet(array('Content-ID' => $cid)); + + $cid->shouldReceive('setFieldBodyModel') + ->once() + ->with('foo@bar'); + $cid->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setId('foo@bar'); + } + + public function testIdIsAutoGenerated() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertRegExp('/^.*?@.*?$/D', $entity->getId()); + } + + public function testGenerateIdCreatesNewId() + { + $headers = $this->_createHeaderSet(); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $id1 = $entity->generateId(); + $id2 = $entity->generateId(); + $this->assertNotEquals($id1, $id2); + } + + public function testGenerateIdSetsNewId() + { + $headers = $this->_createHeaderSet(); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $id = $entity->generateId(); + $this->assertEquals($id, $entity->getId()); + } + + public function testDescriptionIsReadFromHeader() + { + /* -- RFC 2045, 8. + The ability to associate some descriptive information with a given + body is often desirable. For example, it may be useful to mark an + "image" body as "a picture of the Space Shuttle Endeavor." Such text + may be placed in the Content-Description header field. This header + field is always optional. + */ + + $desc = $this->_createHeader('Content-Description', 'something'); + $headers = $this->_createHeaderSet(array('Content-Description' => $desc)); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $this->assertEquals('something', $entity->getDescription()); + } + + public function testDescriptionIsSetInHeader() + { + $desc = $this->_createHeader('Content-Description', '', array(), false); + $desc->shouldReceive('setFieldBodyModel')->once()->with('whatever'); + + $headers = $this->_createHeaderSet(array('Content-Description' => $desc)); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setDescription('whatever'); + } + + public function testDescriptionHeaderIsAddedIfNotPresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addTextHeader') + ->once() + ->with('Content-Description', 'whatever'); + $headers->shouldReceive('addTextHeader') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setDescription('whatever'); + } + + public function testSetAndGetMaxLineLength() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setMaxLineLength(60); + $this->assertEquals(60, $entity->getMaxLineLength()); + } + + public function testEncoderIsUsedForStringGeneration() + { + $encoder = $this->_createEncoder('base64', false); + $encoder->expects($this->once()) + ->method('encodeString') + ->with('blah'); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $encoder, $this->_createCache() + ); + $entity->setBody("blah"); + $entity->toString(); + } + + public function testMaxLineLengthIsProvidedWhenEncoding() + { + $encoder = $this->_createEncoder('base64', false); + $encoder->expects($this->once()) + ->method('encodeString') + ->with('blah', 0, 65); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $encoder, $this->_createCache() + ); + $entity->setBody("blah"); + $entity->setMaxLineLength(65); + $entity->toString(); + } + + public function testHeadersAppearInString() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->once() + ->andReturn( + "Content-Type: text/plain; charset=utf-8\r\n". + "X-MyHeader: foobar\r\n" + ); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $this->assertEquals( + "Content-Type: text/plain; charset=utf-8\r\n". + "X-MyHeader: foobar\r\n", + $entity->toString() + ); + } + + public function testSetAndGetBody() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setBody("blah\r\nblah!"); + $this->assertEquals("blah\r\nblah!", $entity->getBody()); + } + + public function testBodyIsAppended() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->once() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBody("blah\r\nblah!"); + $this->assertEquals( + "Content-Type: text/plain; charset=utf-8\r\n". + "\r\n". + "blah\r\nblah!", + $entity->toString() + ); + } + + public function testGetBodyReturnsStringFromByteStream() + { + $os = $this->_createOutputStream("byte stream string"); + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setBody($os); + $this->assertEquals("byte stream string", $entity->getBody()); + } + + public function testByteStreamBodyIsAppended() + { + $headers = $this->_createHeaderSet(array(), false); + $os = $this->_createOutputStream("streamed"); + $headers->shouldReceive('toString') + ->once() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBody($os); + $this->assertEquals( + "Content-Type: text/plain; charset=utf-8\r\n". + "\r\n". + "streamed", + $entity->toString() + ); + } + + public function testBoundaryCanBeRetrieved() + { + /* -- RFC 2046, 5.1.1. + boundary := 0*69 bcharsnospace + + bchars := bcharsnospace / " " + + bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / + "+" / "_" / "," / "-" / "." / + "/" / ":" / "=" / "?" + */ + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertRegExp( + '/^[a-zA-Z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-zA-Z0-9\'\(\)\+_\-,\.\/:=\?]$/D', + $entity->getBoundary() + ); + } + + public function testBoundaryNeverChanges() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $firstBoundary = $entity->getBoundary(); + for ($i = 0; $i < 10; $i++) { + $this->assertEquals($firstBoundary, $entity->getBoundary()); + } + } + + public function testBoundaryCanBeSet() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setBoundary('foobar'); + $this->assertEquals('foobar', $entity->getBoundary()); + } + + public function testAddingChildrenGeneratesBoundaryInHeaders() + { + $child = $this->_createChild(); + $cType = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $cType->shouldReceive('setParameter') + ->once() + ->with('boundary', \Mockery::any()); + $cType->shouldReceive('setParameter') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($this->_createHeaderSet(array( + 'Content-Type' => $cType, + )), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + } + + public function testChildrenOfLevelAttachmentAndLessCauseMultipartMixed() + { + for ($level = Swift_Mime_MimeEntity::LEVEL_MIXED; + $level > Swift_Mime_MimeEntity::LEVEL_TOP; $level /= 2) { + $child = $this->_createChild($level); + $cType = $this->_createHeader( + 'Content-Type', 'text/plain', array(), false + ); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with('multipart/mixed'); + $cType->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + } + } + + public function testChildrenOfLevelAlternativeAndLessCauseMultipartAlternative() + { + for ($level = Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE; + $level > Swift_Mime_MimeEntity::LEVEL_MIXED; $level /= 2) { + $child = $this->_createChild($level); + $cType = $this->_createHeader( + 'Content-Type', 'text/plain', array(), false + ); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with('multipart/alternative'); + $cType->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + } + } + + public function testChildrenOfLevelRelatedAndLessCauseMultipartRelated() + { + for ($level = Swift_Mime_MimeEntity::LEVEL_RELATED; + $level > Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE; $level /= 2) { + $child = $this->_createChild($level); + $cType = $this->_createHeader( + 'Content-Type', 'text/plain', array(), false + ); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with('multipart/related'); + $cType->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $entity = $this->_createEntity($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + } + } + + public function testHighestLevelChildDeterminesContentType() + { + $combinations = array( + array('levels' => array(Swift_Mime_MimeEntity::LEVEL_MIXED, + Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + Swift_Mime_MimeEntity::LEVEL_RELATED, + ), + 'type' => 'multipart/mixed', + ), + array('levels' => array(Swift_Mime_MimeEntity::LEVEL_MIXED, + Swift_Mime_MimeEntity::LEVEL_RELATED, + ), + 'type' => 'multipart/mixed', + ), + array('levels' => array(Swift_Mime_MimeEntity::LEVEL_MIXED, + Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + ), + 'type' => 'multipart/mixed', + ), + array('levels' => array(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + Swift_Mime_MimeEntity::LEVEL_RELATED, + ), + 'type' => 'multipart/alternative', + ), + ); + + foreach ($combinations as $combination) { + $children = array(); + foreach ($combination['levels'] as $level) { + $children[] = $this->_createChild($level); + } + + $cType = $this->_createHeader( + 'Content-Type', 'text/plain', array(), false + ); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with($combination['type']); + + $headerSet = $this->_createHeaderSet(array('Content-Type' => $cType)); + $headerSet->shouldReceive('newInstance') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use ($headerSet) { + return $headerSet; + }); + $entity = $this->_createEntity($headerSet, + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren($children); + } + } + + public function testChildrenAppearNestedInString() + { + /* -- RFC 2046, 5.1.1. + (excerpt too verbose to paste here) + */ + + $headers = $this->_createHeaderSet(array(), false); + + $child1 = new MimeEntityFixture(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + "Content-Type: text/plain\r\n". + "\r\n". + "foobar" + ); + + $child2 = new MimeEntityFixture(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + "Content-Type: text/html\r\n". + "\r\n". + "foobar" + ); + + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: multipart/alternative; boundary=\"xxx\"\r\n"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBoundary('xxx'); + $entity->setChildren(array($child1, $child2)); + + $this->assertEquals( + "Content-Type: multipart/alternative; boundary=\"xxx\"\r\n". + "\r\n". + "\r\n--xxx\r\n". + "Content-Type: text/plain\r\n". + "\r\n". + "foobar\r\n". + "\r\n--xxx\r\n". + "Content-Type: text/html\r\n". + "\r\n". + "foobar\r\n". + "\r\n--xxx--\r\n", + $entity->toString() + ); + } + + public function testMixingLevelsIsHierarchical() + { + $headers = $this->_createHeaderSet(array(), false); + $newHeaders = $this->_createHeaderSet(array(), false); + + $part = $this->_createChild(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + "Content-Type: text/plain\r\n". + "\r\n". + "foobar" + ); + + $attachment = $this->_createChild(Swift_Mime_MimeEntity::LEVEL_MIXED, + "Content-Type: application/octet-stream\r\n". + "\r\n". + "data" + ); + + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: multipart/mixed; boundary=\"xxx\"\r\n"); + $headers->shouldReceive('newInstance') + ->zeroOrMoreTimes() + ->andReturn($newHeaders); + $newHeaders->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: multipart/alternative; boundary=\"yyy\"\r\n"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBoundary('xxx'); + $entity->setChildren(array($part, $attachment)); + + $this->assertRegExp( + "~^". + "Content-Type: multipart/mixed; boundary=\"xxx\"\r\n". + "\r\n\r\n--xxx\r\n". + "Content-Type: multipart/alternative; boundary=\"yyy\"\r\n". + "\r\n\r\n--(.*?)\r\n". + "Content-Type: text/plain\r\n". + "\r\n". + "foobar". + "\r\n\r\n--\\1--\r\n". + "\r\n\r\n--xxx\r\n". + "Content-Type: application/octet-stream\r\n". + "\r\n". + "data". + "\r\n\r\n--xxx--\r\n". + "\$~", + $entity->toString() + ); + } + + public function testSettingEncoderNotifiesChildren() + { + $child = $this->_createChild(0, '', false); + $encoder = $this->_createEncoder('base64'); + + $child->shouldReceive('encoderChanged') + ->once() + ->with($encoder); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + $entity->setEncoder($encoder); + } + + public function testReceiptOfEncoderChangeNotifiesChildren() + { + $child = $this->_createChild(0, '', false); + $encoder = $this->_createEncoder('base64'); + + $child->shouldReceive('encoderChanged') + ->once() + ->with($encoder); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + $entity->encoderChanged($encoder); + } + + public function testReceiptOfCharsetChangeNotifiesChildren() + { + $child = $this->_createChild(0, '', false); + $child->shouldReceive('charsetChanged') + ->once() + ->with('windows-874'); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $entity->setChildren(array($child)); + $entity->charsetChanged('windows-874'); + } + + public function testEntityIsWrittenToByteStream() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $is = $this->_createInputStream(false); + $is->expects($this->atLeastOnce()) + ->method('write'); + + $entity->toByteStream($is); + } + + public function testEntityHeadersAreComittedToByteStream() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $is = $this->_createInputStream(false); + $is->expects($this->atLeastOnce()) + ->method('write'); + $is->expects($this->atLeastOnce()) + ->method('commit'); + + $entity->toByteStream($is); + } + + public function testOrderingTextBeforeHtml() + { + $htmlChild = new MimeEntityFixture(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + "Content-Type: text/html\r\n". + "\r\n". + "HTML PART", + 'text/html' + ); + $textChild = new MimeEntityFixture(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, + "Content-Type: text/plain\r\n". + "\r\n". + "TEXT PART", + 'text/plain' + ); + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: multipart/alternative; boundary=\"xxx\"\r\n"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $this->_createCache() + ); + $entity->setBoundary('xxx'); + $entity->setChildren(array($htmlChild, $textChild)); + + $this->assertEquals( + "Content-Type: multipart/alternative; boundary=\"xxx\"\r\n". + "\r\n\r\n--xxx\r\n". + "Content-Type: text/plain\r\n". + "\r\n". + "TEXT PART". + "\r\n\r\n--xxx\r\n". + "Content-Type: text/html\r\n". + "\r\n". + "HTML PART". + "\r\n\r\n--xxx--\r\n", + $entity->toString() + ); + } + + public function testUnsettingChildrenRestoresContentType() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $child = $this->_createChild(Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE); + + $cType->shouldReceive('setFieldBodyModel') + ->twice() + ->with('image/jpeg'); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with('multipart/alternative'); + $cType->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes() + ->with(\Mockery::not('multipart/alternative', 'image/jpeg')); + + $entity = $this->_createEntity($this->_createHeaderSet(array( + 'Content-Type' => $cType, + )), + $this->_createEncoder(), $this->_createCache() + ); + + $entity->setContentType('image/jpeg'); + $entity->setChildren(array($child)); + $entity->setChildren(array()); + } + + public function testBodyIsReadFromCacheWhenUsingToStringIfPresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + $cache->shouldReceive('hasKey') + ->once() + ->with(\Mockery::any(), 'body') + ->andReturn(true); + $cache->shouldReceive('getString') + ->once() + ->with(\Mockery::any(), 'body') + ->andReturn("\r\ncache\r\ncache!"); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $this->assertEquals( + "Content-Type: text/plain; charset=utf-8\r\n". + "\r\n". + "cache\r\ncache!", + $entity->toString() + ); + } + + public function testBodyIsAddedToCacheWhenUsingToString() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + $cache->shouldReceive('hasKey') + ->once() + ->with(\Mockery::any(), 'body') + ->andReturn(false); + $cache->shouldReceive('setString') + ->once() + ->with(\Mockery::any(), 'body', "\r\nblah\r\nblah!", Swift_KeyCache::MODE_WRITE); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $entity->toString(); + } + + public function testBodyIsClearedFromCacheIfNewBodySet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $entity->toString(); + + // We set the expectation at this point because we only care what happens when calling setBody() + $cache->shouldReceive('clearKey') + ->once() + ->with(\Mockery::any(), 'body'); + + $entity->setBody("new\r\nnew!"); + } + + public function testBodyIsNotClearedFromCacheIfSameBodySet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $entity->toString(); + + // We set the expectation at this point because we only care what happens when calling setBody() + $cache->shouldReceive('clearKey') + ->never(); + + $entity->setBody("blah\r\nblah!"); + } + + public function testBodyIsClearedFromCacheIfNewEncoderSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + $otherEncoder = $this->_createEncoder(); + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $entity->toString(); + + // We set the expectation at this point because we only care what happens when calling setEncoder() + $cache->shouldReceive('clearKey') + ->once() + ->with(\Mockery::any(), 'body'); + + $entity->setEncoder($otherEncoder); + } + + public function testBodyIsReadFromCacheWhenUsingToByteStreamIfPresent() + { + $is = $this->_createInputStream(); + $cache = $this->_createCache(false); + $cache->shouldReceive('hasKey') + ->once() + ->with(\Mockery::any(), 'body') + ->andReturn(true); + $cache->shouldReceive('exportToByteStream') + ->once() + ->with(\Mockery::any(), 'body', $is); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $cache + ); + $entity->setBody('foo'); + + $entity->toByteStream($is); + } + + public function testBodyIsAddedToCacheWhenUsingToByteStream() + { + $is = $this->_createInputStream(); + $cache = $this->_createCache(false); + $cache->shouldReceive('hasKey') + ->once() + ->with(\Mockery::any(), 'body') + ->andReturn(false); + $cache->shouldReceive('getInputByteStream') + ->once() + ->with(\Mockery::any(), 'body'); + + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $cache + ); + $entity->setBody('foo'); + + $entity->toByteStream($is); + } + + public function testFluidInterface() + { + $entity = $this->_createEntity($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $this->assertSame($entity, + $entity + ->setContentType('text/plain') + ->setEncoder($this->_createEncoder()) + ->setId('foo@bar') + ->setDescription('my description') + ->setMaxLineLength(998) + ->setBody('xx') + ->setBoundary('xyz') + ->setChildren(array()) + ); + } + + // -- Private helpers + + abstract protected function _createEntity($headers, $encoder, $cache); + + protected function _createChild($level = null, $string = '', $stub = true) + { + $child = $this->getMockery('Swift_Mime_MimeEntity')->shouldIgnoreMissing(); + if (isset($level)) { + $child->shouldReceive('getNestingLevel') + ->zeroOrMoreTimes() + ->andReturn($level); + } + $child->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn($string); + + return $child; + } + + protected function _createEncoder($name = 'quoted-printable', $stub = true) + { + $encoder = $this->getMock('Swift_Mime_ContentEncoder'); + $encoder->expects($this->any()) + ->method('getName') + ->will($this->returnValue($name)); + $encoder->expects($this->any()) + ->method('encodeString') + ->will($this->returnCallback(function () { + $args = func_get_args(); + + return array_shift($args); + })); + + return $encoder; + } + + protected function _createCache($stub = true) + { + return $this->getMockery('Swift_KeyCache')->shouldIgnoreMissing(); + } + + protected function _createHeaderSet($headers = array(), $stub = true) + { + $set = $this->getMockery('Swift_Mime_HeaderSet')->shouldIgnoreMissing(); + $set->shouldReceive('get') + ->zeroOrMoreTimes() + ->andReturnUsing(function ($key) use ($headers) { + return $headers[$key]; + }); + $set->shouldReceive('has') + ->zeroOrMoreTimes() + ->andReturnUsing(function ($key) use ($headers) { + return array_key_exists($key, $headers); + }); + + return $set; + } + + protected function _createHeader($name, $model = null, $params = array(), $stub = true) + { + $header = $this->getMockery('Swift_Mime_ParameterizedHeader')->shouldIgnoreMissing(); + $header->shouldReceive('getFieldName') + ->zeroOrMoreTimes() + ->andReturn($name); + $header->shouldReceive('getFieldBodyModel') + ->zeroOrMoreTimes() + ->andReturn($model); + $header->shouldReceive('getParameter') + ->zeroOrMoreTimes() + ->andReturnUsing(function ($key) use ($params) { + return $params[$key]; + }); + + return $header; + } + + protected function _createOutputStream($data = null, $stub = true) + { + $os = $this->getMockery('Swift_OutputByteStream'); + if (isset($data)) { + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use ($data) { + static $first = true; + if (!$first) { + return false; + } + + $first = false; + + return $data; + }); + } + + return $os; + } + + protected function _createInputStream($stub = true) + { + return $this->getMock('Swift_InputByteStream'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AttachmentTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AttachmentTest.php new file mode 100644 index 00000000..ca0b8d91 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/AttachmentTest.php @@ -0,0 +1,318 @@ +_createAttachment($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals( + Swift_Mime_MimeEntity::LEVEL_MIXED, $attachment->getNestingLevel() + ); + } + + public function testDispositionIsReturnedFromHeader() + { + /* -- RFC 2183, 2.1, 2.2. + */ + + $disposition = $this->_createHeader('Content-Disposition', 'attachment'); + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('attachment', $attachment->getDisposition()); + } + + public function testDispositionIsSetInHeader() + { + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array(), false + ); + $disposition->shouldReceive('setFieldBodyModel') + ->once() + ->with('inline'); + $disposition->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setDisposition('inline'); + } + + public function testDispositionIsAddedIfNonePresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addParameterizedHeader') + ->once() + ->with('Content-Disposition', 'inline'); + $headers->shouldReceive('addParameterizedHeader') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($headers, $this->_createEncoder(), + $this->_createCache() + ); + $attachment->setDisposition('inline'); + } + + public function testDispositionIsAutoDefaultedToAttachment() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addParameterizedHeader') + ->once() + ->with('Content-Disposition', 'attachment'); + $headers->shouldReceive('addParameterizedHeader') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($headers, $this->_createEncoder(), + $this->_createCache() + ); + } + + public function testDefaultContentTypeInitializedToOctetStream() + { + $cType = $this->_createHeader('Content-Type', '', + array(), false + ); + $cType->shouldReceive('setFieldBodyModel') + ->once() + ->with('application/octet-stream'); + $cType->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + } + + public function testFilenameIsReturnedFromHeader() + { + /* -- RFC 2183, 2.3. + */ + + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('filename' => 'foo.txt') + ); + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('foo.txt', $attachment->getFilename()); + } + + public function testFilenameIsSetInHeader() + { + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('filename' => 'foo.txt'), false + ); + $disposition->shouldReceive('setParameter') + ->once() + ->with('filename', 'bar.txt'); + $disposition->shouldReceive('setParameter') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setFilename('bar.txt'); + } + + public function testSettingFilenameSetsNameInContentType() + { + /* + This is a legacy requirement which isn't covered by up-to-date RFCs. + */ + + $cType = $this->_createHeader('Content-Type', 'text/plain', + array(), false + ); + $cType->shouldReceive('setParameter') + ->once() + ->with('name', 'bar.txt'); + $cType->shouldReceive('setParameter') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setFilename('bar.txt'); + } + + public function testSizeIsReturnedFromHeader() + { + /* -- RFC 2183, 2.7. + */ + + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('size' => 1234) + ); + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(1234, $attachment->getSize()); + } + + public function testSizeIsSetInHeader() + { + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array(), false + ); + $disposition->shouldReceive('setParameter') + ->once() + ->with('size', 12345); + $disposition->shouldReceive('setParameter') + ->zeroOrMoreTimes(); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setSize(12345); + } + + public function testFilnameCanBeReadFromFileStream() + { + $file = $this->_createFileStream('/bar/file.ext', ''); + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('filename' => 'foo.txt'), false + ); + $disposition->shouldReceive('setParameter') + ->once() + ->with('filename', 'file.ext'); + + $attachment = $this->_createAttachment($this->_createHeaderSet(array( + 'Content-Disposition' => $disposition,)), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setFile($file); + } + + public function testContentTypeCanBeSetViaSetFile() + { + $file = $this->_createFileStream('/bar/file.ext', ''); + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('filename' => 'foo.txt'), false + ); + $disposition->shouldReceive('setParameter') + ->once() + ->with('filename', 'file.ext'); + + $ctype = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $ctype->shouldReceive('setFieldBodyModel') + ->once() + ->with('text/html'); + $ctype->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $headers = $this->_createHeaderSet(array( + 'Content-Disposition' => $disposition, + 'Content-Type' => $ctype, + )); + + $attachment = $this->_createAttachment($headers, $this->_createEncoder(), + $this->_createCache() + ); + $attachment->setFile($file, 'text/html'); + } + + public function XtestContentTypeCanBeLookedUpFromCommonListIfNotProvided() + { + $file = $this->_createFileStream('/bar/file.zip', ''); + $disposition = $this->_createHeader('Content-Disposition', 'attachment', + array('filename' => 'foo.zip'), false + ); + $disposition->shouldReceive('setParameter') + ->once() + ->with('filename', 'file.zip'); + + $ctype = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $ctype->shouldReceive('setFieldBodyModel') + ->once() + ->with('application/zip'); + $ctype->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $headers = $this->_createHeaderSet(array( + 'Content-Disposition' => $disposition, + 'Content-Type' => $ctype, + )); + + $attachment = $this->_createAttachment($headers, $this->_createEncoder(), + $this->_createCache(), array('zip' => 'application/zip', 'txt' => 'text/plain') + ); + $attachment->setFile($file); + } + + public function testDataCanBeReadFromFile() + { + $file = $this->_createFileStream('/foo/file.ext', ''); + $attachment = $this->_createAttachment($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $attachment->setFile($file); + $this->assertEquals('', $attachment->getBody()); + } + + public function testFluidInterface() + { + $attachment = $this->_createAttachment($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertSame($attachment, + $attachment + ->setContentType('application/pdf') + ->setEncoder($this->_createEncoder()) + ->setId('foo@bar') + ->setDescription('my pdf') + ->setMaxLineLength(998) + ->setBody('xx') + ->setBoundary('xyz') + ->setChildren(array()) + ->setDisposition('inline') + ->setFilename('afile.txt') + ->setSize(123) + ->setFile($this->_createFileStream('foo.txt', '')) + ); + } + + // -- Private helpers + + protected function _createEntity($headers, $encoder, $cache) + { + return $this->_createAttachment($headers, $encoder, $cache); + } + + protected function _createAttachment($headers, $encoder, $cache, $mimeTypes = array()) + { + return new Swift_Mime_Attachment($headers, $encoder, $cache, new Swift_Mime_Grammar(), $mimeTypes); + } + + protected function _createFileStream($path, $data, $stub = true) + { + $file = $this->getMockery('Swift_FileStream'); + $file->shouldReceive('getPath') + ->zeroOrMoreTimes() + ->andReturn($path); + $file->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use ($data) { + static $first = true; + if (!$first) { + return false; + } + + $first = false; + + return $data; + }); + + return $file; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/Base64ContentEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/Base64ContentEncoderTest.php new file mode 100644 index 00000000..7c427d85 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/Base64ContentEncoderTest.php @@ -0,0 +1,323 @@ +_encoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + } + + public function testNameIsBase64() + { + $this->assertEquals('base64', $this->_encoder->getName()); + } + + /* + There's really no point in testing the entire base64 encoding to the + level QP encoding has been tested. base64_encode() has been in PHP for + years. + */ + + public function testInputOutputRatioIs3to4Bytes() + { + /* + RFC 2045, 6.8 + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + */ + + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('123'); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is); + $this->assertEquals('MTIz', $collection->content); + } + + public function testPadLength() + { + /* + RFC 2045, 6.8 + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a body. When fewer than 24 input bits + are available in an input group, zero bits are added (on the right) + to form an integral number of 6-bit groups. Padding at the end of + the data is performed using the "=" character. Since all base64 + input is an integral number of octets, only the following cases can + arise: (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded output will be + an integral multiple of 4 characters with no "=" padding, (2) the + final quantum of encoding input is exactly 8 bits; here, the final + unit of encoded output will be two characters followed by two "=" + padding characters, or (3) the final quantum of encoding input is + exactly 16 bits; here, the final unit of encoded output will be three + characters followed by one "=" padding character. + */ + + for ($i = 0; $i < 30; ++$i) { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn(pack('C', rand(0, 255))); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is); + $this->assertRegExp('~^[a-zA-Z0-9/\+]{2}==$~', $collection->content, + '%s: A single byte should have 2 bytes of padding' + ); + } + + for ($i = 0; $i < 30; ++$i) { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn(pack('C*', rand(0, 255), rand(0, 255))); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is); + $this->assertRegExp('~^[a-zA-Z0-9/\+]{3}=$~', $collection->content, + '%s: Two bytes should have 1 byte of padding' + ); + } + + for ($i = 0; $i < 30; ++$i) { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn(pack('C*', rand(0, 255), rand(0, 255), rand(0, 255))); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is); + $this->assertRegExp('~^[a-zA-Z0-9/\+]{4}$~', $collection->content, + '%s: Three bytes should have no padding' + ); + } + } + + public function testMaximumLineLengthIs76Characters() + { + /* + The encoded output stream must be represented in lines of no more + than 76 characters each. All line breaks or other characters not + found in Table 1 must be ignored by decoding software. + */ + + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //12 + $os->shouldReceive('read') + ->once() + ->andReturn('mnopqrstuvwx'); //24 + $os->shouldReceive('read') + ->once() + ->andReturn('yzabc1234567'); //36 + $os->shouldReceive('read') + ->once() + ->andReturn('890ABCDEFGHI'); //48 + $os->shouldReceive('read') + ->once() + ->andReturn('JKLMNOPQRSTU'); //60 + $os->shouldReceive('read') + ->once() + ->andReturn('VWXYZ1234567'); //72 + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //84 + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is); + $this->assertEquals( + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmMxMjM0NTY3ODkwQUJDREVGR0hJSktMTU5PUFFS\r\n". + "U1RVVldYWVoxMjM0NTY3YWJjZGVmZ2hpamts", + $collection->content + ); + } + + public function testMaximumLineLengthCanBeDifferent() + { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //12 + $os->shouldReceive('read') + ->once() + ->andReturn('mnopqrstuvwx'); //24 + $os->shouldReceive('read') + ->once() + ->andReturn('yzabc1234567'); //36 + $os->shouldReceive('read') + ->once() + ->andReturn('890ABCDEFGHI'); //48 + $os->shouldReceive('read') + ->once() + ->andReturn('JKLMNOPQRSTU'); //60 + $os->shouldReceive('read') + ->once() + ->andReturn('VWXYZ1234567'); //72 + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //84 + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is, 0, 50); + $this->assertEquals( + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmMxMjM0NTY3OD\r\n". + "kwQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoxMjM0NTY3YWJj\r\n". + "ZGVmZ2hpamts", + $collection->content + ); + } + + public function testMaximumLineLengthIsNeverMoreThan76Chars() + { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //12 + $os->shouldReceive('read') + ->once() + ->andReturn('mnopqrstuvwx'); //24 + $os->shouldReceive('read') + ->once() + ->andReturn('yzabc1234567'); //36 + $os->shouldReceive('read') + ->once() + ->andReturn('890ABCDEFGHI'); //48 + $os->shouldReceive('read') + ->once() + ->andReturn('JKLMNOPQRSTU'); //60 + $os->shouldReceive('read') + ->once() + ->andReturn('VWXYZ1234567'); //72 + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //84 + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is, 0, 100); + $this->assertEquals( + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmMxMjM0NTY3ODkwQUJDREVGR0hJSktMTU5PUFFS\r\n". + "U1RVVldYWVoxMjM0NTY3YWJjZGVmZ2hpamts", + $collection->content + ); + } + + public function testFirstLineLengthCanBeDifferent() + { + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //12 + $os->shouldReceive('read') + ->once() + ->andReturn('mnopqrstuvwx'); //24 + $os->shouldReceive('read') + ->once() + ->andReturn('yzabc1234567'); //36 + $os->shouldReceive('read') + ->once() + ->andReturn('890ABCDEFGHI'); //48 + $os->shouldReceive('read') + ->once() + ->andReturn('JKLMNOPQRSTU'); //60 + $os->shouldReceive('read') + ->once() + ->andReturn('VWXYZ1234567'); //72 + $os->shouldReceive('read') + ->once() + ->andReturn('abcdefghijkl'); //84 + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_encoder->encodeByteStream($os, $is, 19); + $this->assertEquals( + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXphYmMxMjM0NTY3ODkwQUJDR\r\n". + "EVGR0hJSktMTU5PUFFSU1RVVldYWVoxMjM0NTY3YWJjZGVmZ2hpamts", + $collection->content + ); + } + + private function _createOutputByteStream($stub = false) + { + return $this->getMockery('Swift_OutputByteStream')->shouldIgnoreMissing(); + } + + private function _createInputByteStream($stub = false) + { + return $this->getMockery('Swift_InputByteStream')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/PlainContentEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/PlainContentEncoderTest.php new file mode 100644 index 00000000..526cedc5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/PlainContentEncoderTest.php @@ -0,0 +1,173 @@ +_getEncoder('7bit'); + $this->assertEquals('7bit', $encoder->getName()); + + $encoder = $this->_getEncoder('8bit'); + $this->assertEquals('8bit', $encoder->getName()); + } + + public function testNoOctetsAreModifiedInString() + { + $encoder = $this->_getEncoder('7bit'); + foreach (range(0x00, 0xFF) as $octet) { + $byte = pack('C', $octet); + $this->assertIdenticalBinary($byte, $encoder->encodeString($byte)); + } + } + + public function testNoOctetsAreModifiedInByteStream() + { + $encoder = $this->_getEncoder('7bit'); + foreach (range(0x00, 0xFF) as $octet) { + $byte = pack('C', $octet); + + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn($byte); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder->encodeByteStream($os, $is); + $this->assertIdenticalBinary($byte, $collection->content); + } + } + + public function testLineLengthCanBeSpecified() + { + $encoder = $this->_getEncoder('7bit'); + + $chars = array(); + for ($i = 0; $i < 50; $i++) { + $chars[] = 'a'; + } + $input = implode(' ', $chars); //99 chars long + + $this->assertEquals( + 'a a a a a a a a a a a a a a a a a a a a a a a a a '."\r\n".//50 * + 'a a a a a a a a a a a a a a a a a a a a a a a a a', //99 + $encoder->encodeString($input, 0, 50), + '%s: Lines should be wrapped at 50 chars' + ); + } + + public function testLineLengthCanBeSpecifiedInByteStream() + { + $encoder = $this->_getEncoder('7bit'); + + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + + for ($i = 0; $i < 50; $i++) { + $os->shouldReceive('read') + ->once() + ->andReturn('a '); + } + + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder->encodeByteStream($os, $is, 0, 50); + $this->assertEquals( + str_repeat('a ', 25)."\r\n".str_repeat('a ', 25), + $collection->content + ); + } + + public function testencodeStringGeneratesCorrectCrlf() + { + $encoder = $this->_getEncoder('7bit', true); + $this->assertEquals("a\r\nb", $encoder->encodeString("a\rb"), + '%s: Line endings should be standardized' + ); + $this->assertEquals("a\r\nb", $encoder->encodeString("a\nb"), + '%s: Line endings should be standardized' + ); + $this->assertEquals("a\r\n\r\nb", $encoder->encodeString("a\n\rb"), + '%s: Line endings should be standardized' + ); + $this->assertEquals("a\r\n\r\nb", $encoder->encodeString("a\r\rb"), + '%s: Line endings should be standardized' + ); + $this->assertEquals("a\r\n\r\nb", $encoder->encodeString("a\n\nb"), + '%s: Line endings should be standardized' + ); + } + + public function crlfProvider() + { + return array( + array("\r", "a\r\nb"), + array("\n", "a\r\nb"), + array("\n\r", "a\r\n\r\nb"), + array("\n\n", "a\r\n\r\nb"), + array("\r\r", "a\r\n\r\nb"), + ); + } + + /** + * @dataProvider crlfProvider + */ + public function testCanonicEncodeByteStreamGeneratesCorrectCrlf($test, $expected) + { + $encoder = $this->_getEncoder('7bit', true); + + $os = $this->_createOutputByteStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $os->shouldReceive('read') + ->once() + ->andReturn('a'); + $os->shouldReceive('read') + ->once() + ->andReturn($test); + $os->shouldReceive('read') + ->once() + ->andReturn('b'); + $os->shouldReceive('read') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder->encodeByteStream($os, $is); + $this->assertEquals($expected, $collection->content); + } + + // -- Private helpers + + private function _getEncoder($name, $canonical = false) + { + return new Swift_Mime_ContentEncoder_PlainContentEncoder($name, $canonical); + } + + private function _createOutputByteStream($stub = false) + { + return $this->getMockery('Swift_OutputByteStream')->shouldIgnoreMissing(); + } + + private function _createInputByteStream($stub = false) + { + return $this->getMockery('Swift_InputByteStream')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/QpContentEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/QpContentEncoderTest.php new file mode 100644 index 00000000..66fa8f38 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/ContentEncoder/QpContentEncoderTest.php @@ -0,0 +1,496 @@ +_createCharacterStream(true) + ); + $this->assertEquals('quoted-printable', $encoder->getName()); + } + + /* -- RFC 2045, 6.7 -- + (1) (General 8bit representation) Any octet, except a CR or + LF that is part of a CRLF line break of the canonical + (standard) form of the data being encoded, may be + represented by an "=" followed by a two digit + hexadecimal representation of the octet's value. The + digits of the hexadecimal alphabet, for this purpose, + are "0123456789ABCDEF". Uppercase letters must be + used; lowercase letters are not allowed. Thus, for + example, the decimal value 12 (US-ASCII form feed) can + be represented by "=0C", and the decimal value 61 (US- + ASCII EQUAL SIGN) can be represented by "=3D". This + rule must be followed except when the following rules + allow an alternative encoding. + */ + + public function testPermittedCharactersAreNotEncoded() + { + /* -- RFC 2045, 6.7 -- + (2) (Literal representation) Octets with decimal values of + 33 through 60 inclusive, and 62 through 126, inclusive, + MAY be represented as the US-ASCII characters which + correspond to those octets (EXCLAMATION POINT through + LESS THAN, and GREATER THAN through TILDE, + respectively). + */ + + foreach (array_merge(range(33, 60), range(62, 126)) as $ordinal) { + $char = chr($ordinal); + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertIdenticalBinary($char, $collection->content); + } + } + + public function testLinearWhiteSpaceAtLineEndingIsEncoded() + { + /* -- RFC 2045, 6.7 -- + (3) (White Space) Octets with values of 9 and 32 MAY be + represented as US-ASCII TAB (HT) and SPACE characters, + respectively, but MUST NOT be so represented at the end + of an encoded line. Any TAB (HT) or SPACE characters + on an encoded line MUST thus be followed on that line + by a printable character. In particular, an "=" at the + end of an encoded line, indicating a soft line break + (see rule #5) may follow one or more TAB (HT) or SPACE + characters. It follows that an octet with decimal + value 9 or 32 appearing at the end of an encoded line + must be represented according to Rule #1. This rule is + necessary because some MTAs (Message Transport Agents, + programs which transport messages from one user to + another, or perform a portion of such transfers) are + known to pad lines of text with SPACEs, and others are + known to remove "white space" characters from the end + of a line. Therefore, when decoding a Quoted-Printable + body, any trailing white space on a line must be + deleted, as it will necessarily have been added by + intermediate transport agents. + */ + + $HT = chr(0x09); //9 + $SPACE = chr(0x20); //32 + + //HT + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x09)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x09)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + + $this->assertEquals("a\t=09\r\nb", $collection->content); + + //SPACE + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x20)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x20)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + + $this->assertEquals("a =20\r\nb", $collection->content); + } + + public function testCRLFIsLeftAlone() + { + /* + (4) (Line Breaks) A line break in a text body, represented + as a CRLF sequence in the text canonical form, must be + represented by a (RFC 822) line break, which is also a + CRLF sequence, in the Quoted-Printable encoding. Since + the canonical representation of media types other than + text do not generally include the representation of + line breaks as CRLF sequences, no hard line breaks + (i.e. line breaks that are intended to be meaningful + and to be displayed to the user) can occur in the + quoted-printable encoding of such types. Sequences + like "=0D", "=0A", "=0A=0D" and "=0D=0A" will routinely + appear in non-text data represented in quoted- + printable, of course. + + Note that many implementations may elect to encode the + local representation of various content types directly + rather than converting to canonical form first, + encoding, and then converting back to local + representation. In particular, this may apply to plain + text material on systems that use newline conventions + other than a CRLF terminator sequence. Such an + implementation optimization is permissible, but only + when the combined canonicalization-encoding step is + equivalent to performing the three steps separately. + */ + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('c'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0D)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x0A)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertEquals("a\r\nb\r\nc\r\n", $collection->content); + } + + public function testLinesLongerThan76CharactersAreSoftBroken() + { + /* + (5) (Soft Line Breaks) The Quoted-Printable encoding + REQUIRES that encoded lines be no more than 76 + characters long. If longer lines are to be encoded + with the Quoted-Printable encoding, "soft" line breaks + must be used. An equal sign as the last character on a + encoded line indicates such a non-significant ("soft") + line break in the encoded text. + */ + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + + for ($seq = 0; $seq <= 140; ++$seq) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + } + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertEquals(str_repeat('a', 75)."=\r\n".str_repeat('a', 66), $collection->content); + } + + public function testMaxLineLengthCanBeSpecified() + { + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + + for ($seq = 0; $seq <= 100; ++$seq) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + } + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is, 0, 54); + $this->assertEquals(str_repeat('a', 53)."=\r\n".str_repeat('a', 48), $collection->content); + } + + public function testBytesBelowPermittedRangeAreEncoded() + { + /* + According to Rule (1 & 2) + */ + + foreach (range(0, 32) as $ordinal) { + $char = chr($ordinal); + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertEquals(sprintf('=%02X', $ordinal), $collection->content); + } + } + + public function testDecimalByte61IsEncoded() + { + /* + According to Rule (1 & 2) + */ + + $char = chr(61); + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(61)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertEquals(sprintf('=%02X', 61), $collection->content); + } + + public function testBytesAbovePermittedRangeAreEncoded() + { + /* + According to Rule (1 & 2) + */ + + foreach (range(127, 255) as $ordinal) { + $char = chr($ordinal); + + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($ordinal)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is); + $this->assertEquals(sprintf('=%02X', $ordinal), $collection->content); + } + } + + public function testFirstLineLengthCanBeDifferent() + { + $os = $this->_createOutputByteStream(true); + $charStream = $this->_createCharacterStream(); + $is = $this->_createInputByteStream(); + $collection = new Swift_StreamCollector(); + + $is->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturnUsing($collection); + $charStream->shouldReceive('flushContents') + ->once(); + $charStream->shouldReceive('importByteStream') + ->once() + ->with($os); + + for ($seq = 0; $seq <= 140; ++$seq) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + } + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($charStream); + $encoder->encodeByteStream($os, $is, 22); + $this->assertEquals( + str_repeat('a', 53)."=\r\n".str_repeat('a', 75)."=\r\n".str_repeat('a', 13), + $collection->content + ); + } + + public function testObserverInterfaceCanChangeCharset() + { + $stream = $this->_createCharacterStream(); + $stream->shouldReceive('setCharacterSet') + ->once() + ->with('windows-1252'); + + $encoder = new Swift_Mime_ContentEncoder_QpContentEncoder($stream); + $encoder->charsetChanged('windows-1252'); + } + + // -- Creation Methods + + private function _createCharacterStream($stub = false) + { + return $this->getMockery('Swift_CharacterStream')->shouldIgnoreMissing(); + } + + private function _createEncoder($charStream) + { + return new Swift_Mime_HeaderEncoder_QpHeaderEncoder($charStream); + } + + private function _createOutputByteStream($stub = false) + { + return $this->getMockery('Swift_OutputByteStream')->shouldIgnoreMissing(); + } + + private function _createInputByteStream($stub = false) + { + return $this->getMockery('Swift_InputByteStream')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/EmbeddedFileTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/EmbeddedFileTest.php new file mode 100644 index 00000000..f4c3ac89 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/EmbeddedFileTest.php @@ -0,0 +1,57 @@ +_createEmbeddedFile($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals( + Swift_Mime_MimeEntity::LEVEL_RELATED, $file->getNestingLevel() + ); + } + + public function testIdIsAutoGenerated() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addIdHeader') + ->once() + ->with('Content-ID', '/^.*?@.*?$/D'); + + $file = $this->_createEmbeddedFile($headers, $this->_createEncoder(), + $this->_createCache() + ); + } + + public function testDefaultDispositionIsInline() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addParameterizedHeader') + ->once() + ->with('Content-Disposition', 'inline'); + $headers->shouldReceive('addParameterizedHeader') + ->zeroOrMoreTimes(); + + $file = $this->_createEmbeddedFile($headers, $this->_createEncoder(), + $this->_createCache() + ); + } + + // -- Private helpers + + protected function _createAttachment($headers, $encoder, $cache, $mimeTypes = array()) + { + return $this->_createEmbeddedFile($headers, $encoder, $cache, $mimeTypes); + } + + private function _createEmbeddedFile($headers, $encoder, $cache) + { + return new Swift_Mime_EmbeddedFile($headers, $encoder, $cache, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/Base64HeaderEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/Base64HeaderEncoderTest.php new file mode 100644 index 00000000..35801556 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/Base64HeaderEncoderTest.php @@ -0,0 +1,13 @@ +assertEquals('B', $encoder->getName()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/QpHeaderEncoderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/QpHeaderEncoderTest.php new file mode 100644 index 00000000..54a792a6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/HeaderEncoder/QpHeaderEncoderTest.php @@ -0,0 +1,223 @@ +_createEncoder( + $this->_createCharacterStream(true) + ); + $this->assertEquals('Q', $encoder->getName()); + } + + public function testSpaceAndTabNeverAppear() + { + /* -- RFC 2047, 4. + Only a subset of the printable ASCII characters may be used in + 'encoded-text'. Space and tab characters are not allowed, so that + the beginning and end of an 'encoded-word' are obvious. + */ + + $charStream = $this->_createCharacterStream(); + $charStream->shouldReceive('readBytes') + ->atLeast()->times(6) + ->andReturn(array(ord('a')), array(0x20), array(0x09), array(0x20), array(ord('b')), false); + + $encoder = $this->_createEncoder($charStream); + $this->assertNotRegExp('~[ \t]~', $encoder->encodeString("a \t b"), + '%s: encoded-words in headers cannot contain LWSP as per RFC 2047.' + ); + } + + public function testSpaceIsRepresentedByUnderscore() + { + /* -- RFC 2047, 4.2. + (2) The 8-bit hexadecimal value 20 (e.g., ISO-8859-1 SPACE) may be + represented as "_" (underscore, ASCII 95.). (This character may + not pass through some internetwork mail gateways, but its use + will greatly enhance readability of "Q" encoded data with mail + readers that do not support this encoding.) Note that the "_" + always represents hexadecimal 20, even if the SPACE character + occupies a different code position in the character set in use. + */ + $charStream = $this->_createCharacterStream(); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(0x20)); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('b'))); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = $this->_createEncoder($charStream); + $this->assertEquals('a_b', $encoder->encodeString('a b'), + '%s: Spaces can be represented by more readable underscores as per RFC 2047.' + ); + } + + public function testEqualsAndQuestionAndUnderscoreAreEncoded() + { + /* -- RFC 2047, 4.2. + (3) 8-bit values which correspond to printable ASCII characters other + than "=", "?", and "_" (underscore), MAY be represented as those + characters. (But see section 5 for restrictions.) In + particular, SPACE and TAB MUST NOT be represented as themselves + within encoded words. + */ + $charStream = $this->_createCharacterStream(); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('='))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('?'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('_'))); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = $this->_createEncoder($charStream); + $this->assertEquals('=3D=3F=5F', $encoder->encodeString('=?_'), + '%s: Chars =, ? and _ (underscore) may not appear as per RFC 2047.' + ); + } + + public function testParensAndQuotesAreEncoded() + { + /* -- RFC 2047, 5 (2). + A "Q"-encoded 'encoded-word' which appears in a 'comment' MUST NOT + contain the characters "(", ")" or " + */ + + $charStream = $this->_createCharacterStream(); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('('))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('"'))); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord(')'))); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = $this->_createEncoder($charStream); + $this->assertEquals('=28=22=29', $encoder->encodeString('(")'), + '%s: Chars (, " (DQUOTE) and ) may not appear as per RFC 2047.' + ); + } + + public function testOnlyCharactersAllowedInPhrasesAreUsed() + { + /* -- RFC 2047, 5. + (3) As a replacement for a 'word' entity within a 'phrase', for example, + one that precedes an address in a From, To, or Cc header. The ABNF + definition for 'phrase' from RFC 822 thus becomes: + + phrase = 1*( encoded-word / word ) + + In this case the set of characters that may be used in a "Q"-encoded + 'encoded-word' is restricted to: . An 'encoded-word' that appears within a + 'phrase' MUST be separated from any adjacent 'word', 'text' or + 'special' by 'linear-white-space'. + */ + + $allowedBytes = array_merge( + range(ord('a'), ord('z')), range(ord('A'), ord('Z')), + range(ord('0'), ord('9')), + array(ord('!'), ord('*'), ord('+'), ord('-'), ord('/')) + ); + + foreach (range(0x00, 0xFF) as $byte) { + $char = pack('C', $byte); + + $charStream = $this->_createCharacterStream(); + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array($byte)); + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = $this->_createEncoder($charStream); + $encodedChar = $encoder->encodeString($char); + + if (in_array($byte, $allowedBytes)) { + $this->assertEquals($char, $encodedChar, + '%s: Character '.$char.' should not be encoded.' + ); + } elseif (0x20 == $byte) { + //Special case + $this->assertEquals('_', $encodedChar, + '%s: Space character should be replaced.' + ); + } else { + $this->assertEquals(sprintf('=%02X', $byte), $encodedChar, + '%s: Byte '.$byte.' should be encoded.' + ); + } + } + } + + public function testEqualsNeverAppearsAtEndOfLine() + { + /* -- RFC 2047, 5 (3). + The 'encoded-text' in an 'encoded-word' must be self-contained; + 'encoded-text' MUST NOT be continued from one 'encoded-word' to + another. This implies that the 'encoded-text' portion of a "B" + 'encoded-word' will be a multiple of 4 characters long; for a "Q" + 'encoded-word', any "=" character that appears in the 'encoded-text' + portion will be followed by two hexadecimal characters. + */ + + $input = str_repeat('a', 140); + + $charStream = $this->_createCharacterStream(); + + $output = ''; + $seq = 0; + for (; $seq < 140; ++$seq) { + $charStream->shouldReceive('readBytes') + ->once() + ->andReturn(array(ord('a'))); + + if (75 == $seq) { + $output .= "\r\n"; // =\r\n + } + $output .= 'a'; + } + + $charStream->shouldReceive('readBytes') + ->zeroOrMoreTimes() + ->andReturn(false); + + $encoder = $this->_createEncoder($charStream); + $this->assertEquals($output, $encoder->encodeString($input)); + } + + // -- Creation Methods + + private function _createEncoder($charStream) + { + return new Swift_Mime_HeaderEncoder_QpHeaderEncoder($charStream); + } + + private function _createCharacterStream($stub = false) + { + return $this->getMockery('Swift_CharacterStream')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/DateHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/DateHeaderTest.php new file mode 100644 index 00000000..1822ea68 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/DateHeaderTest.php @@ -0,0 +1,69 @@ +_getHeader('Date'); + $this->assertEquals(Swift_Mime_Header::TYPE_DATE, $header->getFieldType()); + } + + public function testGetTimestamp() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setTimestamp($timestamp); + $this->assertSame($timestamp, $header->getTimestamp()); + } + + public function testTimestampCanBeSetBySetter() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setTimestamp($timestamp); + $this->assertSame($timestamp, $header->getTimestamp()); + } + + public function testIntegerTimestampIsConvertedToRfc2822Date() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setTimestamp($timestamp); + $this->assertEquals(date('r', $timestamp), $header->getFieldBody()); + } + + public function testSetBodyModel() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setFieldBodyModel($timestamp); + $this->assertEquals(date('r', $timestamp), $header->getFieldBody()); + } + + public function testGetBodyModel() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setTimestamp($timestamp); + $this->assertEquals($timestamp, $header->getFieldBodyModel()); + } + + public function testToString() + { + $timestamp = time(); + $header = $this->_getHeader('Date'); + $header->setTimestamp($timestamp); + $this->assertEquals('Date: '.date('r', $timestamp)."\r\n", + $header->toString() + ); + } + + private function _getHeader($name) + { + return new Swift_Mime_Headers_DateHeader($name, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php new file mode 100644 index 00000000..93b3f609 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/IdentificationHeaderTest.php @@ -0,0 +1,189 @@ +_getHeader('Message-ID'); + $this->assertEquals(Swift_Mime_Header::TYPE_ID, $header->getFieldType()); + } + + public function testValueMatchesMsgIdSpec() + { + /* -- RFC 2822, 3.6.4. + message-id = "Message-ID:" msg-id CRLF + + in-reply-to = "In-Reply-To:" 1*msg-id CRLF + + references = "References:" 1*msg-id CRLF + + msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS] + + id-left = dot-atom-text / no-fold-quote / obs-id-left + + id-right = dot-atom-text / no-fold-literal / obs-id-right + + no-fold-quote = DQUOTE *(qtext / quoted-pair) DQUOTE + + no-fold-literal = "[" *(dtext / quoted-pair) "]" + */ + + $header = $this->_getHeader('Message-ID'); + $header->setId('id-left@id-right'); + $this->assertEquals('', $header->getFieldBody()); + } + + public function testIdCanBeRetrievedVerbatim() + { + $header = $this->_getHeader('Message-ID'); + $header->setId('id-left@id-right'); + $this->assertEquals('id-left@id-right', $header->getId()); + } + + public function testMultipleIdsCanBeSet() + { + $header = $this->_getHeader('References'); + $header->setIds(array('a@b', 'x@y')); + $this->assertEquals(array('a@b', 'x@y'), $header->getIds()); + } + + public function testSettingMultipleIdsProducesAListValue() + { + /* -- RFC 2822, 3.6.4. + The "References:" and "In-Reply-To:" field each contain one or more + unique message identifiers, optionally separated by CFWS. + + .. SNIP .. + + in-reply-to = "In-Reply-To:" 1*msg-id CRLF + + references = "References:" 1*msg-id CRLF + */ + + $header = $this->_getHeader('References'); + $header->setIds(array('a@b', 'x@y')); + $this->assertEquals(' ', $header->getFieldBody()); + } + + public function testIdLeftCanBeQuoted() + { + /* -- RFC 2822, 3.6.4. + id-left = dot-atom-text / no-fold-quote / obs-id-left + */ + + $header = $this->_getHeader('References'); + $header->setId('"ab"@c'); + $this->assertEquals('"ab"@c', $header->getId()); + $this->assertEquals('<"ab"@c>', $header->getFieldBody()); + } + + public function testIdLeftCanContainAnglesAsQuotedPairs() + { + /* -- RFC 2822, 3.6.4. + no-fold-quote = DQUOTE *(qtext / quoted-pair) DQUOTE + */ + + $header = $this->_getHeader('References'); + $header->setId('"a\\<\\>b"@c'); + $this->assertEquals('"a\\<\\>b"@c', $header->getId()); + $this->assertEquals('<"a\\<\\>b"@c>', $header->getFieldBody()); + } + + public function testIdLeftCanBeDotAtom() + { + $header = $this->_getHeader('References'); + $header->setId('a.b+&%$.c@d'); + $this->assertEquals('a.b+&%$.c@d', $header->getId()); + $this->assertEquals('', $header->getFieldBody()); + } + + public function testInvalidIdLeftThrowsException() + { + try { + $header = $this->_getHeader('References'); + $header->setId('a b c@d'); + $this->fail( + 'Exception should be thrown since "a b c" is not valid id-left.' + ); + } catch (Exception $e) { + } + } + + public function testIdRightCanBeDotAtom() + { + /* -- RFC 2822, 3.6.4. + id-right = dot-atom-text / no-fold-literal / obs-id-right + */ + + $header = $this->_getHeader('References'); + $header->setId('a@b.c+&%$.d'); + $this->assertEquals('a@b.c+&%$.d', $header->getId()); + $this->assertEquals('', $header->getFieldBody()); + } + + public function testIdRightCanBeLiteral() + { + /* -- RFC 2822, 3.6.4. + no-fold-literal = "[" *(dtext / quoted-pair) "]" + */ + + $header = $this->_getHeader('References'); + $header->setId('a@[1.2.3.4]'); + $this->assertEquals('a@[1.2.3.4]', $header->getId()); + $this->assertEquals('', $header->getFieldBody()); + } + + public function testInvalidIdRightThrowsException() + { + try { + $header = $this->_getHeader('References'); + $header->setId('a@b c d'); + $this->fail( + 'Exception should be thrown since "b c d" is not valid id-right.' + ); + } catch (Exception $e) { + } + } + + public function testMissingAtSignThrowsException() + { + /* -- RFC 2822, 3.6.4. + msg-id = [CFWS] "<" id-left "@" id-right ">" [CFWS] + */ + + try { + $header = $this->_getHeader('References'); + $header->setId('abc'); + $this->fail( + 'Exception should be thrown since "abc" is does not contain @.' + ); + } catch (Exception $e) { + } + } + + public function testSetBodyModel() + { + $header = $this->_getHeader('Message-ID'); + $header->setFieldBodyModel('a@b'); + $this->assertEquals(array('a@b'), $header->getIds()); + } + + public function testGetBodyModel() + { + $header = $this->_getHeader('Message-ID'); + $header->setId('a@b'); + $this->assertEquals(array('a@b'), $header->getFieldBodyModel()); + } + + public function testStringValue() + { + $header = $this->_getHeader('References'); + $header->setIds(array('a@b', 'x@y')); + $this->assertEquals('References: '."\r\n", $header->toString()); + } + + private function _getHeader($name) + { + return new Swift_Mime_Headers_IdentificationHeader($name, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/MailboxHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/MailboxHeaderTest.php new file mode 100644 index 00000000..e5f2238a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/MailboxHeaderTest.php @@ -0,0 +1,327 @@ +_getHeader('To', $this->_getEncoder('Q', true)); + $this->assertEquals(Swift_Mime_Header::TYPE_MAILBOX, $header->getFieldType()); + } + + public function testMailboxIsSetForAddress() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses('chris@swiftmailer.org'); + $this->assertEquals(array('chris@swiftmailer.org'), + $header->getNameAddressStrings() + ); + } + + public function testMailboxIsRenderedForNameAddress() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array('chris@swiftmailer.org' => 'Chris Corbyn')); + $this->assertEquals( + array('Chris Corbyn '), $header->getNameAddressStrings() + ); + } + + public function testAddressCanBeReturnedForAddress() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses('chris@swiftmailer.org'); + $this->assertEquals(array('chris@swiftmailer.org'), $header->getAddresses()); + } + + public function testAddressCanBeReturnedForNameAddress() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array('chris@swiftmailer.org' => 'Chris Corbyn')); + $this->assertEquals(array('chris@swiftmailer.org'), $header->getAddresses()); + } + + public function testQuotesInNameAreQuoted() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn, "DHE"', + )); + $this->assertEquals( + array('"Chris Corbyn, \"DHE\"" '), + $header->getNameAddressStrings() + ); + } + + public function testEscapeCharsInNameAreQuoted() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn, \\escaped\\', + )); + $this->assertEquals( + array('"Chris Corbyn, \\\\escaped\\\\" '), + $header->getNameAddressStrings() + ); + } + + public function testGetMailboxesReturnsNameValuePairs() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn, DHE', + )); + $this->assertEquals( + array('chris@swiftmailer.org' => 'Chris Corbyn, DHE'), $header->getNameAddresses() + ); + } + + public function testMultipleAddressesCanBeSetAndFetched() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses(array( + 'chris@swiftmailer.org', 'mark@swiftmailer.org', + )); + $this->assertEquals( + array('chris@swiftmailer.org', 'mark@swiftmailer.org'), + $header->getAddresses() + ); + } + + public function testMultipleAddressesAsMailboxes() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses(array( + 'chris@swiftmailer.org', 'mark@swiftmailer.org', + )); + $this->assertEquals( + array('chris@swiftmailer.org' => null, 'mark@swiftmailer.org' => null), + $header->getNameAddresses() + ); + } + + public function testMultipleAddressesAsMailboxStrings() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses(array( + 'chris@swiftmailer.org', 'mark@swiftmailer.org', + )); + $this->assertEquals( + array('chris@swiftmailer.org', 'mark@swiftmailer.org'), + $header->getNameAddressStrings() + ); + } + + public function testMultipleNamedMailboxesReturnsMultipleAddresses() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals( + array('chris@swiftmailer.org', 'mark@swiftmailer.org'), + $header->getAddresses() + ); + } + + public function testMultipleNamedMailboxesReturnsMultipleMailboxes() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + ), + $header->getNameAddresses() + ); + } + + public function testMultipleMailboxesProducesMultipleMailboxStrings() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals(array( + 'Chris Corbyn ', + 'Mark Corbyn ', + ), + $header->getNameAddressStrings() + ); + } + + public function testSetAddressesOverwritesAnyMailboxes() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals( + array('chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn',), + $header->getNameAddresses() + ); + $this->assertEquals( + array('chris@swiftmailer.org', 'mark@swiftmailer.org'), + $header->getAddresses() + ); + + $header->setAddresses(array('chris@swiftmailer.org', 'mark@swiftmailer.org')); + + $this->assertEquals( + array('chris@swiftmailer.org' => null, 'mark@swiftmailer.org' => null), + $header->getNameAddresses() + ); + $this->assertEquals( + array('chris@swiftmailer.org', 'mark@swiftmailer.org'), + $header->getAddresses() + ); + } + + public function testNameIsEncodedIfNonAscii() + { + $name = 'C'.pack('C', 0x8F).'rbyn'; + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($name, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('C=8Frbyn'); + + $header = $this->_getHeader('From', $encoder); + $header->setNameAddresses(array('chris@swiftmailer.org' => 'Chris '.$name)); + + $addresses = $header->getNameAddressStrings(); + $this->assertEquals( + 'Chris =?'.$this->_charset.'?Q?C=8Frbyn?= ', + array_shift($addresses) + ); + } + + public function testEncodingLineLengthCalculations() + { + /* -- RFC 2047, 2. + An 'encoded-word' may not be more than 75 characters long, including + 'charset', 'encoding', 'encoded-text', and delimiters. + */ + + $name = 'C'.pack('C', 0x8F).'rbyn'; + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($name, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('C=8Frbyn'); + + $header = $this->_getHeader('From', $encoder); + $header->setNameAddresses(array('chris@swiftmailer.org' => 'Chris '.$name)); + + $header->getNameAddressStrings(); + } + + public function testGetValueReturnsMailboxStringValue() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + )); + $this->assertEquals( + 'Chris Corbyn ', $header->getFieldBody() + ); + } + + public function testGetValueReturnsMailboxStringValueForMultipleMailboxes() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals( + 'Chris Corbyn , Mark Corbyn ', + $header->getFieldBody() + ); + } + + public function testRemoveAddressesWithSingleValue() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $header->removeAddresses('chris@swiftmailer.org'); + $this->assertEquals(array('mark@swiftmailer.org'), + $header->getAddresses() + ); + } + + public function testRemoveAddressesWithList() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $header->removeAddresses( + array('chris@swiftmailer.org', 'mark@swiftmailer.org') + ); + $this->assertEquals(array(), $header->getAddresses()); + } + + public function testSetBodyModel() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setFieldBodyModel('chris@swiftmailer.org'); + $this->assertEquals(array('chris@swiftmailer.org' => null), $header->getNameAddresses()); + } + + public function testGetBodyModel() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setAddresses(array('chris@swiftmailer.org')); + $this->assertEquals(array('chris@swiftmailer.org' => null), $header->getFieldBodyModel()); + } + + public function testToString() + { + $header = $this->_getHeader('From', $this->_getEncoder('Q', true)); + $header->setNameAddresses(array( + 'chris@swiftmailer.org' => 'Chris Corbyn', + 'mark@swiftmailer.org' => 'Mark Corbyn', + )); + $this->assertEquals( + 'From: Chris Corbyn , '. + 'Mark Corbyn '."\r\n", + $header->toString() + ); + } + + private function _getHeader($name, $encoder) + { + $header = new Swift_Mime_Headers_MailboxHeader($name, $encoder, new Swift_Mime_Grammar()); + $header->setCharset($this->_charset); + + return $header; + } + + private function _getEncoder($type, $stub = false) + { + $encoder = $this->getMockery('Swift_Mime_HeaderEncoder')->shouldIgnoreMissing(); + $encoder->shouldReceive('getName') + ->zeroOrMoreTimes() + ->andReturn($type); + + return $encoder; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/ParameterizedHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/ParameterizedHeaderTest.php new file mode 100644 index 00000000..0f3fe145 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/ParameterizedHeaderTest.php @@ -0,0 +1,400 @@ +_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $this->assertEquals(Swift_Mime_Header::TYPE_PARAMETERIZED, $header->getFieldType()); + } + + public function testValueIsReturnedVerbatim() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setValue('text/plain'); + $this->assertEquals('text/plain', $header->getValue()); + } + + public function testParametersAreAppended() + { + /* -- RFC 2045, 5.1 + parameter := attribute "=" value + + attribute := token + ; Matching of attributes + ; is ALWAYS case-insensitive. + + value := token / quoted-string + + token := 1* + + tspecials := "(" / ")" / "<" / ">" / "@" / + "," / ";" / ":" / "\" / <"> + "/" / "[" / "]" / "?" / "=" + ; Must be in quoted-string, + ; to use within parameter values + */ + + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setValue('text/plain'); + $header->setParameters(array('charset' => 'utf-8')); + $this->assertEquals('text/plain; charset=utf-8', $header->getFieldBody()); + } + + public function testSpaceInParamResultsInQuotedString() + { + $header = $this->_getHeader('Content-Disposition', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setValue('attachment'); + $header->setParameters(array('filename' => 'my file.txt')); + $this->assertEquals('attachment; filename="my file.txt"', + $header->getFieldBody() + ); + } + + public function testLongParamsAreBrokenIntoMultipleAttributeStrings() + { + /* -- RFC 2231, 3. + The asterisk character ("*") followed + by a decimal count is employed to indicate that multiple parameters + are being used to encapsulate a single parameter value. The count + starts at 0 and increments by 1 for each subsequent section of the + parameter value. Decimal values are used and neither leading zeroes + nor gaps in the sequence are allowed. + + The original parameter value is recovered by concatenating the + various sections of the parameter, in order. For example, the + content-type field + + Content-Type: message/external-body; access-type=URL; + URL*0="ftp://"; + URL*1="cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar" + + is semantically identical to + + Content-Type: message/external-body; access-type=URL; + URL="ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar" + + Note that quotes around parameter values are part of the value + syntax; they are NOT part of the value itself. Furthermore, it is + explicitly permitted to have a mixture of quoted and unquoted + continuation fields. + */ + + $value = str_repeat('a', 180); + + $encoder = $this->_getParameterEncoder(); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), 63, \Mockery::any()) + ->andReturn(str_repeat('a', 63)."\r\n". + str_repeat('a', 63)."\r\n".str_repeat('a', 54)); + + $header = $this->_getHeader('Content-Disposition', + $this->_getHeaderEncoder('Q', true), $encoder + ); + $header->setValue('attachment'); + $header->setParameters(array('filename' => $value)); + $header->setMaxLineLength(78); + $this->assertEquals( + 'attachment; '. + 'filename*0*=utf-8\'\''.str_repeat('a', 63).";\r\n ". + 'filename*1*='.str_repeat('a', 63).";\r\n ". + 'filename*2*='.str_repeat('a', 54), + $header->getFieldBody() + ); + } + + public function testEncodedParamDataIncludesCharsetAndLanguage() + { + /* -- RFC 2231, 4. + Asterisks ("*") are reused to provide the indicator that language and + character set information is present and encoding is being used. A + single quote ("'") is used to delimit the character set and language + information at the beginning of the parameter value. Percent signs + ("%") are used as the encoding flag, which agrees with RFC 2047. + + Specifically, an asterisk at the end of a parameter name acts as an + indicator that character set and language information may appear at + the beginning of the parameter value. A single quote is used to + separate the character set, language, and actual value information in + the parameter value string, and an percent sign is used to flag + octets encoded in hexadecimal. For example: + + Content-Type: application/x-stuff; + title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A + + Note that it is perfectly permissible to leave either the character + set or language field blank. Note also that the single quote + delimiters MUST be present even when one of the field values is + omitted. + */ + + $value = str_repeat('a', 20).pack('C', 0x8F).str_repeat('a', 10); + + $encoder = $this->_getParameterEncoder(); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, 12, 62, \Mockery::any()) + ->andReturn(str_repeat('a', 20).'%8F'.str_repeat('a', 10)); + + $header = $this->_getHeader('Content-Disposition', + $this->_getHeaderEncoder('Q', true), $encoder + ); + $header->setValue('attachment'); + $header->setParameters(array('filename' => $value)); + $header->setMaxLineLength(78); + $header->setLanguage($this->_lang); + $this->assertEquals( + 'attachment; filename*='.$this->_charset."'".$this->_lang."'". + str_repeat('a', 20).'%8F'.str_repeat('a', 10), + $header->getFieldBody() + ); + } + + public function testMultipleEncodedParamLinesAreFormattedCorrectly() + { + /* -- RFC 2231, 4.1. + Character set and language information may be combined with the + parameter continuation mechanism. For example: + + Content-Type: application/x-stuff + title*0*=us-ascii'en'This%20is%20even%20more%20 + title*1*=%2A%2A%2Afun%2A%2A%2A%20 + title*2="isn't it!" + + Note that: + + (1) Language and character set information only appear at + the beginning of a given parameter value. + + (2) Continuations do not provide a facility for using more + than one character set or language in the same + parameter value. + + (3) A value presented using multiple continuations may + contain a mixture of encoded and unencoded segments. + + (4) The first segment of a continuation MUST be encoded if + language and character set information are given. + + (5) If the first segment of a continued parameter value is + encoded the language and character set field delimiters + MUST be present even when the fields are left blank. + */ + + $value = str_repeat('a', 20).pack('C', 0x8F).str_repeat('a', 60); + + $encoder = $this->_getParameterEncoder(); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, 12, 62, \Mockery::any()) + ->andReturn(str_repeat('a', 20).'%8F'.str_repeat('a', 28)."\r\n". + str_repeat('a', 32)); + + $header = $this->_getHeader('Content-Disposition', + $this->_getHeaderEncoder('Q', true), $encoder + ); + $header->setValue('attachment'); + $header->setParameters(array('filename' => $value)); + $header->setMaxLineLength(78); + $header->setLanguage($this->_lang); + $this->assertEquals( + 'attachment; filename*0*='.$this->_charset."'".$this->_lang."'". + str_repeat('a', 20).'%8F'.str_repeat('a', 28).";\r\n ". + 'filename*1*='.str_repeat('a', 32), + $header->getFieldBody() + ); + } + + public function testToString() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setValue('text/html'); + $header->setParameters(array('charset' => 'utf-8')); + $this->assertEquals('Content-Type: text/html; charset=utf-8'."\r\n", + $header->toString() + ); + } + + public function testValueCanBeEncodedIfNonAscii() + { + $value = 'fo'.pack('C', 0x8F).'bar'; + + $encoder = $this->_getHeaderEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo=8Fbar'); + + $header = $this->_getHeader('X-Foo', $encoder, $this->_getParameterEncoder(true)); + $header->setValue($value); + $header->setParameters(array('lookslike' => 'foobar')); + $this->assertEquals('X-Foo: =?utf-8?Q?fo=8Fbar?=; lookslike=foobar'."\r\n", + $header->toString() + ); + } + + public function testValueAndParamCanBeEncodedIfNonAscii() + { + $value = 'fo'.pack('C', 0x8F).'bar'; + + $encoder = $this->_getHeaderEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo=8Fbar'); + + $paramEncoder = $this->_getParameterEncoder(); + $paramEncoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo%8Fbar'); + + $header = $this->_getHeader('X-Foo', $encoder, $paramEncoder); + $header->setValue($value); + $header->setParameters(array('says' => $value)); + $this->assertEquals("X-Foo: =?utf-8?Q?fo=8Fbar?=; says*=utf-8''fo%8Fbar\r\n", + $header->toString() + ); + } + + public function testParamsAreEncodedWithEncodedWordsIfNoParamEncoderSet() + { + $value = 'fo'.pack('C', 0x8F).'bar'; + + $encoder = $this->_getHeaderEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo=8Fbar'); + + $header = $this->_getHeader('X-Foo', $encoder, null); + $header->setValue('bar'); + $header->setParameters(array('says' => $value)); + $this->assertEquals("X-Foo: bar; says=\"=?utf-8?Q?fo=8Fbar?=\"\r\n", + $header->toString() + ); + } + + public function testLanguageInformationAppearsInEncodedWords() + { + /* -- RFC 2231, 5. + 5. Language specification in Encoded Words + + RFC 2047 provides support for non-US-ASCII character sets in RFC 822 + message header comments, phrases, and any unstructured text field. + This is done by defining an encoded word construct which can appear + in any of these places. Given that these are fields intended for + display, it is sometimes necessary to associate language information + with encoded words as well as just the character set. This + specification extends the definition of an encoded word to allow the + inclusion of such information. This is simply done by suffixing the + character set specification with an asterisk followed by the language + tag. For example: + + From: =?US-ASCII*EN?Q?Keith_Moore?= + */ + + $value = 'fo'.pack('C', 0x8F).'bar'; + + $encoder = $this->_getHeaderEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo=8Fbar'); + + $paramEncoder = $this->_getParameterEncoder(); + $paramEncoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo%8Fbar'); + + $header = $this->_getHeader('X-Foo', $encoder, $paramEncoder); + $header->setLanguage('en'); + $header->setValue($value); + $header->setParameters(array('says' => $value)); + $this->assertEquals("X-Foo: =?utf-8*en?Q?fo=8Fbar?=; says*=utf-8'en'fo%8Fbar\r\n", + $header->toString() + ); + } + + public function testSetBodyModel() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setFieldBodyModel('text/html'); + $this->assertEquals('text/html', $header->getValue()); + } + + public function testGetBodyModel() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setValue('text/plain'); + $this->assertEquals('text/plain', $header->getFieldBodyModel()); + } + + public function testSetParameter() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setParameters(array('charset' => 'utf-8', 'delsp' => 'yes')); + $header->setParameter('delsp', 'no'); + $this->assertEquals(array('charset' => 'utf-8', 'delsp' => 'no'), + $header->getParameters() + ); + } + + public function testGetParameter() + { + $header = $this->_getHeader('Content-Type', + $this->_getHeaderEncoder('Q', true), $this->_getParameterEncoder(true) + ); + $header->setParameters(array('charset' => 'utf-8', 'delsp' => 'yes')); + $this->assertEquals('utf-8', $header->getParameter('charset')); + } + + // -- Private helper + + private function _getHeader($name, $encoder, $paramEncoder) + { + $header = new Swift_Mime_Headers_ParameterizedHeader($name, $encoder, + $paramEncoder, new Swift_Mime_Grammar() + ); + $header->setCharset($this->_charset); + + return $header; + } + + private function _getHeaderEncoder($type, $stub = false) + { + $encoder = $this->getMockery('Swift_Mime_HeaderEncoder')->shouldIgnoreMissing(); + $encoder->shouldReceive('getName') + ->zeroOrMoreTimes() + ->andReturn($type); + + return $encoder; + } + + private function _getParameterEncoder($stub = false) + { + return $this->getMockery('Swift_Encoder')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/PathHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/PathHeaderTest.php new file mode 100644 index 00000000..a9f35e9d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/PathHeaderTest.php @@ -0,0 +1,77 @@ +_getHeader('Return-Path'); + $this->assertEquals(Swift_Mime_Header::TYPE_PATH, $header->getFieldType()); + } + + public function testSingleAddressCanBeSetAndFetched() + { + $header = $this->_getHeader('Return-Path'); + $header->setAddress('chris@swiftmailer.org'); + $this->assertEquals('chris@swiftmailer.org', $header->getAddress()); + } + + public function testAddressMustComplyWithRfc2822() + { + try { + $header = $this->_getHeader('Return-Path'); + $header->setAddress('chr is@swiftmailer.org'); + $this->fail('Addresses not valid according to RFC 2822 addr-spec grammar must be rejected.'); + } catch (Exception $e) { + } + } + + public function testValueIsAngleAddrWithValidAddress() + { + /* -- RFC 2822, 3.6.7. + + return = "Return-Path:" path CRLF + + path = ([CFWS] "<" ([CFWS] / addr-spec) ">" [CFWS]) / + obs-path + */ + + $header = $this->_getHeader('Return-Path'); + $header->setAddress('chris@swiftmailer.org'); + $this->assertEquals('', $header->getFieldBody()); + } + + public function testValueIsEmptyAngleBracketsIfEmptyAddressSet() + { + $header = $this->_getHeader('Return-Path'); + $header->setAddress(''); + $this->assertEquals('<>', $header->getFieldBody()); + } + + public function testSetBodyModel() + { + $header = $this->_getHeader('Return-Path'); + $header->setFieldBodyModel('foo@bar.tld'); + $this->assertEquals('foo@bar.tld', $header->getAddress()); + } + + public function testGetBodyModel() + { + $header = $this->_getHeader('Return-Path'); + $header->setAddress('foo@bar.tld'); + $this->assertEquals('foo@bar.tld', $header->getFieldBodyModel()); + } + + public function testToString() + { + $header = $this->_getHeader('Return-Path'); + $header->setAddress('chris@swiftmailer.org'); + $this->assertEquals('Return-Path: '."\r\n", + $header->toString() + ); + } + + private function _getHeader($name) + { + return new Swift_Mime_Headers_PathHeader($name, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/UnstructuredHeaderTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/UnstructuredHeaderTest.php new file mode 100644 index 00000000..2e1dc8ca --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/Headers/UnstructuredHeaderTest.php @@ -0,0 +1,355 @@ +_getHeader('Subject', $this->_getEncoder('Q', true)); + $this->assertEquals(Swift_Mime_Header::TYPE_TEXT, $header->getFieldType()); + } + + public function testGetNameReturnsNameVerbatim() + { + $header = $this->_getHeader('Subject', $this->_getEncoder('Q', true)); + $this->assertEquals('Subject', $header->getFieldName()); + } + + public function testGetValueReturnsValueVerbatim() + { + $header = $this->_getHeader('Subject', $this->_getEncoder('Q', true)); + $header->setValue('Test'); + $this->assertEquals('Test', $header->getValue()); + } + + public function testBasicStructureIsKeyValuePair() + { + /* -- RFC 2822, 2.2 + Header fields are lines composed of a field name, followed by a colon + (":"), followed by a field body, and terminated by CRLF. + */ + $header = $this->_getHeader('Subject', $this->_getEncoder('Q', true)); + $header->setValue('Test'); + $this->assertEquals('Subject: Test'."\r\n", $header->toString()); + } + + public function testLongHeadersAreFoldedAtWordBoundary() + { + /* -- RFC 2822, 2.2.3 + Each header field is logically a single line of characters comprising + the field name, the colon, and the field body. For convenience + however, and to deal with the 998/78 character limitations per line, + the field body portion of a header field can be split into a multiple + line representation; this is called "folding". The general rule is + that wherever this standard allows for folding white space (not + simply WSP characters), a CRLF may be inserted before any WSP. + */ + + $value = 'The quick brown fox jumped over the fence, he was a very very '. + 'scary brown fox with a bushy tail'; + $header = $this->_getHeader('X-Custom-Header', + $this->_getEncoder('Q', true) + ); + $header->setValue($value); + $header->setMaxLineLength(78); //A safe [RFC 2822, 2.2.3] default + /* + X-Custom-Header: The quick brown fox jumped over the fence, he was a very very + scary brown fox with a bushy tail + */ + $this->assertEquals( + 'X-Custom-Header: The quick brown fox jumped over the fence, he was a'. + ' very very'."\r\n".//Folding + ' scary brown fox with a bushy tail'."\r\n", + $header->toString(), '%s: The header should have been folded at 78th char' + ); + } + + public function testPrintableAsciiOnlyAppearsInHeaders() + { + /* -- RFC 2822, 2.2. + A field name MUST be composed of printable US-ASCII characters (i.e., + characters that have values between 33 and 126, inclusive), except + colon. A field body may be composed of any US-ASCII characters, + except for CR and LF. + */ + + $nonAsciiChar = pack('C', 0x8F); + $header = $this->_getHeader('X-Test', $this->_getEncoder('Q', true)); + $header->setValue($nonAsciiChar); + $this->assertRegExp( + '~^[^:\x00-\x20\x80-\xFF]+: [^\x80-\xFF\r\n]+\r\n$~s', + $header->toString() + ); + } + + public function testEncodedWordsFollowGeneralStructure() + { + /* -- RFC 2047, 1. + Generally, an "encoded-word" is a sequence of printable ASCII + characters that begins with "=?", ends with "?=", and has two "?"s in + between. + */ + + $nonAsciiChar = pack('C', 0x8F); + $header = $this->_getHeader('X-Test', $this->_getEncoder('Q', true)); + $header->setValue($nonAsciiChar); + $this->assertRegExp( + '~^X-Test: \=?.*?\?.*?\?.*?\?=\r\n$~s', + $header->toString() + ); + } + + public function testEncodedWordIncludesCharsetAndEncodingMethodAndText() + { + /* -- RFC 2047, 2. + An 'encoded-word' is defined by the following ABNF grammar. The + notation of RFC 822 is used, with the exception that white space + characters MUST NOT appear between components of an 'encoded-word'. + + encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" + */ + + $nonAsciiChar = pack('C', 0x8F); + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($nonAsciiChar, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('=8F'); + + $header = $this->_getHeader('X-Test', $encoder); + $header->setValue($nonAsciiChar); + $this->assertEquals( + 'X-Test: =?'.$this->_charset.'?Q?=8F?='."\r\n", + $header->toString() + ); + } + + public function testEncodedWordsAreUsedToEncodedNonPrintableAscii() + { + //SPACE and TAB permitted + $nonPrintableBytes = array_merge( + range(0x00, 0x08), range(0x10, 0x19), array(0x7F) + ); + + foreach ($nonPrintableBytes as $byte) { + $char = pack('C', $byte); + $encodedChar = sprintf('=%02X', $byte); + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($char, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn($encodedChar); + + $header = $this->_getHeader('X-A', $encoder); + $header->setValue($char); + + $this->assertEquals( + 'X-A: =?'.$this->_charset.'?Q?'.$encodedChar.'?='."\r\n", + $header->toString(), '%s: Non-printable ascii should be encoded' + ); + } + } + + public function testEncodedWordsAreUsedToEncode8BitOctets() + { + $_8BitBytes = range(0x80, 0xFF); + + foreach ($_8BitBytes as $byte) { + $char = pack('C', $byte); + $encodedChar = sprintf('=%02X', $byte); + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($char, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn($encodedChar); + + $header = $this->_getHeader('X-A', $encoder); + $header->setValue($char); + + $this->assertEquals( + 'X-A: =?'.$this->_charset.'?Q?'.$encodedChar.'?='."\r\n", + $header->toString(), '%s: 8-bit octets should be encoded' + ); + } + } + + public function testEncodedWordsAreNoMoreThan75CharsPerLine() + { + /* -- RFC 2047, 2. + An 'encoded-word' may not be more than 75 characters long, including + 'charset', 'encoding', 'encoded-text', and delimiters. + + ... SNIP ... + + While there is no limit to the length of a multiple-line header + field, each line of a header field that contains one or more + 'encoded-word's is limited to 76 characters. + */ + + $nonAsciiChar = pack('C', 0x8F); + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($nonAsciiChar, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('=8F'); + //Note that multi-line headers begin with LWSP which makes 75 + 1 = 76 + //Note also that =?utf-8?q??= is 12 chars which makes 75 - 12 = 63 + + //* X-Test: is 8 chars + $header = $this->_getHeader('X-Test', $encoder); + $header->setValue($nonAsciiChar); + + $this->assertEquals( + 'X-Test: =?'.$this->_charset.'?Q?=8F?='."\r\n", + $header->toString() + ); + } + + public function testFWSPIsUsedWhenEncoderReturnsMultipleLines() + { + /* --RFC 2047, 2. + If it is desirable to encode more text than will fit in an 'encoded-word' of + 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may + be used. + */ + + //Note the Mock does NOT return 8F encoded, the 8F merely triggers + // encoding for the sake of testing + $nonAsciiChar = pack('C', 0x8F); + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($nonAsciiChar, 8, 63, \Mockery::any()) + ->andReturn('line_one_here'."\r\n".'line_two_here'); + + //Note that multi-line headers begin with LWSP which makes 75 + 1 = 76 + //Note also that =?utf-8?q??= is 12 chars which makes 75 - 12 = 63 + + //* X-Test: is 8 chars + $header = $this->_getHeader('X-Test', $encoder); + $header->setValue($nonAsciiChar); + + $this->assertEquals( + 'X-Test: =?'.$this->_charset.'?Q?line_one_here?='."\r\n". + ' =?'.$this->_charset.'?Q?line_two_here?='."\r\n", + $header->toString() + ); + } + + public function testAdjacentWordsAreEncodedTogether() + { + /* -- RFC 2047, 5 (1) + Ordinary ASCII text and 'encoded-word's may appear together in the + same header field. However, an 'encoded-word' that appears in a + header field defined as '*text' MUST be separated from any adjacent + 'encoded-word' or 'text' by 'linear-white-space'. + + -- RFC 2047, 2. + IMPORTANT: 'encoded-word's are designed to be recognized as 'atom's + by an RFC 822 parser. As a consequence, unencoded white space + characters (such as SPACE and HTAB) are FORBIDDEN within an + 'encoded-word'. + */ + + //It would be valid to encode all words needed, however it's probably + // easiest to encode the longest amount required at a time + + $word = 'w'.pack('C', 0x8F).'rd'; + $text = 'start '.$word.' '.$word.' then end '.$word; + // 'start', ' word word', ' and end', ' word' + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($word.' '.$word, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('w=8Frd_w=8Frd'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($word, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('w=8Frd'); + + $header = $this->_getHeader('X-Test', $encoder); + $header->setValue($text); + + $headerString = $header->toString(); + + $this->assertEquals('X-Test: start =?'.$this->_charset.'?Q?'. + 'w=8Frd_w=8Frd?= then end =?'.$this->_charset.'?Q?'. + 'w=8Frd?='."\r\n", $headerString, + '%s: Adjacent encoded words should appear grouped with WSP encoded' + ); + } + + public function testLanguageInformationAppearsInEncodedWords() + { + /* -- RFC 2231, 5. + 5. Language specification in Encoded Words + + RFC 2047 provides support for non-US-ASCII character sets in RFC 822 + message header comments, phrases, and any unstructured text field. + This is done by defining an encoded word construct which can appear + in any of these places. Given that these are fields intended for + display, it is sometimes necessary to associate language information + with encoded words as well as just the character set. This + specification extends the definition of an encoded word to allow the + inclusion of such information. This is simply done by suffixing the + character set specification with an asterisk followed by the language + tag. For example: + + From: =?US-ASCII*EN?Q?Keith_Moore?= + */ + + $value = 'fo'.pack('C', 0x8F).'bar'; + + $encoder = $this->_getEncoder('Q'); + $encoder->shouldReceive('encodeString') + ->once() + ->with($value, \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn('fo=8Fbar'); + + $header = $this->_getHeader('Subject', $encoder); + $header->setLanguage('en'); + $header->setValue($value); + $this->assertEquals("Subject: =?utf-8*en?Q?fo=8Fbar?=\r\n", + $header->toString() + ); + } + + public function testSetBodyModel() + { + $header = $this->_getHeader('Subject', $this->_getEncoder('Q', true)); + $header->setFieldBodyModel('test'); + $this->assertEquals('test', $header->getValue()); + } + + public function testGetBodyModel() + { + $header = $this->_getHeader('Subject', $this->_getEncoder('Q', true)); + $header->setValue('test'); + $this->assertEquals('test', $header->getFieldBodyModel()); + } + + private function _getHeader($name, $encoder) + { + $header = new Swift_Mime_Headers_UnstructuredHeader($name, $encoder, new Swift_Mime_Grammar()); + $header->setCharset($this->_charset); + + return $header; + } + + private function _getEncoder($type, $stub = false) + { + $encoder = $this->getMockery('Swift_Mime_HeaderEncoder')->shouldIgnoreMissing(); + $encoder->shouldReceive('getName') + ->zeroOrMoreTimes() + ->andReturn($type); + + return $encoder; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/MimePartTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/MimePartTest.php new file mode 100644 index 00000000..176207aa --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/MimePartTest.php @@ -0,0 +1,233 @@ +_createMimePart($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals( + Swift_Mime_MimeEntity::LEVEL_ALTERNATIVE, $part->getNestingLevel() + ); + } + + public function testCharsetIsReturnedFromHeader() + { + /* -- RFC 2046, 4.1.2. + A critical parameter that may be specified in the Content-Type field + for "text/plain" data is the character set. This is specified with a + "charset" parameter, as in: + + Content-type: text/plain; charset=iso-8859-1 + + Unlike some other parameter values, the values of the charset + parameter are NOT case sensitive. The default character set, which + must be assumed in the absence of a charset parameter, is US-ASCII. + */ + + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('charset' => 'iso-8859-1') + ); + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('iso-8859-1', $part->getCharset()); + } + + public function testCharsetIsSetInHeader() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('charset' => 'iso-8859-1'), false + ); + $cType->shouldReceive('setParameter')->once()->with('charset', 'utf-8'); + + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $part->setCharset('utf-8'); + } + + public function testCharsetIsSetInHeaderIfPassedToSetBody() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('charset' => 'iso-8859-1'), false + ); + $cType->shouldReceive('setParameter')->once()->with('charset', 'utf-8'); + + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $part->setBody('', 'text/plian', 'utf-8'); + } + + public function testSettingCharsetNotifiesEncoder() + { + $encoder = $this->_createEncoder('quoted-printable', false); + $encoder->expects($this->once()) + ->method('charsetChanged') + ->with('utf-8'); + + $part = $this->_createMimePart($this->_createHeaderSet(), + $encoder, $this->_createCache() + ); + $part->setCharset('utf-8'); + } + + public function testSettingCharsetNotifiesHeaders() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('charsetChanged') + ->zeroOrMoreTimes() + ->with('utf-8'); + + $part = $this->_createMimePart($headers, $this->_createEncoder(), + $this->_createCache() + ); + $part->setCharset('utf-8'); + } + + public function testSettingCharsetNotifiesChildren() + { + $child = $this->_createChild(0, '', false); + $child->shouldReceive('charsetChanged') + ->once() + ->with('windows-874'); + + $part = $this->_createMimePart($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $part->setChildren(array($child)); + $part->setCharset('windows-874'); + } + + public function testCharsetChangeUpdatesCharset() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('charset' => 'iso-8859-1'), false + ); + $cType->shouldReceive('setParameter')->once()->with('charset', 'utf-8'); + + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $part->charsetChanged('utf-8'); + } + + public function testSettingCharsetClearsCache() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn("Content-Type: text/plain; charset=utf-8\r\n"); + + $cache = $this->_createCache(false); + + $entity = $this->_createEntity($headers, $this->_createEncoder(), + $cache + ); + + $entity->setBody("blah\r\nblah!"); + $entity->toString(); + + // Initialize the expectation here because we only care about what happens in setCharset() + $cache->shouldReceive('clearKey') + ->once() + ->with(\Mockery::any(), 'body'); + + $entity->setCharset('iso-2022'); + } + + public function testFormatIsReturnedFromHeader() + { + /* -- RFC 3676. + */ + + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('format' => 'flowed') + ); + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('flowed', $part->getFormat()); + } + + public function testFormatIsSetInHeader() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $cType->shouldReceive('setParameter')->once()->with('format', 'fixed'); + + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $part->setFormat('fixed'); + } + + public function testDelSpIsReturnedFromHeader() + { + /* -- RFC 3676. + */ + + $cType = $this->_createHeader('Content-Type', 'text/plain', + array('delsp' => 'no') + ); + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertSame(false, $part->getDelSp()); + } + + public function testDelSpIsSetInHeader() + { + $cType = $this->_createHeader('Content-Type', 'text/plain', array(), false); + $cType->shouldReceive('setParameter')->once()->with('delsp', 'yes'); + + $part = $this->_createMimePart($this->_createHeaderSet(array( + 'Content-Type' => $cType,)), + $this->_createEncoder(), $this->_createCache() + ); + $part->setDelSp(true); + } + + public function testFluidInterface() + { + $part = $this->_createMimePart($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $this->assertSame($part, + $part + ->setContentType('text/plain') + ->setEncoder($this->_createEncoder()) + ->setId('foo@bar') + ->setDescription('my description') + ->setMaxLineLength(998) + ->setBody('xx') + ->setBoundary('xyz') + ->setChildren(array()) + ->setCharset('utf-8') + ->setFormat('flowed') + ->setDelSp(true) + ); + } + + // -- Private helpers + + //abstract + protected function _createEntity($headers, $encoder, $cache) + { + return $this->_createMimePart($headers, $encoder, $cache); + } + + protected function _createMimePart($headers, $encoder, $cache) + { + return new Swift_Mime_MimePart($headers, $encoder, $cache, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderFactoryTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderFactoryTest.php new file mode 100644 index 00000000..0d5573f8 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderFactoryTest.php @@ -0,0 +1,168 @@ +_factory = $this->_createFactory(); + } + + public function testMailboxHeaderIsCorrectType() + { + $header = $this->_factory->createMailboxHeader('X-Foo'); + $this->assertInstanceof('Swift_Mime_Headers_MailboxHeader', $header); + } + + public function testMailboxHeaderHasCorrectName() + { + $header = $this->_factory->createMailboxHeader('X-Foo'); + $this->assertEquals('X-Foo', $header->getFieldName()); + } + + public function testMailboxHeaderHasCorrectModel() + { + $header = $this->_factory->createMailboxHeader('X-Foo', + array('foo@bar' => 'FooBar') + ); + $this->assertEquals(array('foo@bar' => 'FooBar'), $header->getFieldBodyModel()); + } + + public function testDateHeaderHasCorrectType() + { + $header = $this->_factory->createDateHeader('X-Date'); + $this->assertInstanceof('Swift_Mime_Headers_DateHeader', $header); + } + + public function testDateHeaderHasCorrectName() + { + $header = $this->_factory->createDateHeader('X-Date'); + $this->assertEquals('X-Date', $header->getFieldName()); + } + + public function testDateHeaderHasCorrectModel() + { + $header = $this->_factory->createDateHeader('X-Date', 123); + $this->assertEquals(123, $header->getFieldBodyModel()); + } + + public function testTextHeaderHasCorrectType() + { + $header = $this->_factory->createTextHeader('X-Foo'); + $this->assertInstanceof('Swift_Mime_Headers_UnstructuredHeader', $header); + } + + public function testTextHeaderHasCorrectName() + { + $header = $this->_factory->createTextHeader('X-Foo'); + $this->assertEquals('X-Foo', $header->getFieldName()); + } + + public function testTextHeaderHasCorrectModel() + { + $header = $this->_factory->createTextHeader('X-Foo', 'bar'); + $this->assertEquals('bar', $header->getFieldBodyModel()); + } + + public function testParameterizedHeaderHasCorrectType() + { + $header = $this->_factory->createParameterizedHeader('X-Foo'); + $this->assertInstanceof('Swift_Mime_Headers_ParameterizedHeader', $header); + } + + public function testParameterizedHeaderHasCorrectName() + { + $header = $this->_factory->createParameterizedHeader('X-Foo'); + $this->assertEquals('X-Foo', $header->getFieldName()); + } + + public function testParameterizedHeaderHasCorrectModel() + { + $header = $this->_factory->createParameterizedHeader('X-Foo', 'bar'); + $this->assertEquals('bar', $header->getFieldBodyModel()); + } + + public function testParameterizedHeaderHasCorrectParams() + { + $header = $this->_factory->createParameterizedHeader('X-Foo', 'bar', + array('zip' => 'button') + ); + $this->assertEquals(array('zip' => 'button'), $header->getParameters()); + } + + public function testIdHeaderHasCorrectType() + { + $header = $this->_factory->createIdHeader('X-ID'); + $this->assertInstanceof('Swift_Mime_Headers_IdentificationHeader', $header); + } + + public function testIdHeaderHasCorrectName() + { + $header = $this->_factory->createIdHeader('X-ID'); + $this->assertEquals('X-ID', $header->getFieldName()); + } + + public function testIdHeaderHasCorrectModel() + { + $header = $this->_factory->createIdHeader('X-ID', 'xyz@abc'); + $this->assertEquals(array('xyz@abc'), $header->getFieldBodyModel()); + } + + public function testPathHeaderHasCorrectType() + { + $header = $this->_factory->createPathHeader('X-Path'); + $this->assertInstanceof('Swift_Mime_Headers_PathHeader', $header); + } + + public function testPathHeaderHasCorrectName() + { + $header = $this->_factory->createPathHeader('X-Path'); + $this->assertEquals('X-Path', $header->getFieldName()); + } + + public function testPathHeaderHasCorrectModel() + { + $header = $this->_factory->createPathHeader('X-Path', 'foo@bar'); + $this->assertEquals('foo@bar', $header->getFieldBodyModel()); + } + + public function testCharsetChangeNotificationNotifiesEncoders() + { + $encoder = $this->_createHeaderEncoder(); + $encoder->expects($this->once()) + ->method('charsetChanged') + ->with('utf-8'); + $paramEncoder = $this->_createParamEncoder(); + $paramEncoder->expects($this->once()) + ->method('charsetChanged') + ->with('utf-8'); + + $factory = $this->_createFactory($encoder, $paramEncoder); + + $factory->charsetChanged('utf-8'); + } + + // -- Creation methods + + private function _createFactory($encoder = null, $paramEncoder = null) + { + return new Swift_Mime_SimpleHeaderFactory( + $encoder + ? $encoder : $this->_createHeaderEncoder(), + $paramEncoder + ? $paramEncoder : $this->_createParamEncoder(), + new Swift_Mime_Grammar() + ); + } + + private function _createHeaderEncoder() + { + return $this->getMock('Swift_Mime_HeaderEncoder'); + } + + private function _createParamEncoder() + { + return $this->getMock('Swift_Encoder'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderSetTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderSetTest.php new file mode 100644 index 00000000..a781a088 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleHeaderSetTest.php @@ -0,0 +1,734 @@ +_createFactory(); + $factory->expects($this->once()) + ->method('createMailboxHeader') + ->with('From', array('person@domain' => 'Person')) + ->will($this->returnValue($this->_createHeader('From'))); + + $set = $this->_createSet($factory); + $set->addMailboxHeader('From', array('person@domain' => 'Person')); + } + + public function testAddDateHeaderDelegatesToFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createDateHeader') + ->with('Date', 1234) + ->will($this->returnValue($this->_createHeader('Date'))); + + $set = $this->_createSet($factory); + $set->addDateHeader('Date', 1234); + } + + public function testAddTextHeaderDelegatesToFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createTextHeader') + ->with('Subject', 'some text') + ->will($this->returnValue($this->_createHeader('Subject'))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Subject', 'some text'); + } + + public function testAddParameterizedHeaderDelegatesToFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createParameterizedHeader') + ->with('Content-Type', 'text/plain', array('charset' => 'utf-8')) + ->will($this->returnValue($this->_createHeader('Content-Type'))); + + $set = $this->_createSet($factory); + $set->addParameterizedHeader('Content-Type', 'text/plain', + array('charset' => 'utf-8') + ); + } + + public function testAddIdHeaderDelegatesToFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + } + + public function testAddPathHeaderDelegatesToFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createPathHeader') + ->with('Return-Path', 'some@path') + ->will($this->returnValue($this->_createHeader('Return-Path'))); + + $set = $this->_createSet($factory); + $set->addPathHeader('Return-Path', 'some@path'); + } + + public function testHasReturnsFalseWhenNoHeaders() + { + $set = $this->_createSet($this->_createFactory()); + $this->assertFalse($set->has('Some-Header')); + } + + public function testAddedMailboxHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createMailboxHeader') + ->with('From', array('person@domain' => 'Person')) + ->will($this->returnValue($this->_createHeader('From'))); + + $set = $this->_createSet($factory); + $set->addMailboxHeader('From', array('person@domain' => 'Person')); + $this->assertTrue($set->has('From')); + } + + public function testAddedDateHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createDateHeader') + ->with('Date', 1234) + ->will($this->returnValue($this->_createHeader('Date'))); + + $set = $this->_createSet($factory); + $set->addDateHeader('Date', 1234); + $this->assertTrue($set->has('Date')); + } + + public function testAddedTextHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createTextHeader') + ->with('Subject', 'some text') + ->will($this->returnValue($this->_createHeader('Subject'))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Subject', 'some text'); + $this->assertTrue($set->has('Subject')); + } + + public function testAddedParameterizedHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createParameterizedHeader') + ->with('Content-Type', 'text/plain', array('charset' => 'utf-8')) + ->will($this->returnValue($this->_createHeader('Content-Type'))); + + $set = $this->_createSet($factory); + $set->addParameterizedHeader('Content-Type', 'text/plain', + array('charset' => 'utf-8') + ); + $this->assertTrue($set->has('Content-Type')); + } + + public function testAddedIdHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertTrue($set->has('Message-ID')); + } + + public function testAddedPathHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createPathHeader') + ->with('Return-Path', 'some@path') + ->will($this->returnValue($this->_createHeader('Return-Path'))); + + $set = $this->_createSet($factory); + $set->addPathHeader('Return-Path', 'some@path'); + $this->assertTrue($set->has('Return-Path')); + } + + public function testNewlySetHeaderIsSeenByHas() + { + $factory = $this->_createFactory(); + $header = $this->_createHeader('X-Foo', 'bar'); + $set = $this->_createSet($factory); + $set->set($header); + $this->assertTrue($set->has('X-Foo')); + } + + public function testHasCanAcceptOffset() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertTrue($set->has('Message-ID', 0)); + } + + public function testHasWithIllegalOffsetReturnsFalse() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertFalse($set->has('Message-ID', 1)); + } + + public function testHasCanDistinguishMultipleHeaders() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($this->_createHeader('Message-ID'))); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $this->assertTrue($set->has('Message-ID', 1)); + } + + public function testGetWithUnspecifiedOffset() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertSame($header, $set->get('Message-ID')); + } + + public function testGetWithSpeiciedOffset() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Message-ID'); + $header2 = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($header1)); + $factory->expects($this->at(2)) + ->method('createIdHeader') + ->with('Message-ID', 'more@id') + ->will($this->returnValue($header2)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $set->addIdHeader('Message-ID', 'more@id'); + $this->assertSame($header1, $set->get('Message-ID', 1)); + } + + public function testGetReturnsNullIfHeaderNotSet() + { + $set = $this->_createSet($this->_createFactory()); + $this->assertNull($set->get('Message-ID', 99)); + } + + public function testGetAllReturnsAllHeadersMatchingName() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Message-ID'); + $header2 = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($header1)); + $factory->expects($this->at(2)) + ->method('createIdHeader') + ->with('Message-ID', 'more@id') + ->will($this->returnValue($header2)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $set->addIdHeader('Message-ID', 'more@id'); + + $this->assertEquals(array($header0, $header1, $header2), + $set->getAll('Message-ID') + ); + } + + public function testGetAllReturnsAllHeadersIfNoArguments() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Subject'); + $header2 = $this->_createHeader('To'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Subject', 'thing') + ->will($this->returnValue($header1)); + $factory->expects($this->at(2)) + ->method('createIdHeader') + ->with('To', 'person@example.org') + ->will($this->returnValue($header2)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Subject', 'thing'); + $set->addIdHeader('To', 'person@example.org'); + + $this->assertEquals(array($header0, $header1, $header2), + $set->getAll() + ); + } + + public function testGetAllReturnsEmptyArrayIfNoneSet() + { + $set = $this->_createSet($this->_createFactory()); + $this->assertEquals(array(), $set->getAll('Received')); + } + + public function testRemoveWithUnspecifiedOffset() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->remove('Message-ID'); + $this->assertFalse($set->has('Message-ID')); + } + + public function testRemoveWithSpecifiedIndexRemovesHeader() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($header1)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $set->remove('Message-ID', 1); + $this->assertFalse($set->has('Message-ID', 1)); + } + + public function testRemoveWithSpecifiedIndexLeavesOtherHeaders() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($header1)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $set->remove('Message-ID', 1); + $this->assertTrue($set->has('Message-ID', 0)); + } + + public function testRemoveWithInvalidOffsetDoesNothing() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->remove('Message-ID', 50); + $this->assertTrue($set->has('Message-ID')); + } + + public function testRemoveAllRemovesAllHeadersWithName() + { + $header0 = $this->_createHeader('Message-ID'); + $header1 = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header0)); + $factory->expects($this->at(1)) + ->method('createIdHeader') + ->with('Message-ID', 'other@id') + ->will($this->returnValue($header1)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->addIdHeader('Message-ID', 'other@id'); + $set->removeAll('Message-ID'); + $this->assertFalse($set->has('Message-ID', 0)); + $this->assertFalse($set->has('Message-ID', 1)); + } + + public function testHasIsNotCaseSensitive() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertTrue($set->has('message-id')); + } + + public function testGetIsNotCaseSensitive() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertSame($header, $set->get('message-id')); + } + + public function testGetAllIsNotCaseSensitive() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $this->assertEquals(array($header), $set->getAll('message-id')); + } + + public function testRemoveIsNotCaseSensitive() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->remove('message-id'); + $this->assertFalse($set->has('Message-ID')); + } + + public function testRemoveAllIsNotCaseSensitive() + { + $header = $this->_createHeader('Message-ID'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createIdHeader') + ->with('Message-ID', 'some@id') + ->will($this->returnValue($header)); + + $set = $this->_createSet($factory); + $set->addIdHeader('Message-ID', 'some@id'); + $set->removeAll('message-id'); + $this->assertFalse($set->has('Message-ID')); + } + + public function testNewInstance() + { + $set = $this->_createSet($this->_createFactory()); + $instance = $set->newInstance(); + $this->assertInstanceof('Swift_Mime_HeaderSet', $instance); + } + + public function testToStringJoinsHeadersTogether() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Foo', 'bar') + ->will($this->returnValue($this->_createHeader('Foo', 'bar'))); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('Zip', 'buttons') + ->will($this->returnValue($this->_createHeader('Zip', 'buttons'))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Foo', 'bar'); + $set->addTextHeader('Zip', 'buttons'); + $this->assertEquals( + "Foo: bar\r\n". + "Zip: buttons\r\n", + $set->toString() + ); + } + + public function testHeadersWithoutBodiesAreNotDisplayed() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Foo', 'bar') + ->will($this->returnValue($this->_createHeader('Foo', 'bar'))); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('Zip', '') + ->will($this->returnValue($this->_createHeader('Zip', ''))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Foo', 'bar'); + $set->addTextHeader('Zip', ''); + $this->assertEquals( + "Foo: bar\r\n", + $set->toString() + ); + } + + public function testHeadersWithoutBodiesCanBeForcedToDisplay() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Foo', '') + ->will($this->returnValue($this->_createHeader('Foo', ''))); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('Zip', '') + ->will($this->returnValue($this->_createHeader('Zip', ''))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Foo', ''); + $set->addTextHeader('Zip', ''); + $set->setAlwaysDisplayed(array('Foo', 'Zip')); + $this->assertEquals( + "Foo: \r\n". + "Zip: \r\n", + $set->toString() + ); + } + + public function testHeaderSequencesCanBeSpecified() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Third', 'three') + ->will($this->returnValue($this->_createHeader('Third', 'three'))); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('First', 'one') + ->will($this->returnValue($this->_createHeader('First', 'one'))); + $factory->expects($this->at(2)) + ->method('createTextHeader') + ->with('Second', 'two') + ->will($this->returnValue($this->_createHeader('Second', 'two'))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Third', 'three'); + $set->addTextHeader('First', 'one'); + $set->addTextHeader('Second', 'two'); + + $set->defineOrdering(array('First', 'Second', 'Third')); + + $this->assertEquals( + "First: one\r\n". + "Second: two\r\n". + "Third: three\r\n", + $set->toString() + ); + } + + public function testUnsortedHeadersAppearAtEnd() + { + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Fourth', 'four') + ->will($this->returnValue($this->_createHeader('Fourth', 'four'))); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('Fifth', 'five') + ->will($this->returnValue($this->_createHeader('Fifth', 'five'))); + $factory->expects($this->at(2)) + ->method('createTextHeader') + ->with('Third', 'three') + ->will($this->returnValue($this->_createHeader('Third', 'three'))); + $factory->expects($this->at(3)) + ->method('createTextHeader') + ->with('First', 'one') + ->will($this->returnValue($this->_createHeader('First', 'one'))); + $factory->expects($this->at(4)) + ->method('createTextHeader') + ->with('Second', 'two') + ->will($this->returnValue($this->_createHeader('Second', 'two'))); + + $set = $this->_createSet($factory); + $set->addTextHeader('Fourth', 'four'); + $set->addTextHeader('Fifth', 'five'); + $set->addTextHeader('Third', 'three'); + $set->addTextHeader('First', 'one'); + $set->addTextHeader('Second', 'two'); + + $set->defineOrdering(array('First', 'Second', 'Third')); + + $this->assertEquals( + "First: one\r\n". + "Second: two\r\n". + "Third: three\r\n". + "Fourth: four\r\n". + "Fifth: five\r\n", + $set->toString() + ); + } + + public function testSettingCharsetNotifiesAlreadyExistingHeaders() + { + $subject = $this->_createHeader('Subject', 'some text'); + $xHeader = $this->_createHeader('X-Header', 'some text'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Subject', 'some text') + ->will($this->returnValue($subject)); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('X-Header', 'some text') + ->will($this->returnValue($xHeader)); + $subject->expects($this->once()) + ->method('setCharset') + ->with('utf-8'); + $xHeader->expects($this->once()) + ->method('setCharset') + ->with('utf-8'); + + $set = $this->_createSet($factory); + $set->addTextHeader('Subject', 'some text'); + $set->addTextHeader('X-Header', 'some text'); + + $set->setCharset('utf-8'); + } + + public function testCharsetChangeNotifiesAlreadyExistingHeaders() + { + $subject = $this->_createHeader('Subject', 'some text'); + $xHeader = $this->_createHeader('X-Header', 'some text'); + $factory = $this->_createFactory(); + $factory->expects($this->at(0)) + ->method('createTextHeader') + ->with('Subject', 'some text') + ->will($this->returnValue($subject)); + $factory->expects($this->at(1)) + ->method('createTextHeader') + ->with('X-Header', 'some text') + ->will($this->returnValue($xHeader)); + $subject->expects($this->once()) + ->method('setCharset') + ->with('utf-8'); + $xHeader->expects($this->once()) + ->method('setCharset') + ->with('utf-8'); + + $set = $this->_createSet($factory); + $set->addTextHeader('Subject', 'some text'); + $set->addTextHeader('X-Header', 'some text'); + + $set->charsetChanged('utf-8'); + } + + public function testCharsetChangeNotifiesFactory() + { + $factory = $this->_createFactory(); + $factory->expects($this->once()) + ->method('charsetChanged') + ->with('utf-8'); + + $set = $this->_createSet($factory); + + $set->setCharset('utf-8'); + } + + // -- Creation methods + + private function _createSet($factory) + { + return new Swift_Mime_SimpleHeaderSet($factory); + } + + private function _createFactory() + { + return $this->getMock('Swift_Mime_HeaderFactory'); + } + + private function _createHeader($name, $body = '') + { + $header = $this->getMock('Swift_Mime_Header'); + $header->expects($this->any()) + ->method('getFieldName') + ->will($this->returnValue($name)); + $header->expects($this->any()) + ->method('toString') + ->will($this->returnValue(sprintf("%s: %s\r\n", $name, $body))); + $header->expects($this->any()) + ->method('getFieldBody') + ->will($this->returnValue($body)); + + return $header; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMessageTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMessageTest.php new file mode 100644 index 00000000..a2cbbcab --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMessageTest.php @@ -0,0 +1,829 @@ +_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals( + Swift_Mime_MimeEntity::LEVEL_TOP, $message->getNestingLevel() + ); + } + + public function testDateIsReturnedFromHeader() + { + $date = $this->_createHeader('Date', 123); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Date' => $date)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(123, $message->getDate()); + } + + public function testDateIsSetInHeader() + { + $date = $this->_createHeader('Date', 123, array(), false); + $date->shouldReceive('setFieldBodyModel') + ->once() + ->with(1234); + $date->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Date' => $date)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setDate(1234); + } + + public function testDateHeaderIsCreatedIfNonePresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addDateHeader') + ->once() + ->with('Date', 1234); + $headers->shouldReceive('addDateHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setDate(1234); + } + + public function testDateHeaderIsAddedDuringConstruction() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addDateHeader') + ->once() + ->with('Date', '/^[0-9]+$/D'); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + } + + public function testIdIsReturnedFromHeader() + { + /* -- RFC 2045, 7. + In constructing a high-level user agent, it may be desirable to allow + one body to make reference to another. Accordingly, bodies may be + labelled using the "Content-ID" header field, which is syntactically + identical to the "Message-ID" header field + */ + + $messageId = $this->_createHeader('Message-ID', 'a@b'); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Message-ID' => $messageId)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('a@b', $message->getId()); + } + + public function testIdIsSetInHeader() + { + $messageId = $this->_createHeader('Message-ID', 'a@b', array(), false); + $messageId->shouldReceive('setFieldBodyModel') + ->once() + ->with('x@y'); + $messageId->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Message-ID' => $messageId)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setId('x@y'); + } + + public function testIdIsAutoGenerated() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addIdHeader') + ->once() + ->with('Message-ID', '/^.*?@.*?$/D'); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + } + + public function testSubjectIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.5. + */ + + $subject = $this->_createHeader('Subject', 'example subject'); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Subject' => $subject)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('example subject', $message->getSubject()); + } + + public function testSubjectIsSetInHeader() + { + $subject = $this->_createHeader('Subject', '', array(), false); + $subject->shouldReceive('setFieldBodyModel') + ->once() + ->with('foo'); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Subject' => $subject)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setSubject('foo'); + } + + public function testSubjectHeaderIsCreatedIfNotPresent() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addTextHeader') + ->once() + ->with('Subject', 'example subject'); + $headers->shouldReceive('addTextHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setSubject('example subject'); + } + + public function testReturnPathIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.7. + */ + + $path = $this->_createHeader('Return-Path', 'bounces@domain'); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Return-Path' => $path)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals('bounces@domain', $message->getReturnPath()); + } + + public function testReturnPathIsSetInHeader() + { + $path = $this->_createHeader('Return-Path', '', array(), false); + $path->shouldReceive('setFieldBodyModel') + ->once() + ->with('bounces@domain'); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Return-Path' => $path)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setReturnPath('bounces@domain'); + } + + public function testReturnPathHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addPathHeader') + ->once() + ->with('Return-Path', 'bounces@domain'); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setReturnPath('bounces@domain'); + } + + public function testSenderIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.2. + */ + + $sender = $this->_createHeader('Sender', array('sender@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Sender' => $sender)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('sender@domain' => 'Name'), $message->getSender()); + } + + public function testSenderIsSetInHeader() + { + $sender = $this->_createHeader('Sender', array('sender@domain' => 'Name'), + array(), false + ); + $sender->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Sender' => $sender)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setSender(array('other@domain' => 'Other')); + } + + public function testSenderHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Sender', (array) 'sender@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setSender('sender@domain'); + } + + public function testNameCanBeUsedInSenderHeader() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Sender', array('sender@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setSender('sender@domain', 'Name'); + } + + public function testFromIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.2. + */ + + $from = $this->_createHeader('From', array('from@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('From' => $from)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('from@domain' => 'Name'), $message->getFrom()); + } + + public function testFromIsSetInHeader() + { + $from = $this->_createHeader('From', array('from@domain' => 'Name'), + array(), false + ); + $from->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('From' => $from)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setFrom(array('other@domain' => 'Other')); + } + + public function testFromIsAddedToHeadersDuringAddFrom() + { + $from = $this->_createHeader('From', array('from@domain' => 'Name'), + array(), false + ); + $from->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('from@domain' => 'Name', 'other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('From' => $from)), + $this->_createEncoder(), $this->_createCache() + ); + $message->addFrom('other@domain', 'Other'); + } + + public function testFromHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('From', (array) 'from@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setFrom('from@domain'); + } + + public function testPersonalNameCanBeUsedInFromAddress() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('From', array('from@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setFrom('from@domain', 'Name'); + } + + public function testReplyToIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.2. + */ + + $reply = $this->_createHeader('Reply-To', array('reply@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Reply-To' => $reply)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('reply@domain' => 'Name'), $message->getReplyTo()); + } + + public function testReplyToIsSetInHeader() + { + $reply = $this->_createHeader('Reply-To', array('reply@domain' => 'Name'), + array(), false + ); + $reply->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Reply-To' => $reply)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setReplyTo(array('other@domain' => 'Other')); + } + + public function testReplyToIsAddedToHeadersDuringAddReplyTo() + { + $replyTo = $this->_createHeader('Reply-To', array('from@domain' => 'Name'), + array(), false + ); + $replyTo->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('from@domain' => 'Name', 'other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Reply-To' => $replyTo)), + $this->_createEncoder(), $this->_createCache() + ); + $message->addReplyTo('other@domain', 'Other'); + } + + public function testReplyToHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Reply-To', (array) 'reply@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setReplyTo('reply@domain'); + } + + public function testNameCanBeUsedInReplyTo() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Reply-To', array('reply@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setReplyTo('reply@domain', 'Name'); + } + + public function testToIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.3. + */ + + $to = $this->_createHeader('To', array('to@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('To' => $to)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('to@domain' => 'Name'), $message->getTo()); + } + + public function testToIsSetInHeader() + { + $to = $this->_createHeader('To', array('to@domain' => 'Name'), + array(), false + ); + $to->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('To' => $to)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setTo(array('other@domain' => 'Other')); + } + + public function testToIsAddedToHeadersDuringAddTo() + { + $to = $this->_createHeader('To', array('from@domain' => 'Name'), + array(), false + ); + $to->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('from@domain' => 'Name', 'other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('To' => $to)), + $this->_createEncoder(), $this->_createCache() + ); + $message->addTo('other@domain', 'Other'); + } + + public function testToHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('To', (array) 'to@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setTo('to@domain'); + } + + public function testNameCanBeUsedInToHeader() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('To', array('to@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setTo('to@domain', 'Name'); + } + + public function testCcIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.3. + */ + + $cc = $this->_createHeader('Cc', array('cc@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Cc' => $cc)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('cc@domain' => 'Name'), $message->getCc()); + } + + public function testCcIsSetInHeader() + { + $cc = $this->_createHeader('Cc', array('cc@domain' => 'Name'), + array(), false + ); + $cc->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Cc' => $cc)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setCc(array('other@domain' => 'Other')); + } + + public function testCcIsAddedToHeadersDuringAddCc() + { + $cc = $this->_createHeader('Cc', array('from@domain' => 'Name'), + array(), false + ); + $cc->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('from@domain' => 'Name', 'other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Cc' => $cc)), + $this->_createEncoder(), $this->_createCache() + ); + $message->addCc('other@domain', 'Other'); + } + + public function testCcHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Cc', (array) 'cc@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setCc('cc@domain'); + } + + public function testNameCanBeUsedInCcHeader() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Cc', array('cc@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setCc('cc@domain', 'Name'); + } + + public function testBccIsReturnedFromHeader() + { + /* -- RFC 2822, 3.6.3. + */ + + $bcc = $this->_createHeader('Bcc', array('bcc@domain' => 'Name')); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Bcc' => $bcc)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('bcc@domain' => 'Name'), $message->getBcc()); + } + + public function testBccIsSetInHeader() + { + $bcc = $this->_createHeader('Bcc', array('bcc@domain' => 'Name'), + array(), false + ); + $bcc->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Bcc' => $bcc)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setBcc(array('other@domain' => 'Other')); + } + + public function testBccIsAddedToHeadersDuringAddBcc() + { + $bcc = $this->_createHeader('Bcc', array('from@domain' => 'Name'), + array(), false + ); + $bcc->shouldReceive('setFieldBodyModel') + ->once() + ->with(array('from@domain' => 'Name', 'other@domain' => 'Other')); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Bcc' => $bcc)), + $this->_createEncoder(), $this->_createCache() + ); + $message->addBcc('other@domain', 'Other'); + } + + public function testBccHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Bcc', (array) 'bcc@domain'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setBcc('bcc@domain'); + } + + public function testNameCanBeUsedInBcc() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Bcc', array('bcc@domain' => 'Name')); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setBcc('bcc@domain', 'Name'); + } + + public function testPriorityIsReadFromHeader() + { + $prio = $this->_createHeader('X-Priority', '2 (High)'); + $message = $this->_createMessage( + $this->_createHeaderSet(array('X-Priority' => $prio)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(2, $message->getPriority()); + } + + public function testPriorityIsSetInHeader() + { + $prio = $this->_createHeader('X-Priority', '2 (High)', array(), false); + $prio->shouldReceive('setFieldBodyModel') + ->once() + ->with('5 (Lowest)'); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('X-Priority' => $prio)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setPriority(5); + } + + public function testPriorityHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addTextHeader') + ->once() + ->with('X-Priority', '4 (Low)'); + $headers->shouldReceive('addTextHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setPriority(4); + } + + public function testReadReceiptAddressReadFromHeader() + { + $rcpt = $this->_createHeader('Disposition-Notification-To', + array('chris@swiftmailer.org' => 'Chris') + ); + $message = $this->_createMessage( + $this->_createHeaderSet(array('Disposition-Notification-To' => $rcpt)), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertEquals(array('chris@swiftmailer.org' => 'Chris'), + $message->getReadReceiptTo() + ); + } + + public function testReadReceiptIsSetInHeader() + { + $rcpt = $this->_createHeader('Disposition-Notification-To', array(), array(), false); + $rcpt->shouldReceive('setFieldBodyModel') + ->once() + ->with('mark@swiftmailer.org'); + + $message = $this->_createMessage( + $this->_createHeaderSet(array('Disposition-Notification-To' => $rcpt)), + $this->_createEncoder(), $this->_createCache() + ); + $message->setReadReceiptTo('mark@swiftmailer.org'); + } + + public function testReadReceiptHeaderIsAddedIfNoneSet() + { + $headers = $this->_createHeaderSet(array(), false); + $headers->shouldReceive('addMailboxHeader') + ->once() + ->with('Disposition-Notification-To', 'mark@swiftmailer.org'); + $headers->shouldReceive('addMailboxHeader') + ->zeroOrMoreTimes(); + + $message = $this->_createMessage($headers, $this->_createEncoder(), + $this->_createCache() + ); + $message->setReadReceiptTo('mark@swiftmailer.org'); + } + + public function testChildrenCanBeAttached() + { + $child1 = $this->_createChild(); + $child2 = $this->_createChild(); + + $message = $this->_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $message->attach($child1); + $message->attach($child2); + + $this->assertEquals(array($child1, $child2), $message->getChildren()); + } + + public function testChildrenCanBeDetached() + { + $child1 = $this->_createChild(); + $child2 = $this->_createChild(); + + $message = $this->_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $message->attach($child1); + $message->attach($child2); + + $message->detach($child1); + + $this->assertEquals(array($child2), $message->getChildren()); + } + + public function testEmbedAttachesChild() + { + $child = $this->_createChild(); + + $message = $this->_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $message->embed($child); + + $this->assertEquals(array($child), $message->getChildren()); + } + + public function testEmbedReturnsValidCid() + { + $child = $this->_createChild(Swift_Mime_MimeEntity::LEVEL_RELATED, '', + false + ); + $child->shouldReceive('getId') + ->zeroOrMoreTimes() + ->andReturn('foo@bar'); + + $message = $this->_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + + $this->assertEquals('cid:foo@bar', $message->embed($child)); + } + + public function testFluidInterface() + { + $child = $this->_createChild(); + $message = $this->_createMessage($this->_createHeaderSet(), + $this->_createEncoder(), $this->_createCache() + ); + $this->assertSame($message, + $message + ->setContentType('text/plain') + ->setEncoder($this->_createEncoder()) + ->setId('foo@bar') + ->setDescription('my description') + ->setMaxLineLength(998) + ->setBody('xx') + ->setBoundary('xyz') + ->setChildren(array()) + ->setCharset('iso-8859-1') + ->setFormat('flowed') + ->setDelSp(false) + ->setSubject('subj') + ->setDate(123) + ->setReturnPath('foo@bar') + ->setSender('foo@bar') + ->setFrom(array('x@y' => 'XY')) + ->setReplyTo(array('ab@cd' => 'ABCD')) + ->setTo(array('chris@site.tld', 'mark@site.tld')) + ->setCc('john@somewhere.tld') + ->setBcc(array('one@site', 'two@site' => 'Two')) + ->setPriority(4) + ->setReadReceiptTo('a@b') + ->attach($child) + ->detach($child) + ); + } + + // -- Private helpers + + //abstract + protected function _createEntity($headers, $encoder, $cache) + { + return $this->_createMessage($headers, $encoder, $cache); + } + + protected function _createMimePart($headers, $encoder, $cache) + { + return $this->_createMessage($headers, $encoder, $cache); + } + + private function _createMessage($headers, $encoder, $cache) + { + return new Swift_Mime_SimpleMessage($headers, $encoder, $cache, new Swift_Mime_Grammar()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMimeEntityTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMimeEntityTest.php new file mode 100644 index 00000000..b54d7f87 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Mime/SimpleMimeEntityTest.php @@ -0,0 +1,11 @@ +assertEquals(10, $plugin->getThreshold()); + $plugin->setThreshold(100); + $this->assertEquals(100, $plugin->getThreshold()); + } + + public function testSleepTimeCanBeSetAndFetched() + { + $plugin = new Swift_Plugins_AntiFloodPlugin(10, 5); + $this->assertEquals(5, $plugin->getSleepTime()); + $plugin->setSleepTime(1); + $this->assertEquals(1, $plugin->getSleepTime()); + } + + public function testPluginStopsConnectionAfterThreshold() + { + $transport = $this->_createTransport(); + $transport->expects($this->once()) + ->method('start'); + $transport->expects($this->once()) + ->method('stop'); + + $evt = $this->_createSendEvent($transport); + + $plugin = new Swift_Plugins_AntiFloodPlugin(10); + for ($i = 0; $i < 12; $i++) { + $plugin->sendPerformed($evt); + } + } + + public function testPluginCanStopAndStartMultipleTimes() + { + $transport = $this->_createTransport(); + $transport->expects($this->exactly(5)) + ->method('start'); + $transport->expects($this->exactly(5)) + ->method('stop'); + + $evt = $this->_createSendEvent($transport); + + $plugin = new Swift_Plugins_AntiFloodPlugin(2); + for ($i = 0; $i < 11; $i++) { + $plugin->sendPerformed($evt); + } + } + + public function testPluginCanSleepDuringRestart() + { + $sleeper = $this->getMock('Swift_Plugins_Sleeper'); + $sleeper->expects($this->once()) + ->method('sleep') + ->with(10); + + $transport = $this->_createTransport(); + $transport->expects($this->once()) + ->method('start'); + $transport->expects($this->once()) + ->method('stop'); + + $evt = $this->_createSendEvent($transport); + + $plugin = new Swift_Plugins_AntiFloodPlugin(99, 10, $sleeper); + for ($i = 0; $i < 101; $i++) { + $plugin->sendPerformed($evt); + } + } + + // -- Creation Methods + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } + + private function _createSendEvent($transport) + { + $evt = $this->getMockBuilder('Swift_Events_SendEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getSource') + ->will($this->returnValue($transport)); + $evt->expects($this->any()) + ->method('getTransport') + ->will($this->returnValue($transport)); + + return $evt; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/BandwidthMonitorPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/BandwidthMonitorPluginTest.php new file mode 100644 index 00000000..20ad73eb --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/BandwidthMonitorPluginTest.php @@ -0,0 +1,127 @@ +_monitor = new Swift_Plugins_BandwidthMonitorPlugin(); + } + + public function testBytesOutIncreasesWhenCommandsSent() + { + $evt = $this->_createCommandEvent("RCPT TO: \r\n"); + + $this->assertEquals(0, $this->_monitor->getBytesOut()); + $this->_monitor->commandSent($evt); + $this->assertEquals(24, $this->_monitor->getBytesOut()); + $this->_monitor->commandSent($evt); + $this->assertEquals(48, $this->_monitor->getBytesOut()); + } + + public function testBytesInIncreasesWhenResponsesReceived() + { + $evt = $this->_createResponseEvent("250 Ok\r\n"); + + $this->assertEquals(0, $this->_monitor->getBytesIn()); + $this->_monitor->responseReceived($evt); + $this->assertEquals(8, $this->_monitor->getBytesIn()); + $this->_monitor->responseReceived($evt); + $this->assertEquals(16, $this->_monitor->getBytesIn()); + } + + public function testCountersCanBeReset() + { + $evt = $this->_createResponseEvent("250 Ok\r\n"); + + $this->assertEquals(0, $this->_monitor->getBytesIn()); + $this->_monitor->responseReceived($evt); + $this->assertEquals(8, $this->_monitor->getBytesIn()); + $this->_monitor->responseReceived($evt); + $this->assertEquals(16, $this->_monitor->getBytesIn()); + + $evt = $this->_createCommandEvent("RCPT TO: \r\n"); + + $this->assertEquals(0, $this->_monitor->getBytesOut()); + $this->_monitor->commandSent($evt); + $this->assertEquals(24, $this->_monitor->getBytesOut()); + $this->_monitor->commandSent($evt); + $this->assertEquals(48, $this->_monitor->getBytesOut()); + + $this->_monitor->reset(); + + $this->assertEquals(0, $this->_monitor->getBytesOut()); + $this->assertEquals(0, $this->_monitor->getBytesIn()); + } + + public function testBytesOutIncreasesAccordingToMessageLength() + { + $message = $this->_createMessageWithByteCount(6); + $evt = $this->_createSendEvent($message); + + $this->assertEquals(0, $this->_monitor->getBytesOut()); + $this->_monitor->sendPerformed($evt); + $this->assertEquals(6, $this->_monitor->getBytesOut()); + $this->_monitor->sendPerformed($evt); + $this->assertEquals(12, $this->_monitor->getBytesOut()); + } + + // -- Creation Methods + + private function _createSendEvent($message) + { + $evt = $this->getMockBuilder('Swift_Events_SendEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getMessage') + ->will($this->returnValue($message)); + + return $evt; + } + + private function _createCommandEvent($command) + { + $evt = $this->getMockBuilder('Swift_Events_CommandEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getCommand') + ->will($this->returnValue($command)); + + return $evt; + } + + private function _createResponseEvent($response) + { + $evt = $this->getMockBuilder('Swift_Events_ResponseEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getResponse') + ->will($this->returnValue($response)); + + return $evt; + } + + private function _createMessageWithByteCount($bytes) + { + $this->_bytes = $bytes; + $msg = $this->getMock('Swift_Mime_Message'); + $msg->expects($this->any()) + ->method('toByteStream') + ->will($this->returnCallback(array($this, '_write'))); + /* $this->_checking(Expectations::create() + -> ignoring($msg)->toByteStream(any()) -> calls(array($this, '_write')) + ); */ + + return $msg; + } + + private $_bytes = 0; + public function _write($is) + { + for ($i = 0; $i < $this->_bytes; ++$i) { + $is->write('x'); + } + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/DecoratorPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/DecoratorPluginTest.php new file mode 100644 index 00000000..7f4cdef1 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/DecoratorPluginTest.php @@ -0,0 +1,269 @@ +_createMessage( + $this->_createHeaders(), + array('zip@button.tld' => 'Zipathon'), + array('chris.corbyn@swiftmailer.org' => 'Chris'), + 'Subject', + 'Hello {name}, you are customer #{id}' + ); + $message->shouldReceive('setBody') + ->once() + ->with('Hello Zip, you are customer #456'); + $message->shouldReceive('setBody') + ->zeroOrMoreTimes(); + + $plugin = $this->_createPlugin( + array('zip@button.tld' => array('{name}' => 'Zip', '{id}' => '456')) + ); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + + public function testReplacementsCanBeAppliedToSameMessageMultipleTimes() + { + $message = $this->_createMessage( + $this->_createHeaders(), + array('zip@button.tld' => 'Zipathon', 'foo@bar.tld' => 'Foo'), + array('chris.corbyn@swiftmailer.org' => 'Chris'), + 'Subject', + 'Hello {name}, you are customer #{id}' + ); + $message->shouldReceive('setBody') + ->once() + ->with('Hello Zip, you are customer #456'); + $message->shouldReceive('setBody') + ->once() + ->with('Hello {name}, you are customer #{id}'); + $message->shouldReceive('setBody') + ->once() + ->with('Hello Foo, you are customer #123'); + $message->shouldReceive('setBody') + ->zeroOrMoreTimes(); + + $plugin = $this->_createPlugin( + array( + 'foo@bar.tld' => array('{name}' => 'Foo', '{id}' => '123'), + 'zip@button.tld' => array('{name}' => 'Zip', '{id}' => '456'), + ) + ); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + + public function testReplacementsCanBeMadeInHeaders() + { + $headers = $this->_createHeaders(array( + $returnPathHeader = $this->_createHeader('Return-Path', 'foo-{id}@swiftmailer.org'), + $toHeader = $this->_createHeader('Subject', 'A message for {name}!'), + )); + + $message = $this->_createMessage( + $headers, + array('zip@button.tld' => 'Zipathon'), + array('chris.corbyn@swiftmailer.org' => 'Chris'), + 'A message for {name}!', + 'Hello {name}, you are customer #{id}' + ); + + $message->shouldReceive('setBody') + ->once() + ->with('Hello Zip, you are customer #456'); + $toHeader->shouldReceive('setFieldBodyModel') + ->once() + ->with('A message for Zip!'); + $returnPathHeader->shouldReceive('setFieldBodyModel') + ->once() + ->with('foo-456@swiftmailer.org'); + $message->shouldReceive('setBody') + ->zeroOrMoreTimes(); + $toHeader->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + $returnPathHeader->shouldReceive('setFieldBodyModel') + ->zeroOrMoreTimes(); + + $plugin = $this->_createPlugin( + array('zip@button.tld' => array('{name}' => 'Zip', '{id}' => '456')) + ); + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + + public function testReplacementsAreMadeOnSubparts() + { + $part1 = $this->_createPart('text/plain', 'Your name is {name}?', '1@x'); + $part2 = $this->_createPart('text/html', 'Your name is {name}?', '2@x'); + $message = $this->_createMessage( + $this->_createHeaders(), + array('zip@button.tld' => 'Zipathon'), + array('chris.corbyn@swiftmailer.org' => 'Chris'), + 'A message for {name}!', + 'Subject' + ); + $message->shouldReceive('getChildren') + ->zeroOrMoreTimes() + ->andReturn(array($part1, $part2)); + $part1->shouldReceive('setBody') + ->once() + ->with('Your name is Zip?'); + $part2->shouldReceive('setBody') + ->once() + ->with('Your name is Zip?'); + $part1->shouldReceive('setBody') + ->zeroOrMoreTimes(); + $part2->shouldReceive('setBody') + ->zeroOrMoreTimes(); + + $plugin = $this->_createPlugin( + array('zip@button.tld' => array('{name}' => 'Zip', '{id}' => '456')) + ); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + + public function testReplacementsCanBeTakenFromCustomReplacementsObject() + { + $message = $this->_createMessage( + $this->_createHeaders(), + array('foo@bar' => 'Foobar', 'zip@zap' => 'Zip zap'), + array('chris.corbyn@swiftmailer.org' => 'Chris'), + 'Subject', + 'Something {a}' + ); + + $replacements = $this->_createReplacements(); + + $message->shouldReceive('setBody') + ->once() + ->with('Something b'); + $message->shouldReceive('setBody') + ->once() + ->with('Something c'); + $message->shouldReceive('setBody') + ->zeroOrMoreTimes(); + $replacements->shouldReceive('getReplacementsFor') + ->once() + ->with('foo@bar') + ->andReturn(array('{a}' => 'b')); + $replacements->shouldReceive('getReplacementsFor') + ->once() + ->with('zip@zap') + ->andReturn(array('{a}' => 'c')); + + $plugin = $this->_createPlugin($replacements); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + + // -- Creation methods + + private function _createMessage($headers, $to = array(), $from = null, $subject = null, + $body = null) + { + $message = $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + foreach ($to as $addr => $name) { + $message->shouldReceive('getTo') + ->once() + ->andReturn(array($addr => $name)); + } + $message->shouldReceive('getHeaders') + ->zeroOrMoreTimes() + ->andReturn($headers); + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn($from); + $message->shouldReceive('getSubject') + ->zeroOrMoreTimes() + ->andReturn($subject); + $message->shouldReceive('getBody') + ->zeroOrMoreTimes() + ->andReturn($body); + + return $message; + } + + private function _createPlugin($replacements) + { + return new Swift_Plugins_DecoratorPlugin($replacements); + } + + private function _createReplacements() + { + return $this->getMockery('Swift_Plugins_Decorator_Replacements')->shouldIgnoreMissing(); + } + + private function _createSendEvent(Swift_Mime_Message $message) + { + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $evt->shouldReceive('getMessage') + ->zeroOrMoreTimes() + ->andReturn($message); + + return $evt; + } + + private function _createPart($type, $body, $id) + { + $part = $this->getMockery('Swift_Mime_MimeEntity')->shouldIgnoreMissing(); + $part->shouldReceive('getContentType') + ->zeroOrMoreTimes() + ->andReturn($type); + $part->shouldReceive('getBody') + ->zeroOrMoreTimes() + ->andReturn($body); + $part->shouldReceive('getId') + ->zeroOrMoreTimes() + ->andReturn($id); + + return $part; + } + + private function _createHeaders($headers = array()) + { + $set = $this->getMockery('Swift_Mime_HeaderSet')->shouldIgnoreMissing(); + $set->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->andReturn($headers); + + foreach ($headers as $header) { + $set->set($header); + } + + return $set; + } + + private function _createHeader($name, $body = '') + { + $header = $this->getMockery('Swift_Mime_Header')->shouldIgnoreMissing(); + $header->shouldReceive('getFieldName') + ->zeroOrMoreTimes() + ->andReturn($name); + $header->shouldReceive('getFieldBodyModel') + ->zeroOrMoreTimes() + ->andReturn($body); + + return $header; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/LoggerPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/LoggerPluginTest.php new file mode 100644 index 00000000..bd1fd97a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/LoggerPluginTest.php @@ -0,0 +1,190 @@ +_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with('foo'); + + $plugin = $this->_createPlugin($logger); + $plugin->add('foo'); + } + + public function testLoggerDelegatesDumpingEntries() + { + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('dump') + ->will($this->returnValue('foobar')); + + $plugin = $this->_createPlugin($logger); + $this->assertEquals('foobar', $plugin->dump()); + } + + public function testLoggerDelegatesClearingEntries() + { + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('clear'); + + $plugin = $this->_createPlugin($logger); + $plugin->clear(); + } + + public function testCommandIsSentToLogger() + { + $evt = $this->_createCommandEvent("foo\r\n"); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->regExp('~foo\r\n~')); + + $plugin = $this->_createPlugin($logger); + $plugin->commandSent($evt); + } + + public function testResponseIsSentToLogger() + { + $evt = $this->_createResponseEvent("354 Go ahead\r\n"); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->regExp('~354 Go ahead\r\n~')); + + $plugin = $this->_createPlugin($logger); + $plugin->responseReceived($evt); + } + + public function testTransportBeforeStartChangeIsSentToLogger() + { + $evt = $this->_createTransportChangeEvent(); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->anything()); + + $plugin = $this->_createPlugin($logger); + $plugin->beforeTransportStarted($evt); + } + + public function testTransportStartChangeIsSentToLogger() + { + $evt = $this->_createTransportChangeEvent(); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->anything()); + + $plugin = $this->_createPlugin($logger); + $plugin->transportStarted($evt); + } + + public function testTransportStopChangeIsSentToLogger() + { + $evt = $this->_createTransportChangeEvent(); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->anything()); + + $plugin = $this->_createPlugin($logger); + $plugin->transportStopped($evt); + } + + public function testTransportBeforeStopChangeIsSentToLogger() + { + $evt = $this->_createTransportChangeEvent(); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->anything()); + + $plugin = $this->_createPlugin($logger); + $plugin->beforeTransportStopped($evt); + } + + public function testExceptionsArePassedToDelegateAndLeftToBubbleUp() + { + $transport = $this->_createTransport(); + $evt = $this->_createTransportExceptionEvent(); + $logger = $this->_createLogger(); + $logger->expects($this->once()) + ->method('add') + ->with($this->anything()); + + $plugin = $this->_createPlugin($logger); + try { + $plugin->exceptionThrown($evt); + $this->fail('Exception should bubble up.'); + } catch (Swift_TransportException $ex) { + } + } + + // -- Creation Methods + + private function _createLogger() + { + return $this->getMock('Swift_Plugins_Logger'); + } + + private function _createPlugin($logger) + { + return new Swift_Plugins_LoggerPlugin($logger); + } + + private function _createCommandEvent($command) + { + $evt = $this->getMockBuilder('Swift_Events_CommandEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getCommand') + ->will($this->returnValue($command)); + + return $evt; + } + + private function _createResponseEvent($response) + { + $evt = $this->getMockBuilder('Swift_Events_ResponseEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getResponse') + ->will($this->returnValue($response)); + + return $evt; + } + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } + + private function _createTransportChangeEvent() + { + $evt = $this->getMockBuilder('Swift_Events_TransportChangeEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getSource') + ->will($this->returnValue($this->_createTransport())); + + return $evt; + } + + public function _createTransportExceptionEvent() + { + $evt = $this->getMockBuilder('Swift_Events_TransportExceptionEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getException') + ->will($this->returnValue(new Swift_TransportException(''))); + + return $evt; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/ArrayLoggerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/ArrayLoggerTest.php new file mode 100644 index 00000000..880bb32c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/ArrayLoggerTest.php @@ -0,0 +1,65 @@ +add(">> Foo\r\n"); + $this->assertEquals(">> Foo\r\n", $logger->dump()); + } + + public function testAddingMultipleEntriesDumpsMultipleLines() + { + $logger = new Swift_Plugins_Loggers_ArrayLogger(); + $logger->add(">> FOO\r\n"); + $logger->add("<< 502 That makes no sense\r\n"); + $logger->add(">> RSET\r\n"); + $logger->add("<< 250 OK\r\n"); + + $this->assertEquals( + ">> FOO\r\n".PHP_EOL. + "<< 502 That makes no sense\r\n".PHP_EOL. + ">> RSET\r\n".PHP_EOL. + "<< 250 OK\r\n", + $logger->dump() + ); + } + + public function testLogCanBeCleared() + { + $logger = new Swift_Plugins_Loggers_ArrayLogger(); + $logger->add(">> FOO\r\n"); + $logger->add("<< 502 That makes no sense\r\n"); + $logger->add(">> RSET\r\n"); + $logger->add("<< 250 OK\r\n"); + + $this->assertEquals( + ">> FOO\r\n".PHP_EOL. + "<< 502 That makes no sense\r\n".PHP_EOL. + ">> RSET\r\n".PHP_EOL. + "<< 250 OK\r\n", + $logger->dump() + ); + + $logger->clear(); + + $this->assertEquals('', $logger->dump()); + } + + public function testLengthCanBeTruncated() + { + $logger = new Swift_Plugins_Loggers_ArrayLogger(2); + $logger->add(">> FOO\r\n"); + $logger->add("<< 502 That makes no sense\r\n"); + $logger->add(">> RSET\r\n"); + $logger->add("<< 250 OK\r\n"); + + $this->assertEquals( + ">> RSET\r\n".PHP_EOL. + "<< 250 OK\r\n", + $logger->dump(), + '%s: Log should be truncated to last 2 entries' + ); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/EchoLoggerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/EchoLoggerTest.php new file mode 100644 index 00000000..aa2bd233 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Loggers/EchoLoggerTest.php @@ -0,0 +1,24 @@ +add(">> Foo"); + $data = ob_get_clean(); + + $this->assertEquals(">> Foo".PHP_EOL, $data); + } + + public function testAddingEntryDumpsEscapedLineWithHtml() + { + $logger = new Swift_Plugins_Loggers_EchoLogger(true); + ob_start(); + $logger->add(">> Foo"); + $data = ob_get_clean(); + + $this->assertEquals(">> Foo
".PHP_EOL, $data); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/PopBeforeSmtpPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/PopBeforeSmtpPluginTest.php new file mode 100644 index 00000000..1227c24c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/PopBeforeSmtpPluginTest.php @@ -0,0 +1,103 @@ +_createConnection(); + $connection->expects($this->once()) + ->method('connect'); + + $plugin = $this->_createPlugin('pop.host.tld', 110); + $plugin->setConnection($connection); + + $transport = $this->_createTransport(); + $evt = $this->_createTransportChangeEvent($transport); + + $plugin->beforeTransportStarted($evt); + } + + public function testPluginDisconnectsFromPop3HostBeforeTransportStarts() + { + $connection = $this->_createConnection(); + $connection->expects($this->once()) + ->method('disconnect'); + + $plugin = $this->_createPlugin('pop.host.tld', 110); + $plugin->setConnection($connection); + + $transport = $this->_createTransport(); + $evt = $this->_createTransportChangeEvent($transport); + + $plugin->beforeTransportStarted($evt); + } + + public function testPluginDoesNotConnectToSmtpIfBoundToDifferentTransport() + { + $connection = $this->_createConnection(); + $connection->expects($this->never()) + ->method('disconnect'); + $connection->expects($this->never()) + ->method('connect'); + + $smtp = $this->_createTransport(); + + $plugin = $this->_createPlugin('pop.host.tld', 110); + $plugin->setConnection($connection); + $plugin->bindSmtp($smtp); + + $transport = $this->_createTransport(); + $evt = $this->_createTransportChangeEvent($transport); + + $plugin->beforeTransportStarted($evt); + } + + public function testPluginCanBindToSpecificTransport() + { + $connection = $this->_createConnection(); + $connection->expects($this->once()) + ->method('connect'); + + $smtp = $this->_createTransport(); + + $plugin = $this->_createPlugin('pop.host.tld', 110); + $plugin->setConnection($connection); + $plugin->bindSmtp($smtp); + + $evt = $this->_createTransportChangeEvent($smtp); + + $plugin->beforeTransportStarted($evt); + } + + // -- Creation Methods + + private function _createTransport() + { + return $this->getMock('Swift_Transport'); + } + + private function _createTransportChangeEvent($transport) + { + $evt = $this->getMockBuilder('Swift_Events_TransportChangeEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getSource') + ->will($this->returnValue($transport)); + $evt->expects($this->any()) + ->method('getTransport') + ->will($this->returnValue($transport)); + + return $evt; + } + + public function _createConnection() + { + return $this->getMock('Swift_Plugins_Pop_Pop3Connection'); + } + + public function _createPlugin($host, $port, $crypto = null) + { + return new Swift_Plugins_PopBeforeSmtpPlugin($host, $port, $crypto); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/RedirectingPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/RedirectingPluginTest.php new file mode 100644 index 00000000..4cc7e89f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/RedirectingPluginTest.php @@ -0,0 +1,185 @@ +assertEquals('fabien@example.com', $plugin->getRecipient()); + $plugin->setRecipient('chris@example.com'); + $this->assertEquals('chris@example.com', $plugin->getRecipient()); + } + + public function testPluginChangesRecipients() + { + $message = Swift_Message::newInstance() + ->setSubject('...') + ->setFrom(array('john@example.com' => 'John Doe')) + ->setTo($to = array( + 'fabien-to@example.com' => 'Fabien (To)', + 'chris-to@example.com' => 'Chris (To)', + )) + ->setCc($cc = array( + 'fabien-cc@example.com' => 'Fabien (Cc)', + 'chris-cc@example.com' => 'Chris (Cc)', + )) + ->setBcc($bcc = array( + 'fabien-bcc@example.com' => 'Fabien (Bcc)', + 'chris-bcc@example.com' => 'Chris (Bcc)', + )) + ->setBody('...') + ; + + $plugin = new Swift_Plugins_RedirectingPlugin('god@example.com'); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + + $this->assertEquals($message->getTo(), array('god@example.com' => '')); + $this->assertEquals($message->getCc(), array()); + $this->assertEquals($message->getBcc(), array()); + + $plugin->sendPerformed($evt); + + $this->assertEquals($message->getTo(), $to); + $this->assertEquals($message->getCc(), $cc); + $this->assertEquals($message->getBcc(), $bcc); + } + + public function testPluginRespectsUnsetToList() + { + $message = Swift_Message::newInstance() + ->setSubject('...') + ->setFrom(array('john@example.com' => 'John Doe')) + ->setCc($cc = array( + 'fabien-cc@example.com' => 'Fabien (Cc)', + 'chris-cc@example.com' => 'Chris (Cc)', + )) + ->setBcc($bcc = array( + 'fabien-bcc@example.com' => 'Fabien (Bcc)', + 'chris-bcc@example.com' => 'Chris (Bcc)', + )) + ->setBody('...') + ; + + $plugin = new Swift_Plugins_RedirectingPlugin('god@example.com'); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + + $this->assertEquals($message->getTo(), array('god@example.com' => '')); + $this->assertEquals($message->getCc(), array()); + $this->assertEquals($message->getBcc(), array()); + + $plugin->sendPerformed($evt); + + $this->assertEquals($message->getTo(), array()); + $this->assertEquals($message->getCc(), $cc); + $this->assertEquals($message->getBcc(), $bcc); + } + + public function testPluginRespectsAWhitelistOfPatterns() + { + $message = Swift_Message::newInstance() + ->setSubject('...') + ->setFrom(array('john@example.com' => 'John Doe')) + ->setTo($to = array( + 'fabien-to@example.com' => 'Fabien (To)', + 'chris-to@example.com' => 'Chris (To)', + 'lars-to@internal.com' => 'Lars (To)', + )) + ->setCc($cc = array( + 'fabien-cc@example.com' => 'Fabien (Cc)', + 'chris-cc@example.com' => 'Chris (Cc)', + 'lars-cc@internal.org' => 'Lars (Cc)', + )) + ->setBcc($bcc = array( + 'fabien-bcc@example.com' => 'Fabien (Bcc)', + 'chris-bcc@example.com' => 'Chris (Bcc)', + 'john-bcc@example.org' => 'John (Bcc)', + )) + ->setBody('...') + ; + + $recipient = 'god@example.com'; + $patterns = array('/^.*@internal.[a-z]+$/', '/^john-.*$/'); + + $plugin = new Swift_Plugins_RedirectingPlugin($recipient, $patterns); + + $this->assertEquals($recipient, $plugin->getRecipient()); + $this->assertEquals($plugin->getWhitelist(), $patterns); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + + $this->assertEquals($message->getTo(), array('lars-to@internal.com' => 'Lars (To)', 'god@example.com' => null)); + $this->assertEquals($message->getCc(), array('lars-cc@internal.org' => 'Lars (Cc)')); + $this->assertEquals($message->getBcc(), array('john-bcc@example.org' => 'John (Bcc)')); + + $plugin->sendPerformed($evt); + + $this->assertEquals($message->getTo(), $to); + $this->assertEquals($message->getCc(), $cc); + $this->assertEquals($message->getBcc(), $bcc); + } + + public function testArrayOfRecipientsCanBeExplicitlyDefined() + { + $message = Swift_Message::newInstance() + ->setSubject('...') + ->setFrom(array('john@example.com' => 'John Doe')) + ->setTo(array( + 'fabien@example.com' => 'Fabien', + 'chris@example.com' => 'Chris (To)', + 'lars-to@internal.com' => 'Lars (To)', + )) + ->setCc(array( + 'fabien@example.com' => 'Fabien', + 'chris-cc@example.com' => 'Chris (Cc)', + 'lars-cc@internal.org' => 'Lars (Cc)', + )) + ->setBcc(array( + 'fabien@example.com' => 'Fabien', + 'chris-bcc@example.com' => 'Chris (Bcc)', + 'john-bcc@example.org' => 'John (Bcc)', + )) + ->setBody('...') + ; + + $recipients = array('god@example.com', 'fabien@example.com'); + $patterns = array('/^.*@internal.[a-z]+$/'); + + $plugin = new Swift_Plugins_RedirectingPlugin($recipients, $patterns); + + $evt = $this->_createSendEvent($message); + + $plugin->beforeSendPerformed($evt); + + $this->assertEquals( + $message->getTo(), + array('fabien@example.com' => 'Fabien', 'lars-to@internal.com' => 'Lars (To)', 'god@example.com' => null) + ); + $this->assertEquals( + $message->getCc(), + array('fabien@example.com' => 'Fabien', 'lars-cc@internal.org' => 'Lars (Cc)') + ); + $this->assertEquals($message->getBcc(), array('fabien@example.com' => 'Fabien')); + } + + // -- Creation Methods + + private function _createSendEvent(Swift_Mime_Message $message) + { + $evt = $this->getMockBuilder('Swift_Events_SendEvent') + ->disableOriginalConstructor() + ->getMock(); + $evt->expects($this->any()) + ->method('getMessage') + ->will($this->returnValue($message)); + + return $evt; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ReporterPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ReporterPluginTest.php new file mode 100644 index 00000000..81018830 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ReporterPluginTest.php @@ -0,0 +1,88 @@ +_createMessage(); + $evt = $this->_createSendEvent(); + $reporter = $this->_createReporter(); + + $message->shouldReceive('getTo')->zeroOrMoreTimes()->andReturn(array('foo@bar.tld' => 'Foo')); + $evt->shouldReceive('getMessage')->zeroOrMoreTimes()->andReturn($message); + $evt->shouldReceive('getFailedRecipients')->zeroOrMoreTimes()->andReturn(array()); + $reporter->shouldReceive('notify')->once()->with($message, 'foo@bar.tld', Swift_Plugins_Reporter::RESULT_PASS); + + $plugin = new Swift_Plugins_ReporterPlugin($reporter); + $plugin->sendPerformed($evt); + } + + public function testReportingFailedTo() + { + $message = $this->_createMessage(); + $evt = $this->_createSendEvent(); + $reporter = $this->_createReporter(); + + $message->shouldReceive('getTo')->zeroOrMoreTimes()->andReturn(array('foo@bar.tld' => 'Foo', 'zip@button' => 'Zip')); + $evt->shouldReceive('getMessage')->zeroOrMoreTimes()->andReturn($message); + $evt->shouldReceive('getFailedRecipients')->zeroOrMoreTimes()->andReturn(array('zip@button')); + $reporter->shouldReceive('notify')->once()->with($message, 'foo@bar.tld', Swift_Plugins_Reporter::RESULT_PASS); + $reporter->shouldReceive('notify')->once()->with($message, 'zip@button', Swift_Plugins_Reporter::RESULT_FAIL); + + $plugin = new Swift_Plugins_ReporterPlugin($reporter); + $plugin->sendPerformed($evt); + } + + public function testReportingFailedCc() + { + $message = $this->_createMessage(); + $evt = $this->_createSendEvent(); + $reporter = $this->_createReporter(); + + $message->shouldReceive('getTo')->zeroOrMoreTimes()->andReturn(array('foo@bar.tld' => 'Foo')); + $message->shouldReceive('getCc')->zeroOrMoreTimes()->andReturn(array('zip@button' => 'Zip', 'test@test.com' => 'Test')); + $evt->shouldReceive('getMessage')->zeroOrMoreTimes()->andReturn($message); + $evt->shouldReceive('getFailedRecipients')->zeroOrMoreTimes()->andReturn(array('zip@button')); + $reporter->shouldReceive('notify')->once()->with($message, 'foo@bar.tld', Swift_Plugins_Reporter::RESULT_PASS); + $reporter->shouldReceive('notify')->once()->with($message, 'zip@button', Swift_Plugins_Reporter::RESULT_FAIL); + $reporter->shouldReceive('notify')->once()->with($message, 'test@test.com', Swift_Plugins_Reporter::RESULT_PASS); + + $plugin = new Swift_Plugins_ReporterPlugin($reporter); + $plugin->sendPerformed($evt); + } + + public function testReportingFailedBcc() + { + $message = $this->_createMessage(); + $evt = $this->_createSendEvent(); + $reporter = $this->_createReporter(); + + $message->shouldReceive('getTo')->zeroOrMoreTimes()->andReturn(array('foo@bar.tld' => 'Foo')); + $message->shouldReceive('getBcc')->zeroOrMoreTimes()->andReturn(array('zip@button' => 'Zip', 'test@test.com' => 'Test')); + $evt->shouldReceive('getMessage')->zeroOrMoreTimes()->andReturn($message); + $evt->shouldReceive('getFailedRecipients')->zeroOrMoreTimes()->andReturn(array('zip@button')); + $reporter->shouldReceive('notify')->once()->with($message, 'foo@bar.tld', Swift_Plugins_Reporter::RESULT_PASS); + $reporter->shouldReceive('notify')->once()->with($message, 'zip@button', Swift_Plugins_Reporter::RESULT_FAIL); + $reporter->shouldReceive('notify')->once()->with($message, 'test@test.com', Swift_Plugins_Reporter::RESULT_PASS); + + $plugin = new Swift_Plugins_ReporterPlugin($reporter); + $plugin->sendPerformed($evt); + } + + // -- Creation Methods + + private function _createMessage() + { + return $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + } + + private function _createSendEvent() + { + return $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + } + + private function _createReporter() + { + return $this->getMockery('Swift_Plugins_Reporter')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HitReporterTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HitReporterTest.php new file mode 100644 index 00000000..4d31c3c6 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HitReporterTest.php @@ -0,0 +1,64 @@ +_hitReporter = new Swift_Plugins_Reporters_HitReporter(); + $this->_message = $this->getMock('Swift_Mime_Message'); + } + + public function testReportingFail() + { + $this->_hitReporter->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->assertEquals(array('foo@bar.tld'), + $this->_hitReporter->getFailedRecipients() + ); + } + + public function testMultipleReports() + { + $this->_hitReporter->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->_hitReporter->notify($this->_message, 'zip@button', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->assertEquals(array('foo@bar.tld', 'zip@button'), + $this->_hitReporter->getFailedRecipients() + ); + } + + public function testReportingPassIsIgnored() + { + $this->_hitReporter->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->_hitReporter->notify($this->_message, 'zip@button', + Swift_Plugins_Reporter::RESULT_PASS + ); + $this->assertEquals(array('foo@bar.tld'), + $this->_hitReporter->getFailedRecipients() + ); + } + + public function testBufferCanBeCleared() + { + $this->_hitReporter->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->_hitReporter->notify($this->_message, 'zip@button', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $this->assertEquals(array('foo@bar.tld', 'zip@button'), + $this->_hitReporter->getFailedRecipients() + ); + $this->_hitReporter->clear(); + $this->assertEquals(array(), $this->_hitReporter->getFailedRecipients()); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HtmlReporterTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HtmlReporterTest.php new file mode 100644 index 00000000..3e78fca5 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/Reporters/HtmlReporterTest.php @@ -0,0 +1,54 @@ +_html = new Swift_Plugins_Reporters_HtmlReporter(); + $this->_message = $this->getMock('Swift_Mime_Message'); + } + + public function testReportingPass() + { + ob_start(); + $this->_html->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_PASS + ); + $html = ob_get_clean(); + + $this->assertRegExp('~ok|pass~i', $html, '%s: Reporter should indicate pass'); + $this->assertRegExp('~foo@bar\.tld~', $html, '%s: Reporter should show address'); + } + + public function testReportingFail() + { + ob_start(); + $this->_html->notify($this->_message, 'zip@button', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $html = ob_get_clean(); + + $this->assertRegExp('~fail~i', $html, '%s: Reporter should indicate fail'); + $this->assertRegExp('~zip@button~', $html, '%s: Reporter should show address'); + } + + public function testMultipleReports() + { + ob_start(); + $this->_html->notify($this->_message, 'foo@bar.tld', + Swift_Plugins_Reporter::RESULT_PASS + ); + $this->_html->notify($this->_message, 'zip@button', + Swift_Plugins_Reporter::RESULT_FAIL + ); + $html = ob_get_clean(); + + $this->assertRegExp('~ok|pass~i', $html, '%s: Reporter should indicate pass'); + $this->assertRegExp('~foo@bar\.tld~', $html, '%s: Reporter should show address'); + $this->assertRegExp('~fail~i', $html, '%s: Reporter should indicate fail'); + $this->assertRegExp('~zip@button~', $html, '%s: Reporter should show address'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ThrottlerPluginTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ThrottlerPluginTest.php new file mode 100644 index 00000000..a50f14f9 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Plugins/ThrottlerPluginTest.php @@ -0,0 +1,104 @@ +_createSleeper(); + $timer = $this->_createTimer(); + + //10MB/min + $plugin = new Swift_Plugins_ThrottlerPlugin( + 10000000, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE, + $sleeper, $timer + ); + + $timer->shouldReceive('getTimestamp')->once()->andReturn(0); + $timer->shouldReceive('getTimestamp')->once()->andReturn(1); //expected 0.6 + $timer->shouldReceive('getTimestamp')->once()->andReturn(1); //expected 1.2 (sleep 1) + $timer->shouldReceive('getTimestamp')->once()->andReturn(2); //expected 1.8 + $timer->shouldReceive('getTimestamp')->once()->andReturn(2); //expected 2.4 (sleep 1) + $sleeper->shouldReceive('sleep')->twice()->with(1); + + //10,000,000 bytes per minute + //100,000 bytes per email + + // .: (10,000,000/100,000)/60 emails per second = 1.667 emais/sec + + $message = $this->_createMessageWithByteCount(100000); //100KB + + $evt = $this->_createSendEvent($message); + + for ($i = 0; $i < 5; ++$i) { + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + } + + public function testMessagesPerMinuteThrottling() + { + $sleeper = $this->_createSleeper(); + $timer = $this->_createTimer(); + + //60/min + $plugin = new Swift_Plugins_ThrottlerPlugin( + 60, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE, + $sleeper, $timer + ); + + $timer->shouldReceive('getTimestamp')->once()->andReturn(0); + $timer->shouldReceive('getTimestamp')->once()->andReturn(0); //expected 1 (sleep 1) + $timer->shouldReceive('getTimestamp')->once()->andReturn(2); //expected 2 + $timer->shouldReceive('getTimestamp')->once()->andReturn(2); //expected 3 (sleep 1) + $timer->shouldReceive('getTimestamp')->once()->andReturn(4); //expected 4 + $sleeper->shouldReceive('sleep')->twice()->with(1); + + //60 messages per minute + //1 message per second + + $message = $this->_createMessageWithByteCount(10); + + $evt = $this->_createSendEvent($message); + + for ($i = 0; $i < 5; ++$i) { + $plugin->beforeSendPerformed($evt); + $plugin->sendPerformed($evt); + } + } + + // -- Creation Methods + + private function _createSleeper() + { + return $this->getMockery('Swift_Plugins_Sleeper'); + } + + private function _createTimer() + { + return $this->getMockery('Swift_Plugins_Timer'); + } + + private function _createMessageWithByteCount($bytes) + { + $msg = $this->getMockery('Swift_Mime_Message'); + $msg->shouldReceive('toByteStream') + ->zeroOrMoreTimes() + ->andReturnUsing(function ($is) use ($bytes) { + for ($i = 0; $i < $bytes; ++$i) { + $is->write('x'); + } + }); + + return $msg; + } + + private function _createSendEvent($message) + { + $evt = $this->getMockery('Swift_Events_SendEvent'); + $evt->shouldReceive('getMessage') + ->zeroOrMoreTimes() + ->andReturn($message); + + return $evt; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/DKIMSignerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/DKIMSignerTest.php new file mode 100644 index 00000000..b122ad03 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/DKIMSignerTest.php @@ -0,0 +1,227 @@ +markTestSkipped( + 'skipping because of https://bugs.php.net/bug.php?id=61421' + ); + } + } + + public function testBasicSigningHeaderManipulation() + { + $headers = $this->_createHeaders(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + /* @var $signer Swift_Signers_HeaderSigner */ + $altered = $signer->getAlteredHeaders(); + $signer->reset(); + // Headers + $signer->setHeaders($headers); + // Body + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + // Signing + $signer->addSignature($headers); + } + + // Default Signing + public function testSigningDefaults() + { + $headerSet = $this->_createHeaderSet(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + $signer->setSignatureTimestamp('1299879181'); + $altered = $signer->getAlteredHeaders(); + $this->assertEquals(array('DKIM-Signature'), $altered); + $signer->reset(); + $signer->setHeaders($headerSet); + $this->assertFalse($headerSet->has('DKIM-Signature')); + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + $signer->addSignature($headerSet); + $this->assertTrue($headerSet->has('DKIM-Signature')); + $dkim = $headerSet->getAll('DKIM-Signature'); + $sig = reset($dkim); + $this->assertEquals($sig->getValue(), 'v=1; a=rsa-sha1; bh=wlbYcY9O9OPInGJ4D0E/rGsvMLE=; d=dummy.nxdomain.be; h=; i=@dummy.nxdomain.be; s=dummySelector; t=1299879181; b=RMSNelzM2O5MAAnMjT3G3/VF36S3DGJXoPCXR001F1WDReu0prGphWjuzK/m6V1pwqQL8cCNg Hi74mTx2bvyAvmkjvQtJf1VMUOCc9WHGcm1Yec66I3ZWoNMGSWZ1EKAm2CtTzyG0IFw4ml9DI wSkyAFxlgicckDD6FibhqwX4w='); + } + + // SHA256 Signing + public function testSigning256() + { + $headerSet = $this->_createHeaderSet(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + $signer->setHashAlgorithm('rsa-sha256'); + $signer->setSignatureTimestamp('1299879181'); + $altered = $signer->getAlteredHeaders(); + $this->assertEquals(array('DKIM-Signature'), $altered); + $signer->reset(); + $signer->setHeaders($headerSet); + $this->assertFalse($headerSet->has('DKIM-Signature')); + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + $signer->addSignature($headerSet); + $this->assertTrue($headerSet->has('DKIM-Signature')); + $dkim = $headerSet->getAll('DKIM-Signature'); + $sig = reset($dkim); + $this->assertEquals($sig->getValue(), 'v=1; a=rsa-sha256; bh=f+W+hu8dIhf2VAni89o8lF6WKTXi7nViA4RrMdpD5/U=; d=dummy.nxdomain.be; h=; i=@dummy.nxdomain.be; s=dummySelector; t=1299879181; b=jqPmieHzF5vR9F4mXCAkowuphpO4iJ8IAVuioh1BFZ3VITXZj5jlOFxULJMBiiApm2keJirnh u4mzogj444QkpT3lJg8/TBGAYQPdcvkG3KC0jdyN6QpSgpITBJG2BwWa+keXsv2bkQgLRAzNx qRhP45vpHCKun0Tg9LrwW/KCg='); + } + + // Relaxed/Relaxed Hash Signing + public function testSigningRelaxedRelaxed256() + { + $headerSet = $this->_createHeaderSet(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + $signer->setHashAlgorithm('rsa-sha256'); + $signer->setSignatureTimestamp('1299879181'); + $signer->setBodyCanon('relaxed'); + $signer->setHeaderCanon('relaxed'); + $altered = $signer->getAlteredHeaders(); + $this->assertEquals(array('DKIM-Signature'), $altered); + $signer->reset(); + $signer->setHeaders($headerSet); + $this->assertFalse($headerSet->has('DKIM-Signature')); + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + $signer->addSignature($headerSet); + $this->assertTrue($headerSet->has('DKIM-Signature')); + $dkim = $headerSet->getAll('DKIM-Signature'); + $sig = reset($dkim); + $this->assertEquals($sig->getValue(), 'v=1; a=rsa-sha256; bh=f+W+hu8dIhf2VAni89o8lF6WKTXi7nViA4RrMdpD5/U=; d=dummy.nxdomain.be; h=; i=@dummy.nxdomain.be; s=dummySelector; c=relaxed/relaxed; t=1299879181; b=gzOI+PX6HpZKQFzwwmxzcVJsyirdLXOS+4pgfCpVHQIdqYusKLrhlLeFBTNoz75HrhNvGH6T0 Rt3w5aTqkrWfUuAEYt0Ns14GowLM7JojaFN+pZ4eYnRB3CBBgW6fee4NEMD5WPca3uS09tr1E 10RYh9ILlRtl+84sovhx5id3Y='); + } + + // Relaxed/Simple Hash Signing + public function testSigningRelaxedSimple256() + { + $headerSet = $this->_createHeaderSet(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + $signer->setHashAlgorithm('rsa-sha256'); + $signer->setSignatureTimestamp('1299879181'); + $signer->setHeaderCanon('relaxed'); + $altered = $signer->getAlteredHeaders(); + $this->assertEquals(array('DKIM-Signature'), $altered); + $signer->reset(); + $signer->setHeaders($headerSet); + $this->assertFalse($headerSet->has('DKIM-Signature')); + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + $signer->addSignature($headerSet); + $this->assertTrue($headerSet->has('DKIM-Signature')); + $dkim = $headerSet->getAll('DKIM-Signature'); + $sig = reset($dkim); + $this->assertEquals($sig->getValue(), 'v=1; a=rsa-sha256; bh=f+W+hu8dIhf2VAni89o8lF6WKTXi7nViA4RrMdpD5/U=; d=dummy.nxdomain.be; h=; i=@dummy.nxdomain.be; s=dummySelector; c=relaxed; t=1299879181; b=dLPJNec5v81oelyzGOY0qPqTlGnQeNfUNBOrV/JKbStr3NqWGI9jH4JAe2YvO2V32lfPNoby1 4MMzZ6EPkaZkZDDSPa+53YbCPQAlqiD9QZZIUe2UNM33HN8yAMgiWEF5aP7MbQnxeVZMfVLEl 9S8qOImu+K5JZqhQQTL0dgLwA='); + } + + // Simple/Relaxed Hash Signing + public function testSigningSimpleRelaxed256() + { + $headerSet = $this->_createHeaderSet(); + $messageContent = "Hello World"; + $signer = new Swift_Signers_DKIMSigner(file_get_contents(dirname(dirname(dirname(__DIR__))).'/_samples/dkim/dkim.test.priv'), 'dummy.nxdomain.be', 'dummySelector'); + $signer->setHashAlgorithm('rsa-sha256'); + $signer->setSignatureTimestamp('1299879181'); + $signer->setBodyCanon('relaxed'); + $altered = $signer->getAlteredHeaders(); + $this->assertEquals(array('DKIM-Signature'), $altered); + $signer->reset(); + $signer->setHeaders($headerSet); + $this->assertFalse($headerSet->has('DKIM-Signature')); + $signer->startBody(); + $signer->write($messageContent); + $signer->endBody(); + $signer->addSignature($headerSet); + $this->assertTrue($headerSet->has('DKIM-Signature')); + $dkim = $headerSet->getAll('DKIM-Signature'); + $sig = reset($dkim); + $this->assertEquals($sig->getValue(), 'v=1; a=rsa-sha256; bh=f+W+hu8dIhf2VAni89o8lF6WKTXi7nViA4RrMdpD5/U=; d=dummy.nxdomain.be; h=; i=@dummy.nxdomain.be; s=dummySelector; c=simple/relaxed; t=1299879181; b=M5eomH/zamyzix9kOes+6YLzQZxuJdBP4x3nP9zF2N26eMLG2/cBKbnNyqiOTDhJdYfWPbLIa 1CWnjST0j5p4CpeOkGYuiE+M4TWEZwhRmRWootlPO3Ii6XpbBJKFk1o9zviS7OmXblUUE4aqb yRSIMDhtLdCK5GlaCneFLN7RQ='); + } + + // -- Creation Methods + private function _createHeaderSet() + { + $cache = new Swift_KeyCache_ArrayKeyCache(new Swift_KeyCache_SimpleKeyCacheInputStream()); + $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + $contentEncoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + + $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder(new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')); + $paramEncoder = new Swift_Encoder_Rfc2231Encoder(new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')); + $grammar = new Swift_Mime_Grammar(); + $headers = new Swift_Mime_SimpleHeaderSet(new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $grammar)); + + return $headers; + } + + /** + * @return Swift_Mime_Headers + */ + private function _createHeaders() + { + $x = 0; + $cache = new Swift_KeyCache_ArrayKeyCache(new Swift_KeyCache_SimpleKeyCacheInputStream()); + $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory(); + $contentEncoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder(); + + $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder(new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')); + $paramEncoder = new Swift_Encoder_Rfc2231Encoder(new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')); + $grammar = new Swift_Mime_Grammar(); + $headerFactory = new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $grammar); + $headers = $this->getMockery('Swift_Mime_HeaderSet'); + + $headers->shouldReceive('listAll') + ->zeroOrMoreTimes() + ->andReturn(array('From', 'To', 'Date', 'Subject')); + $headers->shouldReceive('has') + ->zeroOrMoreTimes() + ->with('From') + ->andReturn(true); + $headers->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->with('From') + ->andReturn(array($headerFactory->createMailboxHeader('From', 'test@test.test'))); + $headers->shouldReceive('has') + ->zeroOrMoreTimes() + ->with('To') + ->andReturn(true); + $headers->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->with('To') + ->andReturn(array($headerFactory->createMailboxHeader('To', 'test@test.test'))); + $headers->shouldReceive('has') + ->zeroOrMoreTimes() + ->with('Date') + ->andReturn(true); + $headers->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->with('Date') + ->andReturn(array($headerFactory->createTextHeader('Date', 'Fri, 11 Mar 2011 20:56:12 +0000 (GMT)'))); + $headers->shouldReceive('has') + ->zeroOrMoreTimes() + ->with('Subject') + ->andReturn(true); + $headers->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->with('Subject') + ->andReturn(array($headerFactory->createTextHeader('Subject', 'Foo Bar Text Message'))); + $headers->shouldReceive('addTextHeader') + ->zeroOrMoreTimes() + ->with('DKIM-Signature', \Mockery::any()) + ->andReturn(true); + $headers->shouldReceive('getAll') + ->zeroOrMoreTimes() + ->with('DKIM-Signature') + ->andReturn(array($headerFactory->createTextHeader('DKIM-Signature', 'Foo Bar Text Message'))); + + return $headers; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/OpenDKIMSignerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/OpenDKIMSignerTest.php new file mode 100644 index 00000000..00e48c13 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/OpenDKIMSignerTest.php @@ -0,0 +1,45 @@ +markTestSkipped( + 'Need OpenDKIM extension run these tests.' + ); + } + } + + public function testBasicSigningHeaderManipulation() + { + } + + // Default Signing + public function testSigningDefaults() + { + } + + // SHA256 Signing + public function testSigning256() + { + } + + // Relaxed/Relaxed Hash Signing + public function testSigningRelaxedRelaxed256() + { + } + + // Relaxed/Simple Hash Signing + public function testSigningRelaxedSimple256() + { + } + + // Simple/Relaxed Hash Signing + public function testSigningSimpleRelaxed256() + { + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/SMimeSignerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/SMimeSignerTest.php new file mode 100644 index 00000000..f74cba0a --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Signers/SMimeSignerTest.php @@ -0,0 +1,511 @@ +replacementFactory = Swift_DependencyContainer::getInstance() + ->lookup('transport.replacementfactory'); + + $this->samplesDir = str_replace('\\', '/', realpath(__DIR__.'/../../../_samples/')).'/'; + } + + public function testUnSingedMessage() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $this->assertEquals('Here is the message itself', $message->getBody()); + } + + public function testSingedMessage() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setSignCertificate($this->samplesDir.'smime/sign.crt', $this->samplesDir.'smime/sign.key'); + $message->attachSigner($signer); + + $messageStream = $this->newFilteredStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!($boundary = $this->getBoundary($headers['content-type']))) { + return false; + } + + $expectedBody = <<assertValidVerify($expectedBody, $messageStream); + unset($messageStream); + } + + public function testSingedMessageBinary() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setSignCertificate($this->samplesDir.'smime/sign.crt', $this->samplesDir.'smime/sign.key', PKCS7_BINARY); + $message->attachSigner($signer); + + $messageStream = $this->newFilteredStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!preg_match('#^application/(x\-)?pkcs7-mime; smime-type=signed\-data;#', $headers['content-type'])) { + $this->fail('Content-type does not match.'); + + return false; + } + + $this->assertEquals($headers['content-transfer-encoding'], 'base64'); + $this->assertEquals($headers['content-disposition'], 'attachment; filename="smime.p7m"'); + + $expectedBody = '(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2})'; + + $messageStreamClean = $this->newFilteredStream(); + + $this->assertValidVerify($expectedBody, $messageStream); + unset($messageStreamClean, $messageStream); + } + + public function testSingedMessageWithAttachments() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $message->attach(Swift_Attachment::fromPath($this->samplesDir.'/files/textfile.zip')); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setSignCertificate($this->samplesDir.'smime/sign.crt', $this->samplesDir.'smime/sign.key'); + $message->attachSigner($signer); + + $messageStream = $this->newFilteredStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!($boundary = $this->getBoundary($headers['content-type']))) { + return false; + } + + $expectedBody = <<assertValidVerify($expectedBody, $messageStream); + unset($messageStream); + } + + public function testEncryptedMessage() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $originalMessage = $this->cleanMessage($message->toString()); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setEncryptCertificate($this->samplesDir.'smime/encrypt.crt'); + $message->attachSigner($signer); + + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!preg_match('#^application/(x\-)?pkcs7-mime; smime-type=enveloped\-data;#', $headers['content-type'])) { + $this->fail('Content-type does not match.'); + + return false; + } + + $expectedBody = '(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2})'; + + $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_decrypt($messageStream->getPath(), $decryptedMessageStream->getPath(), 'file://'.$this->samplesDir.'smime/encrypt.crt', array('file://'.$this->samplesDir.'smime/encrypt.key', 'swift'))) { + $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string())); + } + + $this->assertEquals($originalMessage, $decryptedMessageStream->getContent()); + unset($decryptedMessageStream, $messageStream); + } + + public function testEncryptedMessageWithMultipleCerts() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $originalMessage = $this->cleanMessage($message->toString()); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setEncryptCertificate(array($this->samplesDir.'smime/encrypt.crt', $this->samplesDir.'smime/encrypt2.crt')); + $message->attachSigner($signer); + + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!preg_match('#^application/(x\-)?pkcs7-mime; smime-type=enveloped\-data;#', $headers['content-type'])) { + $this->fail('Content-type does not match.'); + + return false; + } + + $expectedBody = '(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2})'; + + $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_decrypt($messageStream->getPath(), $decryptedMessageStream->getPath(), 'file://'.$this->samplesDir.'smime/encrypt.crt', array('file://'.$this->samplesDir.'smime/encrypt.key', 'swift'))) { + $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string())); + } + + $this->assertEquals($originalMessage, $decryptedMessageStream->getContent()); + unset($decryptedMessageStream); + + $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_decrypt($messageStream->getPath(), $decryptedMessageStream->getPath(), 'file://'.$this->samplesDir.'smime/encrypt2.crt', array('file://'.$this->samplesDir.'smime/encrypt2.key', 'swift'))) { + $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string())); + } + + $this->assertEquals($originalMessage, $decryptedMessageStream->getContent()); + unset($decryptedMessageStream, $messageStream); + } + + public function testSignThenEncryptedMessage() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $signer = new Swift_Signers_SMimeSigner(); + $signer->setSignCertificate($this->samplesDir.'smime/sign.crt', $this->samplesDir.'smime/sign.key'); + $signer->setEncryptCertificate($this->samplesDir.'smime/encrypt.crt'); + $message->attachSigner($signer); + + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!preg_match('#^application/(x\-)?pkcs7-mime; smime-type=enveloped\-data;#', $headers['content-type'])) { + $this->fail('Content-type does not match.'); + + return false; + } + + $expectedBody = '(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2})'; + + $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_decrypt($messageStream->getPath(), $decryptedMessageStream->getPath(), 'file://'.$this->samplesDir.'smime/encrypt.crt', array('file://'.$this->samplesDir.'smime/encrypt.key', 'swift'))) { + $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string())); + } + + $entityString = $decryptedMessageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!($boundary = $this->getBoundary($headers['content-type']))) { + return false; + } + + $expectedBody = <<assertValidVerify($expectedBody, $decryptedMessageStream)) { + return false; + } + + unset($decryptedMessageStream, $messageStream); + } + + public function testEncryptThenSignMessage() + { + $message = Swift_SignedMessage::newInstance('Wonderful Subject') + ->setFrom(array('john@doe.com' => 'John Doe')) + ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name')) + ->setBody('Here is the message itself'); + + $originalMessage = $this->cleanMessage($message->toString()); + + $signer = Swift_Signers_SMimeSigner::newInstance(); + $signer->setSignCertificate($this->samplesDir.'smime/sign.crt', $this->samplesDir.'smime/sign.key'); + $signer->setEncryptCertificate($this->samplesDir.'smime/encrypt.crt'); + $signer->setSignThenEncrypt(false); + $message->attachSigner($signer); + + $messageStream = $this->newFilteredStream(); + $message->toByteStream($messageStream); + $messageStream->commit(); + + $entityString = $messageStream->getContent(); + $headers = self::getHeadersOfMessage($entityString); + + if (!($boundary = $this->getBoundary($headers['content-type']))) { + return false; + } + + $expectedBody = <<MIME-Version: 1\.0 +Content-Disposition: attachment; filename="smime\.p7m" +Content-Type: application/(x\-)?pkcs7-mime; smime-type=enveloped-data; name="smime\.p7m" +Content-Transfer-Encoding: base64 + +(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2}) + + +)--$boundary +Content-Type: application/(x\-)?pkcs7-signature; name="smime\.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime\.p7s" + +(?:^[a-zA-Z0-9\/\\r\\n+]*={0,2}) + +--$boundary-- +OEL; + + if (!$this->assertValidVerify($expectedBody, $messageStream)) { + return false; + } + + $expectedBody = str_replace("\n", "\r\n", $expectedBody); + if (!preg_match('%'.$expectedBody.'*%m', $entityString, $entities)) { + $this->fail('Failed regex match.'); + + return false; + } + + $messageStreamClean = new Swift_ByteStream_TemporaryFileByteStream(); + $messageStreamClean->write($entities['encrypted_message']); + + $decryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); + + if (!openssl_pkcs7_decrypt($messageStreamClean->getPath(), $decryptedMessageStream->getPath(), 'file://'.$this->samplesDir.'smime/encrypt.crt', array('file://'.$this->samplesDir.'smime/encrypt.key', 'swift'))) { + $this->fail(sprintf('Decrypt of the message failed. Internal error "%s".', openssl_error_string())); + } + + $this->assertEquals($originalMessage, $decryptedMessageStream->getContent()); + unset($messageStreamClean, $messageStream, $decryptedMessageStream); + } + + protected function assertValidVerify($expected, Swift_ByteStream_TemporaryFileByteStream $messageStream) + { + $actual = $messageStream->getContent(); + + // File is UNIX encoded so convert them to correct line ending + $expected = str_replace("\n", "\r\n", $expected); + + $actual = trim(self::getBodyOfMessage($actual)); + if (!$this->assertRegExp('%^'.$expected.'$\s*%m', $actual)) { + return false; + } + + $opensslOutput = new Swift_ByteStream_TemporaryFileByteStream(); + $verify = openssl_pkcs7_verify($messageStream->getPath(), null, $opensslOutput->getPath(), array($this->samplesDir.'smime/ca.crt')); + + if (false === $verify) { + $this->fail('Verification of the message failed.'); + + return false; + } elseif (-1 === $verify) { + $this->fail(sprintf('Verification of the message failed. Internal error "%s".', openssl_error_string())); + + return false; + } + + return true; + } + + protected function getBoundary($contentType) + { + if (!preg_match('/boundary=("[^"]+"|(?:[^\s]+|$))/is', $contentType, $contentTypeData)) { + $this->fail('Failed to find Boundary parameter'); + + return false; + } + + return trim($contentTypeData[1], '"'); + } + + protected function newFilteredStream() + { + $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); + $messageStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); + $messageStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); + + return $messageStream; + } + + protected static function getBodyOfMessage($message) + { + return substr($message, strpos($message, "\r\n\r\n")); + } + + /** + * Strips of the sender headers and Mime-Version. + * + * @param Swift_ByteStream_TemporaryFileByteStream $messageStream + * @param Swift_ByteStream_TemporaryFileByteStream $inputStream + */ + protected function cleanMessage($content) + { + $newContent = ''; + + $headers = self::getHeadersOfMessage($content); + foreach ($headers as $headerName => $value) { + if (!in_array($headerName, array('content-type', 'content-transfer-encoding', 'content-disposition'))) { + continue; + } + + $headerName = explode('-', $headerName); + $headerName = array_map('ucfirst', $headerName); + $headerName = implode('-', $headerName); + + if (strlen($value) > 62) { + $value = wordwrap($value, 62, "\n "); + } + + $newContent .= "$headerName: $value\r\n"; + } + + return $newContent."\r\n".ltrim(self::getBodyOfMessage($content)); + } + + /** + * Returns the headers of the message. + * + * Header-names are lowercase. + * + * @param string $message + * + * @return array + */ + protected static function getHeadersOfMessage($message) + { + $headersPosEnd = strpos($message, "\r\n\r\n"); + $headerData = substr($message, 0, $headersPosEnd); + $headerLines = explode("\r\n", $headerData); + + if (empty($headerLines)) { + return array(); + } + + $headers = array(); + + foreach ($headerLines as $headerLine) { + if (ctype_space($headerLines[0]) || false === strpos($headerLine, ':')) { + $headers[$currentHeaderName] .= ' '.trim($headerLine); + continue; + } + + $header = explode(':', $headerLine, 2); + $currentHeaderName = strtolower($header[0]); + $headers[$currentHeaderName] = trim($header[1]); + } + + return $headers; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/ByteArrayReplacementFilterTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/ByteArrayReplacementFilterTest.php new file mode 100644 index 00000000..e4d4f48d --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/ByteArrayReplacementFilterTest.php @@ -0,0 +1,131 @@ +_createFilter(array(0x61, 0x62), array(0x63, 0x64)); + $this->assertEquals( + array(0x59, 0x60, 0x63, 0x64, 0x65), + $filter->filter(array(0x59, 0x60, 0x61, 0x62, 0x65)) + ); + } + + public function testShouldBufferReturnsTrueIfPartialMatchAtEndOfBuffer() + { + $filter = $this->_createFilter(array(0x61, 0x62), array(0x63, 0x64)); + $this->assertTrue($filter->shouldBuffer(array(0x59, 0x60, 0x61)), + '%s: Filter should buffer since 0x61 0x62 is the needle and the ending '. + '0x61 could be from 0x61 0x62' + ); + } + + public function testFilterCanMakeMultipleReplacements() + { + $filter = $this->_createFilter(array(array(0x61), array(0x62)), array(0x63)); + $this->assertEquals( + array(0x60, 0x63, 0x60, 0x63, 0x60), + $filter->filter(array(0x60, 0x61, 0x60, 0x62, 0x60)) + ); + } + + public function testMultipleReplacementsCanBeDifferent() + { + $filter = $this->_createFilter(array(array(0x61), array(0x62)), array(array(0x63), array(0x64))); + $this->assertEquals( + array(0x60, 0x63, 0x60, 0x64, 0x60), + $filter->filter(array(0x60, 0x61, 0x60, 0x62, 0x60)) + ); + } + + public function testShouldBufferReturnsFalseIfPartialMatchNotAtEndOfString() + { + $filter = $this->_createFilter(array(0x0D, 0x0A), array(0x0A)); + $this->assertFalse($filter->shouldBuffer(array(0x61, 0x62, 0x0D, 0x0A, 0x63)), + '%s: Filter should not buffer since x0Dx0A is the needle and is not at EOF' + ); + } + + public function testShouldBufferReturnsTrueIfAnyOfMultipleMatchesAtEndOfString() + { + $filter = $this->_createFilter(array(array(0x61, 0x62), array(0x63)), array(0x64)); + $this->assertTrue($filter->shouldBuffer(array(0x59, 0x60, 0x61)), + '%s: Filter should buffer since 0x61 0x62 is a needle and the ending '. + '0x61 could be from 0x61 0x62' + ); + } + + public function testConvertingAllLineEndingsToCRLFWhenInputIsLF() + { + $filter = $this->_createFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ); + + $this->assertEquals( + array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), + $filter->filter(array(0x60, 0x0A, 0x61, 0x0A, 0x62, 0x0A, 0x63)) + ); + } + + public function testConvertingAllLineEndingsToCRLFWhenInputIsCR() + { + $filter = $this->_createFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ); + + $this->assertEquals( + array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), + $filter->filter(array(0x60, 0x0D, 0x61, 0x0D, 0x62, 0x0D, 0x63)) + ); + } + + public function testConvertingAllLineEndingsToCRLFWhenInputIsCRLF() + { + $filter = $this->_createFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ); + + $this->assertEquals( + array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63), + $filter->filter(array(0x60, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x63)) + ); + } + + public function testConvertingAllLineEndingsToCRLFWhenInputIsLFCR() + { + $filter = $this->_createFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ); + + $this->assertEquals( + array(0x60, 0x0D, 0x0A, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x0D, 0x0A, 0x63), + $filter->filter(array(0x60, 0x0A, 0x0D, 0x61, 0x0A, 0x0D, 0x62, 0x0A, 0x0D, 0x63)) + ); + } + + public function testConvertingAllLineEndingsToCRLFWhenInputContainsLFLF() + { + //Lighthouse Bug #23 + + $filter = $this->_createFilter( + array(array(0x0D, 0x0A), array(0x0D), array(0x0A)), + array(array(0x0A), array(0x0A), array(0x0D, 0x0A)) + ); + + $this->assertEquals( + array(0x60, 0x0D, 0x0A, 0x0D, 0x0A, 0x61, 0x0D, 0x0A, 0x0D, 0x0A, 0x62, 0x0D, 0x0A, 0x0D, 0x0A, 0x63), + $filter->filter(array(0x60, 0x0A, 0x0A, 0x61, 0x0A, 0x0A, 0x62, 0x0A, 0x0A, 0x63)) + ); + } + + // -- Creation methods + + private function _createFilter($search, $replace) + { + return new Swift_StreamFilters_ByteArrayReplacementFilter($search, $replace); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterFactoryTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterFactoryTest.php new file mode 100644 index 00000000..bd44f5c7 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterFactoryTest.php @@ -0,0 +1,38 @@ +_createFactory(); + $this->assertInstanceof( + 'Swift_StreamFilters_StringReplacementFilter', + $factory->createFilter('a', 'b') + ); + } + + public function testSameInstancesAreCached() + { + $factory = $this->_createFactory(); + $filter1 = $factory->createFilter('a', 'b'); + $filter2 = $factory->createFilter('a', 'b'); + $this->assertSame($filter1, $filter2, '%s: Instances should be cached'); + } + + public function testDifferingInstancesAreNotCached() + { + $factory = $this->_createFactory(); + $filter1 = $factory->createFilter('a', 'b'); + $filter2 = $factory->createFilter('a', 'c'); + $this->assertNotEquals($filter1, $filter2, + '%s: Differing instances should not be cached' + ); + } + + // -- Creation methods + + private function _createFactory() + { + return new Swift_StreamFilters_StringReplacementFilterFactory(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterTest.php new file mode 100644 index 00000000..7a98a2f2 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/StreamFilters/StringReplacementFilterTest.php @@ -0,0 +1,55 @@ +_createFilter('foo', 'bar'); + $this->assertEquals('XbarYbarZ', $filter->filter('XfooYfooZ')); + } + + public function testShouldBufferReturnsTrueIfPartialMatchAtEndOfBuffer() + { + $filter = $this->_createFilter('foo', 'bar'); + $this->assertTrue($filter->shouldBuffer('XfooYf'), + '%s: Filter should buffer since "foo" is the needle and the ending '. + '"f" could be from "foo"' + ); + } + + public function testFilterCanMakeMultipleReplacements() + { + $filter = $this->_createFilter(array('a', 'b'), 'foo'); + $this->assertEquals('XfooYfooZ', $filter->filter('XaYbZ')); + } + + public function testMultipleReplacementsCanBeDifferent() + { + $filter = $this->_createFilter(array('a', 'b'), array('foo', 'zip')); + $this->assertEquals('XfooYzipZ', $filter->filter('XaYbZ')); + } + + public function testShouldBufferReturnsFalseIfPartialMatchNotAtEndOfString() + { + $filter = $this->_createFilter("\r\n", "\n"); + $this->assertFalse($filter->shouldBuffer("foo\r\nbar"), + '%s: Filter should not buffer since x0Dx0A is the needle and is not at EOF' + ); + } + + public function testShouldBufferReturnsTrueIfAnyOfMultipleMatchesAtEndOfString() + { + $filter = $this->_createFilter(array('foo', 'zip'), 'bar'); + $this->assertTrue($filter->shouldBuffer('XfooYzi'), + '%s: Filter should buffer since "zip" is a needle and the ending '. + '"zi" could be from "zip"' + ); + } + + // -- Creation methods + + private function _createFilter($search, $replace) + { + return new Swift_StreamFilters_StringReplacementFilter($search, $replace); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpEventSupportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpEventSupportTest.php new file mode 100644 index 00000000..163c0320 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpEventSupportTest.php @@ -0,0 +1,560 @@ +_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $listener = $this->getMockery('Swift_Events_EventListener'); + $smtp = $this->_getTransport($buf, $dispatcher); + $dispatcher->shouldReceive('bindEventListener') + ->once() + ->with($listener); + + $smtp->registerPlugin($listener); + } + + public function testSendingDispatchesBeforeSendEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $message = $this->_createMessage(); + $smtp = $this->_getTransport($buf, $dispatcher); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('mark@swiftmailer.org' => 'Mark')); + $dispatcher->shouldReceive('createSendEvent') + ->once() + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeSendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(1, $smtp->send($message)); + } + + public function testSendingDispatchesSendEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $message = $this->_createMessage(); + $smtp = $this->_getTransport($buf, $dispatcher); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('mark@swiftmailer.org' => 'Mark')); + $dispatcher->shouldReceive('createSendEvent') + ->once() + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'sendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(1, $smtp->send($message)); + } + + public function testSendEventCapturesFailures() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('mark@swiftmailer.org' => 'Mark')); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("500 Not now\r\n"); + $dispatcher->shouldReceive('createSendEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'sendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + $evt->shouldReceive('setFailedRecipients') + ->once() + ->with(array('mark@swiftmailer.org')); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(0, $smtp->send($message)); + } + + public function testSendEventHasResultFailedIfAllFailures() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('mark@swiftmailer.org' => 'Mark')); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("500 Not now\r\n"); + $dispatcher->shouldReceive('createSendEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'sendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + $evt->shouldReceive('setResult') + ->once() + ->with(Swift_Events_SendEvent::RESULT_FAILED); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(0, $smtp->send($message)); + } + + public function testSendEventHasResultTentativeIfSomeFailures() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array( + 'mark@swiftmailer.org' => 'Mark', + 'chris@site.tld' => 'Chris', + )); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("500 Not now\r\n"); + $dispatcher->shouldReceive('createSendEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'sendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + $evt->shouldReceive('setResult') + ->once() + ->with(Swift_Events_SendEvent::RESULT_TENTATIVE); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(1, $smtp->send($message)); + } + + public function testSendEventHasResultSuccessIfNoFailures() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array( + 'mark@swiftmailer.org' => 'Mark', + 'chris@site.tld' => 'Chris', + )); + $dispatcher->shouldReceive('createSendEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'sendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturn(false); + $evt->shouldReceive('setResult') + ->once() + ->with(Swift_Events_SendEvent::RESULT_SUCCESS); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(2, $smtp->send($message)); + } + + public function testCancellingEventBubbleBeforeSendStopsEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_SendEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('chris@swiftmailer.org' => null)); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('mark@swiftmailer.org' => 'Mark')); + $dispatcher->shouldReceive('createSendEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeSendPerformed'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(true); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(0, $smtp->send($message)); + } + + public function testStartingTransportDispatchesTransportChangeEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'transportStarted'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(false); + + $this->_finishBuffer($buf); + $smtp->start(); + } + + public function testStartingTransportDispatchesBeforeTransportChangeEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeTransportStarted'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(false); + + $this->_finishBuffer($buf); + $smtp->start(); + } + + public function testCancellingBubbleBeforeTransportStartStopsEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeTransportStarted'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(true); + + $this->_finishBuffer($buf); + $smtp->start(); + + $this->assertFalse($smtp->isStarted(), + '%s: Transport should not be started since event bubble was cancelled' + ); + } + + public function testStoppingTransportDispatchesTransportChangeEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'transportStopped'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->stop(); + } + + public function testStoppingTransportDispatchesBeforeTransportChangeEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent')->shouldIgnoreMissing(); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeTransportStopped'); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->stop(); + } + + public function testCancellingBubbleBeforeTransportStoppedStopsEvent() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportChangeEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $hasRun = false; + $dispatcher->shouldReceive('createTransportChangeEvent') + ->atLeast()->once() + ->with($smtp) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'beforeTransportStopped') + ->andReturnUsing(function () use (&$hasRun) { + $hasRun = true; + }); + $dispatcher->shouldReceive('dispatchEvent') + ->zeroOrMoreTimes(); + $evt->shouldReceive('bubbleCancelled') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$hasRun) { + return $hasRun; + }); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->stop(); + + $this->assertTrue($smtp->isStarted(), + '%s: Transport should not be stopped since event bubble was cancelled' + ); + } + + public function testResponseEventsAreGenerated() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_ResponseEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createResponseEvent') + ->atLeast()->once() + ->with($smtp, \Mockery::any(), \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->atLeast()->once() + ->with($evt, 'responseReceived'); + + $this->_finishBuffer($buf); + $smtp->start(); + } + + public function testCommandEventsAreGenerated() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_CommandEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $dispatcher->shouldReceive('createCommandEvent') + ->once() + ->with($smtp, \Mockery::any(), \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'commandSent'); + + $this->_finishBuffer($buf); + $smtp->start(); + } + + public function testExceptionsCauseExceptionEvents() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportExceptionEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $buf->shouldReceive('readLine') + ->atLeast()->once() + ->andReturn("503 I'm sleepy, go away!\r\n"); + $dispatcher->shouldReceive('createTransportExceptionEvent') + ->zeroOrMoreTimes() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->once() + ->with($evt, 'exceptionThrown'); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(false); + + try { + $smtp->start(); + $this->fail('TransportException should be thrown on invalid response'); + } catch (Swift_TransportException $e) { + } + } + + public function testExceptionBubblesCanBeCancelled() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(false); + $evt = $this->getMockery('Swift_Events_TransportExceptionEvent'); + $smtp = $this->_getTransport($buf, $dispatcher); + + $buf->shouldReceive('readLine') + ->atLeast()->once() + ->andReturn("503 I'm sleepy, go away!\r\n"); + $dispatcher->shouldReceive('createTransportExceptionEvent') + ->twice() + ->with($smtp, \Mockery::any()) + ->andReturn($evt); + $dispatcher->shouldReceive('dispatchEvent') + ->twice() + ->with($evt, 'exceptionThrown'); + $evt->shouldReceive('bubbleCancelled') + ->atLeast()->once() + ->andReturn(true); + + $this->_finishBuffer($buf); + $smtp->start(); + } + + // -- Creation Methods + + protected function _createEventDispatcher($stub = true) + { + return $this->getMockery('Swift_Events_EventDispatcher')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpTest.php new file mode 100644 index 00000000..626248d0 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/AbstractSmtpTest.php @@ -0,0 +1,1249 @@ +_getBuffer(); + $smtp = $this->_getTransport($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + + $this->_finishBuffer($buf); + try { + $this->assertFalse($smtp->isStarted(), '%s: SMTP should begin non-started'); + $smtp->start(); + $this->assertTrue($smtp->isStarted(), '%s: start() should have started connection'); + } catch (Exception $e) { + $this->fail('220 is a valid SMTP greeting and should be accepted'); + } + } + + public function testBadGreetingCausesException() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("554 I'm busy\r\n"); + $this->_finishBuffer($buf); + try { + $this->assertFalse($smtp->isStarted(), '%s: SMTP should begin non-started'); + $smtp->start(); + $this->fail('554 greeting indicates an error and should cause an exception'); + } catch (Exception $e) { + $this->assertFalse($smtp->isStarted(), '%s: start() should have failed'); + } + } + + public function testStartSendsHeloToInitiate() + { + /* -- RFC 2821, 3.2. + + 3.2 Client Initiation + + Once the server has sent the welcoming message and the client has + received it, the client normally sends the EHLO command to the + server, indicating the client's identity. In addition to opening the + session, use of EHLO indicates that the client is able to process + service extensions and requests that the server provide a list of the + extensions it supports. Older SMTP systems which are unable to + support service extensions and contemporary clients which do not + require service extensions in the mail session being initiated, MAY + use HELO instead of EHLO. Servers MUST NOT return the extended + EHLO-style response to a HELO command. For a particular connection + attempt, if the server returns a "command not recognized" response to + EHLO, the client SHOULD be able to fall back and send HELO. + + In the EHLO command the host sending the command identifies itself; + the command may be interpreted as saying "Hello, I am " (and, + in the case of EHLO, "and I support service extension requests"). + + -- RFC 2281, 4.1.1.1. + + ehlo = "EHLO" SP Domain CRLF + helo = "HELO" SP Domain CRLF + + -- RFC 2821, 4.3.2. + + EHLO or HELO + S: 250 + E: 504, 550 + + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^HELO .*?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 ServerName'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + } catch (Exception $e) { + $this->fail('Starting SMTP should send HELO and accept 250 response'); + } + } + + public function testInvalidHeloResponseCausesException() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^HELO .*?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('504 WTF'."\r\n"); + + $this->_finishBuffer($buf); + try { + $this->assertFalse($smtp->isStarted(), '%s: SMTP should begin non-started'); + $smtp->start(); + $this->fail('Non 250 HELO response should raise Exception'); + } catch (Exception $e) { + $this->assertFalse($smtp->isStarted(), '%s: SMTP start() should have failed'); + } + } + + public function testDomainNameIsPlacedInHelo() + { + /* -- RFC 2821, 4.1.4. + + The SMTP client MUST, if possible, ensure that the domain parameter + to the EHLO command is a valid principal host name (not a CNAME or MX + name) for its host. If this is not possible (e.g., when the client's + address is dynamically assigned and the client does not have an + obvious name), an address literal SHOULD be substituted for the + domain name and supplemental information provided that will assist in + identifying the client. + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("HELO mydomain.com\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 ServerName'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->setLocalDomain('mydomain.com'); + $smtp->start(); + } + + public function testSuccessfulMailCommand() + { + /* -- RFC 2821, 3.3. + + There are three steps to SMTP mail transactions. The transaction + starts with a MAIL command which gives the sender identification. + + ..... + + The first step in the procedure is the MAIL command. + + MAIL FROM: [SP ] + + -- RFC 2821, 4.1.1.2. + + Syntax: + + "MAIL FROM:" ("<>" / Reverse-Path) + [SP Mail-parameters] CRLF + -- RFC 2821, 4.1.2. + + Reverse-path = Path + Forward-path = Path + Path = "<" [ A-d-l ":" ] Mailbox ">" + A-d-l = At-domain *( "," A-d-l ) + ; Note that this form, the so-called "source route", + ; MUST BE accepted, SHOULD NOT be generated, and SHOULD be + ; ignored. + At-domain = "@" domain + + -- RFC 2821, 4.3.2. + + MAIL + S: 250 + E: 552, 451, 452, 550, 553, 503 + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 OK\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + } catch (Exception $e) { + $this->fail('MAIL FROM should accept a 250 response'); + } + } + + public function testInvalidResponseCodeFromMailCausesException() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('553 Bad'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + $this->fail('MAIL FROM should accept a 250 response'); + } catch (Exception $e) { + } + } + + public function testSenderIsPreferredOverFrom() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getSender') + ->once() + ->andReturn(array('another@domain.com' => 'Someone')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testReturnPathIsPreferredOverSender() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getSender') + ->once() + ->andReturn(array('another@domain.com' => 'Someone')); + $message->shouldReceive('getReturnPath') + ->once() + ->andReturn('more@domain.com'); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testSuccessfulRcptCommandWith250Response() + { + /* -- RFC 2821, 3.3. + + The second step in the procedure is the RCPT command. + + RCPT TO: [ SP ] + + The first or only argument to this command includes a forward-path + (normally a mailbox and domain, always surrounded by "<" and ">" + brackets) identifying one recipient. If accepted, the SMTP server + returns a 250 OK reply and stores the forward-path. If the recipient + is known not to be a deliverable address, the SMTP server returns a + 550 reply, typically with a string such as "no such user - " and the + mailbox name (other circumstances and reply codes are possible). + This step of the procedure can be repeated any number of times. + + -- RFC 2821, 4.1.1.3. + + This command is used to identify an individual recipient of the mail + data; multiple recipients are specified by multiple use of this + command. The argument field contains a forward-path and may contain + optional parameters. + + The forward-path normally consists of the required destination + mailbox. Sending systems SHOULD not generate the optional list of + hosts known as a source route. + + ....... + + "RCPT TO:" ("" / "" / Forward-Path) + [SP Rcpt-parameters] CRLF + + -- RFC 2821, 4.2.2. + + 250 Requested mail action okay, completed + 251 User not local; will forward to + (See section 3.4) + 252 Cannot VRFY user, but will accept message and attempt + delivery + + -- RFC 2821, 4.3.2. + + RCPT + S: 250, 251 (but see section 3.4 for discussion of 251 and 551) + E: 550, 551, 552, 553, 450, 451, 452, 503, 550 + */ + + //We'll treat 252 as accepted since it isn't really a failure + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + } catch (Exception $e) { + $this->fail('RCPT TO should accept a 250 response'); + } + } + + public function testMailFromCommandIsOnlySentOncePerMessage() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->never() + ->with("MAIL FROM: \r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testMultipleRecipientsSendsMultipleRcpt() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array( + 'foo@bar' => null, + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testCcRecipientsSendsMultipleRcpt() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getCc') + ->once() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testSendReturnsNumberOfSuccessfulRecipients() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getCc') + ->once() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('501 Nobody here'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(2, $smtp->send($message), + '%s: 1 of 3 recipients failed so 2 should be returned' + ); + } + + public function testRsetIsSentIfNoSuccessfulRecipients() + { + /* --RFC 2821, 4.1.1.5. + + This command specifies that the current mail transaction will be + aborted. Any stored sender, recipients, and mail data MUST be + discarded, and all buffers and state tables cleared. The receiver + MUST send a "250 OK" reply to a RSET command with no arguments. A + reset command may be issued by the client at any time. + + -- RFC 2821, 4.3.2. + + RSET + S: 250 + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('503 Bad'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RSET\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(0, $smtp->send($message), + '%s: 1 of 1 recipients failed so 0 should be returned' + ); + } + + public function testSuccessfulDataCommand() + { + /* -- RFC 2821, 3.3. + + The third step in the procedure is the DATA command (or some + alternative specified in a service extension). + + DATA + + If accepted, the SMTP server returns a 354 Intermediate reply and + considers all succeeding lines up to but not including the end of + mail data indicator to be the message text. + + -- RFC 2821, 4.1.1.4. + + The receiver normally sends a 354 response to DATA, and then treats + the lines (strings ending in sequences, as described in + section 2.3.7) following the command as mail data from the sender. + This command causes the mail data to be appended to the mail data + buffer. The mail data may contain any of the 128 ASCII character + codes, although experience has indicated that use of control + characters other than SP, HT, CR, and LF may cause problems and + SHOULD be avoided when possible. + + -- RFC 2821, 4.3.2. + + DATA + I: 354 -> data -> S: 250 + E: 552, 554, 451, 452 + E: 451, 554, 503 + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("DATA\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('354 Go ahead'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + } catch (Exception $e) { + $this->fail('354 is the expected response to DATA'); + } + } + + public function testBadDataResponseCausesException() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("DATA\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('451 Bad'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + $this->fail('354 is the expected response to DATA (not observed)'); + } catch (Exception $e) { + } + } + + public function testMessageIsStreamedToBufferForData() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("DATA\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('354 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("\r\n.\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 OK'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testBadResponseAfterDataTransmissionCausesException() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->once() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->once() + ->andReturn(array('foo@bar' => null)); + $buf->shouldReceive('write') + ->once() + ->with("DATA\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('354 OK'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("\r\n.\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('554 Error'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + $smtp->send($message); + $this->fail('250 is the expected response after a DATA transmission (not observed)'); + } catch (Exception $e) { + } + } + + public function testBccRecipientsAreRemovedFromHeaders() + { + /* -- RFC 2821, 7.2. + + Addresses that do not appear in the message headers may appear in the + RCPT commands to an SMTP server for a number of reasons. The two + most common involve the use of a mailing address as a "list exploder" + (a single address that resolves into multiple addresses) and the + appearance of "blind copies". Especially when more than one RCPT + command is present, and in order to avoid defeating some of the + purpose of these mechanisms, SMTP clients and servers SHOULD NOT copy + the full set of RCPT command arguments into the headers, either as + part of trace headers or as informational or private-extension + headers. Since this rule is often violated in practice, and cannot + be enforced, sending SMTP systems that are aware of "bcc" use MAY + find it helpful to send each blind copy as a separate message + transaction containing only a single RCPT command. + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getBcc') + ->zeroOrMoreTimes() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $message->shouldReceive('setBcc') + ->once() + ->with(array()); + $message->shouldReceive('setBcc') + ->zeroOrMoreTimes(); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + public function testEachBccRecipientIsSentASeparateMessage() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getBcc') + ->zeroOrMoreTimes() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $message->shouldReceive('setBcc') + ->atLeast()->once() + ->with(array()); + $message->shouldReceive('setBcc') + ->once() + ->with(array('zip@button' => 'Zip Button')); + $message->shouldReceive('setBcc') + ->once() + ->with(array('test@domain' => 'Test user')); + $message->shouldReceive('setBcc') + ->atLeast()->once() + ->with(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(1); + $buf->shouldReceive('readLine')->once()->with(1)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(2); + $buf->shouldReceive('readLine')->once()->with(2)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("DATA\r\n")->andReturn(3); + $buf->shouldReceive('readLine')->once()->with(3)->andReturn("354 OK\r\n"); + $buf->shouldReceive('write')->once()->with("\r\n.\r\n")->andReturn(4); + $buf->shouldReceive('readLine')->once()->with(4)->andReturn("250 OK\r\n"); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(5); + $buf->shouldReceive('readLine')->once()->with(5)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(6); + $buf->shouldReceive('readLine')->once()->with(6)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("DATA\r\n")->andReturn(7); + $buf->shouldReceive('readLine')->once()->with(7)->andReturn("354 OK\r\n"); + $buf->shouldReceive('write')->once()->with("\r\n.\r\n")->andReturn(8); + $buf->shouldReceive('readLine')->once()->with(8)->andReturn("250 OK\r\n"); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(9); + $buf->shouldReceive('readLine')->once()->with(9)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(10); + $buf->shouldReceive('readLine')->once()->with(10)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("DATA\r\n")->andReturn(11); + $buf->shouldReceive('readLine')->once()->with(11)->andReturn("354 OK\r\n"); + $buf->shouldReceive('write')->once()->with("\r\n.\r\n")->andReturn(12); + $buf->shouldReceive('readLine')->once()->with(12)->andReturn("250 OK\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(3, $smtp->send($message)); + } + + public function testMessageStateIsRestoredOnFailure() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getBcc') + ->zeroOrMoreTimes() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $message->shouldReceive('setBcc') + ->once() + ->with(array()); + $message->shouldReceive('setBcc') + ->once() + ->with(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("DATA\r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn("451 No\r\n"); + + $this->_finishBuffer($buf); + + $smtp->start(); + try { + $smtp->send($message); + $this->fail('A bad response was given so exception is expected'); + } catch (Exception $e) { + } + } + + public function testStopSendsQuitCommand() + { + /* -- RFC 2821, 4.1.1.10. + + This command specifies that the receiver MUST send an OK reply, and + then close the transmission channel. + + The receiver MUST NOT intentionally close the transmission channel + until it receives and replies to a QUIT command (even if there was an + error). The sender MUST NOT intentionally close the transmission + channel until it sends a QUIT command and SHOULD wait until it + receives the reply (even if there was an error response to a previous + command). If the connection is closed prematurely due to violations + of the above or system or network failure, the server MUST cancel any + pending transaction, but not undo any previously completed + transaction, and generally MUST act as if the command or transaction + in progress had received a temporary error (i.e., a 4yz response). + + The QUIT command may be issued at any time. + + Syntax: + "QUIT" CRLF + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('write') + ->once() + ->with("QUIT\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("221 Bye\r\n"); + $buf->shouldReceive('terminate') + ->once(); + + $this->_finishBuffer($buf); + + $this->assertFalse($smtp->isStarted()); + $smtp->start(); + $this->assertTrue($smtp->isStarted()); + $smtp->stop(); + $this->assertFalse($smtp->isStarted()); + } + + public function testBufferCanBeFetched() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ref = $smtp->getBuffer(); + $this->assertEquals($buf, $ref); + } + + public function testBufferCanBeWrittenToUsingExecuteCommand() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with("FOO\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with(1) + ->andReturn("250 OK\r\n"); + + $res = $smtp->executeCommand("FOO\r\n"); + $this->assertEquals("250 OK\r\n", $res); + } + + public function testResponseCodesAreValidated() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with("FOO\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with(1) + ->andReturn("551 Not ok\r\n"); + + try { + $smtp->executeCommand("FOO\r\n", array(250, 251)); + $this->fail('A 250 or 251 response was needed but 551 was returned.'); + } catch (Exception $e) { + } + } + + public function testFailedRecipientsCanBeCollectedByReference() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('getBcc') + ->zeroOrMoreTimes() + ->andReturn(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + $message->shouldReceive('setBcc') + ->atLeast()->once() + ->with(array()); + $message->shouldReceive('setBcc') + ->once() + ->with(array('zip@button' => 'Zip Button')); + $message->shouldReceive('setBcc') + ->once() + ->with(array('test@domain' => 'Test user')); + $message->shouldReceive('setBcc') + ->atLeast()->once() + ->with(array( + 'zip@button' => 'Zip Button', + 'test@domain' => 'Test user', + )); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(1); + $buf->shouldReceive('readLine')->once()->with(1)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(2); + $buf->shouldReceive('readLine')->once()->with(2)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("DATA\r\n")->andReturn(3); + $buf->shouldReceive('readLine')->once()->with(3)->andReturn("354 OK\r\n"); + $buf->shouldReceive('write')->once()->with("\r\n.\r\n")->andReturn(4); + $buf->shouldReceive('readLine')->once()->with(4)->andReturn("250 OK\r\n"); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(5); + $buf->shouldReceive('readLine')->once()->with(5)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(6); + $buf->shouldReceive('readLine')->once()->with(6)->andReturn("500 Bad\r\n"); + $buf->shouldReceive('write')->once()->with("RSET\r\n")->andReturn(7); + $buf->shouldReceive('readLine')->once()->with(7)->andReturn("250 OK\r\n"); + + $buf->shouldReceive('write')->once()->with("MAIL FROM: \r\n")->andReturn(9); + $buf->shouldReceive('readLine')->once()->with(9)->andReturn("250 OK\r\n"); + $buf->shouldReceive('write')->once()->with("RCPT TO: \r\n")->andReturn(10); + $buf->shouldReceive('readLine')->once()->with(10)->andReturn("500 Bad\r\n"); + $buf->shouldReceive('write')->once()->with("RSET\r\n")->andReturn(11); + $buf->shouldReceive('readLine')->once()->with(11)->andReturn("250 OK\r\n"); + + $this->_finishBuffer($buf); + $smtp->start(); + $this->assertEquals(1, $smtp->send($message, $failures)); + $this->assertEquals(array('zip@button', 'test@domain'), $failures, + '%s: Failures should be caught in an array' + ); + } + + public function testSendingRegeneratesMessageId() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $message = $this->_createMessage(); + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain.com' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + $message->shouldReceive('generateId') + ->once(); + + $this->_finishBuffer($buf); + $smtp->start(); + $smtp->send($message); + } + + protected function _getBuffer() + { + return $this->getMockery('Swift_Transport_IoBuffer')->shouldIgnoreMissing(); + } + + protected function _createMessage() + { + return $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + } + + protected function _finishBuffer($buf) + { + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with(0) + ->andReturn('220 server.com foo'."\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with('~^(EH|HE)LO .*?\r\n$~D') + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn('250 ServerName'."\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with('~^MAIL FROM: <.*?>\r\n$~D') + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with('~^RCPT TO: <.*?>\r\n$~D') + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with("DATA\r\n") + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn("354 OK\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with("\r\n.\r\n") + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->with("RSET\r\n") + ->andReturn($x = uniqid()); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->with($x) + ->andReturn("250 OK\r\n"); + + $buf->shouldReceive('write') + ->zeroOrMoreTimes() + ->andReturn(false); + $buf->shouldReceive('readLine') + ->zeroOrMoreTimes() + ->andReturn(false); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/CramMd5AuthenticatorTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/CramMd5AuthenticatorTest.php new file mode 100644 index 00000000..2f773f51 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/CramMd5AuthenticatorTest.php @@ -0,0 +1,66 @@ +_agent = $this->getMockery('Swift_Transport_SmtpAgent')->shouldIgnoreMissing(); + } + + public function testKeywordIsCramMd5() + { + /* -- RFC 2195, 2. + The authentication type associated with CRAM is "CRAM-MD5". + */ + + $cram = $this->_getAuthenticator(); + $this->assertEquals('CRAM-MD5', $cram->getAuthKeyword()); + } + + public function testSuccessfulAuthentication() + { + $cram = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("AUTH CRAM-MD5\r\n", array(334)) + ->andReturn('334 '.base64_encode('')."\r\n"); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(\Mockery::any(), array(235)); + + $this->assertTrue($cram->authenticate($this->_agent, 'jack', 'pass'), + '%s: The buffer accepted all commands authentication should succeed' + ); + } + + public function testAuthenticationFailureSendRsetAndReturnFalse() + { + $cram = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("AUTH CRAM-MD5\r\n", array(334)) + ->andReturn('334 '.base64_encode('')."\r\n"); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(\Mockery::any(), array(235)) + ->andThrow(new Swift_TransportException("")); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("RSET\r\n", array(250)); + + $this->assertFalse($cram->authenticate($this->_agent, 'jack', 'pass'), + '%s: Authentication fails, so RSET should be sent' + ); + } + + // -- Private helpers + + private function _getAuthenticator() + { + return new Swift_Transport_Esmtp_Auth_CramMd5Authenticator(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/LoginAuthenticatorTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/LoginAuthenticatorTest.php new file mode 100644 index 00000000..1eedbc08 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/LoginAuthenticatorTest.php @@ -0,0 +1,66 @@ +_agent = $this->getMockery('Swift_Transport_SmtpAgent')->shouldIgnoreMissing(); + } + + public function testKeywordIsLogin() + { + $login = $this->_getAuthenticator(); + $this->assertEquals('LOGIN', $login->getAuthKeyword()); + } + + public function testSuccessfulAuthentication() + { + $login = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("AUTH LOGIN\r\n", array(334)); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(base64_encode('jack')."\r\n", array(334)); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(base64_encode('pass')."\r\n", array(235)); + + $this->assertTrue($login->authenticate($this->_agent, 'jack', 'pass'), + '%s: The buffer accepted all commands authentication should succeed' + ); + } + + public function testAuthenticationFailureSendRsetAndReturnFalse() + { + $login = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("AUTH LOGIN\r\n", array(334)); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(base64_encode('jack')."\r\n", array(334)); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with(base64_encode('pass')."\r\n", array(235)) + ->andThrow(new Swift_TransportException("")); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("RSET\r\n", array(250)); + + $this->assertFalse($login->authenticate($this->_agent, 'jack', 'pass'), + '%s: Authentication fails, so RSET should be sent' + ); + } + + // -- Private helpers + + private function _getAuthenticator() + { + return new Swift_Transport_Esmtp_Auth_LoginAuthenticator(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/NTLMAuthenticatorTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/NTLMAuthenticatorTest.php new file mode 100644 index 00000000..ae969ad4 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/NTLMAuthenticatorTest.php @@ -0,0 +1,233 @@ +markTestSkipped( + 'One of the required functions is not available.' + ); + } + } + + public function testKeywordIsNtlm() + { + $login = $this->_getAuthenticator(); + $this->assertEquals('NTLM', $login->getAuthKeyword()); + } + + public function testMessage1Generator() + { + $login = $this->_getAuthenticator(); + $message1 = $this->_invokePrivateMethod('createMessage1', $login); + + $this->assertEquals($this->_message1, bin2hex($message1), + '%s: We send the smallest ntlm message which should never fail.' + ); + } + + public function testLMv1Generator() + { + $password = "test1234"; + $challenge = "b019d38bad875c9d"; + $lmv1 = "1879f60127f8a877022132ec221bcbf3ca016a9f76095606"; + + $login = $this->_getAuthenticator(); + $lmv1Result = $this->_invokePrivateMethod('createLMPassword', $login, array($password, $this->hex2bin($challenge))); + + $this->assertEquals($lmv1, bin2hex($lmv1Result), + '%s: The keys should be the same cause we use the same values to generate them.' + ); + } + + public function testLMv2Generator() + { + $username = "user"; + $password = "SecREt01"; + $domain = "DOMAIN"; + $challenge = "0123456789abcdef"; + $lmv2 = "d6e6152ea25d03b7c6ba6629c2d6aaf0ffffff0011223344"; + + $login = $this->_getAuthenticator(); + $lmv2Result = $this->_invokePrivateMethod('createLMv2Password', $login, array($password, $username, $domain, $this->hex2bin($challenge), $this->hex2bin("ffffff0011223344"))); + + $this->assertEquals($lmv2, bin2hex($lmv2Result), + '%s: The keys should be the same cause we use the same values to generate them.' + ); + } + + public function testMessage3v1Generator() + { + $username = "test"; + $domain = "TESTNT"; + $workstation = "MEMBER"; + $lmResponse = "1879f60127f8a877022132ec221bcbf3ca016a9f76095606"; + $ntlmResponse = "e6285df3287c5d194f84df1a94817c7282d09754b6f9e02a"; + $message3T = "4e544c4d5353500003000000180018006000000018001800780000000c000c0040000000080008004c0000000c000c0054000000000000009a0000000102000054004500530054004e00540074006500730074004d0045004d004200450052001879f60127f8a877022132ec221bcbf3ca016a9f76095606e6285df3287c5d194f84df1a94817c7282d09754b6f9e02a"; + + $login = $this->_getAuthenticator(); + $message3 = $this->_invokePrivateMethod('createMessage3', $login, array($domain, $username, $workstation, $this->hex2bin($lmResponse), $this->hex2bin($ntlmResponse))); + + $this->assertEquals($message3T, bin2hex($message3), + '%s: We send the same information as the example is created with so this should be the same' + ); + } + + public function testMessage3v2Generator() + { + $username = "test"; + $domain = "TESTNT"; + $workstation = "MEMBER"; + $lmResponse = "bf2e015119f6bdb3f6fdb768aa12d478f5ce3d2401c8f6e9"; + $ntlmResponse = "caa4da8f25d5e840974ed8976d3ada46010100000000000030fa7e3c677bc301f5ce3d2401c8f6e90000000002000c0054004500530054004e00540001000c004d0045004d0042004500520003001e006d0065006d006200650072002e0074006500730074002e0063006f006d000000000000000000"; + + $login = $this->_getAuthenticator(); + $message3 = $this->_invokePrivateMethod('createMessage3', $login, array($domain, $username, $workstation, $this->hex2bin($lmResponse), $this->hex2bin($ntlmResponse))); + + $this->assertEquals($this->_message3, bin2hex($message3), + '%s: We send the same information as the example is created with so this should be the same' + ); + } + + public function testGetDomainAndUsername() + { + $username = "DOMAIN\user"; + + $login = $this->_getAuthenticator(); + list($domain, $user) = $this->_invokePrivateMethod('getDomainAndUsername', $login, array($username)); + + $this->assertEquals('DOMAIN', $domain, + '%s: the fetched domain did not match' + ); + $this->assertEquals('user', $user, + '%s: the fetched user did not match' + ); + } + + public function testGetDomainAndUsernameWithExtension() + { + $username = "domain.com\user"; + + $login = $this->_getAuthenticator(); + list($domain, $user) = $this->_invokePrivateMethod('getDomainAndUsername', $login, array($username)); + + $this->assertEquals('domain.com', $domain, + '%s: the fetched domain did not match' + ); + $this->assertEquals('user', $user, + '%s: the fetched user did not match' + ); + } + + public function testGetDomainAndUsernameWithAtSymbol() + { + $username = "user@DOMAIN"; + + $login = $this->_getAuthenticator(); + list($domain, $user) = $this->_invokePrivateMethod('getDomainAndUsername', $login, array($username)); + + $this->assertEquals('DOMAIN', $domain, + '%s: the fetched domain did not match' + ); + $this->assertEquals('user', $user, + '%s: the fetched user did not match' + ); + } + + public function testGetDomainAndUsernameWithAtSymbolAndExtension() + { + $username = "user@domain.com"; + + $login = $this->_getAuthenticator(); + list($domain, $user) = $this->_invokePrivateMethod('getDomainAndUsername', $login, array($username)); + + $this->assertEquals('domain.com', $domain, + '%s: the fetched domain did not match' + ); + $this->assertEquals('user', $user, + '%s: the fetched user did not match' + ); + } + + public function testSuccessfulAuthentication() + { + $domain = "TESTNT"; + $username = "test"; + $secret = "test1234"; + + $ntlm = $this->_getAuthenticator(); + $agent = $this->_getAgent(); + $agent->shouldReceive('executeCommand') + ->once() + ->with('AUTH NTLM '.base64_encode( + $this->_invokePrivateMethod('createMessage1', $ntlm) + )."\r\n", array(334)) + ->andReturn("334 ".base64_encode($this->hex2bin("4e544c4d53535000020000000c000c003000000035828980514246973ea892c10000000000000000460046003c00000054004500530054004e00540002000c0054004500530054004e00540001000c004d0045004d0042004500520003001e006d0065006d006200650072002e0074006500730074002e0063006f006d0000000000"))); + $agent->shouldReceive('executeCommand') + ->once() + ->with(base64_encode( + $this->_invokePrivateMethod('createMessage3', $ntlm, array($domain, $username, $this->hex2bin("4d0045004d00420045005200"), $this->hex2bin("bf2e015119f6bdb3f6fdb768aa12d478f5ce3d2401c8f6e9"), $this->hex2bin("caa4da8f25d5e840974ed8976d3ada46010100000000000030fa7e3c677bc301f5ce3d2401c8f6e90000000002000c0054004500530054004e00540001000c004d0045004d0042004500520003001e006d0065006d006200650072002e0074006500730074002e0063006f006d000000000000000000")) + ))."\r\n", array(235)); + + $this->assertTrue($ntlm->authenticate($agent, $username.'@'.$domain, $secret, $this->hex2bin("30fa7e3c677bc301"), $this->hex2bin("f5ce3d2401c8f6e9")), + '%s: The buffer accepted all commands authentication should succeed' + ); + } + + public function testAuthenticationFailureSendRsetAndReturnFalse() + { + $domain = "TESTNT"; + $username = "test"; + $secret = "test1234"; + + $ntlm = $this->_getAuthenticator(); + $agent = $this->_getAgent(); + $agent->shouldReceive('executeCommand') + ->once() + ->with('AUTH NTLM '.base64_encode( + $this->_invokePrivateMethod('createMessage1', $ntlm) + )."\r\n", array(334)) + ->andThrow(new Swift_TransportException("")); + $agent->shouldReceive('executeCommand') + ->once() + ->with("RSET\r\n", array(250)); + + $this->assertFalse($ntlm->authenticate($agent, $username.'@'.$domain, $secret, $this->hex2bin("30fa7e3c677bc301"), $this->hex2bin("f5ce3d2401c8f6e9")), + '%s: Authentication fails, so RSET should be sent' + ); + } + + // -- Private helpers + private function _getAuthenticator() + { + return new Swift_Transport_Esmtp_Auth_NTLMAuthenticator(); + } + + private function _getAgent() + { + return $this->getMockery('Swift_Transport_SmtpAgent')->shouldIgnoreMissing(); + } + + private function _invokePrivateMethod($method, $instance, array $args = array()) + { + $methodC = new ReflectionMethod($instance, trim($method)); + $methodC->setAccessible(true); + + return $methodC->invokeArgs($instance, $args); + } + + /** + * Hex2bin replacement for < PHP 5.4 + * @param string $hex + * @return string Binary + */ + protected function hex2bin($hex) + { + return function_exists('hex2bin') ? hex2bin($hex) : pack('H*', $hex); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/PlainAuthenticatorTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/PlainAuthenticatorTest.php new file mode 100644 index 00000000..e705cb9c --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/Auth/PlainAuthenticatorTest.php @@ -0,0 +1,69 @@ +_agent = $this->getMockery('Swift_Transport_SmtpAgent')->shouldIgnoreMissing(); + } + + public function testKeywordIsPlain() + { + /* -- RFC 4616, 1. + The name associated with this mechanism is "PLAIN". + */ + + $login = $this->_getAuthenticator(); + $this->assertEquals('PLAIN', $login->getAuthKeyword()); + } + + public function testSuccessfulAuthentication() + { + /* -- RFC 4616, 2. + The client presents the authorization identity (identity to act as), + followed by a NUL (U+0000) character, followed by the authentication + identity (identity whose password will be used), followed by a NUL + (U+0000) character, followed by the clear-text password. + */ + + $plain = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with('AUTH PLAIN '.base64_encode( + 'jack'.chr(0).'jack'.chr(0).'pass' + )."\r\n", array(235)); + + $this->assertTrue($plain->authenticate($this->_agent, 'jack', 'pass'), + '%s: The buffer accepted all commands authentication should succeed' + ); + } + + public function testAuthenticationFailureSendRsetAndReturnFalse() + { + $plain = $this->_getAuthenticator(); + + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with('AUTH PLAIN '.base64_encode( + 'jack'.chr(0).'jack'.chr(0).'pass' + )."\r\n", array(235)) + ->andThrow(new Swift_TransportException("")); + $this->_agent->shouldReceive('executeCommand') + ->once() + ->with("RSET\r\n", array(250)); + + $this->assertFalse($plain->authenticate($this->_agent, 'jack', 'pass'), + '%s: Authentication fails, so RSET should be sent' + ); + } + + // -- Private helpers + + private function _getAuthenticator() + { + return new Swift_Transport_Esmtp_Auth_PlainAuthenticator(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/AuthHandlerTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/AuthHandlerTest.php new file mode 100644 index 00000000..64327d47 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/Esmtp/AuthHandlerTest.php @@ -0,0 +1,167 @@ +_agent = $this->getMockery('Swift_Transport_SmtpAgent')->shouldIgnoreMissing(); + } + + public function testKeywordIsAuth() + { + $auth = $this->_createHandler(array()); + $this->assertEquals('AUTH', $auth->getHandledKeyword()); + } + + public function testUsernameCanBeSetAndFetched() + { + $auth = $this->_createHandler(array()); + $auth->setUsername('jack'); + $this->assertEquals('jack', $auth->getUsername()); + } + + public function testPasswordCanBeSetAndFetched() + { + $auth = $this->_createHandler(array()); + $auth->setPassword('pass'); + $this->assertEquals('pass', $auth->getPassword()); + } + + public function testAuthModeCanBeSetAndFetched() + { + $auth = $this->_createHandler(array()); + $auth->setAuthMode('PLAIN'); + $this->assertEquals('PLAIN', $auth->getAuthMode()); + } + + public function testMixinMethods() + { + $auth = $this->_createHandler(array()); + $mixins = $auth->exposeMixinMethods(); + $this->assertTrue(in_array('getUsername', $mixins), + '%s: getUsername() should be accessible via mixin' + ); + $this->assertTrue(in_array('setUsername', $mixins), + '%s: setUsername() should be accessible via mixin' + ); + $this->assertTrue(in_array('getPassword', $mixins), + '%s: getPassword() should be accessible via mixin' + ); + $this->assertTrue(in_array('setPassword', $mixins), + '%s: setPassword() should be accessible via mixin' + ); + $this->assertTrue(in_array('setAuthMode', $mixins), + '%s: setAuthMode() should be accessible via mixin' + ); + $this->assertTrue(in_array('getAuthMode', $mixins), + '%s: getAuthMode() should be accessible via mixin' + ); + } + + public function testAuthenticatorsAreCalledAccordingToParamsAfterEhlo() + { + $a1 = $this->_createMockAuthenticator('PLAIN'); + $a2 = $this->_createMockAuthenticator('LOGIN'); + + $a1->shouldReceive('authenticate') + ->never() + ->with($this->_agent, 'jack', 'pass'); + $a2->shouldReceive('authenticate') + ->once() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(true); + + $auth = $this->_createHandler(array($a1, $a2)); + $auth->setUsername('jack'); + $auth->setPassword('pass'); + + $auth->setKeywordParams(array('CRAM-MD5', 'LOGIN')); + $auth->afterEhlo($this->_agent); + } + + public function testAuthenticatorsAreNotUsedIfNoUsernameSet() + { + $a1 = $this->_createMockAuthenticator('PLAIN'); + $a2 = $this->_createMockAuthenticator('LOGIN'); + + $a1->shouldReceive('authenticate') + ->never() + ->with($this->_agent, 'jack', 'pass'); + $a2->shouldReceive('authenticate') + ->never() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(true); + + $auth = $this->_createHandler(array($a1, $a2)); + + $auth->setKeywordParams(array('CRAM-MD5', 'LOGIN')); + $auth->afterEhlo($this->_agent); + } + + public function testSeveralAuthenticatorsAreTriedIfNeeded() + { + $a1 = $this->_createMockAuthenticator('PLAIN'); + $a2 = $this->_createMockAuthenticator('LOGIN'); + + $a1->shouldReceive('authenticate') + ->once() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(false); + $a2->shouldReceive('authenticate') + ->once() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(true); + + $auth = $this->_createHandler(array($a1, $a2)); + $auth->setUsername('jack'); + $auth->setPassword('pass'); + + $auth->setKeywordParams(array('PLAIN', 'LOGIN')); + $auth->afterEhlo($this->_agent); + } + + public function testFirstAuthenticatorToPassBreaksChain() + { + $a1 = $this->_createMockAuthenticator('PLAIN'); + $a2 = $this->_createMockAuthenticator('LOGIN'); + $a3 = $this->_createMockAuthenticator('CRAM-MD5'); + + $a1->shouldReceive('authenticate') + ->once() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(false); + $a2->shouldReceive('authenticate') + ->once() + ->with($this->_agent, 'jack', 'pass') + ->andReturn(true); + $a3->shouldReceive('authenticate') + ->never() + ->with($this->_agent, 'jack', 'pass'); + + $auth = $this->_createHandler(array($a1, $a2)); + $auth->setUsername('jack'); + $auth->setPassword('pass'); + + $auth->setKeywordParams(array('PLAIN', 'LOGIN', 'CRAM-MD5')); + $auth->afterEhlo($this->_agent); + } + + // -- Private helpers + + private function _createHandler($authenticators) + { + return new Swift_Transport_Esmtp_AuthHandler($authenticators); + } + + private function _createMockAuthenticator($type) + { + $authenticator = $this->getMockery('Swift_Transport_Esmtp_Authenticator')->shouldIgnoreMissing(); + $authenticator->shouldReceive('getAuthKeyword') + ->zeroOrMoreTimes() + ->andReturn($type); + + return $authenticator; + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransport/ExtensionSupportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransport/ExtensionSupportTest.php new file mode 100644 index 00000000..73362018 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransport/ExtensionSupportTest.php @@ -0,0 +1,530 @@ +_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('STARTTLS') + ->andReturn(0); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext2->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('AUTH') + ->andReturn(-1); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2)); + $this->assertEquals(array($ext2, $ext1), $smtp->getExtensionHandlers()); + } + + public function testHandlersAreNotifiedOfParams() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .*?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('setKeywordParams') + ->once() + ->with(array('PLAIN', 'LOGIN')); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('setKeywordParams') + ->zeroOrMoreTimes() + ->with(array('123456')); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2)); + $smtp->start(); + } + + public function testSupportedExtensionHandlersAreRunAfterEhlo() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext3 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .*?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('afterEhlo') + ->once() + ->with($smtp); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('afterEhlo') + ->zeroOrMoreTimes() + ->with($smtp); + $ext3->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext3->shouldReceive('afterEhlo') + ->never() + ->with($smtp); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2, $ext3)); + $smtp->start(); + } + + public function testExtensionsCanModifyMailFromParams() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(); + $smtp = new EsmtpTransportFixture($buf, array(), $dispatcher); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext3 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .*?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: FOO ZIP\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: \r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn("250 OK\r\n"); + $this->_finishBuffer($buf); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('getMailParams') + ->once() + ->andReturn('FOO'); + $ext1->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('AUTH') + ->andReturn(-1); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('getMailParams') + ->once() + ->andReturn('ZIP'); + $ext2->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('AUTH') + ->andReturn(1); + $ext3->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext3->shouldReceive('getMailParams') + ->never(); + + $smtp->setExtensionHandlers(array($ext1, $ext2, $ext3)); + $smtp->start(); + $smtp->send($message); + } + + public function testExtensionsCanModifyRcptParams() + { + $buf = $this->_getBuffer(); + $dispatcher = $this->_createEventDispatcher(); + $smtp = new EsmtpTransportFixture($buf, array(), $dispatcher); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext3 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $message = $this->_createMessage(); + + $message->shouldReceive('getFrom') + ->zeroOrMoreTimes() + ->andReturn(array('me@domain' => 'Me')); + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null)); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("MAIL FROM: \r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("250 OK\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("RCPT TO: FOO ZIP\r\n") + ->andReturn(3); + $buf->shouldReceive('readLine') + ->once() + ->with(3) + ->andReturn("250 OK\r\n"); + $this->_finishBuffer($buf); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('getRcptParams') + ->once() + ->andReturn('FOO'); + $ext1->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('AUTH') + ->andReturn(-1); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('getRcptParams') + ->once() + ->andReturn('ZIP'); + $ext2->shouldReceive('getPriorityOver') + ->zeroOrMoreTimes() + ->with('AUTH') + ->andReturn(1); + $ext3->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext3->shouldReceive('getRcptParams') + ->never(); + + $smtp->setExtensionHandlers(array($ext1, $ext2, $ext3)); + $smtp->start(); + $smtp->send($message); + } + + public function testExtensionsAreNotifiedOnCommand() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext3 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("FOO\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn("250 Cool\r\n"); + $this->_finishBuffer($buf); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('onCommand') + ->once() + ->with($smtp, "FOO\r\n", array(250, 251), \Mockery::any(), \Mockery::any()); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('onCommand') + ->once() + ->with($smtp, "FOO\r\n", array(250, 251), \Mockery::any(), \Mockery::any()); + $ext3->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext3->shouldReceive('onCommand') + ->never() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $smtp->setExtensionHandlers(array($ext1, $ext2, $ext3)); + $smtp->start(); + $smtp->executeCommand("FOO\r\n", array(250, 251)); + } + + public function testChainOfCommandAlgorithmWhenNotifyingExtensions() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + $ext3 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 server.com foo\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-ServerName.tld\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250-AUTH PLAIN LOGIN\r\n"); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn("250 SIZE=123456\r\n"); + $buf->shouldReceive('write') + ->never() + ->with("FOO\r\n"); + $this->_finishBuffer($buf); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('onCommand') + ->once() + ->with($smtp, "FOO\r\n", array(250, 251), \Mockery::any(), \Mockery::any()) + ->andReturnUsing(function ($a, $b, $c, $d, &$e) { + $e = true; + + return "250 ok"; + }); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('SIZE'); + $ext2->shouldReceive('onCommand') + ->never() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $ext3->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $ext3->shouldReceive('onCommand') + ->never() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $smtp->setExtensionHandlers(array($ext1, $ext2, $ext3)); + $smtp->start(); + $smtp->executeCommand("FOO\r\n", array(250, 251)); + } + + public function testExtensionsCanExposeMixinMethods() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandlerMixin')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('exposeMixinMethods') + ->zeroOrMoreTimes() + ->andReturn(array('setUsername', 'setPassword')); + $ext1->shouldReceive('setUsername') + ->once() + ->with('mick'); + $ext1->shouldReceive('setPassword') + ->once() + ->with('pass'); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2)); + $smtp->setUsername('mick'); + $smtp->setPassword('pass'); + } + + public function testMixinMethodsBeginningWithSetAndNullReturnAreFluid() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandlerMixin')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('exposeMixinMethods') + ->zeroOrMoreTimes() + ->andReturn(array('setUsername', 'setPassword')); + $ext1->shouldReceive('setUsername') + ->once() + ->with('mick') + ->andReturn(null); + $ext1->shouldReceive('setPassword') + ->once() + ->with('pass') + ->andReturn(null); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2)); + $ret = $smtp->setUsername('mick'); + $this->assertEquals($smtp, $ret); + $ret = $smtp->setPassword('pass'); + $this->assertEquals($smtp, $ret); + } + + public function testMixinSetterWhichReturnValuesAreNotFluid() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $ext1 = $this->getMockery('Swift_Transport_EsmtpHandlerMixin')->shouldIgnoreMissing(); + $ext2 = $this->getMockery('Swift_Transport_EsmtpHandler')->shouldIgnoreMissing(); + + $ext1->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('AUTH'); + $ext1->shouldReceive('exposeMixinMethods') + ->zeroOrMoreTimes() + ->andReturn(array('setUsername', 'setPassword')); + $ext1->shouldReceive('setUsername') + ->once() + ->with('mick') + ->andReturn('x'); + $ext1->shouldReceive('setPassword') + ->once() + ->with('pass') + ->andReturn('x'); + $ext2->shouldReceive('getHandledKeyword') + ->zeroOrMoreTimes() + ->andReturn('STARTTLS'); + $this->_finishBuffer($buf); + + $smtp->setExtensionHandlers(array($ext1, $ext2)); + $this->assertEquals('x', $smtp->setUsername('mick')); + $this->assertEquals('x', $smtp->setPassword('pass')); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransportTest.php new file mode 100644 index 00000000..95a9ce2f --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/EsmtpTransportTest.php @@ -0,0 +1,298 @@ +_createEventDispatcher(); + } + + return new Swift_Transport_EsmtpTransport($buf, array(), $dispatcher); + } + + public function testHostCanBeSetAndFetched() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $smtp->setHost('foo'); + $this->assertEquals('foo', $smtp->getHost(), '%s: Host should be returned'); + } + + public function testPortCanBeSetAndFetched() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $smtp->setPort(25); + $this->assertEquals(25, $smtp->getPort(), '%s: Port should be returned'); + } + + public function testTimeoutCanBeSetAndFetched() + { + $buf = $this->_getBuffer(); + $buf->shouldReceive('setParam') + ->once() + ->with('timeout', 10); + + $smtp = $this->_getTransport($buf); + $smtp->setTimeout(10); + $this->assertEquals(10, $smtp->getTimeout(), '%s: Timeout should be returned'); + } + + public function testEncryptionCanBeSetAndFetched() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $smtp->setEncryption('tls'); + $this->assertEquals('tls', $smtp->getEncryption(), '%s: Crypto should be returned'); + } + + public function testStartSendsHeloToInitiate() + { + //Overridden for EHLO instead + } + + public function testStartSendsEhloToInitiate() + { + /* -- RFC 2821, 3.2. + + 3.2 Client Initiation + + Once the server has sent the welcoming message and the client has + received it, the client normally sends the EHLO command to the + server, indicating the client's identity. In addition to opening the + session, use of EHLO indicates that the client is able to process + service extensions and requests that the server provide a list of the + extensions it supports. Older SMTP systems which are unable to + support service extensions and contemporary clients which do not + require service extensions in the mail session being initiated, MAY + use HELO instead of EHLO. Servers MUST NOT return the extended + EHLO-style response to a HELO command. For a particular connection + attempt, if the server returns a "command not recognized" response to + EHLO, the client SHOULD be able to fall back and send HELO. + + In the EHLO command the host sending the command identifies itself; + the command may be interpreted as saying "Hello, I am " (and, + in the case of EHLO, "and I support service extension requests"). + + -- RFC 2281, 4.1.1.1. + + ehlo = "EHLO" SP Domain CRLF + helo = "HELO" SP Domain CRLF + + -- RFC 2821, 4.3.2. + + EHLO or HELO + S: 250 + E: 504, 550 + + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 ServerName'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + } catch (Exception $e) { + $this->fail('Starting Esmtp should send EHLO and accept 250 response'); + } + } + + public function testHeloIsUsedAsFallback() + { + /* -- RFC 2821, 4.1.4. + + If the EHLO command is not acceptable to the SMTP server, 501, 500, + or 502 failure replies MUST be returned as appropriate. The SMTP + server MUST stay in the same state after transmitting these replies + that it was in before the EHLO was received. + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('501 WTF'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^HELO .+?\r\n$~D') + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 HELO'."\r\n"); + + $this->_finishBuffer($buf); + try { + $smtp->start(); + } catch (Exception $e) { + $this->fail( + 'Starting Esmtp should fallback to HELO if needed and accept 250 response' + ); + } + } + + public function testInvalidHeloResponseCausesException() + { + //Overridden to first try EHLO + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('501 WTF'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^HELO .+?\r\n$~D') + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('504 WTF'."\r\n"); + $this->_finishBuffer($buf); + + try { + $this->assertFalse($smtp->isStarted(), '%s: SMTP should begin non-started'); + $smtp->start(); + $this->fail('Non 250 HELO response should raise Exception'); + } catch (Exception $e) { + $this->assertFalse($smtp->isStarted(), '%s: SMTP start() should have failed'); + } + } + + public function testDomainNameIsPlacedInEhlo() + { + /* -- RFC 2821, 4.1.4. + + The SMTP client MUST, if possible, ensure that the domain parameter + to the EHLO command is a valid principal host name (not a CNAME or MX + name) for its host. If this is not possible (e.g., when the client's + address is dynamically assigned and the client does not have an + obvious name), an address literal SHOULD be substituted for the + domain name and supplemental information provided that will assist in + identifying the client. + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("EHLO mydomain.com\r\n") + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('250 ServerName'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->setLocalDomain('mydomain.com'); + $smtp->start(); + } + + public function testDomainNameIsPlacedInHelo() + { + //Overridden to include ESMTP + /* -- RFC 2821, 4.1.4. + + The SMTP client MUST, if possible, ensure that the domain parameter + to the EHLO command is a valid principal host name (not a CNAME or MX + name) for its host. If this is not possible (e.g., when the client's + address is dynamically assigned and the client does not have an + obvious name), an address literal SHOULD be substituted for the + domain name and supplemental information provided that will assist in + identifying the client. + */ + + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('readLine') + ->once() + ->with(0) + ->andReturn("220 some.server.tld bleh\r\n"); + $buf->shouldReceive('write') + ->once() + ->with('~^EHLO .+?\r\n$~D') + ->andReturn(1); + $buf->shouldReceive('readLine') + ->once() + ->with(1) + ->andReturn('501 WTF'."\r\n"); + $buf->shouldReceive('write') + ->once() + ->with("HELO mydomain.com\r\n") + ->andReturn(2); + $buf->shouldReceive('readLine') + ->once() + ->with(2) + ->andReturn('250 ServerName'."\r\n"); + + $this->_finishBuffer($buf); + $smtp->setLocalDomain('mydomain.com'); + $smtp->start(); + } + + public function testFluidInterface() + { + $buf = $this->_getBuffer(); + $smtp = $this->_getTransport($buf); + $buf->shouldReceive('setParam') + ->once() + ->with('timeout', 30); + + $ref = $smtp + ->setHost('foo') + ->setPort(25) + ->setEncryption('tls') + ->setTimeout(30) + ; + $this->assertEquals($ref, $smtp); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/FailoverTransportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/FailoverTransportTest.php new file mode 100644 index 00000000..8a90f4d1 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/FailoverTransportTest.php @@ -0,0 +1,525 @@ +getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState) { + return $connectionState; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState) { + if (!$connectionState) { + $connectionState = true; + } + }); + $t1->shouldReceive('send') + ->twice() + ->with(\Mockery::anyOf($message1, $message2), \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState) { + if ($connectionState) { + return 1; + } + }); + $t2->shouldReceive('start')->never(); + $t2->shouldReceive('send')->never(); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message1)); + $this->assertEquals(1, $transport->send($message2)); + } + + public function testMessageCanBeTriedOnNextTransportIfExceptionThrown() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + throw $e; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + return 1; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message)); + } + + public function testZeroIsReturnedIfTransportReturnsZero() + { + $message = $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + $t1 = $this->getMockery('Swift_Transport')->shouldIgnoreMissing(); + + $connectionState = false; + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState) { + return $connectionState; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState) { + if (!$connectionState) { + $connectionState = true; + } + }); + $testCase = $this; + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState, $testCase) { + if (!$connectionState) { + $testCase->fail(); + } + + return 0; + }); + + $transport = $this->_getTransport(array($t1)); + $transport->start(); + $this->assertEquals(0, $transport->send($message)); + } + + public function testTransportsWhichThrowExceptionsAreNotRetried() + { + $e = new Swift_TransportException('maur b0rken'); + + $message1 = $this->getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $message3 = $this->getMockery('Swift_Mime_Message'); + $message4 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + throw $e; + } + }); + $t1->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + $t1->shouldReceive('send') + ->never() + ->with($message3, \Mockery::any()); + $t1->shouldReceive('send') + ->never() + ->with($message4, \Mockery::any()); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->times(4) + ->with(\Mockery::anyOf($message1, $message2, $message3, $message4), \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + return 1; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message1)); + $this->assertEquals(1, $transport->send($message2)); + $this->assertEquals(1, $transport->send($message3)); + $this->assertEquals(1, $transport->send($message4)); + } + + public function testExceptionIsThrownIfAllTransportsDie() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + throw $e; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + throw $e; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + try { + $transport->send($message); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + } + } + + public function testStoppingTransportStopsAllDelegates() + { + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + + $connectionState1 = true; + $connectionState2 = true; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('stop') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if ($connectionState1) { + $connectionState1 = false; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('stop') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if ($connectionState2) { + $connectionState2 = false; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $transport->stop(); + } + + public function testTransportShowsAsNotStartedIfAllDelegatesDead() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + $connectionState1 = false; + throw $e; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + $connectionState2 = false; + throw $e; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertTrue($transport->isStarted()); + try { + $transport->send($message); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + $this->assertFalse($transport->isStarted()); + } + } + + public function testRestartingTransportRestartsDeadDelegates() + { + $e = new Swift_TransportException('b0rken'); + + $message1 = $this->getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->twice() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + $connectionState1 = false; + throw $e; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message2, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1) { + if ($connectionState1) { + return 10; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + $connectionState2 = false; + throw $e; + } + }); + $t2->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertTrue($transport->isStarted()); + try { + $transport->send($message1); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + $this->assertFalse($transport->isStarted()); + } + //Restart and re-try + $transport->start(); + $this->assertTrue($transport->isStarted()); + $this->assertEquals(10, $transport->send($message2)); + } + + public function testFailureReferenceIsPassedToDelegates() + { + $failures = array(); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + + $connectionState = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use ($connectionState) { + return $connectionState; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use ($connectionState) { + if (!$connectionState) { + $connectionState = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, $failures) + ->andReturnUsing(function () use ($connectionState) { + if ($connectionState) { + return 1; + } + }); + + $transport = $this->_getTransport(array($t1)); + $transport->start(); + $transport->send($message, $failures); + } + + public function testRegisterPluginDelegatesToLoadedTransports() + { + $plugin = $this->_createPlugin(); + + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $t1->shouldReceive('registerPlugin') + ->once() + ->with($plugin); + $t2->shouldReceive('registerPlugin') + ->once() + ->with($plugin); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->registerPlugin($plugin); + } + + // -- Private helpers + + private function _getTransport(array $transports) + { + $transport = new Swift_Transport_FailoverTransport(); + $transport->setTransports($transports); + + return $transport; + } + + private function _createPlugin() + { + return $this->getMockery('Swift_Events_EventListener'); + } + + private function _createInnerTransport() + { + return $this->getMockery('Swift_Transport'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/LoadBalancedTransportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/LoadBalancedTransportTest.php new file mode 100644 index 00000000..c397cd68 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/LoadBalancedTransportTest.php @@ -0,0 +1,756 @@ +getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $testCase = $this; + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $testCase) { + if ($connectionState1) { + return 1; + } + $testCase->fail(); + }); + $t1->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message2, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $testCase) { + if ($connectionState2) { + return 1; + } + $testCase->fail(); + }); + $t2->shouldReceive('send') + ->never() + ->with($message1, \Mockery::any()); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message1)); + $this->assertEquals(1, $transport->send($message2)); + } + + public function testTransportsAreReusedInRotatingFashion() + { + $message1 = $this->getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $message3 = $this->getMockery('Swift_Mime_Message'); + $message4 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $testCase = $this; + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $testCase) { + if ($connectionState1) { + return 1; + } + $testCase->fail(); + }); + $t1->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + $t1->shouldReceive('send') + ->once() + ->with($message3, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $testCase) { + if ($connectionState1) { + return 1; + } + $testCase->fail(); + }); + $t1->shouldReceive('send') + ->never() + ->with($message4, \Mockery::any()); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message2, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $testCase) { + if ($connectionState2) { + return 1; + } + $testCase->fail(); + }); + $t2->shouldReceive('send') + ->never() + ->with($message1, \Mockery::any()); + $t2->shouldReceive('send') + ->once() + ->with($message4, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $testCase) { + if ($connectionState2) { + return 1; + } + $testCase->fail(); + }); + $t2->shouldReceive('send') + ->never() + ->with($message3, \Mockery::any()); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + + $this->assertEquals(1, $transport->send($message1)); + $this->assertEquals(1, $transport->send($message2)); + $this->assertEquals(1, $transport->send($message3)); + $this->assertEquals(1, $transport->send($message4)); + } + + public function testMessageCanBeTriedOnNextTransportIfExceptionThrown() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $testCase = $this; + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e, $testCase) { + if ($connectionState1) { + throw $e; + } + $testCase->fail(); + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $testCase) { + if ($connectionState2) { + return 1; + } + $testCase->fail(); + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message)); + } + + public function testMessageIsTriedOnNextTransportIfZeroReturned() + { + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1) { + if ($connectionState1) { + return 0; + } + + return 1; + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2) { + if ($connectionState2) { + return 1; + } + + return 0; + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message)); + } + + public function testZeroIsReturnedIfAllTransportsReturnZero() + { + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1) { + if ($connectionState1) { + return 0; + } + + return 1; + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2) { + if ($connectionState2) { + return 0; + } + + return 1; + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(0, $transport->send($message)); + } + + public function testTransportsWhichThrowExceptionsAreNotRetried() + { + $e = new Swift_TransportException('maur b0rken'); + + $message1 = $this->getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $message3 = $this->getMockery('Swift_Mime_Message'); + $message4 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $testCase = $this; + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e, $testCase) { + if ($connectionState1) { + throw $e; + } + $testCase->fail(); + }); + $t1->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + $t1->shouldReceive('send') + ->never() + ->with($message3, \Mockery::any()); + $t1->shouldReceive('send') + ->never() + ->with($message4, \Mockery::any()); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->times(4) + ->with(\Mockery::anyOf($message1, $message3, $message3, $message4), \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $testCase) { + if ($connectionState2) { + return 1; + } + $testCase->fail(); + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertEquals(1, $transport->send($message1)); + $this->assertEquals(1, $transport->send($message2)); + $this->assertEquals(1, $transport->send($message3)); + $this->assertEquals(1, $transport->send($message4)); + } + + public function testExceptionIsThrownIfAllTransportsDie() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + throw $e; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + throw $e; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + try { + $transport->send($message); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + } + } + + public function testStoppingTransportStopsAllDelegates() + { + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = true; + $connectionState2 = true; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('stop') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if ($connectionState1) { + $connectionState1 = false; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('stop') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if ($connectionState2) { + $connectionState2 = false; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $transport->stop(); + } + + public function testTransportShowsAsNotStartedIfAllDelegatesDead() + { + $e = new Swift_TransportException('b0rken'); + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + throw $e; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + throw $e; + } + }); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertTrue($transport->isStarted()); + try { + $transport->send($message); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + $this->assertFalse($transport->isStarted()); + } + } + + public function testRestartingTransportRestartsDeadDelegates() + { + $e = new Swift_TransportException('b0rken'); + + $message1 = $this->getMockery('Swift_Mime_Message'); + $message2 = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + $connectionState1 = false; + $connectionState2 = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState1) { + return $connectionState1; + }); + $t1->shouldReceive('start') + ->twice() + ->andReturnUsing(function () use (&$connectionState1) { + if (!$connectionState1) { + $connectionState1 = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + $connectionState1 = false; + throw $e; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message2, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState1, $e) { + if ($connectionState1) { + return 10; + } + }); + + $t2->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState2) { + return $connectionState2; + }); + $t2->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState2) { + if (!$connectionState2) { + $connectionState2 = true; + } + }); + $t2->shouldReceive('send') + ->once() + ->with($message1, \Mockery::any()) + ->andReturnUsing(function () use (&$connectionState2, $e) { + if ($connectionState2) { + throw $e; + } + }); + $t2->shouldReceive('send') + ->never() + ->with($message2, \Mockery::any()); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->start(); + $this->assertTrue($transport->isStarted()); + try { + $transport->send($message1); + $this->fail('All transports failed so Exception should be thrown'); + } catch (Exception $e) { + $this->assertFalse($transport->isStarted()); + } + //Restart and re-try + $transport->start(); + $this->assertTrue($transport->isStarted()); + $this->assertEquals(10, $transport->send($message2)); + } + + public function testFailureReferenceIsPassedToDelegates() + { + $failures = array(); + $testCase = $this; + + $message = $this->getMockery('Swift_Mime_Message'); + $t1 = $this->getMockery('Swift_Transport'); + $connectionState = false; + + $t1->shouldReceive('isStarted') + ->zeroOrMoreTimes() + ->andReturnUsing(function () use (&$connectionState) { + return $connectionState; + }); + $t1->shouldReceive('start') + ->once() + ->andReturnUsing(function () use (&$connectionState) { + if (!$connectionState) { + $connectionState = true; + } + }); + $t1->shouldReceive('send') + ->once() + ->with($message, \Mockery::on(function (&$var) use (&$failures, $testCase) { + return $testCase->varsAreReferences($var, $failures); + })) + ->andReturnUsing(function () use (&$connectionState) { + if ($connectionState) { + return 1; + } + }); + + $transport = $this->_getTransport(array($t1)); + $transport->start(); + $transport->send($message, $failures); + } + + public function testRegisterPluginDelegatesToLoadedTransports() + { + $plugin = $this->_createPlugin(); + + $t1 = $this->getMockery('Swift_Transport'); + $t2 = $this->getMockery('Swift_Transport'); + + $t1->shouldReceive('registerPlugin') + ->once() + ->with($plugin); + $t2->shouldReceive('registerPlugin') + ->once() + ->with($plugin); + + $transport = $this->_getTransport(array($t1, $t2)); + $transport->registerPlugin($plugin); + } + + /** + * Adapted from Yay_Matchers_ReferenceMatcher + */ + public function varsAreReferences(&$ref1, &$ref2) + { + if (is_object($ref2)) { + return ($ref1 === $ref2); + } + if ($ref1 !== $ref2) { + return false; + } + + $copy = $ref2; + $randomString = uniqid('yay'); + $ref2 = $randomString; + $isRef = ($ref1 === $ref2); + $ref2 = $copy; + + return $isRef; + } + + // -- Private helpers + + private function _getTransport(array $transports) + { + $transport = new Swift_Transport_LoadBalancedTransport(); + $transport->setTransports($transports); + + return $transport; + } + + private function _createPlugin() + { + return $this->getMockery('Swift_Events_EventListener'); + } + + private function _createInnerTransport() + { + return $this->getMockery('Swift_Transport'); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/MailTransportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/MailTransportTest.php new file mode 100644 index 00000000..89cb2d50 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/MailTransportTest.php @@ -0,0 +1,311 @@ +_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $headers = $this->_createHeaders(); + $message = $this->_createMessage($headers); + + $invoker->shouldReceive('mail') + ->once(); + + $transport->send($message); + } + + public function testTransportUsesToFieldBodyInSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $to = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'To' => $to, + )); + $message = $this->_createMessage($headers); + + $to->shouldReceive('getFieldBody') + ->zeroOrMoreTimes() + ->andReturn("Foo "); + $invoker->shouldReceive('mail') + ->once() + ->with("Foo ", \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testTransportUsesSubjectFieldBodyInSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $subj = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'Subject' => $subj, + )); + $message = $this->_createMessage($headers); + + $subj->shouldReceive('getFieldBody') + ->zeroOrMoreTimes() + ->andReturn("Thing"); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), "Thing", \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testTransportUsesBodyOfMessage() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $headers = $this->_createHeaders(); + $message = $this->_createMessage($headers); + + $message->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn( + "To: Foo \r\n". + "\r\n". + "This body" + ); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), "This body", \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testTransportUsesHeadersFromMessage() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $headers = $this->_createHeaders(); + $message = $this->_createMessage($headers); + + $message->shouldReceive('toString') + ->zeroOrMoreTimes() + ->andReturn( + "Subject: Stuff\r\n". + "\r\n". + "This body" + ); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), "Subject: Stuff".PHP_EOL, \Mockery::any()); + + $transport->send($message); + } + + public function testTransportReturnsCountOfAllRecipientsIfInvokerReturnsTrue() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $headers = $this->_createHeaders(); + $message = $this->_createMessage($headers); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null, 'zip@button' => null)); + $message->shouldReceive('getCc') + ->zeroOrMoreTimes() + ->andReturn(array('test@test' => null)); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn(true); + + $this->assertEquals(3, $transport->send($message)); + } + + public function testTransportReturnsZeroIfInvokerReturnsFalse() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $headers = $this->_createHeaders(); + $message = $this->_createMessage($headers); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => null, 'zip@button' => null)); + $message->shouldReceive('getCc') + ->zeroOrMoreTimes() + ->andReturn(array('test@test' => null)); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()) + ->andReturn(false); + + $this->assertEquals(0, $transport->send($message)); + } + + public function testToHeaderIsRemovedFromHeaderSetDuringSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $to = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'To' => $to, + )); + $message = $this->_createMessage($headers); + + $headers->shouldReceive('remove') + ->once() + ->with('To'); + $headers->shouldReceive('remove') + ->zeroOrMoreTimes(); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testSubjectHeaderIsRemovedFromHeaderSetDuringSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $subject = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'Subject' => $subject, + )); + $message = $this->_createMessage($headers); + + $headers->shouldReceive('remove') + ->once() + ->with('Subject'); + $headers->shouldReceive('remove') + ->zeroOrMoreTimes(); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testToHeaderIsPutBackAfterSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $to = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'To' => $to, + )); + $message = $this->_createMessage($headers); + + $headers->shouldReceive('set') + ->once() + ->with($to); + $headers->shouldReceive('set') + ->zeroOrMoreTimes(); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + public function testSubjectHeaderIsPutBackAfterSending() + { + $invoker = $this->_createInvoker(); + $dispatcher = $this->_createEventDispatcher(); + $transport = $this->_createTransport($invoker, $dispatcher); + + $subject = $this->_createHeader(); + $headers = $this->_createHeaders(array( + 'Subject' => $subject, + )); + $message = $this->_createMessage($headers); + + $headers->shouldReceive('set') + ->once() + ->with($subject); + $headers->shouldReceive('set') + ->zeroOrMoreTimes(); + $invoker->shouldReceive('mail') + ->once() + ->with(\Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any(), \Mockery::any()); + + $transport->send($message); + } + + // -- Creation Methods + + private function _createTransport($invoker, $dispatcher) + { + return new Swift_Transport_MailTransport($invoker, $dispatcher); + } + + private function _createEventDispatcher() + { + return $this->getMockery('Swift_Events_EventDispatcher')->shouldIgnoreMissing(); + } + + private function _createInvoker() + { + return $this->getMockery('Swift_Transport_MailInvoker'); + } + + private function _createMessage($headers) + { + $message = $this->getMockery('Swift_Mime_Message')->shouldIgnoreMissing(); + $message->shouldReceive('getHeaders') + ->zeroOrMoreTimes() + ->andReturn($headers); + + return $message; + } + + private function _createHeaders($headers = array()) + { + $set = $this->getMockery('Swift_Mime_HeaderSet')->shouldIgnoreMissing(); + + if (count($headers) > 0) { + foreach ($headers as $name => $header) { + $set->shouldReceive('get') + ->zeroOrMoreTimes() + ->with($name) + ->andReturn($header); + $set->shouldReceive('has') + ->zeroOrMoreTimes() + ->with($name) + ->andReturn(true); + } + } + + $header = $this->_createHeader(); + $set->shouldReceive('get') + ->zeroOrMoreTimes() + ->andReturn($header); + $set->shouldReceive('has') + ->zeroOrMoreTimes() + ->andReturn(true); + + return $set; + } + + private function _createHeader() + { + return $this->getMockery('Swift_Mime_Header')->shouldIgnoreMissing(); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/SendmailTransportTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/SendmailTransportTest.php new file mode 100644 index 00000000..c704c3c3 --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/SendmailTransportTest.php @@ -0,0 +1,152 @@ +_createEventDispatcher(); + } + $transport = new Swift_Transport_SendmailTransport($buf, $dispatcher); + $transport->setCommand($command); + + return $transport; + } + + protected function _getSendmail($buf, $dispatcher = null) + { + if (!$dispatcher) { + $dispatcher = $this->_createEventDispatcher(); + } + $sendmail = new Swift_Transport_SendmailTransport($buf, $dispatcher); + + return $sendmail; + } + + public function testCommandCanBeSetAndFetched() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getSendmail($buf); + + $sendmail->setCommand('/usr/sbin/sendmail -bs'); + $this->assertEquals('/usr/sbin/sendmail -bs', $sendmail->getCommand()); + $sendmail->setCommand('/usr/sbin/sendmail -oi -t'); + $this->assertEquals('/usr/sbin/sendmail -oi -t', $sendmail->getCommand()); + } + + public function testSendingMessageIn_t_ModeUsesSimplePipe() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getSendmail($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => 'Foobar', 'zip@button' => 'Zippy')); + $message->shouldReceive('toByteStream') + ->once() + ->with($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('terminate') + ->once(); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array("\r\n" => "\n", "\n." => "\n..")); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array()); + + $sendmail->setCommand('/usr/sbin/sendmail -t'); + $this->assertEquals(2, $sendmail->send($message)); + } + + public function testSendingIn_t_ModeWith_i_FlagDoesntEscapeDot() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getSendmail($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => 'Foobar', 'zip@button' => 'Zippy')); + $message->shouldReceive('toByteStream') + ->once() + ->with($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('terminate') + ->once(); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array("\r\n" => "\n")); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array()); + + $sendmail->setCommand('/usr/sbin/sendmail -i -t'); + $this->assertEquals(2, $sendmail->send($message)); + } + + public function testSendingInTModeWith_oi_FlagDoesntEscapeDot() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getSendmail($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => 'Foobar', 'zip@button' => 'Zippy')); + $message->shouldReceive('toByteStream') + ->once() + ->with($buf); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('terminate') + ->once(); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array("\r\n" => "\n")); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array()); + + $sendmail->setCommand('/usr/sbin/sendmail -oi -t'); + $this->assertEquals(2, $sendmail->send($message)); + } + + public function testSendingMessageRegeneratesId() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getSendmail($buf); + $message = $this->_createMessage(); + + $message->shouldReceive('getTo') + ->zeroOrMoreTimes() + ->andReturn(array('foo@bar' => 'Foobar', 'zip@button' => 'Zippy')); + $message->shouldReceive('generateId'); + $buf->shouldReceive('initialize') + ->once(); + $buf->shouldReceive('terminate') + ->once(); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array("\r\n" => "\n", "\n." => "\n..")); + $buf->shouldReceive('setWriteTranslations') + ->once() + ->with(array()); + + $sendmail->setCommand('/usr/sbin/sendmail -t'); + $this->assertEquals(2, $sendmail->send($message)); + } + + public function testFluidInterface() + { + $buf = $this->_getBuffer(); + $sendmail = $this->_getTransport($buf); + + $ref = $sendmail->setCommand('/foo'); + $this->assertEquals($ref, $sendmail); + } +} diff --git a/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/StreamBufferTest.php b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/StreamBufferTest.php new file mode 100644 index 00000000..3ec74b3e --- /dev/null +++ b/vendor/swiftmailer/swiftmailer/tests/unit/Swift/Transport/StreamBufferTest.php @@ -0,0 +1,45 @@ +_createFactory(); + $factory->expects($this->once()) + ->method('createFilter') + ->with('a', 'b') + ->will($this->returnCallback(array($this, '_createFilter'))); + + $buffer = $this->_createBuffer($factory); + $buffer->setWriteTranslations(array('a' => 'b')); + } + + public function testOverridingTranslationsOnlyAddsNeededFilters() + { + $factory = $this->_createFactory(); + $factory->expects($this->exactly(2)) + ->method('createFilter') + ->will($this->returnCallback(array($this, '_createFilter'))); + + $buffer = $this->_createBuffer($factory); + $buffer->setWriteTranslations(array('a' => 'b')); + $buffer->setWriteTranslations(array('x' => 'y', 'a' => 'b')); + } + + // -- Creation methods + + private function _createBuffer($replacementFactory) + { + return new Swift_Transport_StreamBuffer($replacementFactory); + } + + private function _createFactory() + { + return $this->getMock('Swift_ReplacementFilterFactory'); + } + + public function _createFilter() + { + return $this->getMock('Swift_StreamFilter'); + } +} -- cgit v1.2.3