From bc862ffb5c0e9dfbb56510eecd2e227bf1403acc Mon Sep 17 00:00:00 2001 From: Martino Facchin Date: Thu, 15 Jun 2017 12:35:19 +0200 Subject: [PATCH 1/3] Move base files and vendor @sandeepmistry paho mqtt fork (until they merge the patch) --- .../bcmi-labs/arduino-connector/main.go | 0 .../bcmi-labs/arduino-connector/status.go | 0 .../eclipse/paho.mqtt.golang/.gitignore | 36 + .../eclipse/paho.mqtt.golang/CONTRIBUTING.md | 56 + .../eclipse/paho.mqtt.golang/DISTRIBUTION | 15 + .../eclipse/paho.mqtt.golang/LICENSE | 87 ++ .../eclipse/paho.mqtt.golang/README.md | 63 + .../eclipse/paho.mqtt.golang/about.html | 41 + .../eclipse/paho.mqtt.golang/client.go | 611 ++++++++++ .../eclipse/paho.mqtt.golang/cmd/build.sh | 11 + .../paho.mqtt.golang/cmd/custom_store/main.go | 96 ++ .../paho.mqtt.golang/cmd/routing/main.go | 105 ++ .../paho.mqtt.golang/cmd/sample/main.go | 130 ++ .../paho.mqtt.golang/cmd/simple/main.go | 65 + .../eclipse/paho.mqtt.golang/cmd/ssl/main.go | 126 ++ .../cmd/ssl/samplecerts/CAfile.pem | 150 +++ .../cmd/ssl/samplecerts/README | 9 + .../cmd/ssl/samplecerts/client-crt.pem | 20 + .../cmd/ssl/samplecerts/client-key.pem | 27 + .../ssl/samplecerts/intermediateCA-crt.pem | 20 + .../ssl/samplecerts/intermediateCA-key.pem | 27 + .../cmd/ssl/samplecerts/mosquitto.org.crt | 18 + .../cmd/ssl/samplecerts/rootCA-crt.pem | 21 + .../cmd/ssl/samplecerts/rootCA-key.pem | 27 + .../cmd/ssl/samplecerts/server-crt.pem | 21 + .../cmd/ssl/samplecerts/server-key.pem | 27 + .../paho.mqtt.golang/cmd/stdinpub/main.go | 70 ++ .../paho.mqtt.golang/cmd/stdoutsub/main.go | 85 ++ .../eclipse/paho.mqtt.golang/components.go | 31 + .../eclipse/paho.mqtt.golang/edl-v10 | 15 + .../eclipse/paho.mqtt.golang/epl-v10 | 70 ++ .../eclipse/paho.mqtt.golang/filestore.go | 235 ++++ .../eclipse/paho.mqtt.golang/fvt/README.md | 74 ++ .../paho.mqtt.golang/fvt/mosquitto.cfg | 17 + .../eclipse/paho.mqtt.golang/fvt/rsmb.cfg | 8 + .../eclipse/paho.mqtt.golang/fvt/setup_IMA.sh | 111 ++ .../paho.mqtt.golang/fvt_client_test.go | 1041 +++++++++++++++++ .../paho.mqtt.golang/fvt_store_test.go | 544 +++++++++ .../eclipse/paho.mqtt.golang/fvt_test.go | 36 + .../eclipse/paho.mqtt.golang/memstore.go | 138 +++ .../eclipse/paho.mqtt.golang/message.go | 104 ++ .../eclipse/paho.mqtt.golang/messageids.go | 79 ++ .../eclipse/paho.mqtt.golang/net.go | 318 +++++ .../eclipse/paho.mqtt.golang/notice.html | 108 ++ .../eclipse/paho.mqtt.golang/oops.go | 21 + .../eclipse/paho.mqtt.golang/options.go | 293 +++++ .../paho.mqtt.golang/options_reader.go | 132 +++ .../paho.mqtt.golang/packets/connack.go | 51 + .../paho.mqtt.golang/packets/connect.go | 122 ++ .../paho.mqtt.golang/packets/disconnect.go | 36 + .../paho.mqtt.golang/packets/packets.go | 322 +++++ .../paho.mqtt.golang/packets/packets_test.go | 159 +++ .../paho.mqtt.golang/packets/pingreq.go | 36 + .../paho.mqtt.golang/packets/pingresp.go | 36 + .../paho.mqtt.golang/packets/puback.go | 44 + .../paho.mqtt.golang/packets/pubcomp.go | 44 + .../paho.mqtt.golang/packets/publish.go | 80 ++ .../paho.mqtt.golang/packets/pubrec.go | 44 + .../paho.mqtt.golang/packets/pubrel.go | 44 + .../paho.mqtt.golang/packets/suback.go | 52 + .../paho.mqtt.golang/packets/subscribe.go | 62 + .../paho.mqtt.golang/packets/unsuback.go | 44 + .../paho.mqtt.golang/packets/unsubscribe.go | 55 + .../eclipse/paho.mqtt.golang/ping.go | 102 ++ .../eclipse/paho.mqtt.golang/router.go | 161 +++ .../eclipse/paho.mqtt.golang/store.go | 126 ++ .../eclipse/paho.mqtt.golang/token.go | 157 +++ .../eclipse/paho.mqtt.golang/topic.go | 82 ++ .../eclipse/paho.mqtt.golang/trace.go | 36 + .../paho.mqtt.golang/unit_client_test.go | 79 ++ .../paho.mqtt.golang/unit_messageids_test.go | 111 ++ .../paho.mqtt.golang/unit_options_test.go | 126 ++ .../paho.mqtt.golang/unit_ping_test.go | 63 + .../paho.mqtt.golang/unit_router_test.go | 288 +++++ .../paho.mqtt.golang/unit_store_test.go | 579 +++++++++ .../paho.mqtt.golang/unit_topic_test.go | 47 + 76 files changed, 8527 insertions(+) rename main.go => src/github.com/bcmi-labs/arduino-connector/main.go (100%) rename status.go => src/github.com/bcmi-labs/arduino-connector/status.go (100%) create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go create mode 100755 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go create mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go diff --git a/main.go b/src/github.com/bcmi-labs/arduino-connector/main.go similarity index 100% rename from main.go rename to src/github.com/bcmi-labs/arduino-connector/main.go diff --git a/status.go b/src/github.com/bcmi-labs/arduino-connector/status.go similarity index 100% rename from status.go rename to src/github.com/bcmi-labs/arduino-connector/status.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore new file mode 100644 index 00000000..47bb0de4 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore @@ -0,0 +1,36 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +*.msg +*.lok + +samples/trivial +samples/trivial2 +samples/sample +samples/reconnect +samples/ssl +samples/custom_store +samples/simple +samples/stdinpub +samples/stdoutsub +samples/routing \ No newline at end of file diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md new file mode 100644 index 00000000..9791dc60 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md @@ -0,0 +1,56 @@ +Contributing to Paho +==================== + +Thanks for your interest in this project. + +Project description: +-------------------- + +The Paho project has been created to provide scalable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). +Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications. Paho is being kicked off with MQTT publish/subscribe client implementations for use on embedded platforms, along with corresponding server support as determined by the community. + +- https://projects.eclipse.org/projects/technology.paho + +Developer resources: +-------------------- + +Information regarding source code management, builds, coding standards, and more. + +- https://projects.eclipse.org/projects/technology.paho/developer + +Contributor License Agreement: +------------------------------ + +Before your contribution can be accepted by the project, you need to create and electronically sign the Eclipse Foundation Contributor License Agreement (CLA). + +- http://www.eclipse.org/legal/CLA.php + +Contributing Code: +------------------ + +The Go client is developed in Github, see their documentation on the process of forking and pull requests; https://help.github.com/categories/collaborating-on-projects-using-pull-requests/ + +Git commit messages should follow the style described here; + +http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html + +Contact: +-------- + +Contact the project developers via the project's "dev" list. + +- https://dev.eclipse.org/mailman/listinfo/paho-dev + +Search for bugs: +---------------- + +This project uses Github issues to track ongoing development and issues. + +- https://github.com/eclipse/paho.mqtt.golang/issues + +Create a new bug: +----------------- + +Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! + +- https://github.com/eclipse/paho.mqtt.golang/issues diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION new file mode 100644 index 00000000..34e49731 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION @@ -0,0 +1,15 @@ + + +Eclipse Distribution License - v 1.0 + +Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE new file mode 100644 index 00000000..aa7cc810 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE @@ -0,0 +1,87 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and + +b) in the case of each subsequent Contributor: + +i) changes to the Program, and + +ii) additions to the Program; + +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. + +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. + +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. + +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and + +b) its license agreement: + +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; + +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; + +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and + +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and + +b) a copy of this Agreement must be included with each copy of the Program. + +Contributors may not remove or alter any copyright notices contained within the Program. + +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. \ No newline at end of file diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md new file mode 100644 index 00000000..09e50072 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md @@ -0,0 +1,63 @@ +Eclipse Paho MQTT Go client +=========================== + + +This repository contains the source code for the [Eclipse Paho](http://eclipse.org/paho) MQTT Go client library. + +This code builds a library which enable applications to connect to an [MQTT](http://mqtt.org) broker to publish messages, and to subscribe to topics and receive published messages. + +This library supports a fully asynchronous mode of operation. + + +Installation and Build +---------------------- + +This client is designed to work with the standard Go tools, so installation is as easy as: + +``` +go get github.com/eclipse/paho.mqtt.golang +``` + +The client depends on Google's [websockets](https://godoc.org/golang.org/x/net/websocket) and [proxy](https://godoc.org/golang.org/x/net/proxy) package, +also easily installed with the commands: + +``` +go get golang.org/x/net/websocket +go get golang.org/x/net/proxy +``` + + +Usage and API +------------- + +Detailed API documentation is available by using to godoc tool, or can be browsed online +using the [godoc.org](http://godoc.org/github.com/eclipse/paho.mqtt.golang) service. + +Make use of the library by importing it in your Go client source code. For example, +``` +import "github.com/eclipse/paho.mqtt.golang" +``` + +Samples are available in the `cmd` directory for reference. + + +Runtime tracing +--------------- + +Tracing is enabled by assigning logs (from the Go log package) to the logging endpoints, ERROR, CRITICAL, WARN and DEBUG + + +Reporting bugs +-------------- + +Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues + + +More information +---------------- + +Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev). + +General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt). + +There is much more information available via the [MQTT community site](http://mqtt.org). diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html new file mode 100644 index 00000000..b183f417 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html @@ -0,0 +1,41 @@ + + + +About + + +

About This Content

+ +

December 9, 2013

+

License

+ +

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). +A copy of the EPL is available at +http://www.eclipse.org/legal/epl-v10.html +and a copy of the EDL is available at +http://www.eclipse.org/org/documents/edl-v10.php. +For purposes of the EPL, "Program" will mean the Content.

+ +

If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party ("Redistributor") and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at http://www.eclipse.org.

+ + +

Third Party Content

+

The Content includes items that have been sourced from third parties as set out below. If you + did not receive this Content directly from the Eclipse Foundation, the following is provided + for informational purposes only, and you should look to the Redistributor's license for + terms and conditions of use.

+

+ None

+

+

+ + + + diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go new file mode 100644 index 00000000..242344bf --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go @@ -0,0 +1,611 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +// Package mqtt provides an MQTT v3.1.1 client library. +package mqtt + +import ( + "errors" + "fmt" + "net" + "sync" + "time" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +type connStatus uint + +const ( + disconnected connStatus = iota + connecting + reconnecting + connected +) + +// Client is the interface definition for a Client as used by this +// library, the interface is primarily to allow mocking tests. +// +// It is an MQTT v3.1.1 client for communicating +// with an MQTT server using non-blocking methods that allow work +// to be done in the background. +// An application may connect to an MQTT server using: +// A plain TCP socket +// A secure SSL/TLS socket +// A websocket +// To enable ensured message delivery at Quality of Service (QoS) levels +// described in the MQTT spec, a message persistence mechanism must be +// used. This is done by providing a type which implements the Store +// interface. For convenience, FileStore and MemoryStore are provided +// implementations that should be sufficient for most use cases. More +// information can be found in their respective documentation. +// Numerous connection options may be specified by configuring a +// and then supplying a ClientOptions type. +type Client interface { + IsConnected() bool + Connect() Token + Disconnect(quiesce uint) + Publish(topic string, qos byte, retained bool, payload interface{}) Token + Subscribe(topic string, qos byte, callback MessageHandler) Token + SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token + Unsubscribe(topics ...string) Token + AddRoute(topic string, callback MessageHandler) +} + +// client implements the Client interface +type client struct { + sync.RWMutex + messageIds + conn net.Conn + ibound chan packets.ControlPacket + obound chan *PacketAndToken + oboundP chan *PacketAndToken + msgRouter *router + stopRouter chan bool + incomingPubChan chan *packets.PublishPacket + errors chan error + stop chan struct{} + persist Store + options ClientOptions + pingResp chan struct{} + packetResp chan struct{} + keepaliveReset chan struct{} + status connStatus + workers sync.WaitGroup +} + +// NewClient will create an MQTT v3.1.1 client with all of the options specified +// in the provided ClientOptions. The client must have the Connect method called +// on it before it may be used. This is to make sure resources (such as a net +// connection) are created before the application is actually ready. +func NewClient(o *ClientOptions) Client { + c := &client{} + c.options = *o + + if c.options.Store == nil { + c.options.Store = NewMemoryStore() + } + switch c.options.ProtocolVersion { + case 3, 4: + c.options.protocolVersionExplicit = true + default: + c.options.ProtocolVersion = 4 + c.options.protocolVersionExplicit = false + } + c.persist = c.options.Store + c.status = disconnected + c.messageIds = messageIds{index: make(map[uint16]Token)} + c.msgRouter, c.stopRouter = newRouter() + c.msgRouter.setDefaultHandler(c.options.DefaultPublishHander) + if !c.options.AutoReconnect { + c.options.MessageChannelDepth = 0 + } + return c +} + +func (c *client) AddRoute(topic string, callback MessageHandler) { + if callback != nil { + c.msgRouter.addRoute(topic, callback) + } +} + +// IsConnected returns a bool signifying whether +// the client is connected or not. +func (c *client) IsConnected() bool { + c.RLock() + defer c.RUnlock() + switch { + case c.status == connected: + return true + case c.options.AutoReconnect && c.status > disconnected: + return true + default: + return false + } +} + +func (c *client) connectionStatus() connStatus { + c.RLock() + defer c.RUnlock() + return c.status +} + +func (c *client) setConnected(status connStatus) { + c.Lock() + defer c.Unlock() + c.status = status +} + +//ErrNotConnected is the error returned from function calls that are +//made when the client is not connected to a broker +var ErrNotConnected = errors.New("Not Connected") + +// Connect will create a connection to the message broker +// If clean session is false, then a slice will +// be returned containing Receipts for all messages +// that were in-flight at the last disconnect. +// If clean session is true, then any existing client +// state will be removed. +func (c *client) Connect() Token { + var err error + t := newToken(packets.Connect).(*ConnectToken) + DEBUG.Println(CLI, "Connect()") + + go func() { + c.persist.Open() + + c.setConnected(connecting) + var rc byte + cm := newConnectMsgFromOptions(&c.options) + + for _, broker := range c.options.Servers { + CONN: + DEBUG.Println(CLI, "about to write new connect msg") + c.conn, err = openConnection(broker, &c.options.TLSConfig, c.options.ConnectTimeout) + if err == nil { + DEBUG.Println(CLI, "socket connected to broker") + switch c.options.ProtocolVersion { + case 3: + DEBUG.Println(CLI, "Using MQTT 3.1 protocol") + cm.ProtocolName = "MQIsdp" + cm.ProtocolVersion = 3 + default: + DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol") + c.options.ProtocolVersion = 4 + cm.ProtocolName = "MQTT" + cm.ProtocolVersion = 4 + } + cm.Write(c.conn) + + rc = c.connect() + if rc != packets.Accepted { + if c.conn != nil { + c.conn.Close() + c.conn = nil + } + //if the protocol version was explicitly set don't do any fallback + if c.options.protocolVersionExplicit { + ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc]) + continue + } + if c.options.ProtocolVersion == 4 { + DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol") + c.options.ProtocolVersion = 3 + goto CONN + } + } + break + } else { + ERROR.Println(CLI, err.Error()) + WARN.Println(CLI, "failed to connect to broker, trying next") + rc = packets.ErrNetworkError + } + } + + if c.conn == nil { + ERROR.Println(CLI, "Failed to connect to a broker") + t.returnCode = rc + if rc != packets.ErrNetworkError { + t.err = packets.ConnErrors[rc] + } else { + t.err = fmt.Errorf("%s : %s", packets.ConnErrors[rc], err) + } + c.setConnected(disconnected) + c.persist.Close() + t.flowComplete() + return + } + + if c.options.KeepAlive != 0 { + c.workers.Add(1) + go keepalive(c) + } + + c.obound = make(chan *PacketAndToken, c.options.MessageChannelDepth) + c.oboundP = make(chan *PacketAndToken, c.options.MessageChannelDepth) + c.ibound = make(chan packets.ControlPacket) + c.errors = make(chan error, 1) + c.stop = make(chan struct{}) + c.pingResp = make(chan struct{}, 1) + c.packetResp = make(chan struct{}, 1) + c.keepaliveReset = make(chan struct{}, 1) + + c.incomingPubChan = make(chan *packets.PublishPacket, c.options.MessageChannelDepth) + c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c) + + c.setConnected(connected) + DEBUG.Println(CLI, "client is connected") + if c.options.OnConnect != nil { + go c.options.OnConnect(c) + } + + // Take care of any messages in the store + //var leftovers []Receipt + if c.options.CleanSession == false { + //leftovers = c.resume() + } else { + c.persist.Reset() + } + + go errorWatch(c) + + // Do not start incoming until resume has completed + c.workers.Add(3) + go alllogic(c) + go outgoing(c) + go incoming(c) + + DEBUG.Println(CLI, "exit startClient") + t.flowComplete() + }() + return t +} + +// internal function used to reconnect the client when it loses its connection +func (c *client) reconnect() { + DEBUG.Println(CLI, "enter reconnect") + var ( + err error + + rc = byte(1) + sleep = time.Duration(1 * time.Second) + ) + + for rc != 0 && c.status != disconnected { + cm := newConnectMsgFromOptions(&c.options) + + for _, broker := range c.options.Servers { + CONN: + DEBUG.Println(CLI, "about to write new connect msg") + c.conn, err = openConnection(broker, &c.options.TLSConfig, c.options.ConnectTimeout) + if err == nil { + DEBUG.Println(CLI, "socket connected to broker") + switch c.options.ProtocolVersion { + case 3: + DEBUG.Println(CLI, "Using MQTT 3.1 protocol") + cm.ProtocolName = "MQIsdp" + cm.ProtocolVersion = 3 + default: + DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol") + c.options.ProtocolVersion = 4 + cm.ProtocolName = "MQTT" + cm.ProtocolVersion = 4 + } + cm.Write(c.conn) + + rc = c.connect() + if rc != packets.Accepted { + c.conn.Close() + c.conn = nil + //if the protocol version was explicitly set don't do any fallback + if c.options.protocolVersionExplicit { + ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not Accepted, but rather", packets.ConnackReturnCodes[rc]) + continue + } + if c.options.ProtocolVersion == 4 { + DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol") + c.options.ProtocolVersion = 3 + goto CONN + } + } + break + } else { + ERROR.Println(CLI, err.Error()) + WARN.Println(CLI, "failed to connect to broker, trying next") + rc = packets.ErrNetworkError + } + } + if rc != 0 { + DEBUG.Println(CLI, "Reconnect failed, sleeping for", int(sleep.Seconds()), "seconds") + time.Sleep(sleep) + if sleep < c.options.MaxReconnectInterval { + sleep *= 2 + } + + if sleep > c.options.MaxReconnectInterval { + sleep = c.options.MaxReconnectInterval + } + } + } + // Disconnect() must have been called while we were trying to reconnect. + if c.status == disconnected { + DEBUG.Println(CLI, "Client moved to disconnected state while reconnecting, abandoning reconnect") + return + } + + if c.options.KeepAlive != 0 { + c.workers.Add(1) + go keepalive(c) + } + + c.stop = make(chan struct{}) + + c.setConnected(connected) + DEBUG.Println(CLI, "client is reconnected") + if c.options.OnConnect != nil { + go c.options.OnConnect(c) + } + + go errorWatch(c) + + c.workers.Add(3) + go alllogic(c) + go outgoing(c) + go incoming(c) +} + +// This function is only used for receiving a connack +// when the connection is first started. +// This prevents receiving incoming data while resume +// is in progress if clean session is false. +func (c *client) connect() byte { + DEBUG.Println(NET, "connect started") + + ca, err := packets.ReadPacket(c.conn) + if err != nil { + ERROR.Println(NET, "connect got error", err) + return packets.ErrNetworkError + } + if ca == nil { + ERROR.Println(NET, "received nil packet") + return packets.ErrNetworkError + } + + msg, ok := ca.(*packets.ConnackPacket) + if !ok { + ERROR.Println(NET, "received msg that was not CONNACK") + return packets.ErrNetworkError + } + + DEBUG.Println(NET, "received connack") + return msg.ReturnCode +} + +// Disconnect will end the connection with the server, but not before waiting +// the specified number of milliseconds to wait for existing work to be +// completed. +func (c *client) Disconnect(quiesce uint) { + if c.status == connected { + DEBUG.Println(CLI, "disconnecting") + c.setConnected(disconnected) + + dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket) + dt := newToken(packets.Disconnect) + c.oboundP <- &PacketAndToken{p: dm, t: dt} + + // wait for work to finish, or quiesce time consumed + dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond) + } else { + WARN.Println(CLI, "Disconnect() called but not connected (disconnected/reconnecting)") + c.setConnected(disconnected) + } + + c.disconnect() +} + +// ForceDisconnect will end the connection with the mqtt broker immediately. +func (c *client) forceDisconnect() { + if !c.IsConnected() { + WARN.Println(CLI, "already disconnected") + return + } + c.setConnected(disconnected) + c.conn.Close() + DEBUG.Println(CLI, "forcefully disconnecting") + c.disconnect() +} + +func (c *client) internalConnLost(err error) { + // Only do anything if this was called and we are still "connected" + // forceDisconnect can cause incoming/outgoing/alllogic to end with + // error from closing the socket but state will be "disconnected" + if c.IsConnected() { + c.closeStop() + c.conn.Close() + c.workers.Wait() + if c.options.CleanSession { + c.messageIds.cleanUp() + } + if c.options.AutoReconnect { + c.setConnected(reconnecting) + go c.reconnect() + } else { + c.setConnected(disconnected) + } + if c.options.OnConnectionLost != nil { + go c.options.OnConnectionLost(c, err) + } + } +} + +func (c *client) closeStop() { + c.Lock() + defer c.Unlock() + select { + case <-c.stop: + DEBUG.Println("In disconnect and stop channel is already closed") + default: + close(c.stop) + } +} + +func (c *client) closeConn() { + c.Lock() + defer c.Unlock() + if c.conn != nil { + c.conn.Close() + } +} + +func (c *client) disconnect() { + c.closeStop() + c.closeConn() + c.workers.Wait() + close(c.stopRouter) + DEBUG.Println(CLI, "disconnected") + c.persist.Close() +} + +// Publish will publish a message with the specified QoS and content +// to the specified topic. +// Returns a token to track delivery of the message to the broker +func (c *client) Publish(topic string, qos byte, retained bool, payload interface{}) Token { + token := newToken(packets.Publish).(*PublishToken) + DEBUG.Println(CLI, "enter Publish") + switch { + case !c.IsConnected(): + token.err = ErrNotConnected + token.flowComplete() + return token + case c.connectionStatus() == reconnecting && qos == 0: + token.flowComplete() + return token + } + pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pub.Qos = qos + pub.TopicName = topic + pub.Retain = retained + switch payload.(type) { + case string: + pub.Payload = []byte(payload.(string)) + case []byte: + pub.Payload = payload.([]byte) + default: + token.err = errors.New("Unknown payload type") + token.flowComplete() + return token + } + + DEBUG.Println(CLI, "sending publish message, topic:", topic) + if pub.Qos != 0 && pub.MessageID == 0 { + pub.MessageID = c.getID(token) + token.messageID = pub.MessageID + } + persistOutbound(c.persist, pub) + c.obound <- &PacketAndToken{p: pub, t: token} + return token +} + +// Subscribe starts a new subscription. Provide a MessageHandler to be executed when +// a message is published on the topic provided. +func (c *client) Subscribe(topic string, qos byte, callback MessageHandler) Token { + token := newToken(packets.Subscribe).(*SubscribeToken) + DEBUG.Println(CLI, "enter Subscribe") + if !c.IsConnected() { + token.err = ErrNotConnected + token.flowComplete() + return token + } + sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) + if err := validateTopicAndQos(topic, qos); err != nil { + token.err = err + return token + } + sub.Topics = append(sub.Topics, topic) + sub.Qoss = append(sub.Qoss, qos) + DEBUG.Println(CLI, sub.String()) + + if callback != nil { + c.msgRouter.addRoute(topic, callback) + } + + token.subs = append(token.subs, topic) + c.oboundP <- &PacketAndToken{p: sub, t: token} + DEBUG.Println(CLI, "exit Subscribe") + return token +} + +// SubscribeMultiple starts a new subscription for multiple topics. Provide a MessageHandler to +// be executed when a message is published on one of the topics provided. +func (c *client) SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token { + var err error + token := newToken(packets.Subscribe).(*SubscribeToken) + DEBUG.Println(CLI, "enter SubscribeMultiple") + if !c.IsConnected() { + token.err = ErrNotConnected + token.flowComplete() + return token + } + sub := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) + if sub.Topics, sub.Qoss, err = validateSubscribeMap(filters); err != nil { + token.err = err + return token + } + + if callback != nil { + for topic := range filters { + c.msgRouter.addRoute(topic, callback) + } + } + token.subs = make([]string, len(sub.Topics)) + copy(token.subs, sub.Topics) + c.oboundP <- &PacketAndToken{p: sub, t: token} + DEBUG.Println(CLI, "exit SubscribeMultiple") + return token +} + +// Unsubscribe will end the subscription from each of the topics provided. +// Messages published to those topics from other clients will no longer be +// received. +func (c *client) Unsubscribe(topics ...string) Token { + token := newToken(packets.Unsubscribe).(*UnsubscribeToken) + DEBUG.Println(CLI, "enter Unsubscribe") + if !c.IsConnected() { + token.err = ErrNotConnected + token.flowComplete() + return token + } + unsub := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket) + unsub.Topics = make([]string, len(topics)) + copy(unsub.Topics, topics) + + c.oboundP <- &PacketAndToken{p: unsub, t: token} + for _, topic := range topics { + c.msgRouter.deleteRoute(topic) + } + + DEBUG.Println(CLI, "exit Unsubscribe") + return token +} + +func (c *client) OptionsReader() ClientOptionsReader { + r := ClientOptionsReader{options: &c.options} + return r +} + +//DefaultConnectionLostHandler is a definition of a function that simply +//reports to the DEBUG log the reason for the client losing a connection. +func DefaultConnectionLostHandler(client Client, reason error) { + DEBUG.Println("Connection lost:", reason.Error()) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh new file mode 100755 index 00000000..c9cec5a8 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +for dir in `ls -d */ | cut -f1 -d'/'` +do + echo "Compiling $dir ...\c" + cd $dir + go clean + go build + cd .. + echo " done." +done diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go new file mode 100644 index 00000000..d5920b82 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +// This demonstrates how to implement your own Store interface and provide +// it to the go-mqtt client. + +package main + +import ( + "fmt" + "time" + + MQTT "github.com/eclipse/paho.mqtt.golang" + "github.com/eclipse/paho.mqtt.golang/packets" +) + +// This NoOpStore type implements the go-mqtt/Store interface, which +// allows it to be used by the go-mqtt client library. However, it is +// highly recommended that you do not use this NoOpStore in production, +// because it will NOT provide any sort of guaruntee of message delivery. +type NoOpStore struct { + // Contain nothing +} + +func (store *NoOpStore) Open() { + // Do nothing +} + +func (store *NoOpStore) Put(string, packets.ControlPacket) { + // Do nothing +} + +func (store *NoOpStore) Get(string) packets.ControlPacket { + // Do nothing + return nil +} + +func (store *NoOpStore) Del(string) { + // Do nothing +} + +func (store *NoOpStore) All() []string { + return nil +} + +func (store *NoOpStore) Close() { + // Do Nothing +} + +func (store *NoOpStore) Reset() { + // Do Nothing +} + +func main() { + myNoOpStore := &NoOpStore{} + + opts := MQTT.NewClientOptions() + opts.AddBroker("tcp://iot.eclipse.org:1883") + opts.SetClientID("custom-store") + opts.SetStore(myNoOpStore) + + var callback MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + } + + c := MQTT.NewClient(opts) + if token := c.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + + c.Subscribe("/go-mqtt/sample", 0, callback) + + for i := 0; i < 5; i++ { + text := fmt.Sprintf("this is msg #%d!", i) + token := c.Publish("/go-mqtt/sample", 0, false, text) + token.Wait() + } + + for i := 1; i < 5; i++ { + time.Sleep(1 * time.Second) + } + + c.Disconnect(250) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go new file mode 100644 index 00000000..de708cc5 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +/*---------------------------------------------------------------------- +This sample is designed to demonstrate the ability to set individual +callbacks on a per-subscription basis. There are three handlers in use: + brokerLoadHandler - $SYS/broker/load/# + brokerConnectionHandler - $SYS/broker/connection/# + brokerClientHandler - $SYS/broker/clients/# +The client will receive 100 messages total from those subscriptions, +and then print the total number of messages received from each. +It may take a few moments for the sample to complete running, as it +must wait for messages to be published. +-----------------------------------------------------------------------*/ + +package main + +import ( + "fmt" + "os" + + MQTT "github.com/eclipse/paho.mqtt.golang" +) + +var brokerLoad = make(chan bool) +var brokerConnection = make(chan bool) +var brokerClients = make(chan bool) + +func brokerLoadHandler(client MQTT.Client, msg MQTT.Message) { + brokerLoad <- true + fmt.Printf("BrokerLoadHandler ") + fmt.Printf("[%s] ", msg.Topic()) + fmt.Printf("%s\n", msg.Payload()) +} + +func brokerConnectionHandler(client MQTT.Client, msg MQTT.Message) { + brokerConnection <- true + fmt.Printf("BrokerConnectionHandler ") + fmt.Printf("[%s] ", msg.Topic()) + fmt.Printf("%s\n", msg.Payload()) +} + +func brokerClientsHandler(client MQTT.Client, msg MQTT.Message) { + brokerClients <- true + fmt.Printf("BrokerClientsHandler ") + fmt.Printf("[%s] ", msg.Topic()) + fmt.Printf("%s\n", msg.Payload()) +} + +func main() { + opts := MQTT.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("router-sample") + opts.SetCleanSession(true) + + c := MQTT.NewClient(opts) + if token := c.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + + if token := c.Subscribe("$SYS/broker/load/#", 0, brokerLoadHandler); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + if token := c.Subscribe("$SYS/broker/connection/#", 0, brokerConnectionHandler); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + if token := c.Subscribe("$SYS/broker/clients/#", 0, brokerClientsHandler); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + loadCount := 0 + connectionCount := 0 + clientsCount := 0 + + for i := 0; i < 100; i++ { + select { + case <-brokerLoad: + loadCount++ + case <-brokerConnection: + connectionCount++ + case <-brokerClients: + clientsCount++ + } + } + + fmt.Printf("Received %3d Broker Load messages\n", loadCount) + fmt.Printf("Received %3d Broker Connection messages\n", connectionCount) + fmt.Printf("Received %3d Broker Clients messages\n", clientsCount) + + c.Disconnect(250) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go new file mode 100644 index 00000000..f144fe02 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package main + +import ( + "flag" + "fmt" + "os" + + MQTT "github.com/eclipse/paho.mqtt.golang" +) + +/* +Options: + [-help] Display help + [-a pub|sub] Action pub (publish) or sub (subscribe) + [-m ] Payload to send + [-n ] Number of messages to send or receive + [-q 0|1|2] Quality of Service + [-clean] CleanSession (true if -clean is present) + [-id ] CliendID + [-user ] User + [-password ] Password + [-broker ] Broker URI + [-topic ] Topic + [-store ] Store Directory + +*/ + +func main() { + topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe") + broker := flag.String("broker", "tcp://iot.eclipse.org:1883", "The broker URI. ex: tcp://10.10.1.1:1883") + password := flag.String("password", "", "The password (optional)") + user := flag.String("user", "", "The User (optional)") + id := flag.String("id", "testgoid", "The ClientID (optional)") + cleansess := flag.Bool("clean", false, "Set Clean Session (default false)") + qos := flag.Int("qos", 0, "The Quality of Service 0,1,2 (default 0)") + num := flag.Int("num", 1, "The number of messages to publish or subscribe (default 1)") + payload := flag.String("message", "", "The message text to publish (default empty)") + action := flag.String("action", "", "Action publish or subscribe (required)") + store := flag.String("store", ":memory:", "The Store Directory (default use memory store)") + flag.Parse() + + if *action != "pub" && *action != "sub" { + fmt.Println("Invalid setting for -action, must be pub or sub") + return + } + + if *topic == "" { + fmt.Println("Invalid setting for -topic, must not be empty") + return + } + + fmt.Printf("Sample Info:\n") + fmt.Printf("\taction: %s\n", *action) + fmt.Printf("\tbroker: %s\n", *broker) + fmt.Printf("\tclientid: %s\n", *id) + fmt.Printf("\tuser: %s\n", *user) + fmt.Printf("\tpassword: %s\n", *password) + fmt.Printf("\ttopic: %s\n", *topic) + fmt.Printf("\tmessage: %s\n", *payload) + fmt.Printf("\tqos: %d\n", *qos) + fmt.Printf("\tcleansess: %v\n", *cleansess) + fmt.Printf("\tnum: %d\n", *num) + fmt.Printf("\tstore: %s\n", *store) + + opts := MQTT.NewClientOptions() + opts.AddBroker(*broker) + opts.SetClientID(*id) + opts.SetUsername(*user) + opts.SetPassword(*password) + opts.SetCleanSession(*cleansess) + if *store != ":memory:" { + opts.SetStore(MQTT.NewFileStore(*store)) + } + + if *action == "pub" { + client := MQTT.NewClient(opts) + if token := client.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + fmt.Println("Sample Publisher Started") + for i := 0; i < *num; i++ { + fmt.Println("---- doing publish ----") + token := client.Publish(*topic, byte(*qos), false, *payload) + token.Wait() + } + + client.Disconnect(250) + fmt.Println("Sample Publisher Disconnected") + } else { + receiveCount := 0 + choke := make(chan [2]string) + + opts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) { + choke <- [2]string{msg.Topic(), string(msg.Payload())} + }) + + client := MQTT.NewClient(opts) + if token := client.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + + if token := client.Subscribe(*topic, byte(*qos), nil); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + for receiveCount < *num { + incoming := <-choke + fmt.Printf("RECEIVED TOPIC: %s MESSAGE: %s\n", incoming[0], incoming[1]) + receiveCount++ + } + + client.Disconnect(250) + fmt.Println("Sample Subscriber Disconnected") + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go new file mode 100644 index 00000000..96459353 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package main + +import ( + "fmt" + "log" + "os" + "time" + + "github.com/eclipse/paho.mqtt.golang" +) + +var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) +} + +func main() { + mqtt.DEBUG = log.New(os.Stdout, "", 0) + mqtt.ERROR = log.New(os.Stdout, "", 0) + opts := mqtt.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("gotrivial") + opts.SetKeepAlive(2 * time.Second) + opts.SetDefaultPublishHandler(f) + opts.SetPingTimeout(1 * time.Second) + + c := mqtt.NewClient(opts) + if token := c.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + + if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + for i := 0; i < 5; i++ { + text := fmt.Sprintf("this is msg #%d!", i) + token := c.Publish("go-mqtt/sample", 0, false, text) + token.Wait() + } + + time.Sleep(6 * time.Second) + + if token := c.Unsubscribe("go-mqtt/sample"); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + os.Exit(1) + } + + c.Disconnect(250) + + time.Sleep(1 * time.Second) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go new file mode 100644 index 00000000..99d4eae8 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +/* +To run this sample, The following certificates +must be created: + + rootCA-crt.pem - root certificate authority that is used + to sign and verify the client and server + certificates. + rootCA-key.pem - keyfile for the rootCA. + + server-crt.pem - server certificate signed by the CA. + server-key.pem - keyfile for the server certificate. + + client-crt.pem - client certificate signed by the CA. + client-key.pem - keyfile for the client certificate. + + CAfile.pem - file containing concatenated CA certificates + if there is more than 1 in the chain. + (e.g. root CA -> intermediate CA -> server cert) + + Instead of creating CAfile.pem, rootCA-crt.pem can be added + to the default openssl CA certificate bundle. To find the + default CA bundle used, check: + $GO_ROOT/src/pks/crypto/x509/root_unix.go + To use this CA bundle, just set tls.Config.RootCAs = nil. +*/ + +package main + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "io/ioutil" + "time" + + MQTT "github.com/eclipse/paho.mqtt.golang" +) + +func NewTLSConfig() *tls.Config { + // Import trusted certificates from CAfile.pem. + // Alternatively, manually add CA certificates to + // default openssl CA bundle. + certpool := x509.NewCertPool() + pemCerts, err := ioutil.ReadFile("samplecerts/CAfile.pem") + if err == nil { + certpool.AppendCertsFromPEM(pemCerts) + } + + // Import client certificate/key pair + cert, err := tls.LoadX509KeyPair("samplecerts/client-crt.pem", "samplecerts/client-key.pem") + if err != nil { + panic(err) + } + + // Just to print out the client certificate.. + cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + panic(err) + } + fmt.Println(cert.Leaf) + + // Create tls.Config with desired tls properties + return &tls.Config{ + // RootCAs = certs used to verify server cert. + RootCAs: certpool, + // ClientAuth = whether to request cert from server. + // Since the server is set up for SSL, this happens + // anyways. + ClientAuth: tls.NoClientCert, + // ClientCAs = certs used to validate client cert. + ClientCAs: nil, + // InsecureSkipVerify = verify that cert contents + // match server. IP matches what is in cert etc. + InsecureSkipVerify: true, + // Certificates = list of certs client sends to server. + Certificates: []tls.Certificate{cert}, + } +} + +var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) +} + +func main() { + tlsconfig := NewTLSConfig() + + opts := MQTT.NewClientOptions() + opts.AddBroker("ssl://iot.eclipse.org:8883") + opts.SetClientID("ssl-sample").SetTLSConfig(tlsconfig) + opts.SetDefaultPublishHandler(f) + + // Start the connection + c := MQTT.NewClient(opts) + if token := c.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + + c.Subscribe("/go-mqtt/sample", 0, nil) + + i := 0 + for _ = range time.Tick(time.Duration(1) * time.Second) { + if i == 5 { + break + } + text := fmt.Sprintf("this is msg #%d!", i) + c.Publish("/go-mqtt/sample", 0, false, text) + i++ + } + + c.Disconnect(250) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem new file mode 100644 index 00000000..16c664a4 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem @@ -0,0 +1,150 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha1WithRSAEncryption + Issuer: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA + Validity + Not Before: Oct 21 19:24:23 2013 GMT + Not After : Sep 25 19:24:23 2018 GMT + Subject: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c2:d1:d0:31:dc:93:c3:ad:88:0d:f8:93:fe:cc: + aa:04:1d:85:aa:c3:bb:bd:87:04:f0:42:67:14:34: + 4a:56:94:2b:bf:d0:6b:72:30:38:39:35:20:8c:e3: + 7e:65:82:b0:7e:3e:1d:f1:18:82:b7:d6:19:59:43: + ed:81:be:eb:51:44:fc:77:9e:37:ad:e1:a0:18:b9: + 4b:59:79:90:81:a4:e4:52:2f:fc:e2:ff:98:10:5e: + d5:13:9a:16:62:1a:e0:cb:ab:1d:ae:da:d1:40:d4: + 97:b1:e6:e3:f1:97:2c:2a:52:73:ab:d0:a2:15:f3: + 1e:9a:b0:67:d0:62:67:4b:74:b0:bb:8f:ef:9e:32: + 6a:4c:27:4e:82:7c:16:66:ce:06:e9:a3:d9:36:4f: + f4:3e:bc:80:00:93:c1:ca:31:cf:03:68:d4:e5:8b: + 38:45:b6:1b:35:b0:c0:e9:4a:62:75:83:01:aa:b9: + c1:0b:c0:ee:97:c0:73:23:cd:34:ec:bb:3c:95:35: + c8:2d:69:ff:86:d8:1f:c8:04:7e:18:de:62:c2:4b: + 37:c6:aa:8e:03:bf:2b:0d:97:20:2a:75:47:ec:98: + 29:3c:64:52:ef:91:8b:63:0f:6a:f8:c2:9d:08:6a: + 61:68:6f:64:9a:56:b2:0a:bc:7b:59:3d:7f:fd:ba: + 12:4b + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + 5B:BB:3E:8E:2D:90:AD:AE:58:07:FF:53:00:18:98:FF:44:84:4C:BA + X509v3 Authority Key Identifier: + keyid:5B:BB:3E:8E:2D:90:AD:AE:58:07:FF:53:00:18:98:FF:44:84:4C:BA + + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha1WithRSAEncryption + 3c:89:0b:bd:49:10:a6:1a:f6:2a:4b:5f:02:3d:ee:f3:19:4f: + c9:10:79:9c:01:ef:88:22:3d:03:5b:1a:14:46:b6:7f:9b:af: + a5:99:1a:d4:d4:9b:d6:6f:c1:fe:96:8f:9a:9e:47:42:b4:ee: + 21:56:6a:c4:92:38:6c:81:cd:8e:31:43:86:7c:97:15:90:80: + d8:21:f0:46:be:2a:2f:f2:96:07:85:74:a8:fa:1b:78:8f:80: + c1:5e:bc:d9:06:c2:33:9e:8e:f9:08:dd:43:7b:6f:5a:22:67: + 46:78:5d:fb:4a:4e:c2:c6:29:94:17:53:a6:c5:a9:d6:67:06: + 4f:07:ef:da:5b:45:21:83:cb:31:b2:dc:dc:ac:13:19:98:3f: + 98:5f:2c:b4:b4:da:d4:43:d7:a9:1a:6e:b6:cf:be:85:a8:80: + 1f:8a:c1:95:8a:83:a4:af:d2:23:4a:b6:18:87:4e:28:31:36: + 03:2c:bf:e4:9e:b6:75:fd:c4:68:ed:4d:d5:a8:fa:a5:81:13: + 17:1c:43:67:02:1c:d0:e6:00:6e:8b:13:e6:60:1f:ba:40:78: + 93:25:ca:59:5a:71:cc:58:d4:52:63:1d:b3:3c:ce:37:f1:89: + 78:fc:13:fa:b3:ea:22:af:17:68:8a:a1:59:57:f5:1a:49:6e: + b9:f6:5f:b3 +-----BEGIN CERTIFICATE----- +MIIDizCCAnOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO +MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy +M1oXDTE4MDkyNTE5MjQyM1owYDELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 +MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 +MREwDwYDVQQDDAhEdW1teSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMLR0DHck8OtiA34k/7MqgQdharDu72HBPBCZxQ0SlaUK7/Qa3IwODk1IIzj +fmWCsH4+HfEYgrfWGVlD7YG+61FE/HeeN63hoBi5S1l5kIGk5FIv/OL/mBBe1ROa +FmIa4MurHa7a0UDUl7Hm4/GXLCpSc6vQohXzHpqwZ9BiZ0t0sLuP754yakwnToJ8 +FmbOBumj2TZP9D68gACTwcoxzwNo1OWLOEW2GzWwwOlKYnWDAaq5wQvA7pfAcyPN +NOy7PJU1yC1p/4bYH8gEfhjeYsJLN8aqjgO/Kw2XICp1R+yYKTxkUu+Ri2MPavjC +nQhqYWhvZJpWsgq8e1k9f/26EksCAwEAAaNQME4wHQYDVR0OBBYEFFu7Po4tkK2u +WAf/UwAYmP9EhEy6MB8GA1UdIwQYMBaAFFu7Po4tkK2uWAf/UwAYmP9EhEy6MAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADyJC71JEKYa9ipLXwI97vMZ +T8kQeZwB74giPQNbGhRGtn+br6WZGtTUm9Zvwf6Wj5qeR0K07iFWasSSOGyBzY4x +Q4Z8lxWQgNgh8Ea+Ki/ylgeFdKj6G3iPgMFevNkGwjOejvkI3UN7b1oiZ0Z4XftK +TsLGKZQXU6bFqdZnBk8H79pbRSGDyzGy3NysExmYP5hfLLS02tRD16kabrbPvoWo +gB+KwZWKg6Sv0iNKthiHTigxNgMsv+SetnX9xGjtTdWo+qWBExccQ2cCHNDmAG6L +E+ZgH7pAeJMlyllaccxY1FJjHbM8zjfxiXj8E/qz6iKvF2iKoVlX9RpJbrn2X7M= +-----END CERTIFICATE----- +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 1 (0x1) + Signature Algorithm: sha1WithRSAEncryption + Issuer: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA + Validity + Not Before: Oct 21 19:24:23 2013 GMT + Not After : Sep 25 19:24:23 2018 GMT + Subject: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy Intermediate CA + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:cf:7d:92:07:a5:56:1b:6f:4c:f3:34:c2:12:c2: + 34:62:3b:69:aa:a6:0c:c6:70:5b:93:bc:dc:41:98: + 61:87:61:36:be:8c:08:dd:31:a9:33:76:d3:66:3e: + 77:60:1e:ed:9e:e1:e5:ef:bf:17:91:ac:0c:63:07: + 01:ab:30:67:bc:16:a6:2f:79:f0:61:8c:79:2d:3c: + 98:60:74:61:c4:5f:60:44:85:71:92:9d:cc:7b:14: + 39:74:aa:44:f9:9f:ae:f6:c7:8d:c3:01:47:53:24: + ac:7b:a2:f6:c5:7d:65:37:40:0b:20:c8:d4:14:cd: + f8:f4:57:ea:23:70:f4:e3:99:2b:1c:9a:67:37:ed: + 93:c7:a7:7c:86:90:f7:ae:fc:6f:4b:18:dc:d5:eb: + f3:68:33:d6:78:14:d1:ca:a7:06:7d:75:34:f6:c0: + d4:15:1b:21:2b:78:d9:76:24:a5:f0:c6:13:c8:1e: + 4a:c8:ca:77:34:4e:f8:fa:49:5f:6c:e1:66:a8:65: + f0:8c:bc:44:20:03:ac:af:4a:61:a5:39:48:51:1b: + cb:d8:22:29:60:27:47:42:fc:bf:6a:77:65:58:09: + 20:82:1c:d1:16:5e:5a:18:ea:99:61:8e:93:94:27: + 30:20:dd:44:03:50:43:b4:ec:a3:0f:ee:91:69:d7: + b1:5b + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha1WithRSAEncryption + 39:a0:8d:2f:68:22:1d:4f:3e:db:f1:9b:29:20:77:23:f8:21: + 34:17:84:00:88:a8:3e:a1:4d:84:94:90:96:02:e6:6a:b4:20: + 51:a0:66:20:38:05:18:aa:2a:3e:9a:50:60:af:eb:4a:70:ac: + 9b:59:30:d5:17:14:9c:b4:91:6a:1b:c3:45:8a:dd:cd:2f:c6: + c5:8c:fe:d0:76:20:63:a4:97:db:e3:2a:8e:c1:3d:c8:b6:06: + 2d:49:7a:d9:8a:de:16:ea:5d:5f:fb:41:79:0d:8f:d2:23:00: + d9:b9:6f:93:45:bb:74:17:ea:6b:72:13:01:86:fe:8d:7e:8f: + 27:71:76:a9:37:6d:6c:90:5a:3f:d9:6d:4d:6c:a4:64:7a:ea: + 82:c9:87:ee:6a:d0:6e:30:05:7f:19:1d:19:31:a9:9a:ce:21: + 84:da:47:c7:a0:66:12:e8:7e:57:69:5d:9c:24:e5:46:3c:bf: + 37:f6:88:c3:b1:42:de:3b:81:ed:f5:ae:e2:23:9e:c2:89:a1: + e7:5c:1d:49:0f:ed:ae:55:60:0e:4e:4c:e9:8a:64:e6:ae:c5: + d1:99:a7:70:4c:7e:5d:53:ac:88:2c:0f:0b:21:94:1a:32:f9: + a1:cc:1e:67:98:6b:b6:e9:b1:b9:4b:46:02:b1:65:c9:49:83: + 80:bd:b9:70 +-----BEGIN CERTIFICATE----- +MIIDWDCCAkCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO +MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy +M1oXDTE4MDkyNTE5MjQyM1owbTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 +MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 +MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDPfZIHpVYbb0zzNMISwjRiO2mqpgzGcFuTvNxBmGGH +YTa+jAjdMakzdtNmPndgHu2e4eXvvxeRrAxjBwGrMGe8FqYvefBhjHktPJhgdGHE +X2BEhXGSncx7FDl0qkT5n672x43DAUdTJKx7ovbFfWU3QAsgyNQUzfj0V+ojcPTj +mSscmmc37ZPHp3yGkPeu/G9LGNzV6/NoM9Z4FNHKpwZ9dTT2wNQVGyEreNl2JKXw +xhPIHkrIync0Tvj6SV9s4WaoZfCMvEQgA6yvSmGlOUhRG8vYIilgJ0dC/L9qd2VY +CSCCHNEWXloY6plhjpOUJzAg3UQDUEO07KMP7pFp17FbAgMBAAGjEDAOMAwGA1Ud +EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADmgjS9oIh1PPtvxmykgdyP4ITQX +hACIqD6hTYSUkJYC5mq0IFGgZiA4BRiqKj6aUGCv60pwrJtZMNUXFJy0kWobw0WK +3c0vxsWM/tB2IGOkl9vjKo7BPci2Bi1JetmK3hbqXV/7QXkNj9IjANm5b5NFu3QX +6mtyEwGG/o1+jydxdqk3bWyQWj/ZbU1spGR66oLJh+5q0G4wBX8ZHRkxqZrOIYTa +R8egZhLofldpXZwk5UY8vzf2iMOxQt47ge31ruIjnsKJoedcHUkP7a5VYA5OTOmK +ZOauxdGZp3BMfl1TrIgsDwshlBoy+aHMHmeYa7bpsblLRgKxZclJg4C9uXA= +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README new file mode 100644 index 00000000..aa7c97d7 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README @@ -0,0 +1,9 @@ +Certificate structure: + +Root CA + | + |-> Intermediate CA + | + |-> Server + | + |-> Client diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem new file mode 100644 index 00000000..5069e08e --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDRzCCAi8CAQIwDQYJKoZIhvcNAQEFBQAwbTELMAkGA1UEBhMCVVMxDjAMBgNV +BAgMBUR1bW15MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNV +BAsMBUR1bW15MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwHhcNMTMx +MDIxMTkyNDIzWhcNMTgwOTI1MTkyNDIzWjBmMQswCQYDVQQGEwJVUzEOMAwGA1UE +CAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEOMAwGA1UE +CwwFRHVtbXkxFzAVBgNVBAMMDkR1bW15IChjbGllbnQpMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA4J/+eKqsjK0QS+cSDa5Fh4XM4THy812JkWMySA5r +bFxHZ5ye36/IuwyRQ0Yn2DvhhsDR5K7yz8K+Yfp9A6WRBkyHK/sy/8vurQHeDH3y +lLtHCLi5nfyt2fDxWOYwFrS1giGn2IxJIHBAWu4cBODCkqwqAp92+Lqp3Sn+D+Fb +maHEU3LHua8OIJiSeAIHo/jPqfHFqZxK1bXhGCSQKvUZCaTftsqDtn+LZSElqj1y +5/cnc7XGsTf8ml/+FDMX1aSAHf+pu+UAp9JqOXOM60A5JIpYu3Lsejp1RppyPJYP +zC4nSN8R2LOdDChP2MB7f1/sXRGlLM/X3Vi4X+c6xQ85TQIDAQABMA0GCSqGSIb3 +DQEBBQUAA4IBAQAMWt9qMUOY5z1uyYcjUnconPHLM9MADCZI2sRbfdBOBHEnTVKv +Y63SWnCt8TRJb01LKLIEys6pW1NUlxr6b+FwicNmycR0L8b63cmNXg2NmSZsnK9C +fGT6BbbDdVPYjvmghpSd3soBGBLPsJvaFc6UL5tunm+hT7PxWjDxHZEiE18PTs05 +Vpp/ytILzhoXvJeFOWQHIdf4DLR5izGMNTKdQzgg1eBq2vKgjJIlEZ3j/AyHkJLE +qFip1tyc0PRzgKYFLWttaZzakCLJOGuxtvYB+GrixVM7U23p5LQbLE0KX7fe2Gql +xKMfSID5NUDNf1SuSrrGLD3gfnJEKVB8TVBk +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem new file mode 100644 index 00000000..7665fb65 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEA4J/+eKqsjK0QS+cSDa5Fh4XM4THy812JkWMySA5rbFxHZ5ye +36/IuwyRQ0Yn2DvhhsDR5K7yz8K+Yfp9A6WRBkyHK/sy/8vurQHeDH3ylLtHCLi5 +nfyt2fDxWOYwFrS1giGn2IxJIHBAWu4cBODCkqwqAp92+Lqp3Sn+D+FbmaHEU3LH +ua8OIJiSeAIHo/jPqfHFqZxK1bXhGCSQKvUZCaTftsqDtn+LZSElqj1y5/cnc7XG +sTf8ml/+FDMX1aSAHf+pu+UAp9JqOXOM60A5JIpYu3Lsejp1RppyPJYPzC4nSN8R +2LOdDChP2MB7f1/sXRGlLM/X3Vi4X+c6xQ85TQIDAQABAoIBABosCiZdHIW3lHKD +leLqL0e/G0QR4dDhUSoTeMRUiceyaM91vD0r6iOBL1u7TOEw+PIOfWY7zCbQ9gXM +fcxy+hbVy9ogBq0vQbv+v7SM6DrUJ06o11fFHSyLmlNVXr0GiS+EZF4i2lJhQd5W +aAVZetJEJRDxK5eHiEswnV2UUGvx6VCpFILL0JVGxWY7oOPxiiBLl+cmfRZdTfGx +46VzQvBu7N8hGpCIsljuVFP/DxR7c+2oyrtFaFSMZBMNI8fICgkb2QeLk/XUBXtn +0bDttgmOP/BvnNAor7nIRoeer/7kbXc9jOsgXwnvDKPapltQddL+exycXzbIjLuY +Z2SFsDECgYEA+2A4QGV0biqdICAoKCHCHCU/CrdDUQiQDHqRU6/nhka7MFPSl4Wy +9oISRrYZhKIbSbaXwTW5ZcYq8Hpn/yGYIWlINP9sjprnOWPE7L74lac+PFWXNMUI +jNJOJkLK1IeppByXAt5ekGBrG556bhzRCJsTjYsyUR/r/bMEF1FD8WMCgYEA5MHM +hqmkDK5CbklVaPonNc251Lx+HSzzQ40WExC/PrCczRaZMKlhmyKZfWJCInQsUDln +w6Lqa5UnwZV2HYAF30VZYQsq84ulNnx1/36BEZyIimfAL1WHvKeGWjGsZqniXxxb +Os5wEMAvxk0SWVrR5v6YpBDv3t9+lLg/bzBOAY8CgYEAuZ0q7CH9/vroWrhj7n4+ +3pmCG1+HDWbNNumqNalFxBimT+EVN1058FvLMvtzjERG8f8pvzj0VPom6rr336Pm +uYUMFFYmyoYHBpFs74Nz+s0rX1Gz/PsgfRstKYNYUeZ6lPunZi7clK8dZ591t6j/ +kOMxZOrLlKuFjieJdc5D5RECgYAVTzxXOwxOJhmIHoq3Sb5HU8/A0oJJA3vxyf3J +buDx3Q/uRvGkR9MQ2YtE09dnUD0kiARzhASkWvOmI98p5lglsVcfJCQvJc4RIkz3 +rPgnBNbvVbTgc+4+E7j/Q+tUcPTmeUTCWKK13MFWjq1r53rwMr1TY0SFFXq8LeGy +4OQTXwKBgQDCuPN3Q+EJusYy7TXt0WicY/xyu15s1216N7PmRKFr/WAn2JdAfjbD +JKDwVqo0AQiEDAobJk0JMPs+ENK2d58GsybCK4QGAh6z5FGunb5T432YfnoXtL3J +ZKVvkf7eowvokTIeiDf3XrCPajLDBpo88Xax+RH03US7XRdu/fVzMA== +-----END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem new file mode 100644 index 00000000..6b2658ae --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDWDCCAkCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO +MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy +M1oXDTE4MDkyNTE5MjQyM1owbTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 +MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 +MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDPfZIHpVYbb0zzNMISwjRiO2mqpgzGcFuTvNxBmGGH +YTa+jAjdMakzdtNmPndgHu2e4eXvvxeRrAxjBwGrMGe8FqYvefBhjHktPJhgdGHE +X2BEhXGSncx7FDl0qkT5n672x43DAUdTJKx7ovbFfWU3QAsgyNQUzfj0V+ojcPTj +mSscmmc37ZPHp3yGkPeu/G9LGNzV6/NoM9Z4FNHKpwZ9dTT2wNQVGyEreNl2JKXw +xhPIHkrIync0Tvj6SV9s4WaoZfCMvEQgA6yvSmGlOUhRG8vYIilgJ0dC/L9qd2VY +CSCCHNEWXloY6plhjpOUJzAg3UQDUEO07KMP7pFp17FbAgMBAAGjEDAOMAwGA1Ud +EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADmgjS9oIh1PPtvxmykgdyP4ITQX +hACIqD6hTYSUkJYC5mq0IFGgZiA4BRiqKj6aUGCv60pwrJtZMNUXFJy0kWobw0WK +3c0vxsWM/tB2IGOkl9vjKo7BPci2Bi1JetmK3hbqXV/7QXkNj9IjANm5b5NFu3QX +6mtyEwGG/o1+jydxdqk3bWyQWj/ZbU1spGR66oLJh+5q0G4wBX8ZHRkxqZrOIYTa +R8egZhLofldpXZwk5UY8vzf2iMOxQt47ge31ruIjnsKJoedcHUkP7a5VYA5OTOmK +ZOauxdGZp3BMfl1TrIgsDwshlBoy+aHMHmeYa7bpsblLRgKxZclJg4C9uXA= +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem new file mode 100644 index 00000000..74773609 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAz32SB6VWG29M8zTCEsI0YjtpqqYMxnBbk7zcQZhhh2E2vowI +3TGpM3bTZj53YB7tnuHl778XkawMYwcBqzBnvBamL3nwYYx5LTyYYHRhxF9gRIVx +kp3MexQ5dKpE+Z+u9seNwwFHUySse6L2xX1lN0ALIMjUFM349FfqI3D045krHJpn +N+2Tx6d8hpD3rvxvSxjc1evzaDPWeBTRyqcGfXU09sDUFRshK3jZdiSl8MYTyB5K +yMp3NE74+klfbOFmqGXwjLxEIAOsr0phpTlIURvL2CIpYCdHQvy/andlWAkgghzR +Fl5aGOqZYY6TlCcwIN1EA1BDtOyjD+6RadexWwIDAQABAoIBAEs6OsS85DBENUEE +QszsTnPDGLd/Rqh3uiwhUDYUGmAsFd4WBWy1AaSgE1tBkKRv8jUlr+kxfkkZeNA6 +jRdVEHc4Ov6Blm63sIN/Mbve1keNUOjm/NtsjOOe3In45dMfWx8sELC/+O0jIcod +tpy5rwXOGXrEdWgpmXZ1nXVGEfOmQH3eGEPkqbY1I4YlAoXD0mc5fNQQrn7qrogH +M5USCnC44yIIF0Yube2Fg0Cem41vzIvENAlZC273gyW+pQwez0uma2LaCWmkEz1N +sESrNSQ4yeQnDQYlgX2w3RRpqql4GDzAdISL2WJcNhW6KJ72B0SQ1ny/TmQgZePG +Ojv1T0ECgYEA9CXqKyXBSPF+Wdc/fNagrIi6tcNkLAN2/p5J3Z6TtbZGjItoMlDX +c+hwHobcI3GZLMlxlBx7ePc7cKgaMDXrl8BZZjFoyEV9OHOLicfNkLFmBIZ14gtX +bGZYDuCcal46r7IKRjT8lcYWCoLJnI9vLEII7Q7P/eBgcntw3+h/ziECgYEA2ZAa +bp9d0xBaOXq/E341guxNG49R09/DeZ/2CEM+V1pMD8OVH9cvxrBdDLUmAnrqeGTh +Djoi1UEbOVAV6/dXbTQHrla+HF4Uq+t9tV+mt68TEa54PQ/ERt5ih3nZGBiqZ6rX +SGeyZmIXMLIZEs2dIbJ2DmLcZj6Tjxkd/PxPt/sCgYBGczZaEv/uK3k5NWplfI1K +m/28e1BJfwp0OHq6D4sx8RH0djmv4zH4iUbpGCMnuxznFo3Gnl1mr3igbnF4HecI +mAF0AqfoulyC0JygOl5v9TCp957Ghl1Is1OPn3KjIuOuVSKv1ZRZJ5qul8TTf3Qm +AjwPI6oS6Q8LmeEdSzqt4QKBgB5MglHboe5t/ZK5tHibgApOrGJlMEkohYmfrFz0 +OG9j5OnhHBiGGGI8V4kYhUWdJqBDtFAN6qH2Yjs2Gwd0t9k+gL9X1zwOIiTbM/OZ +cZdtK2Ov/5DJbFVOTTx+zKwda0Xqtfagcmjtyjr+4p0Kw5JYzzYrsHQQzO4F2nZM +ETIXAoGADskTzhgpPrC5/qfuLY4gBUtCfYIb8kaKN90AT8A/14lBrT4lSnmsEvKP +tRDmFjnc/ogDlHa5SRDijtT6UoyQPuauAt6DYrJ8G6qKJqiMwJcuLV1XFks7z1J8 +VzB8kso1pPAtcvVXBPklsjvZ10NdQOCqm4N3EVp69agbB1oco4I= +-----END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt new file mode 100644 index 00000000..b8535e88 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC8DCCAlmgAwIBAgIJAOD63PlXjJi8MA0GCSqGSIb3DQEBBQUAMIGQMQswCQYD +VQQGEwJHQjEXMBUGA1UECAwOVW5pdGVkIEtpbmdkb20xDjAMBgNVBAcMBURlcmJ5 +MRIwEAYDVQQKDAlNb3NxdWl0dG8xCzAJBgNVBAsMAkNBMRYwFAYDVQQDDA1tb3Nx +dWl0dG8ub3JnMR8wHQYJKoZIhvcNAQkBFhByb2dlckBhdGNob28ub3JnMB4XDTEy +MDYyOTIyMTE1OVoXDTIyMDYyNzIyMTE1OVowgZAxCzAJBgNVBAYTAkdCMRcwFQYD +VQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwGA1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1v +c3F1aXR0bzELMAkGA1UECwwCQ0ExFjAUBgNVBAMMDW1vc3F1aXR0by5vcmcxHzAd +BgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hvby5vcmcwgZ8wDQYJKoZIhvcNAQEBBQAD +gY0AMIGJAoGBAMYkLmX7SqOT/jJCZoQ1NWdCrr/pq47m3xxyXcI+FLEmwbE3R9vM +rE6sRbP2S89pfrCt7iuITXPKycpUcIU0mtcT1OqxGBV2lb6RaOT2gC5pxyGaFJ+h +A+GIbdYKO3JprPxSBoRponZJvDGEZuM3N7p3S/lRoi7G5wG5mvUmaE5RAgMBAAGj +UDBOMB0GA1UdDgQWBBTad2QneVztIPQzRRGj6ZHKqJTv5jAfBgNVHSMEGDAWgBTa +d2QneVztIPQzRRGj6ZHKqJTv5jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA +A4GBAAqw1rK4NlRUCUBLhEFUQasjP7xfFqlVbE2cRy0Rs4o3KS0JwzQVBwG85xge +REyPOFdGdhBY2P1FNRy0MDr6xr+D2ZOwxs63dG1nnAnWZg7qwoLgpZ4fESPD3PkA +1ZgKJc2zbSQ9fCPxt2W3mdVav66c6fsb7els2W2Iz7gERJSX +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem new file mode 100644 index 00000000..1ddb0d49 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDizCCAnOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO +MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy +M1oXDTE4MDkyNTE5MjQyM1owYDELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 +MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 +MREwDwYDVQQDDAhEdW1teSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMLR0DHck8OtiA34k/7MqgQdharDu72HBPBCZxQ0SlaUK7/Qa3IwODk1IIzj +fmWCsH4+HfEYgrfWGVlD7YG+61FE/HeeN63hoBi5S1l5kIGk5FIv/OL/mBBe1ROa +FmIa4MurHa7a0UDUl7Hm4/GXLCpSc6vQohXzHpqwZ9BiZ0t0sLuP754yakwnToJ8 +FmbOBumj2TZP9D68gACTwcoxzwNo1OWLOEW2GzWwwOlKYnWDAaq5wQvA7pfAcyPN +NOy7PJU1yC1p/4bYH8gEfhjeYsJLN8aqjgO/Kw2XICp1R+yYKTxkUu+Ri2MPavjC +nQhqYWhvZJpWsgq8e1k9f/26EksCAwEAAaNQME4wHQYDVR0OBBYEFFu7Po4tkK2u +WAf/UwAYmP9EhEy6MB8GA1UdIwQYMBaAFFu7Po4tkK2uWAf/UwAYmP9EhEy6MAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADyJC71JEKYa9ipLXwI97vMZ +T8kQeZwB74giPQNbGhRGtn+br6WZGtTUm9Zvwf6Wj5qeR0K07iFWasSSOGyBzY4x +Q4Z8lxWQgNgh8Ea+Ki/ylgeFdKj6G3iPgMFevNkGwjOejvkI3UN7b1oiZ0Z4XftK +TsLGKZQXU6bFqdZnBk8H79pbRSGDyzGy3NysExmYP5hfLLS02tRD16kabrbPvoWo +gB+KwZWKg6Sv0iNKthiHTigxNgMsv+SetnX9xGjtTdWo+qWBExccQ2cCHNDmAG6L +E+ZgH7pAeJMlyllaccxY1FJjHbM8zjfxiXj8E/qz6iKvF2iKoVlX9RpJbrn2X7M= +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem new file mode 100644 index 00000000..27828768 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAwtHQMdyTw62IDfiT/syqBB2FqsO7vYcE8EJnFDRKVpQrv9Br +cjA4OTUgjON+ZYKwfj4d8RiCt9YZWUPtgb7rUUT8d543reGgGLlLWXmQgaTkUi/8 +4v+YEF7VE5oWYhrgy6sdrtrRQNSXsebj8ZcsKlJzq9CiFfMemrBn0GJnS3Swu4/v +njJqTCdOgnwWZs4G6aPZNk/0PryAAJPByjHPA2jU5Ys4RbYbNbDA6UpidYMBqrnB +C8Dul8BzI8007Ls8lTXILWn/htgfyAR+GN5iwks3xqqOA78rDZcgKnVH7JgpPGRS +75GLYw9q+MKdCGphaG9kmlayCrx7WT1//boSSwIDAQABAoIBAGphOzge5Cjzdtl6 +JQX7J9M7c6O9YaSqN44iFDs6GmWQXxtMaX9eyTSjx/RmvLwdUtZ8gMkHw0kzBYBy +0RwJ7mDgNKP0px6xl0Qo2fYvpTLFoU8nmQUy4AwAXIVpnFNRrfJIq9qw7ZZi/7pL +A6kGDT3G7Bajw/4MVWfOb8GgGhte1ZhZgXFEZNjGkhwi3Na1/6slOQIfnkkhco0X +ru1Cw82nXNPHqu6K+pbHP9ucYdUNZWRh+yQS3p92lr5tB3/IL/lD0Cl3+xP8JFl+ +5NMSISOKGb3ld0rzrJd1ncgLgv/XlHu8DqvcFs9QwXbaUlG0U/0GrorGYqFaZYaH +R1rkZjECgYEA9mAarVAeL7IOeEIg28f/qyp//5+pMzRpVhnI+xscHB5QUO9WH+uE +nOXwcGvcRME134H4o/0j75aMhVs7sGfMOQ+enAwOxRC5h4MCClDSWysWftU8Ihhf +Sm6eZ0kYLZNqXt/TxTs124NiF1Bb5pekzEr9fTj//vP4meuAQ/D0JoUCgYEAym4f +BCm5tLwYYxZM4tko0g9BHxy4aAPfyshuLed1JjkK4JCFp368GBoknj5rUNewTun2 +1zkQF9b5Mi3k5qWkboP5rpp7DuG3PJdWypV6b/btUeqcyG1gteQwTAwebfqeM0vH +QvpuAoRMtEcSBQBl2s9zgmObXUpDlLwuIlL+to8CgYEAyJBtxx8Mo9k4jE+Q/jnu ++QFtF8R68jM9eRkeksR7+qv2yBw+KVgKKcvKE0rLErGS0LO2nJELexQ8qqcdjTrC +dsUvYmsybtxxnE5bD9jBlfQaqP+fp0Xd9PLeQsivRRLXqgpeFBZifqOS69XAKpTS +VHjLqPAI/hzQCUU8spJpvx0CgYAePgt2NMGgxcUi8I72CRl3IH5LJqBKMeH6Sq1j +QEQZPMZqPE0rc9yoASfdWFfyEPcvIvcUulq0JRK/s2mSJ8cEF8Vyl3OxCnm0nKuD +woczOQHFjjZ0HxsmsXuhsOHO7nU6FqUjVYSf7aIEAOYpRyDwarPIFBd+/XxROTfv +OtUA8wKBgAOiGXRxycb4rAtJBDqPAgdAAwNgvQHyVgn32ArWtgu8ermuZW5h1y45 +hULFvCbLSCpo+I7QhRhw4y2DoB1DgIw04BeFUIcE+az7HH3euAyCLQ0caaA8Xk/6 +bpPfUMe1SNi51f345QlOPvvwGllTC6DeBhZ730k7VNB32dOCV3kE +-----END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem new file mode 100644 index 00000000..f3de3caa --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDYTCCAkmgAwIBAgIBATANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJVUzEO +MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO +MAwGA1UECwwFRHVtbXkxHjAcBgNVBAMMFUR1bW15IEludGVybWVkaWF0ZSBDQTAe +Fw0xMzEwMjExOTI0MjNaFw0xODA5MjUxOTI0MjNaMGYxCzAJBgNVBAYTAlVTMQ4w +DAYDVQQIDAVEdW1teTEOMAwGA1UEBwwFRHVtbXkxDjAMBgNVBAoMBUR1bW15MQ4w +DAYDVQQLDAVEdW1teTEXMBUGA1UEAwwORHVtbXkgKHNlcnZlcikwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0fQCRUWXt+i7JMR55Zuo6wBRxG7RnPutN +2L7J/18io52vxjm8AZDiC0JFkCHh72ZzvbgVA+e+WxAIYfioRis4JWw4jK8v5m8q +cZzS0GJNTMROPiZQi7A81tAbrV00XN7d5PsmIJ2Bf4XbJWMy31CsmoFloeRMd7bR +LxwDIb0qqRawhKsWdfZB/c9wGKmHlei50B7PXk+koKnVdsLwXxtCZDvc/3fNRHEK +lZs4m0N05G38FdrnczPm/0pie87nK9rnklL7u1sYOukOznnOtW5h7+A4M+DxzME0 +HRU6k4d+6QvukxBlsE93gHhwRsejIuDGlqD+DRxk2PdmmgsmPH59AgMBAAGjEzAR +MA8GA1UdEQQIMAaHBAoKBOQwDQYJKoZIhvcNAQEFBQADggEBAJ3bKs2b4cAJWTZj +69dMEfYZKcQIXs7euwtKlP7H8m5c+X5KmZPi1Puq4Z0gtvLu/z7J9UjZjG0CoylV +q15Zp5svryJ7XzcsZs7rwyo1JtngW1z54wr9MezqIOF2w12dTwEAINFsW7TxAsH7 +bfqkzZjuCbbsww5q4eHuZp0yaMHc3hOGaUot27OTlxlIMhv7VBBqWAj0jmvAfTKf +la0SiL/Mc8rD8D5C0SXGcCL6li/kqtinAxzhokuyyPf+hQX35kcZxEPu6WxtYVLv +hMzrokOZP2FrGbCnhaNT8gw4Aa0RXV1JgonRWYSbkeaCzvr2bJ0OuJiDdwdRKvOo +raKLlfY= +-----END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem new file mode 100644 index 00000000..951ad0ef --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAtH0AkVFl7fouyTEeeWbqOsAUcRu0Zz7rTdi+yf9fIqOdr8Y5 +vAGQ4gtCRZAh4e9mc724FQPnvlsQCGH4qEYrOCVsOIyvL+ZvKnGc0tBiTUzETj4m +UIuwPNbQG61dNFze3eT7JiCdgX+F2yVjMt9QrJqBZaHkTHe20S8cAyG9KqkWsISr +FnX2Qf3PcBiph5XoudAez15PpKCp1XbC8F8bQmQ73P93zURxCpWbOJtDdORt/BXa +53Mz5v9KYnvO5yva55JS+7tbGDrpDs55zrVuYe/gODPg8czBNB0VOpOHfukL7pMQ +ZbBPd4B4cEbHoyLgxpag/g0cZNj3ZpoLJjx+fQIDAQABAoIBAG0UfxtUTn4dDdma +TgihIj6Ph8s0Kzua0yshK215YU3WBJ8O9iWh7KYwl8Ti7xdVUF3y8yYATjbFYlMu +otFQVx5/v4ANxnL0mYrVTyo5tq9xDdMbzJwxUDn0uaGAjSvwVOFWWlMYsxhoscVY +OzOrs14dosaBqTBtyZdzGULrSSBWPCBlucRcvTV/eZwgYrYJ3bG66ZTfdc930KPj +nfkWrsAWmPz8irHoWQ2OX+ZJTprVYRYIZXqpFn3zuwmhpJkZUVULMMk6LFBKDmBT +F2+b4h49P+oNJ+6CRoOERHYq2k1MmYBcu1z8lMjdfRGUDdK4vS9pcqhBXJJg1vU9 +APRtfiECgYEA6Y3LqQJLkUI0w6g/9T+XyzUoi0aUfH6PT81XnGYqJxTBHinZvgML +mF3qtZ0bHGwEoAsyhSgDkeCawE/E7Phd+B6aku2QMVm8GHygZg0Pbao4cxXv+CF3 +i1Lo7n3zY0kTVrjsvDRsDDESmRK4Ea48fJwOfUEtfG6VDtwmZAe8chcCgYEAxdWd +sWcc45ARi2vY6yb5Ysgt/g0z26KyQydF+GMWIz1FDfUxXJ/axdCovd3VIHDvItJE +n9LjFiobkyOKX99ou1foWwsmhn11duVrF7hsVrE0nsbd4RX3sTbqXa9x3GN/ujFr +0xHUTmiXt3Qyn/076jBiLGnbtzSxJ/IZIEI9VIsCgYEAketHnTaT5BOLR9ss6ptq +yUlTJYFZcFbaTy+qV0r1dyleZuwa4L6iVfYHmKSptZ4/XYbhb5RKdq/vv8uW679Z +ZpYoWTgX6N15yYrD5D6wrwG09yJzpYGzYNbSNX93u0aC0KIFNqlCAHQAfKbXXiSQ +IgKWgudf9ehZNMmTKtgygs0CgYAoTV9Fr7Lj7QqV84+KQDNX2137PmdNHDTil1Ka +ylzNKwMxV70JmIsx91MY8uMjK76bwmg2gvi+IC/j5r6ez11/pOXx/jCH/3D5mr0Z +ZPm1I36LxgmXfCkskfpmwYIZmq9/l+fWZPByVL5roiFaFHWrPNYTJDGdff+FGr3h +o3zpBwKBgDY1sih/nY+6rwOP+DcabGK9KFFKLXsoJrXobEniLxp7oFaGN2GkmKvN +NajCs5pr3wfb4LrVrsNvERnUsUXWg6ReLqfWbT4bmjzE2iJ3IbtVQ5M4kl6YrbdZ +PMgWoLCqnoo8NoGBtmVMWhaXNJvVZPgZHk33T5F0Cg6PKNdHDchH +-----END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go new file mode 100644 index 00000000..2fdcb407 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package main + +import ( + "bufio" + "crypto/tls" + "flag" + "fmt" + "io" + //"log" + "os" + "strconv" + "time" + + MQTT "github.com/eclipse/paho.mqtt.golang" +) + +func main() { + //MQTT.DEBUG = log.New(os.Stdout, "", 0) + //MQTT.ERROR = log.New(os.Stdout, "", 0) + stdin := bufio.NewReader(os.Stdin) + hostname, _ := os.Hostname() + + server := flag.String("server", "tcp://127.0.0.1:1883", "The full URL of the MQTT server to connect to") + topic := flag.String("topic", hostname, "Topic to publish the messages on") + qos := flag.Int("qos", 0, "The QoS to send the messages at") + retained := flag.Bool("retained", false, "Are the messages sent with the retained flag") + clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection") + username := flag.String("username", "", "A username to authenticate to the MQTT server") + password := flag.String("password", "", "Password to match username") + flag.Parse() + + connOpts := MQTT.NewClientOptions().AddBroker(*server).SetClientID(*clientid).SetCleanSession(true) + if *username != "" { + connOpts.SetUsername(*username) + if *password != "" { + connOpts.SetPassword(*password) + } + } + tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert} + connOpts.SetTLSConfig(tlsConfig) + + client := MQTT.NewClient(connOpts) + if token := client.Connect(); token.Wait() && token.Error() != nil { + fmt.Println(token.Error()) + return + } + fmt.Printf("Connected to %s\n", *server) + + for { + message, err := stdin.ReadString('\n') + if err == io.EOF { + os.Exit(0) + } + client.Publish(*topic, byte(*qos), *retained, message) + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go new file mode 100644 index 00000000..235b477a --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package main + +import ( + "crypto/tls" + "flag" + "fmt" + //"log" + "os" + "os/signal" + "strconv" + "syscall" + "time" + + MQTT "github.com/eclipse/paho.mqtt.golang" +) + +func onMessageReceived(client MQTT.Client, message MQTT.Message) { + fmt.Printf("Received message on topic: %s\nMessage: %s\n", message.Topic(), message.Payload()) +} + +var i int64 + +func main() { + //MQTT.DEBUG = log.New(os.Stdout, "", 0) + //MQTT.ERROR = log.New(os.Stdout, "", 0) + c := make(chan os.Signal, 1) + i = 0 + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + go func() { + <-c + fmt.Println("signal received, exiting") + os.Exit(0) + }() + + hostname, _ := os.Hostname() + + server := flag.String("server", "tcp://127.0.0.1:1883", "The full url of the MQTT server to connect to ex: tcp://127.0.0.1:1883") + topic := flag.String("topic", "#", "Topic to subscribe to") + qos := flag.Int("qos", 0, "The QoS to subscribe to messages at") + clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection") + username := flag.String("username", "", "A username to authenticate to the MQTT server") + password := flag.String("password", "", "Password to match username") + flag.Parse() + + connOpts := &MQTT.ClientOptions{ + ClientID: *clientid, + CleanSession: true, + Username: *username, + Password: *password, + MaxReconnectInterval: 1 * time.Second, + KeepAlive: 30 * time.Second, + TLSConfig: tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert}, + } + connOpts.AddBroker(*server) + connOpts.OnConnect = func(c MQTT.Client) { + if token := c.Subscribe(*topic, byte(*qos), onMessageReceived); token.Wait() && token.Error() != nil { + panic(token.Error()) + } + } + + client := MQTT.NewClient(connOpts) + if token := client.Connect(); token.Wait() && token.Error() != nil { + panic(token.Error()) + } else { + fmt.Printf("Connected to %s\n", *server) + } + + for { + time.Sleep(1 * time.Second) + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go new file mode 100644 index 00000000..01f5fafd --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +type component string + +// Component names for debug output +const ( + NET component = "[net] " + PNG component = "[pinger] " + CLI component = "[client] " + DEC component = "[decode] " + MES component = "[message] " + STR component = "[store] " + MID component = "[msgids] " + TST component = "[test] " + STA component = "[state] " + ERR component = "[error] " +) diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 new file mode 100644 index 00000000..cf989f14 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 @@ -0,0 +1,15 @@ + +Eclipse Distribution License - v 1.0 + +Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 new file mode 100644 index 00000000..79e486c3 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 @@ -0,0 +1,70 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and +b) in the case of each subsequent Contributor: +i) changes to the Program, and +ii) additions to the Program; +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and +b) its license agreement: +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and +b) a copy of this Agreement must be included with each copy of the Program. +Contributors may not remove or alter any copyright notices contained within the Program. + +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go new file mode 100644 index 00000000..daf3a9e4 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "io/ioutil" + "os" + "path" + "sync" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +const ( + msgExt = ".msg" + tmpExt = ".tmp" + corruptExt = ".CORRUPT" +) + +// FileStore implements the store interface using the filesystem to provide +// true persistence, even across client failure. This is designed to use a +// single directory per running client. If you are running multiple clients +// on the same filesystem, you will need to be careful to specify unique +// store directories for each. +type FileStore struct { + sync.RWMutex + directory string + opened bool +} + +// NewFileStore will create a new FileStore which stores its messages in the +// directory provided. +func NewFileStore(directory string) *FileStore { + store := &FileStore{ + directory: directory, + opened: false, + } + return store +} + +// Open will allow the FileStore to be used. +func (store *FileStore) Open() { + store.Lock() + defer store.Unlock() + // if no store directory was specified in ClientOpts, by default use the + // current working directory + if store.directory == "" { + store.directory, _ = os.Getwd() + } + + // if store dir exists, great, otherwise, create it + if !exists(store.directory) { + perms := os.FileMode(0770) + merr := os.MkdirAll(store.directory, perms) + chkerr(merr) + } + store.opened = true + DEBUG.Println(STR, "store is opened at", store.directory) +} + +// Close will disallow the FileStore from being used. +func (store *FileStore) Close() { + store.Lock() + defer store.Unlock() + store.opened = false + DEBUG.Println(STR, "store is closed") +} + +// Put will put a message into the store, associated with the provided +// key value. +func (store *FileStore) Put(key string, m packets.ControlPacket) { + store.Lock() + defer store.Unlock() + if !store.opened { + ERROR.Println(STR, "Trying to use file store, but not open") + return + } + full := fullpath(store.directory, key) + write(store.directory, key, m) + if !exists(full) { + ERROR.Println(STR, "file not created:", full) + } +} + +// Get will retrieve a message from the store, the one associated with +// the provided key value. +func (store *FileStore) Get(key string) packets.ControlPacket { + store.RLock() + defer store.RUnlock() + if !store.opened { + ERROR.Println(STR, "Trying to use file store, but not open") + return nil + } + filepath := fullpath(store.directory, key) + if !exists(filepath) { + return nil + } + mfile, oerr := os.Open(filepath) + chkerr(oerr) + msg, rerr := packets.ReadPacket(mfile) + chkerr(mfile.Close()) + + // Message was unreadable, return nil + if rerr != nil { + newpath := corruptpath(store.directory, key) + WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath) + os.Rename(filepath, newpath) + return nil + } + return msg +} + +// All will provide a list of all of the keys associated with messages +// currenly residing in the FileStore. +func (store *FileStore) All() []string { + store.RLock() + defer store.RUnlock() + return store.all() +} + +// Del will remove the persisted message associated with the provided +// key from the FileStore. +func (store *FileStore) Del(key string) { + store.Lock() + defer store.Unlock() + store.del(key) +} + +// Reset will remove all persisted messages from the FileStore. +func (store *FileStore) Reset() { + store.Lock() + defer store.Unlock() + WARN.Println(STR, "FileStore Reset") + for _, key := range store.all() { + store.del(key) + } +} + +// lockless +func (store *FileStore) all() []string { + if !store.opened { + ERROR.Println(STR, "Trying to use file store, but not open") + return nil + } + keys := []string{} + files, rderr := ioutil.ReadDir(store.directory) + chkerr(rderr) + for _, f := range files { + DEBUG.Println(STR, "file in All():", f.Name()) + name := f.Name() + if name[len(name)-4:len(name)] != msgExt { + DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name) + continue + } + key := name[0 : len(name)-4] // remove file extension + keys = append(keys, key) + } + return keys +} + +// lockless +func (store *FileStore) del(key string) { + if !store.opened { + ERROR.Println(STR, "Trying to use file store, but not open") + return + } + DEBUG.Println(STR, "store del filepath:", store.directory) + DEBUG.Println(STR, "store delete key:", key) + filepath := fullpath(store.directory, key) + DEBUG.Println(STR, "path of deletion:", filepath) + if !exists(filepath) { + WARN.Println(STR, "store could not delete key:", key) + return + } + rerr := os.Remove(filepath) + chkerr(rerr) + DEBUG.Println(STR, "del msg:", key) + if exists(filepath) { + ERROR.Println(STR, "file not deleted:", filepath) + } +} + +func fullpath(store string, key string) string { + p := path.Join(store, key+msgExt) + return p +} + +func tmppath(store string, key string) string { + p := path.Join(store, key+tmpExt) + return p +} + +func corruptpath(store string, key string) string { + p := path.Join(store, key+corruptExt) + return p +} + +// create file called "X.[messageid].tmp" located in the store +// the contents of the file is the bytes of the message, then +// rename it to "X.[messageid].msg", overwriting any existing +// message with the same id +// X will be 'i' for inbound messages, and O for outbound messages +func write(store, key string, m packets.ControlPacket) { + temppath := tmppath(store, key) + f, err := os.Create(temppath) + chkerr(err) + werr := m.Write(f) + chkerr(werr) + cerr := f.Close() + chkerr(cerr) + rerr := os.Rename(temppath, fullpath(store, key)) + chkerr(rerr) +} + +func exists(file string) bool { + if _, err := os.Stat(file); err != nil { + if os.IsNotExist(err) { + return false + } + chkerr(err) + } + return true +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md new file mode 100644 index 00000000..17790426 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md @@ -0,0 +1,74 @@ +FVT Instructions +================ + +The FVT tests are currenly only supported by [IBM MessageSight](http://www-03.ibm.com/software/products/us/en/messagesight/). + +Support for [mosquitto](http://mosquitto.org/) and [IBM Really Small Message Broker](https://www.ibm.com/developerworks/community/groups/service/html/communityview?communityUuid=d5bedadd-e46f-4c97-af89-22d65ffee070) might be added in the future. + + +IBM MessageSight Configuration +------------------------------ + +The IBM MessageSight Virtual Appliance can be downloaded here: +[Download](http://www-933.ibm.com/support/fixcentral/swg/selectFixes?parent=ibm~Other+software&product=ibm/Other+software/MessageSight&function=fixId&fixids=1.0.0.1-IMA-DeveloperImage&includeSupersedes=0 "IBM MessageSight") + +There is a nice blog post about it here: +[Blog](https://www.ibm.com/developerworks/community/blogs/c565c720-fe84-4f63-873f-607d87787327/entry/ibm_messagesight_for_developers_is_here?lang=en "Blog") + + +The virtual appliance must be installed into a virtual machine like +Oracle VirtualBox or VMWare Player. (Follow the instructions that come +with the download). + +Next, copy your authorized keys (basically a file containing the public +rsa key of your own computer) onto the appliance to enable passwordless ssh. + +For example, + + Console> user sshkey add "scp://user@host:~/.ssh/authorized_keys" + +More information can be found in the IBM MessageSight InfoCenter: +[InfoCenter](https://infocenters.hursley.ibm.com/ism/v1/help/index.jsp "InfoCenter") + +Now, execute the script setup_IMA.sh to create the objects necessary +to configure the server for the unit test cases provided. + +For example, + + ./setup_IMA.sh + +You should now be able to view the objects on your server: + + Console> imaserver show Endpoint Name=GoMqttEP1 + Name = GoMqttEP1 + Enabled = True + Port = 17001 + Protocol = MQTT + Interface = all + SecurityProfile = + ConnectionPolicies = GoMqttCP1 + MessagingPolicies = GoMqttMP1 + MaxMessageSize = 1024KB + MessageHub = GoMqttTestHub + Description = + + + +RSMB Configuration +------------------ +Wait for SSL support? + + +Mosquitto Configuration +----------------------- +Launch mosquitto from the fvt directory, specifiying mosquitto.cfg as config file + +``ex: /usr/bin/mosquitto -c ./mosquitto.cfg`` + +Note: Mosquitto requires SSL 1.1 or better, while Go 1.1.2 supports +only SSL v1.0. However, Go 1.2+ supports SSL v1.1 and SSL v1.2. + + +Other Notes +----------- +Go 1.1.2 does not support intermediate certificates, however Go 1.2+ does. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg new file mode 100644 index 00000000..cddb94f3 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg @@ -0,0 +1,17 @@ +allow_anonymous true +allow_duplicate_messages false +connection_messages true +log_dest stdout +log_timestamp true +log_type all +persistence false +bind_address 127.0.0.1 + +listener 17001 +listener 17002 +listener 17003 +listener 17004 + +#capath ../samples/samplecerts +#certfile ../samples/samplecerts/server-crt.pem +#keyfile ../samples/samplecerts/server-key.pem diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg new file mode 100644 index 00000000..1dd77547 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg @@ -0,0 +1,8 @@ +allow_anonymous false +bind_address 127.0.0.1 +connection_messages true +log_level detail + +listener 17001 +#listener 17003 +#listener 17004 \ No newline at end of file diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh new file mode 100644 index 00000000..6ebdda3c --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +####################################################################### +# This script is for configuring your IBM Messaging Appliance for use # +# as an mqtt test server for testing the go-mqtt open source client. # +# It creates the Policies and Endpoints necessary to test particular # +# features of the client, such as IPv6, SSL, and other things # +# # +# You do not need this script for any other purpose. # +####################################################################### + +# Edit options to match your configuration +IMA_HOST=9.41.55.184 +IMA_USER=admin +HOST=9.41.55.146 +USER=root +CERTDIR=~/GO/src/github.com/shoenig/go-mqtt/samples/samplecerts + +echo 'Configuring your IBM Messaging Appliance for testing go-mqtt' +echo 'IMA_HOST: ' $IMA_HOST + + +function ima { + reply=`ssh $IMA_USER@$IMA_HOST imaserver $@` +} + +function imp { + reply=`ssh $IMA_USER@$IMA_HOST file get $@` +} + +ima create MessageHub Name=GoMqttTestHub + +# Config "1" is a basic, open endpoint, port 17001 +ima create MessagingPolicy \ + Name=GoMqttMP1 \ + Protocol=MQTT \ + ActionList=Publish,Subscribe \ + MaxMessages=100000 \ + DestinationType=Topic \ + Destination=* + +ima create ConnectionPolicy \ + Name=GoMqttCP1 \ + Protocol=MQTT + +ima create Endpoint \ + Name=GoMqttEP1 \ + Protocol=MQTT \ + MessageHub=GoMqttTestHub \ + ConnectionPolicies=GoMqttCP1 \ + MessagingPolicies=GoMqttMP1 \ + Port=17001 + +# Config "2" is IPv6 only , port 17002 + +# Config "3" is for authorization failures, port 17003 +ima create ConnectionPolicy \ + Name=GoMqttCP2 \ + Protocol=MQTT \ + ClientID=GoMqttClient + +ima create Endpoint \ + Name=GoMqttEP3 \ + Protocol=MQTT \ + MessageHub=GoMqttTestHub \ + ConnectionPolicies=GoMqttCP2 \ + MessagingPolicies=GoMqttMP1 \ + Port=17003 + +# Config "4" is secure connections, port 17004 +imp scp://$USER@$HOST:${CERTDIR}/server-crt.pem . +imp scp://$USER@$HOST:${CERTDIR}/server-key.pem . +imp scp://$USER@$HOST:${CERTDIR}/rootCA-crt.pem . +imp scp://$USER@$HOST:${CERTDIR}/intermediateCA-crt.pem . + +ima apply Certificate \ + CertFileName=server-crt.pem \ + "CertFilePassword=" \ + KeyFileName=server-key.pem \ + "KeyFilePassword=" + +ima create CertificateProfile \ + Name=GoMqttCertProf \ + Certificate=server-crt.pem \ + Key=server-key.pem + +ima create SecurityProfile \ + Name=GoMqttSecProf \ + MinimumProtocolMethod=SSLv3 \ + UseClientCertificate=True \ + UsePasswordAuthentication=False \ + Ciphers=Fast \ + CertificateProfile=GoMqttCertProf + +ima apply Certificate \ + TrustedCertificate=rootCA-crt.pem \ + SecurityProfileName=GoMqttSecProf + +ima apply Certificate \ + TrustedCertificate=intermediateCA-crt.pem \ + SecurityProfileName=GoMqttSecProf + +ima create Endpoint \ + Name=GoMqttEP4 \ + Port=17004 \ + MessageHub=GoMqttTestHub \ + ConnectionPolicies=GoMqttCP1 \ + MessagingPolicies=GoMqttMP1 \ + SecurityProfile=GoMqttSecProf \ + Protocol=MQTT + diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go new file mode 100644 index 00000000..9cf46cd1 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go @@ -0,0 +1,1041 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "fmt" + "io/ioutil" + "testing" + "time" +) + +func Test_Start(t *testing.T) { + ops := NewClientOptions().SetClientID("Start").AddBroker(FVTTCP) + c := NewClient(ops) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.Disconnect(250) +} + +/* uncomment this if you have connection policy disallowing FailClientID +func Test_InvalidConnRc(t *testing.T) { + ops := NewClientOptions().SetClientID("FailClientID"). + AddBroker("tcp://" + FVT_IP + ":17003"). + SetStore(NewFileStore("/tmp/fvt/InvalidConnRc")) + + c := NewClient(ops) + _, err := c.Connect() + if err != ErrNotAuthorized { + t.Fatalf("Did not receive error as expected, got %v", err) + } + c.Disconnect(250) +} +*/ + +// Helper function for Test_Start_Ssl +func NewTLSConfig() *tls.Config { + certpool := x509.NewCertPool() + pemCerts, err := ioutil.ReadFile("samples/samplecerts/CAfile.pem") + if err == nil { + certpool.AppendCertsFromPEM(pemCerts) + } + + cert, err := tls.LoadX509KeyPair("samples/samplecerts/client-crt.pem", "samples/samplecerts/client-key.pem") + if err != nil { + panic(err) + } + + return &tls.Config{ + RootCAs: certpool, + ClientAuth: tls.NoClientCert, + ClientCAs: nil, + InsecureSkipVerify: true, + Certificates: []tls.Certificate{cert}, + } +} + +/* uncomment this if you have ssl setup +func Test_Start_Ssl(t *testing.T) { + tlsconfig := NewTlsConfig() + ops := NewClientOptions().SetClientID("StartSsl"). + AddBroker(FVT_SSL). + SetStore(NewFileStore("/tmp/fvt/Start_Ssl")). + SetTlsConfig(tlsconfig) + + c := NewClient(ops) + + _, err := c.Connect() + if err != nil { + t.Fatalf("Error on Client.Connect(): %v", err) + } + + c.Disconnect(250) +} +*/ + +func Test_Publish_1(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("Publish_1") + + c := NewClient(ops) + token := c.Connect() + if token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.Publish("test/Publish", 0, false, "Publish qo0") + + c.Disconnect(250) +} + +func Test_Publish_2(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("Publish_2") + + c := NewClient(ops) + token := c.Connect() + if token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.Publish("/test/Publish", 0, false, "Publish1 qos0") + c.Publish("/test/Publish", 0, false, "Publish2 qos0") + + c.Disconnect(250) +} + +func Test_Publish_3(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("Publish_3") + + c := NewClient(ops) + token := c.Connect() + if token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.Publish("/test/Publish", 0, false, "Publish1 qos0") + c.Publish("/test/Publish", 1, false, "Publish2 qos1") + c.Publish("/test/Publish", 2, false, "Publish2 qos2") + + c.Disconnect(250) +} + +func Test_Subscribe(t *testing.T) { + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("Subscribe_tx") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("Subscribe_rx") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + } + sops.SetDefaultPublishHandler(f) + s := NewClient(sops) + + sToken := s.Connect() + if sToken.Wait() && sToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) + } + + s.Subscribe("/test/sub", 0, nil) + + pToken := p.Connect() + if pToken.Wait() && pToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) + } + + p.Publish("/test/sub", 0, false, "Publish qos0") + + p.Disconnect(250) + s.Disconnect(250) +} + +func Test_Will(t *testing.T) { + willmsgc := make(chan string, 1) + + sops := NewClientOptions().AddBroker(FVTTCP) + sops.SetClientID("will-giver") + sops.SetWill("/wills", "good-byte!", 0, false) + sops.SetConnectionLostHandler(func(client Client, err error) { + fmt.Println("OnConnectionLost!") + }) + sops.SetAutoReconnect(false) + c := NewClient(sops).(*client) + + wops := NewClientOptions() + wops.AddBroker(FVTTCP) + wops.SetClientID("will-subscriber") + wops.SetDefaultPublishHandler(func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + willmsgc <- string(msg.Payload()) + }) + wops.SetAutoReconnect(false) + wsub := NewClient(wops) + + if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) + } + + if wsubToken := wsub.Subscribe("/wills", 0, nil); wsubToken.Wait() && wsubToken.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", wsubToken.Error()) + } + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.forceDisconnect() + + if <-willmsgc != "good-byte!" { + t.Fatalf("will message did not have correct payload") + } + + wsub.Disconnect(250) +} + +func Test_CleanSession(t *testing.T) { + clsnc := make(chan string, 1) + + sops := NewClientOptions().AddBroker(FVTTCP) + sops.SetClientID("clsn-sender") + sops.SetConnectionLostHandler(func(client Client, err error) { + fmt.Println("OnConnectionLost!") + }) + sops.SetAutoReconnect(false) + c := NewClient(sops).(*client) + + wops := NewClientOptions() + wops.AddBroker(FVTTCP) + wops.SetClientID("clsn-tester") + wops.SetCleanSession(false) + wops.SetDefaultPublishHandler(func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + clsnc <- string(msg.Payload()) + }) + wops.SetAutoReconnect(false) + wsub := NewClient(wops) + + if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) + } + + if wsubToken := wsub.Subscribe("clean", 1, nil); wsubToken.Wait() && wsubToken.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", wsubToken.Error()) + } + + wsub.Disconnect(250) + time.Sleep(2 * time.Second) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if pToken := c.Publish("clean", 1, false, "clean!"); pToken.Wait() && pToken.Error() != nil { + t.Fatalf("Error on Client.Publish(): %v", pToken.Error()) + } + + c.Disconnect(250) + + wsub = NewClient(wops) + if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) + } + + select { + case msg := <-clsnc: + if msg != "clean!" { + t.Fatalf("will message did not have correct payload") + } + case <-time.NewTicker(5 * time.Second).C: + t.Fatalf("failed to receive publish") + } + + wsub.Disconnect(250) + + wops.SetCleanSession(true) + + wsub = NewClient(wops) + if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) + } + + wsub.Disconnect(250) +} + +func Test_Binary_Will(t *testing.T) { + willmsgc := make(chan []byte, 1) + will := []byte{ + 0xDE, + 0xAD, + 0xBE, + 0xEF, + } + + sops := NewClientOptions().AddBroker(FVTTCP) + sops.SetClientID("will-giver") + sops.SetBinaryWill("/wills", will, 0, false) + sops.SetConnectionLostHandler(func(client Client, err error) { + }) + sops.SetAutoReconnect(false) + c := NewClient(sops).(*client) + + wops := NewClientOptions().AddBroker(FVTTCP) + wops.SetClientID("will-subscriber") + wops.SetDefaultPublishHandler(func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %v\n", msg.Payload()) + willmsgc <- msg.Payload() + }) + wops.SetAutoReconnect(false) + wsub := NewClient(wops) + + if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) + } + + if wsubToken := wsub.Subscribe("/wills", 0, nil); wsubToken.Wait() && wsubToken.Error() != nil { + t.Fatalf("Error on Client.Subscribe() %v", wsubToken.Error()) + } + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + c.forceDisconnect() + + if !bytes.Equal(<-willmsgc, will) { + t.Fatalf("will message did not have correct payload") + } + + wsub.Disconnect(250) +} + +/** +"[...] a publisher is responsible for determining the maximum QoS a +message can be delivered at, but a subscriber is able to downgrade +the QoS to one more suitable for its usage. +The QoS of a message is never upgraded." +**/ + +/*********************************** + * Tests to cover the 9 QoS combos * + ***********************************/ + +func wait(c chan bool) { + fmt.Println("choke is waiting") + <-c +} + +// Pub 0, Sub 0 + +func Test_p0s0(t *testing.T) { + topic := "/test/p0s0" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p0s0-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p0s0-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 0, false, "p0s0 payload 1") + p.Publish(topic, 0, false, "p0s0 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 0, false, "p0s0 payload 3") + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 0, Sub 1 + +func Test_p0s1(t *testing.T) { + topic := "/test/p0s1" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p0s1-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p0s1-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 0, false, "p0s1 payload 1") + p.Publish(topic, 0, false, "p0s1 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 0, false, "p0s1 payload 3") + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 0, Sub 2 + +func Test_p0s2(t *testing.T) { + topic := "/test/p0s2" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p0s2-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p0s2-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 0, false, "p0s2 payload 1") + p.Publish(topic, 0, false, "p0s2 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 0, false, "p0s2 payload 3") + + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 1, Sub 0 + +func Test_p1s0(t *testing.T) { + topic := "/test/p1s0" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p1s0-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p1s0-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 1, false, "p1s0 payload 1") + p.Publish(topic, 1, false, "p1s0 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 1, false, "p1s0 payload 3") + + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 1, Sub 1 + +func Test_p1s1(t *testing.T) { + topic := "/test/p1s1" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p1s1-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p1s1-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 1, false, "p1s1 payload 1") + p.Publish(topic, 1, false, "p1s1 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 1, false, "p1s1 payload 3") + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 1, Sub 2 + +func Test_p1s2(t *testing.T) { + topic := "/test/p1s2" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p1s2-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p1s2-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 1, false, "p1s2 payload 1") + p.Publish(topic, 1, false, "p1s2 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 1, false, "p1s2 payload 3") + + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 2, Sub 0 + +func Test_p2s0(t *testing.T) { + topic := "/test/p2s0" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p2s0-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p2s0-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 2, false, "p2s0 payload 1") + p.Publish(topic, 2, false, "p2s0 payload 2") + wait(choke) + wait(choke) + + p.Publish(topic, 2, false, "p2s0 payload 3") + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 2, Sub 1 + +func Test_p2s1(t *testing.T) { + topic := "/test/p2s1" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p2s1-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p2s1-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 2, false, "p2s1 payload 1") + p.Publish(topic, 2, false, "p2s1 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 2, false, "p2s1 payload 3") + + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +// Pub 2, Sub 2 + +func Test_p2s2(t *testing.T) { + topic := "/test/p2s2" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("p2s2-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("p2s2-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + p.Publish(topic, 2, false, "p2s2 payload 1") + p.Publish(topic, 2, false, "p2s2 payload 2") + + wait(choke) + wait(choke) + + p.Publish(topic, 2, false, "p2s2 payload 3") + + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +func Test_PublishMessage(t *testing.T) { + topic := "/test/pubmsg" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("pubmsg-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("pubmsg-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + if string(msg.Payload()) != "pubmsg payload" { + fmt.Println("Message payload incorrect", msg.Payload(), len("pubmsg payload")) + t.Fatalf("Message payload incorrect") + } + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if token := s.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) + } + + if token := p.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + text := "pubmsg payload" + p.Publish(topic, 0, false, text) + p.Publish(topic, 0, false, text) + wait(choke) + wait(choke) + + p.Publish(topic, 0, false, text) + wait(choke) + + p.Disconnect(250) + s.Disconnect(250) +} + +func Test_PublishEmptyMessage(t *testing.T) { + topic := "/test/pubmsgempty" + choke := make(chan bool) + + pops := NewClientOptions() + pops.AddBroker(FVTTCP) + pops.SetClientID("pubmsgempty-pub") + p := NewClient(pops) + + sops := NewClientOptions() + sops.AddBroker(FVTTCP) + sops.SetClientID("pubmsgempty-sub") + var f MessageHandler = func(client Client, msg Message) { + fmt.Printf("TOPIC: %s\n", msg.Topic()) + fmt.Printf("MSG: %s\n", msg.Payload()) + if string(msg.Payload()) != "" { + t.Fatalf("Message payload incorrect") + } + choke <- true + } + sops.SetDefaultPublishHandler(f) + + s := NewClient(sops) + if sToken := s.Connect(); sToken.Wait() && sToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) + } + + if sToken := s.Subscribe(topic, 2, nil); sToken.Wait() && sToken.Error() != nil { + t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error()) + } + + if pToken := p.Connect(); pToken.Wait() && pToken.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) + } + + p.Publish(topic, 0, false, "") + p.Publish(topic, 0, false, "") + wait(choke) + wait(choke) + + p.Publish(topic, 0, false, "") + wait(choke) + + p.Disconnect(250) +} + +// func Test_Cleanstore(t *testing.T) { +// store := "/tmp/fvt/cleanstore" +// topic := "/test/cleanstore" + +// pops := NewClientOptions() +// pops.AddBroker(FVTTCP) +// pops.SetClientID("cleanstore-pub") +// pops.SetStore(NewFileStore(store + "/p")) +// p := NewClient(pops) + +// var s *Client +// sops := NewClientOptions() +// sops.AddBroker(FVTTCP) +// sops.SetClientID("cleanstore-sub") +// sops.SetCleanSession(false) +// sops.SetStore(NewFileStore(store + "/s")) +// var f MessageHandler = func(client Client, msg Message) { +// fmt.Printf("TOPIC: %s\n", msg.Topic()) +// fmt.Printf("MSG: %s\n", msg.Payload()) +// // Close the connection after receiving +// // the first message so that hopefully +// // there is something in the store to be +// // cleaned. +// s.ForceDisconnect() +// } +// sops.SetDefaultPublishHandler(f) + +// s = NewClient(sops) +// sToken := s.Connect() +// if sToken.Wait() && sToken.Error() != nil { +// t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) +// } + +// sToken = s.Subscribe(topic, 2, nil) +// if sToken.Wait() && sToken.Error() != nil { +// t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error()) +// } + +// pToken := p.Connect() +// if pToken.Wait() && pToken.Error() != nil { +// t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) +// } + +// text := "test message" +// p.Publish(topic, 0, false, text) +// p.Publish(topic, 0, false, text) +// p.Publish(topic, 0, false, text) + +// p.Disconnect(250) + +// s2ops := NewClientOptions() +// s2ops.AddBroker(FVTTCP) +// s2ops.SetClientID("cleanstore-sub") +// s2ops.SetCleanSession(true) +// s2ops.SetStore(NewFileStore(store + "/s")) +// s2ops.SetDefaultPublishHandler(f) + +// s2 := NewClient(s2ops) +// sToken = s2.Connect() +// if sToken.Wait() && sToken.Error() != nil { +// t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) +// } + +// // at this point existing state should be cleared... +// // how to check? +// } + +func Test_MultipleURLs(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker("tcp://127.0.0.1:10000") + ops.AddBroker(FVTTCP) + ops.SetClientID("MultiURL") + + c := NewClient(ops) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + if pToken := c.Publish("/test/MultiURL", 0, false, "Publish qo0"); pToken.Wait() && pToken.Error() != nil { + t.Fatalf("Error on Client.Publish(): %v", pToken.Error()) + } + + c.Disconnect(250) +} + +// A test to make sure ping mechanism is working +func Test_ping1_idle5(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("p3i10") + ops.SetConnectionLostHandler(func(c Client, err error) { + t.Fatalf("Connection-lost handler was called: %s", err) + }) + ops.SetKeepAlive(2 * time.Second) + + c := NewClient(ops) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + time.Sleep(5 * time.Second) + c.Disconnect(250) +} + +func Test_autoreconnect(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("auto_reconnect") + ops.SetAutoReconnect(true) + ops.SetOnConnectHandler(func(c Client) { + t.Log("Connected") + }) + ops.SetKeepAlive(2 * time.Second) + + c := NewClient(ops) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + time.Sleep(5 * time.Second) + + fmt.Println("Breaking connection") + c.(*client).internalConnLost(fmt.Errorf("Autoreconnect test")) + + time.Sleep(5 * time.Second) + if !c.IsConnected() { + t.Fail() + } + + c.Disconnect(250) +} + +func Test_cleanUpMids(t *testing.T) { + ops := NewClientOptions() + ops.AddBroker(FVTTCP) + ops.SetClientID("auto_reconnect") + ops.SetCleanSession(true) + ops.SetAutoReconnect(true) + ops.SetKeepAlive(10 * time.Second) + + c := NewClient(ops) + + if token := c.Connect(); token.Wait() && token.Error() != nil { + t.Fatalf("Error on Client.Connect(): %v", token.Error()) + } + + token := c.Publish("/test/cleanUP", 2, false, "cleanup test") + time.Sleep(10 * time.Millisecond) + fmt.Println("Breaking connection", len(c.(*client).messageIds.index)) + if len(c.(*client).messageIds.index) == 0 { + t.Fatalf("Should be a token in the messageIDs, none found") + } + c.(*client).internalConnLost(fmt.Errorf("cleanup test")) + + time.Sleep(5 * time.Second) + if !c.IsConnected() { + t.Fail() + } + + if len(c.(*client).messageIds.index) > 0 { + t.Fatalf("Should have cleaned up messageIDs, have %d left", len(c.(*client).messageIds.index)) + } + if token.Error() == nil { + t.Fatal("token should have received an error on connection loss") + } + fmt.Println(token.Error()) + + c.Disconnect(250) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go new file mode 100644 index 00000000..f0aa39cd --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go @@ -0,0 +1,544 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "bytes" + "io/ioutil" + "os" + "testing" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +/********************************************** + **** A mock store implementation for test **** + **********************************************/ + +type TestStore struct { + mput []uint16 + mget []uint16 + mdel []uint16 +} + +func (ts *TestStore) Open() { +} + +func (ts *TestStore) Close() { +} + +func (ts *TestStore) Put(key string, m packets.ControlPacket) { + ts.mput = append(ts.mput, m.Details().MessageID) +} + +func (ts *TestStore) Get(key string) packets.ControlPacket { + mid := mIDFromKey(key) + ts.mget = append(ts.mget, mid) + return nil +} + +func (ts *TestStore) All() []string { + return nil +} + +func (ts *TestStore) Del(key string) { + mid := mIDFromKey(key) + ts.mdel = append(ts.mdel, mid) +} + +func (ts *TestStore) Reset() { +} + +/******************* + **** FileStore **** + *******************/ + +func Test_NewFileStore(t *testing.T) { + storedir := "/tmp/TestStore/_new" + f := NewFileStore(storedir) + if f.opened { + t.Fatalf("filestore was opened without opening it") + } + if f.directory != storedir { + t.Fatalf("filestore directory is wrong") + } + // storedir might exist or might not, just like with a real client + // the point is, we don't care, we just want it to exist after it is + // opened +} + +func Test_FileStore_Open(t *testing.T) { + storedir := "/tmp/TestStore/_open" + + f := NewFileStore(storedir) + f.Open() + if !f.opened { + t.Fatalf("filestore was not set open") + } + if f.directory != storedir { + t.Fatalf("filestore directory is wrong") + } + if !exists(storedir) { + t.Fatalf("filestore directory does not exst after opening it") + } +} + +func Test_FileStore_Close(t *testing.T) { + storedir := "/tmp/TestStore/_unopen" + f := NewFileStore(storedir) + f.Open() + if !f.opened { + t.Fatalf("filestore was not set open") + } + if f.directory != storedir { + t.Fatalf("filestore directory is wrong") + } + if !exists(storedir) { + t.Fatalf("filestore directory does not exst after opening it") + } + + f.Close() + if f.opened { + t.Fatalf("filestore was still open after unopen") + } + if !exists(storedir) { + t.Fatalf("filestore was deleted after unopen") + } +} + +func Test_FileStore_write(t *testing.T) { + storedir := "/tmp/TestStore/_write" + f := NewFileStore(storedir) + f.Open() + + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 91 + + key := inboundKeyFromMID(pm.MessageID) + f.Put(key, pm) + + if !exists(storedir + "/i.91.msg") { + t.Fatalf("message not in store") + } + +} + +func Test_FileStore_Get(t *testing.T) { + storedir := "/tmp/TestStore/_get" + f := NewFileStore(storedir) + f.Open() + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "/a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 120 + + key := outboundKeyFromMID(pm.MessageID) + f.Put(key, pm) + + if !exists(storedir + "/o.120.msg") { + t.Fatalf("message not in store") + } + + exp := []byte{ + /* msg type */ + 0x32, // qos 1 + + /* remlen */ + 0x0d, + + /* topic, msg id in varheader */ + 0x00, // length of topic + 0x06, + 0x2F, // / + 0x61, // a + 0x2F, // / + 0x62, // b + 0x2F, // / + 0x63, // c + + /* msg id (is always 2 bytes) */ + 0x00, + 0x78, + + /*payload */ + 0xBE, + 0xEF, + 0xED, + } + + m := f.Get(key) + + if m == nil { + t.Fatalf("message not retreived from store") + } + + var msg bytes.Buffer + m.Write(&msg) + if !bytes.Equal(exp, msg.Bytes()) { + t.Fatal("message from store not same as what went in", msg.Bytes()) + } +} + +func Test_FileStore_Get_Corrupted(t *testing.T) { + storedir := "/tmp/TestStore/_get_error" + f := NewFileStore(storedir) + f.Open() + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "/a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 120 + + key := outboundKeyFromMID(pm.MessageID) + + exp := []byte{ + /* msg type */ + 0x32, // qos 1 + + /* remlen */ + 0x0d, + + /* topic, msg id in varheader */ + 0x00, // length of topic + 0x06, + // Oh no the rest is gone! + } + + file, err := os.Create(storedir + "/o.120.msg") + chkerr(err) + _, err = file.Write(exp) + chkerr(err) + chkerr(file.Close()) + + if !exists(storedir + "/o.120.msg") { + t.Fatalf("corrupt message not in store") + } + + m := f.Get(key) + + if m != nil { + t.Fatalf("corrupted message retrieved from store") + } + + if exists(storedir + "/o.120.msg") { + t.Fatalf("corrupt message left in store") + } + + if !exists(storedir + "/o.120.CORRUPT") { + t.Fatalf("corrupt message not archived") + } + + contents, err := ioutil.ReadFile(storedir + "/o.120.CORRUPT") + chkerr(err) + + if !bytes.Equal(exp, contents) { + t.Fatal("archived corrupted bytes not the same as those saved", exp, contents) + } +} + +func Test_FileStore_All(t *testing.T) { + storedir := "/tmp/TestStore/_all" + f := NewFileStore(storedir) + f.Open() + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 2 + pm.TopicName = "/t/r/v" + pm.Payload = []byte{0x01, 0x02} + pm.MessageID = 121 + + key := outboundKeyFromMID(pm.MessageID) + f.Put(key, pm) + + keys := f.All() + if len(keys) != 1 { + t.Logf("Keys: %s", keys) + t.Fatalf("FileStore.All does not have the messages") + } + + if keys[0] != "o.121" { + t.Fatalf("FileStore.All has wrong key") + } +} + +func Test_FileStore_Del(t *testing.T) { + storedir := "/tmp/TestStore/_del" + f := NewFileStore(storedir) + f.Open() + + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 17 + + key := inboundKeyFromMID(pm.MessageID) + f.Put(key, pm) + + if !exists(storedir + "/i.17.msg") { + t.Fatalf("message not in store") + } + + f.Del(key) + + if exists(storedir + "/i.17.msg") { + t.Fatalf("message still exists after deletion") + } +} + +func Test_FileStore_Reset(t *testing.T) { + storedir := "/tmp/TestStore/_reset" + f := NewFileStore(storedir) + f.Open() + + pm1 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm1.Qos = 1 + pm1.TopicName = "/q/w/e" + pm1.Payload = []byte{0xBB} + pm1.MessageID = 71 + key1 := inboundKeyFromMID(pm1.MessageID) + f.Put(key1, pm1) + + pm2 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm2.Qos = 1 + pm2.TopicName = "/q/w/e" + pm2.Payload = []byte{0xBB} + pm2.MessageID = 72 + key2 := inboundKeyFromMID(pm2.MessageID) + f.Put(key2, pm2) + + pm3 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm3.Qos = 1 + pm3.TopicName = "/q/w/e" + pm3.Payload = []byte{0xBB} + pm3.MessageID = 73 + key3 := inboundKeyFromMID(pm3.MessageID) + f.Put(key3, pm3) + + pm4 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm4.Qos = 1 + pm4.TopicName = "/q/w/e" + pm4.Payload = []byte{0xBB} + pm4.MessageID = 74 + key4 := inboundKeyFromMID(pm4.MessageID) + f.Put(key4, pm4) + + pm5 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm5.Qos = 1 + pm5.TopicName = "/q/w/e" + pm5.Payload = []byte{0xBB} + pm5.MessageID = 75 + key5 := inboundKeyFromMID(pm5.MessageID) + f.Put(key5, pm5) + + if !exists(storedir + "/i.71.msg") { + t.Fatalf("message not in store") + } + + if !exists(storedir + "/i.72.msg") { + t.Fatalf("message not in store") + } + + if !exists(storedir + "/i.73.msg") { + t.Fatalf("message not in store") + } + + if !exists(storedir + "/i.74.msg") { + t.Fatalf("message not in store") + } + + if !exists(storedir + "/i.75.msg") { + t.Fatalf("message not in store") + } + + f.Reset() + + if exists(storedir + "/i.71.msg") { + t.Fatalf("message still exists after reset") + } + + if exists(storedir + "/i.72.msg") { + t.Fatalf("message still exists after reset") + } + + if exists(storedir + "/i.73.msg") { + t.Fatalf("message still exists after reset") + } + + if exists(storedir + "/i.74.msg") { + t.Fatalf("message still exists after reset") + } + + if exists(storedir + "/i.75.msg") { + t.Fatalf("message still exists after reset") + } +} + +/******************* + *** MemoryStore *** + *******************/ + +func Test_NewMemoryStore(t *testing.T) { + m := NewMemoryStore() + if m == nil { + t.Fatalf("MemoryStore could not be created") + } +} + +func Test_MemoryStore_Open(t *testing.T) { + m := NewMemoryStore() + m.Open() + if !m.opened { + t.Fatalf("MemoryStore was not set open") + } +} + +func Test_MemoryStore_Close(t *testing.T) { + m := NewMemoryStore() + m.Open() + if !m.opened { + t.Fatalf("MemoryStore was not set open") + } + + m.Close() + if m.opened { + t.Fatalf("MemoryStore was still open after unopen") + } +} + +func Test_MemoryStore_Reset(t *testing.T) { + m := NewMemoryStore() + m.Open() + + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 2 + pm.TopicName = "/f/r/s" + pm.Payload = []byte{0xAB} + pm.MessageID = 81 + + key := outboundKeyFromMID(pm.MessageID) + m.Put(key, pm) + + if len(m.messages) != 1 { + t.Fatalf("message not in memstore") + } + + m.Reset() + + if len(m.messages) != 0 { + t.Fatalf("reset did not clear memstore") + } +} + +func Test_MemoryStore_write(t *testing.T) { + m := NewMemoryStore() + m.Open() + + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "/a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 91 + key := inboundKeyFromMID(pm.MessageID) + m.Put(key, pm) + + if len(m.messages) != 1 { + t.Fatalf("message not in store") + } +} + +func Test_MemoryStore_Get(t *testing.T) { + m := NewMemoryStore() + m.Open() + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "/a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 120 + + key := outboundKeyFromMID(pm.MessageID) + m.Put(key, pm) + + if len(m.messages) != 1 { + t.Fatalf("message not in store") + } + + exp := []byte{ + /* msg type */ + 0x32, // qos 1 + + /* remlen */ + 0x0d, + + /* topic, msg id in varheader */ + 0x00, // length of topic + 0x06, + 0x2F, // / + 0x61, // a + 0x2F, // / + 0x62, // b + 0x2F, // / + 0x63, // c + + /* msg id (is always 2 bytes) */ + 0x00, + 0x78, + + /*payload */ + 0xBE, + 0xEF, + 0xED, + } + + msg := m.Get(key) + + if msg == nil { + t.Fatalf("message not retreived from store") + } + + var buf bytes.Buffer + msg.Write(&buf) + if !bytes.Equal(exp, buf.Bytes()) { + t.Fatalf("message from store not same as what went in") + } +} + +func Test_MemoryStore_Del(t *testing.T) { + m := NewMemoryStore() + m.Open() + + pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pm.Qos = 1 + pm.TopicName = "/a/b/c" + pm.Payload = []byte{0xBE, 0xEF, 0xED} + pm.MessageID = 17 + + key := outboundKeyFromMID(pm.MessageID) + + m.Put(key, pm) + + if len(m.messages) != 1 { + t.Fatalf("message not in store") + } + + m.Del(key) + + if len(m.messages) != 1 { + t.Fatalf("message still exists after deletion") + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go new file mode 100644 index 00000000..cb3a4545 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import "os" + +// Use setup_IMA.sh for IBM's MessageSight +// Use fvt/rsmb.cfg for IBM's Really Small Message Broker +// Use fvt/mosquitto.cfg for the open source Mosquitto project + +var ( + FVTAddr string + FVTTCP string + FVTSSL string +) + +func init() { + FVTAddr := os.Getenv("TEST_FVT_ADDR") + if FVTAddr == "" { + FVTAddr = "iot.eclipse.org" + } + FVTTCP = "tcp://" + FVTAddr + ":1883" + FVTSSL = "ssl://" + FVTAddr + ":8883" +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go new file mode 100644 index 00000000..d3bfe084 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "sync" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +// MemoryStore implements the store interface to provide a "persistence" +// mechanism wholly stored in memory. This is only useful for +// as long as the client instance exists. +type MemoryStore struct { + sync.RWMutex + messages map[string]packets.ControlPacket + opened bool +} + +// NewMemoryStore returns a pointer to a new instance of +// MemoryStore, the instance is not initialized and ready to +// use until Open() has been called on it. +func NewMemoryStore() *MemoryStore { + store := &MemoryStore{ + messages: make(map[string]packets.ControlPacket), + opened: false, + } + return store +} + +// Open initializes a MemoryStore instance. +func (store *MemoryStore) Open() { + store.Lock() + defer store.Unlock() + store.opened = true + DEBUG.Println(STR, "memorystore initialized") +} + +// Put takes a key and a pointer to a Message and stores the +// message. +func (store *MemoryStore) Put(key string, message packets.ControlPacket) { + store.Lock() + defer store.Unlock() + if !store.opened { + ERROR.Println(STR, "Trying to use memory store, but not open") + return + } + store.messages[key] = message +} + +// Get takes a key and looks in the store for a matching Message +// returning either the Message pointer or nil. +func (store *MemoryStore) Get(key string) packets.ControlPacket { + store.RLock() + defer store.RUnlock() + if !store.opened { + ERROR.Println(STR, "Trying to use memory store, but not open") + return nil + } + mid := mIDFromKey(key) + m := store.messages[key] + if m == nil { + CRITICAL.Println(STR, "memorystore get: message", mid, "not found") + } else { + DEBUG.Println(STR, "memorystore get: message", mid, "found") + } + return m +} + +// All returns a slice of strings containing all the keys currently +// in the MemoryStore. +func (store *MemoryStore) All() []string { + store.RLock() + defer store.RUnlock() + if !store.opened { + ERROR.Println(STR, "Trying to use memory store, but not open") + return nil + } + keys := []string{} + for k := range store.messages { + keys = append(keys, k) + } + return keys +} + +// Del takes a key, searches the MemoryStore and if the key is found +// deletes the Message pointer associated with it. +func (store *MemoryStore) Del(key string) { + store.Lock() + defer store.Unlock() + if !store.opened { + ERROR.Println(STR, "Trying to use memory store, but not open") + return + } + mid := mIDFromKey(key) + m := store.messages[key] + if m == nil { + WARN.Println(STR, "memorystore del: message", mid, "not found") + } else { + store.messages[key] = nil + DEBUG.Println(STR, "memorystore del: message", mid, "was deleted") + } +} + +// Close will disallow modifications to the state of the store. +func (store *MemoryStore) Close() { + store.Lock() + defer store.Unlock() + if !store.opened { + ERROR.Println(STR, "Trying to close memory store, but not open") + return + } + store.opened = false + DEBUG.Println(STR, "memorystore closed") +} + +// Reset eliminates all persisted message data in the store. +func (store *MemoryStore) Reset() { + store.Lock() + defer store.Unlock() + if !store.opened { + ERROR.Println(STR, "Trying to reset memory store, but not open") + } + store.messages = make(map[string]packets.ControlPacket) + WARN.Println(STR, "memorystore wiped") +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go new file mode 100644 index 00000000..b1b71648 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "github.com/eclipse/paho.mqtt.golang/packets" +) + +// Message defines the externals that a message implementation must support +// these are received messages that are passed to the callbacks, not internal +// messages +type Message interface { + Duplicate() bool + Qos() byte + Retained() bool + Topic() string + MessageID() uint16 + Payload() []byte +} + +type message struct { + duplicate bool + qos byte + retained bool + topic string + messageID uint16 + payload []byte +} + +func (m *message) Duplicate() bool { + return m.duplicate +} + +func (m *message) Qos() byte { + return m.qos +} + +func (m *message) Retained() bool { + return m.retained +} + +func (m *message) Topic() string { + return m.topic +} + +func (m *message) MessageID() uint16 { + return m.messageID +} + +func (m *message) Payload() []byte { + return m.payload +} + +func messageFromPublish(p *packets.PublishPacket) Message { + return &message{ + duplicate: p.Dup, + qos: p.Qos, + retained: p.Retain, + topic: p.TopicName, + messageID: p.MessageID, + payload: p.Payload, + } +} + +func newConnectMsgFromOptions(options *ClientOptions) *packets.ConnectPacket { + m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket) + + m.CleanSession = options.CleanSession + m.WillFlag = options.WillEnabled + m.WillRetain = options.WillRetained + m.ClientIdentifier = options.ClientID + + if options.WillEnabled { + m.WillQos = options.WillQos + m.WillTopic = options.WillTopic + m.WillMessage = options.WillPayload + } + + if options.Username != "" { + m.UsernameFlag = true + m.Username = options.Username + //mustn't have password without user as well + if options.Password != "" { + m.PasswordFlag = true + m.Password = []byte(options.Password) + } + } + + m.Keepalive = uint16(options.KeepAlive.Seconds()) + + return m +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go new file mode 100644 index 00000000..9f4d0441 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "fmt" + "sync" +) + +// MId is 16 bit message id as specified by the MQTT spec. +// In general, these values should not be depended upon by +// the client application. +type MId uint16 + +type messageIds struct { + sync.RWMutex + index map[uint16]Token +} + +const ( + midMin uint16 = 1 + midMax uint16 = 65535 +) + +func (mids *messageIds) cleanUp() { + mids.Lock() + for _, token := range mids.index { + switch t := token.(type) { + case *PublishToken: + t.err = fmt.Errorf("Connection lost before Publish completed") + case *SubscribeToken: + t.err = fmt.Errorf("Connection lost before Subscribe completed") + case *UnsubscribeToken: + t.err = fmt.Errorf("Connection lost before Unsubscribe completed") + } + token.flowComplete() + } + mids.index = make(map[uint16]Token) + mids.Unlock() +} + +func (mids *messageIds) freeID(id uint16) { + mids.Lock() + delete(mids.index, id) + mids.Unlock() +} + +func (mids *messageIds) getID(t Token) uint16 { + mids.Lock() + defer mids.Unlock() + for i := midMin; i < midMax; i++ { + if _, ok := mids.index[i]; !ok { + mids.index[i] = t + return i + } + } + return 0 +} + +func (mids *messageIds) getToken(id uint16) Token { + mids.RLock() + defer mids.RUnlock() + if token, ok := mids.index[id]; ok { + return token + } + return nil +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go new file mode 100644 index 00000000..bee0e4d0 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "crypto/tls" + "errors" + "fmt" + "net" + "net/url" + "os" + "reflect" + "time" + + "github.com/eclipse/paho.mqtt.golang/packets" + "golang.org/x/net/proxy" + "golang.org/x/net/websocket" +) + +func signalError(c chan<- error, err error) { + select { + case c <- err: + default: + } +} + +func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration) (net.Conn, error) { + switch uri.Scheme { + case "ws": + conn, err := websocket.Dial(uri.String(), "mqtt", fmt.Sprintf("http://%s", uri.Host)) + if err != nil { + return nil, err + } + conn.PayloadType = websocket.BinaryFrame + return conn, err + case "wss": + config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("https://%s", uri.Host)) + config.Protocol = []string{"mqtt"} + config.TlsConfig = tlsc + conn, err := websocket.DialConfig(config) + if err != nil { + return nil, err + } + conn.PayloadType = websocket.BinaryFrame + return conn, err + case "tcp": + allProxy := os.Getenv("all_proxy") + if len(allProxy) == 0 { + conn, err := net.DialTimeout("tcp", uri.Host, timeout) + if err != nil { + return nil, err + } + return conn, nil + } else { + proxyDialer := proxy.FromEnvironment() + + conn, err := proxyDialer.Dial("tcp", uri.Host) + if err != nil { + return nil, err + } + return conn, nil + } + case "ssl": + fallthrough + case "tls": + fallthrough + case "tcps": + allProxy := os.Getenv("all_proxy") + if len(allProxy) == 0 { + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc) + if err != nil { + return nil, err + } + return conn, nil + } else { + proxyDialer := proxy.FromEnvironment() + + conn, err := proxyDialer.Dial("tcp", uri.Host) + if err != nil { + return nil, err + } + + tlsConn := tls.Client(conn, tlsc) + + err = tlsConn.Handshake() + if err != nil { + conn.Close() + return nil, err + } + + return tlsConn, nil + } + } + return nil, errors.New("Unknown protocol") +} + +// actually read incoming messages off the wire +// send Message object into ibound channel +func incoming(c *client) { + var err error + var cp packets.ControlPacket + + defer c.workers.Done() + + DEBUG.Println(NET, "incoming started") + + for { + if cp, err = packets.ReadPacket(c.conn); err != nil { + break + } + DEBUG.Println(NET, "Received Message") + select { + case c.ibound <- cp: + // Notify keepalive logic that we recently received a packet + if c.options.KeepAlive != 0 { + c.packetResp <- struct{}{} + } + case <-c.stop: + // This avoids a deadlock should a message arrive while shutting down. + // In that case the "reader" of c.ibound might already be gone + WARN.Println(NET, "incoming dropped a received message during shutdown") + break + } + } + // We received an error on read. + // If disconnect is in progress, swallow error and return + select { + case <-c.stop: + DEBUG.Println(NET, "incoming stopped") + return + // Not trying to disconnect, send the error to the errors channel + default: + ERROR.Println(NET, "incoming stopped with error", err) + signalError(c.errors, err) + return + } +} + +// receive a Message object on obound, and then +// actually send outgoing message to the wire +func outgoing(c *client) { + defer c.workers.Done() + DEBUG.Println(NET, "outgoing started") + + for { + DEBUG.Println(NET, "outgoing waiting for an outbound message") + select { + case <-c.stop: + DEBUG.Println(NET, "outgoing stopped") + return + case pub := <-c.obound: + msg := pub.p.(*packets.PublishPacket) + + if c.options.WriteTimeout > 0 { + c.conn.SetWriteDeadline(time.Now().Add(c.options.WriteTimeout)) + } + + if err := msg.Write(c.conn); err != nil { + ERROR.Println(NET, "outgoing stopped with error", err) + signalError(c.errors, err) + return + } + + if c.options.WriteTimeout > 0 { + // If we successfully wrote, we don't want the timeout to happen during an idle period + // so we reset it to infinite. + c.conn.SetWriteDeadline(time.Time{}) + } + + if msg.Qos == 0 { + pub.t.flowComplete() + } + DEBUG.Println(NET, "obound wrote msg, id:", msg.MessageID) + case msg := <-c.oboundP: + switch msg.p.(type) { + case *packets.SubscribePacket: + msg.p.(*packets.SubscribePacket).MessageID = c.getID(msg.t) + case *packets.UnsubscribePacket: + msg.p.(*packets.UnsubscribePacket).MessageID = c.getID(msg.t) + } + DEBUG.Println(NET, "obound priority msg to write, type", reflect.TypeOf(msg.p)) + if err := msg.p.Write(c.conn); err != nil { + ERROR.Println(NET, "outgoing stopped with error", err) + signalError(c.errors, err) + return + } + switch msg.p.(type) { + case *packets.DisconnectPacket: + msg.t.(*DisconnectToken).flowComplete() + DEBUG.Println(NET, "outbound wrote disconnect, stopping") + return + } + } + // Reset ping timer after sending control packet. + if c.options.KeepAlive != 0 { + select { + case c.keepaliveReset <- struct{}{}: + default: + DEBUG.Println(NET, "couldn't send keepalive signal in outbound as channel full") + } + } + } +} + +// receive Message objects on ibound +// store messages if necessary +// send replies on obound +// delete messages from store if necessary +func alllogic(c *client) { + defer c.workers.Done() + DEBUG.Println(NET, "logic started") + + for { + DEBUG.Println(NET, "logic waiting for msg on ibound") + + select { + case msg := <-c.ibound: + DEBUG.Println(NET, "logic got msg on ibound") + persistInbound(c.persist, msg) + switch m := msg.(type) { + case *packets.PingrespPacket: + DEBUG.Println(NET, "received pingresp") + c.pingResp <- struct{}{} + case *packets.SubackPacket: + DEBUG.Println(NET, "received suback, id:", m.MessageID) + token := c.getToken(m.MessageID).(*SubscribeToken) + DEBUG.Println(NET, "granted qoss", m.ReturnCodes) + for i, qos := range m.ReturnCodes { + token.subResult[token.subs[i]] = qos + } + token.flowComplete() + c.freeID(m.MessageID) + case *packets.UnsubackPacket: + DEBUG.Println(NET, "received unsuback, id:", m.MessageID) + token := c.getToken(m.MessageID).(*UnsubscribeToken) + token.flowComplete() + c.freeID(m.MessageID) + case *packets.PublishPacket: + DEBUG.Println(NET, "received publish, msgId:", m.MessageID) + DEBUG.Println(NET, "putting msg on onPubChan") + switch m.Qos { + case 2: + c.incomingPubChan <- m + DEBUG.Println(NET, "done putting msg on incomingPubChan") + pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) + pr.MessageID = m.MessageID + DEBUG.Println(NET, "putting pubrec msg on obound") + c.oboundP <- &PacketAndToken{p: pr, t: nil} + DEBUG.Println(NET, "done putting pubrec msg on obound") + case 1: + c.incomingPubChan <- m + DEBUG.Println(NET, "done putting msg on incomingPubChan") + pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) + pa.MessageID = m.MessageID + DEBUG.Println(NET, "putting puback msg on obound") + c.oboundP <- &PacketAndToken{p: pa, t: nil} + DEBUG.Println(NET, "done putting puback msg on obound") + case 0: + c.incomingPubChan <- m + DEBUG.Println(NET, "done putting msg on incomingPubChan") + } + case *packets.PubackPacket: + DEBUG.Println(NET, "received puback, id:", m.MessageID) + // c.receipts.get(msg.MsgId()) <- Receipt{} + // c.receipts.end(msg.MsgId()) + c.getToken(m.MessageID).flowComplete() + c.freeID(m.MessageID) + case *packets.PubrecPacket: + DEBUG.Println(NET, "received pubrec, id:", m.MessageID) + prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) + prel.MessageID = m.MessageID + select { + case c.oboundP <- &PacketAndToken{p: prel, t: nil}: + case <-time.After(time.Second): + } + case *packets.PubrelPacket: + DEBUG.Println(NET, "received pubrel, id:", m.MessageID) + pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) + pc.MessageID = m.MessageID + select { + case c.oboundP <- &PacketAndToken{p: pc, t: nil}: + case <-time.After(time.Second): + } + case *packets.PubcompPacket: + DEBUG.Println(NET, "received pubcomp, id:", m.MessageID) + c.getToken(m.MessageID).flowComplete() + c.freeID(m.MessageID) + } + case <-c.stop: + WARN.Println(NET, "logic stopped") + return + } + } +} + +func errorWatch(c *client) { + select { + case <-c.stop: + WARN.Println(NET, "errorWatch stopped") + return + case err := <-c.errors: + ERROR.Println(NET, "error triggered, stopping") + c.internalConnLost(err) + return + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html new file mode 100644 index 00000000..f19c483b --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html @@ -0,0 +1,108 @@ + + + + + +Eclipse Foundation Software User Agreement + + + +

Eclipse Foundation Software User Agreement

+

February 1, 2011

+ +

Usage Of Content

+ +

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

+ +

Applicable Licenses

+ +

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. + For purposes of the EPL, "Program" will mean the Content.

+ +

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code + repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

+ +
    +
  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • +
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • +
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.
  • +
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
  • +
+ +

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and +Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:

+ +
    +
  • The top-level (root) directory
  • +
  • Plug-in and Fragment directories
  • +
  • Inside Plug-ins and Fragments packaged as JARs
  • +
  • Sub-directories of the directory named "src" of certain Plug-ins
  • +
  • Feature directories
  • +
+ +

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.

+ +

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

+ + + +

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

+ + +

Use of Provisioning Technology

+ +

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse + Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or + other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to + install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html + ("Specification").

+ +

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the + applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology + in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the + Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

+ +
    +
  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology + on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based + product.
  2. +
  3. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be + accessed and copied to the Target Machine.
  4. +
  5. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable + Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target + Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern + the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such + indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
  6. +
+ +

Cryptography

+ +

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.

+ +

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

+ + diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go new file mode 100644 index 00000000..39630d7f --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +func chkerr(e error) { + if e != nil { + panic(e) + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go new file mode 100644 index 00000000..16129ceb --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "crypto/tls" + "net/url" + "time" +) + +// MessageHandler is a callback type which can be set to be +// executed upon the arrival of messages published to topics +// to which the client is subscribed. +type MessageHandler func(Client, Message) + +// ConnectionLostHandler is a callback type which can be set to be +// executed upon an unintended disconnection from the MQTT broker. +// Disconnects caused by calling Disconnect or ForceDisconnect will +// not cause an OnConnectionLost callback to execute. +type ConnectionLostHandler func(Client, error) + +// OnConnectHandler is a callback that is called when the client +// state changes from unconnected/disconnected to connected. Both +// at initial connection and on reconnection +type OnConnectHandler func(Client) + +// ClientOptions contains configurable options for an Client. +type ClientOptions struct { + Servers []*url.URL + ClientID string + Username string + Password string + CleanSession bool + Order bool + WillEnabled bool + WillTopic string + WillPayload []byte + WillQos byte + WillRetained bool + ProtocolVersion uint + protocolVersionExplicit bool + TLSConfig tls.Config + KeepAlive time.Duration + PingTimeout time.Duration + ConnectTimeout time.Duration + MaxReconnectInterval time.Duration + AutoReconnect bool + Store Store + DefaultPublishHander MessageHandler + OnConnect OnConnectHandler + OnConnectionLost ConnectionLostHandler + WriteTimeout time.Duration + MessageChannelDepth uint +} + +// NewClientOptions will create a new ClientClientOptions type with some +// default values. +// Port: 1883 +// CleanSession: True +// Order: True +// KeepAlive: 30 (seconds) +// ConnectTimeout: 30 (seconds) +// MaxReconnectInterval 10 (minutes) +// AutoReconnect: True +func NewClientOptions() *ClientOptions { + o := &ClientOptions{ + Servers: nil, + ClientID: "", + Username: "", + Password: "", + CleanSession: true, + Order: true, + WillEnabled: false, + WillTopic: "", + WillPayload: nil, + WillQos: 0, + WillRetained: false, + ProtocolVersion: 0, + protocolVersionExplicit: false, + TLSConfig: tls.Config{}, + KeepAlive: 30 * time.Second, + PingTimeout: 10 * time.Second, + ConnectTimeout: 30 * time.Second, + MaxReconnectInterval: 10 * time.Minute, + AutoReconnect: true, + Store: nil, + OnConnect: nil, + OnConnectionLost: DefaultConnectionLostHandler, + WriteTimeout: 0, // 0 represents timeout disabled + MessageChannelDepth: 100, + } + return o +} + +// AddBroker adds a broker URI to the list of brokers to be used. The format should be +// scheme://host:port +// Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) +// and "port" is the port on which the broker is accepting connections. +func (o *ClientOptions) AddBroker(server string) *ClientOptions { + brokerURI, err := url.Parse(server) + if err == nil { + o.Servers = append(o.Servers, brokerURI) + } + return o +} + +// SetClientID will set the client id to be used by this client when +// connecting to the MQTT broker. According to the MQTT v3.1 specification, +// a client id mus be no longer than 23 characters. +func (o *ClientOptions) SetClientID(id string) *ClientOptions { + o.ClientID = id + return o +} + +// SetUsername will set the username to be used by this client when connecting +// to the MQTT broker. Note: without the use of SSL/TLS, this information will +// be sent in plaintext accross the wire. +func (o *ClientOptions) SetUsername(u string) *ClientOptions { + o.Username = u + return o +} + +// SetPassword will set the password to be used by this client when connecting +// to the MQTT broker. Note: without the use of SSL/TLS, this information will +// be sent in plaintext accross the wire. +func (o *ClientOptions) SetPassword(p string) *ClientOptions { + o.Password = p + return o +} + +// SetCleanSession will set the "clean session" flag in the connect message +// when this client connects to an MQTT broker. By setting this flag, you are +// indicating that no messages saved by the broker for this client should be +// delivered. Any messages that were going to be sent by this client before +// diconnecting previously but didn't will not be sent upon connecting to the +// broker. +func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions { + o.CleanSession = clean + return o +} + +// SetOrderMatters will set the message routing to guarantee order within +// each QoS level. By default, this value is true. If set to false, +// this flag indicates that messages can be delivered asynchronously +// from the client to the application and possibly arrive out of order. +func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions { + o.Order = order + return o +} + +// SetTLSConfig will set an SSL/TLS configuration to be used when connecting +// to an MQTT broker. Please read the official Go documentation for more +// information. +func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions { + o.TLSConfig = *t + return o +} + +// SetStore will set the implementation of the Store interface +// used to provide message persistence in cases where QoS levels +// QoS_ONE or QoS_TWO are used. If no store is provided, then the +// client will use MemoryStore by default. +func (o *ClientOptions) SetStore(s Store) *ClientOptions { + o.Store = s + return o +} + +// SetKeepAlive will set the amount of time (in seconds) that the client +// should wait before sending a PING request to the broker. This will +// allow the client to know that a connection has not been lost with the +// server. +func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions { + o.KeepAlive = k + return o +} + +// SetPingTimeout will set the amount of time (in seconds) that the client +// will wait after sending a PING request to the broker, before deciding +// that the connection has been lost. Default is 10 seconds. +func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions { + o.PingTimeout = k + return o +} + +// SetProtocolVersion sets the MQTT version to be used to connect to the +// broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1 +func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions { + if pv >= 3 && pv <= 4 { + o.ProtocolVersion = pv + o.protocolVersionExplicit = true + } + return o +} + +// UnsetWill will cause any set will message to be disregarded. +func (o *ClientOptions) UnsetWill() *ClientOptions { + o.WillEnabled = false + return o +} + +// SetWill accepts a string will message to be set. When the client connects, +// it will give this will message to the broker, which will then publish the +// provided payload (the will) to any clients that are subscribed to the provided +// topic. +func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions { + o.SetBinaryWill(topic, []byte(payload), qos, retained) + return o +} + +// SetBinaryWill accepts a []byte will message to be set. When the client connects, +// it will give this will message to the broker, which will then publish the +// provided payload (the will) to any clients that are subscribed to the provided +// topic. +func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions { + o.WillEnabled = true + o.WillTopic = topic + o.WillPayload = payload + o.WillQos = qos + o.WillRetained = retained + return o +} + +// SetDefaultPublishHandler sets the MessageHandler that will be called when a message +// is received that does not match any known subscriptions. +func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions { + o.DefaultPublishHander = defaultHandler + return o +} + +// SetOnConnectHandler sets the function to be called when the client is connected. Both +// at initial connection time and upon automatic reconnect. +func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions { + o.OnConnect = onConn + return o +} + +// SetConnectionLostHandler will set the OnConnectionLost callback to be executed +// in the case where the client unexpectedly loses connection with the MQTT broker. +func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions { + o.OnConnectionLost = onLost + return o +} + +// SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a +// timeout error. A duration of 0 never times out. Default 30 seconds +func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions { + o.WriteTimeout = t + return o +} + +// SetConnectTimeout limits how long the client will wait when trying to open a connection +// to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out. +// Default 30 seconds. Currently only operational on TCP/TLS connections. +func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions { + o.ConnectTimeout = t + return o +} + +// SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts +// when connection is lost +func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions { + o.MaxReconnectInterval = t + return o +} + +// SetAutoReconnect sets whether the automatic reconnection logic should be used +// when the connection is lost, even if disabled the ConnectionLostHandler is still +// called +func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions { + o.AutoReconnect = a + return o +} + +// SetMessageChannelDepth sets the size of the internal queue that holds messages while the +// client is temporairily offline, allowing the application to publish when the client is +// reconnecting. This setting is only valid if AutoReconnect is set to true, it is otherwise +// ignored. +func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions { + o.MessageChannelDepth = s + return o +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go new file mode 100644 index 00000000..85157d82 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "crypto/tls" + "net/url" + "time" +) + +// ClientOptionsReader provides an interface for reading ClientOptions after the client has been initialized. +type ClientOptionsReader struct { + options *ClientOptions +} + +func (r *ClientOptionsReader) Servers() []*url.URL { + s := make([]*url.URL, len(r.options.Servers)) + + for i, u := range r.options.Servers { + nu := *u + s[i] = &nu + } + + return s +} + +func (r *ClientOptionsReader) ClientID() string { + s := r.options.ClientID + return s +} + +func (r *ClientOptionsReader) Username() string { + s := r.options.Username + return s +} + +func (r *ClientOptionsReader) Password() string { + s := r.options.Password + return s +} + +func (r *ClientOptionsReader) CleanSession() bool { + s := r.options.CleanSession + return s +} + +func (r *ClientOptionsReader) Order() bool { + s := r.options.Order + return s +} + +func (r *ClientOptionsReader) WillEnabled() bool { + s := r.options.WillEnabled + return s +} + +func (r *ClientOptionsReader) WillTopic() string { + s := r.options.WillTopic + return s +} + +func (r *ClientOptionsReader) WillPayload() []byte { + s := r.options.WillPayload + return s +} + +func (r *ClientOptionsReader) WillQos() byte { + s := r.options.WillQos + return s +} + +func (r *ClientOptionsReader) WillRetained() bool { + s := r.options.WillRetained + return s +} + +func (r *ClientOptionsReader) ProtocolVersion() uint { + s := r.options.ProtocolVersion + return s +} + +func (r *ClientOptionsReader) TLSConfig() tls.Config { + s := r.options.TLSConfig + return s +} + +func (r *ClientOptionsReader) KeepAlive() time.Duration { + s := r.options.KeepAlive + return s +} + +func (r *ClientOptionsReader) PingTimeout() time.Duration { + s := r.options.PingTimeout + return s +} + +func (r *ClientOptionsReader) ConnectTimeout() time.Duration { + s := r.options.ConnectTimeout + return s +} + +func (r *ClientOptionsReader) MaxReconnectInterval() time.Duration { + s := r.options.MaxReconnectInterval + return s +} + +func (r *ClientOptionsReader) AutoReconnect() bool { + s := r.options.AutoReconnect + return s +} + +func (r *ClientOptionsReader) WriteTimeout() time.Duration { + s := r.options.WriteTimeout + return s +} + +func (r *ClientOptionsReader) MessageChannelDepth() uint { + s := r.options.MessageChannelDepth + return s +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go new file mode 100644 index 00000000..a512ace0 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go @@ -0,0 +1,51 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//ConnackPacket is an internal representation of the fields of the +//Connack MQTT packet +type ConnackPacket struct { + FixedHeader + SessionPresent bool + ReturnCode byte +} + +func (ca *ConnackPacket) String() string { + str := fmt.Sprintf("%s", ca.FixedHeader) + str += " " + str += fmt.Sprintf("sessionpresent: %t returncode: %d", ca.SessionPresent, ca.ReturnCode) + return str +} + +func (ca *ConnackPacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + + body.WriteByte(boolToByte(ca.SessionPresent)) + body.WriteByte(ca.ReturnCode) + ca.FixedHeader.RemainingLength = 2 + packet := ca.FixedHeader.pack() + packet.Write(body.Bytes()) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (ca *ConnackPacket) Unpack(b io.Reader) error { + ca.SessionPresent = 1&decodeByte(b) > 0 + ca.ReturnCode = decodeByte(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (ca *ConnackPacket) Details() Details { + return Details{Qos: 0, MessageID: 0} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go new file mode 100644 index 00000000..378f0ed5 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go @@ -0,0 +1,122 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//ConnectPacket is an internal representation of the fields of the +//Connect MQTT packet +type ConnectPacket struct { + FixedHeader + ProtocolName string + ProtocolVersion byte + CleanSession bool + WillFlag bool + WillQos byte + WillRetain bool + UsernameFlag bool + PasswordFlag bool + ReservedBit byte + Keepalive uint16 + + ClientIdentifier string + WillTopic string + WillMessage []byte + Username string + Password []byte +} + +func (c *ConnectPacket) String() string { + str := fmt.Sprintf("%s", c.FixedHeader) + str += " " + str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password) + return str +} + +func (c *ConnectPacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + + body.Write(encodeString(c.ProtocolName)) + body.WriteByte(c.ProtocolVersion) + body.WriteByte(boolToByte(c.CleanSession)<<1 | boolToByte(c.WillFlag)<<2 | c.WillQos<<3 | boolToByte(c.WillRetain)<<5 | boolToByte(c.PasswordFlag)<<6 | boolToByte(c.UsernameFlag)<<7) + body.Write(encodeUint16(c.Keepalive)) + body.Write(encodeString(c.ClientIdentifier)) + if c.WillFlag { + body.Write(encodeString(c.WillTopic)) + body.Write(encodeBytes(c.WillMessage)) + } + if c.UsernameFlag { + body.Write(encodeString(c.Username)) + } + if c.PasswordFlag { + body.Write(encodeBytes(c.Password)) + } + c.FixedHeader.RemainingLength = body.Len() + packet := c.FixedHeader.pack() + packet.Write(body.Bytes()) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (c *ConnectPacket) Unpack(b io.Reader) error { + c.ProtocolName = decodeString(b) + c.ProtocolVersion = decodeByte(b) + options := decodeByte(b) + c.ReservedBit = 1 & options + c.CleanSession = 1&(options>>1) > 0 + c.WillFlag = 1&(options>>2) > 0 + c.WillQos = 3 & (options >> 3) + c.WillRetain = 1&(options>>5) > 0 + c.PasswordFlag = 1&(options>>6) > 0 + c.UsernameFlag = 1&(options>>7) > 0 + c.Keepalive = decodeUint16(b) + c.ClientIdentifier = decodeString(b) + if c.WillFlag { + c.WillTopic = decodeString(b) + c.WillMessage = decodeBytes(b) + } + if c.UsernameFlag { + c.Username = decodeString(b) + } + if c.PasswordFlag { + c.Password = decodeBytes(b) + } + + return nil +} + +//Validate performs validation of the fields of a Connect packet +func (c *ConnectPacket) Validate() byte { + if c.PasswordFlag && !c.UsernameFlag { + return ErrRefusedBadUsernameOrPassword + } + if c.ReservedBit != 0 { + //Bad reserved bit + return ErrProtocolViolation + } + if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { + //Mismatched or unsupported protocol version + return ErrRefusedBadProtocolVersion + } + if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { + //Bad protocol name + return ErrProtocolViolation + } + if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { + //Bad size field + return ErrProtocolViolation + } + return Accepted +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (c *ConnectPacket) Details() Details { + return Details{Qos: 0, MessageID: 0} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go new file mode 100644 index 00000000..e5c18692 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go @@ -0,0 +1,36 @@ +package packets + +import ( + "fmt" + "io" +) + +//DisconnectPacket is an internal representation of the fields of the +//Disconnect MQTT packet +type DisconnectPacket struct { + FixedHeader +} + +func (d *DisconnectPacket) String() string { + str := fmt.Sprintf("%s", d.FixedHeader) + return str +} + +func (d *DisconnectPacket) Write(w io.Writer) error { + packet := d.FixedHeader.pack() + _, err := packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (d *DisconnectPacket) Unpack(b io.Reader) error { + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (d *DisconnectPacket) Details() Details { + return Details{Qos: 0, MessageID: 0} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go new file mode 100644 index 00000000..cbc194a2 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go @@ -0,0 +1,322 @@ +package packets + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" +) + +//ControlPacket defines the interface for structs intended to hold +//decoded MQTT packets, either from being read or before being +//written +type ControlPacket interface { + Write(io.Writer) error + Unpack(io.Reader) error + String() string + Details() Details +} + +//PacketNames maps the constants for each of the MQTT packet types +//to a string representation of their name. +var PacketNames = map[uint8]string{ + 1: "CONNECT", + 2: "CONNACK", + 3: "PUBLISH", + 4: "PUBACK", + 5: "PUBREC", + 6: "PUBREL", + 7: "PUBCOMP", + 8: "SUBSCRIBE", + 9: "SUBACK", + 10: "UNSUBSCRIBE", + 11: "UNSUBACK", + 12: "PINGREQ", + 13: "PINGRESP", + 14: "DISCONNECT", +} + +//Below are the constants assigned to each of the MQTT packet types +const ( + Connect = 1 + Connack = 2 + Publish = 3 + Puback = 4 + Pubrec = 5 + Pubrel = 6 + Pubcomp = 7 + Subscribe = 8 + Suback = 9 + Unsubscribe = 10 + Unsuback = 11 + Pingreq = 12 + Pingresp = 13 + Disconnect = 14 +) + +//Below are the const definitions for error codes returned by +//Connect() +const ( + Accepted = 0x00 + ErrRefusedBadProtocolVersion = 0x01 + ErrRefusedIDRejected = 0x02 + ErrRefusedServerUnavailable = 0x03 + ErrRefusedBadUsernameOrPassword = 0x04 + ErrRefusedNotAuthorised = 0x05 + ErrNetworkError = 0xFE + ErrProtocolViolation = 0xFF +) + +//ConnackReturnCodes is a map of the error codes constants for Connect() +//to a string representation of the error +var ConnackReturnCodes = map[uint8]string{ + 0: "Connection Accepted", + 1: "Connection Refused: Bad Protocol Version", + 2: "Connection Refused: Client Identifier Rejected", + 3: "Connection Refused: Server Unavailable", + 4: "Connection Refused: Username or Password in unknown format", + 5: "Connection Refused: Not Authorised", + 254: "Connection Error", + 255: "Connection Refused: Protocol Violation", +} + +//ConnErrors is a map of the errors codes constants for Connect() +//to a Go error +var ConnErrors = map[byte]error{ + Accepted: nil, + ErrRefusedBadProtocolVersion: errors.New("Unnacceptable protocol version"), + ErrRefusedIDRejected: errors.New("Identifier rejected"), + ErrRefusedServerUnavailable: errors.New("Server Unavailable"), + ErrRefusedBadUsernameOrPassword: errors.New("Bad user name or password"), + ErrRefusedNotAuthorised: errors.New("Not Authorized"), + ErrNetworkError: errors.New("Network Error"), + ErrProtocolViolation: errors.New("Protocol Violation"), +} + +//ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts +//to read an MQTT packet from the stream. It returns a ControlPacket +//representing the decoded MQTT packet and an error. One of these returns will +//always be nil, a nil ControlPacket indicating an error occurred. +func ReadPacket(r io.Reader) (cp ControlPacket, err error) { + var fh FixedHeader + b := make([]byte, 1) + + _, err = io.ReadFull(r, b) + if err != nil { + return nil, err + } + fh.unpack(b[0], r) + cp = NewControlPacketWithHeader(fh) + if cp == nil { + return nil, errors.New("Bad data from client") + } + packetBytes := make([]byte, fh.RemainingLength) + _, err = io.ReadFull(r, packetBytes) + if err != nil { + return nil, err + } + err = cp.Unpack(bytes.NewBuffer(packetBytes)) + return cp, err +} + +//NewControlPacket is used to create a new ControlPacket of the type specified +//by packetType, this is usually done by reference to the packet type constants +//defined in packets.go. The newly created ControlPacket is empty and a pointer +//is returned. +func NewControlPacket(packetType byte) (cp ControlPacket) { + switch packetType { + case Connect: + cp = &ConnectPacket{FixedHeader: FixedHeader{MessageType: Connect}} + case Connack: + cp = &ConnackPacket{FixedHeader: FixedHeader{MessageType: Connack}} + case Disconnect: + cp = &DisconnectPacket{FixedHeader: FixedHeader{MessageType: Disconnect}} + case Publish: + cp = &PublishPacket{FixedHeader: FixedHeader{MessageType: Publish}} + case Puback: + cp = &PubackPacket{FixedHeader: FixedHeader{MessageType: Puback}} + case Pubrec: + cp = &PubrecPacket{FixedHeader: FixedHeader{MessageType: Pubrec}} + case Pubrel: + cp = &PubrelPacket{FixedHeader: FixedHeader{MessageType: Pubrel, Qos: 1}} + case Pubcomp: + cp = &PubcompPacket{FixedHeader: FixedHeader{MessageType: Pubcomp}} + case Subscribe: + cp = &SubscribePacket{FixedHeader: FixedHeader{MessageType: Subscribe, Qos: 1}} + case Suback: + cp = &SubackPacket{FixedHeader: FixedHeader{MessageType: Suback}} + case Unsubscribe: + cp = &UnsubscribePacket{FixedHeader: FixedHeader{MessageType: Unsubscribe, Qos: 1}} + case Unsuback: + cp = &UnsubackPacket{FixedHeader: FixedHeader{MessageType: Unsuback}} + case Pingreq: + cp = &PingreqPacket{FixedHeader: FixedHeader{MessageType: Pingreq}} + case Pingresp: + cp = &PingrespPacket{FixedHeader: FixedHeader{MessageType: Pingresp}} + default: + return nil + } + return cp +} + +//NewControlPacketWithHeader is used to create a new ControlPacket of the type +//specified within the FixedHeader that is passed to the function. +//The newly created ControlPacket is empty and a pointer is returned. +func NewControlPacketWithHeader(fh FixedHeader) (cp ControlPacket) { + switch fh.MessageType { + case Connect: + cp = &ConnectPacket{FixedHeader: fh} + case Connack: + cp = &ConnackPacket{FixedHeader: fh} + case Disconnect: + cp = &DisconnectPacket{FixedHeader: fh} + case Publish: + cp = &PublishPacket{FixedHeader: fh} + case Puback: + cp = &PubackPacket{FixedHeader: fh} + case Pubrec: + cp = &PubrecPacket{FixedHeader: fh} + case Pubrel: + cp = &PubrelPacket{FixedHeader: fh} + case Pubcomp: + cp = &PubcompPacket{FixedHeader: fh} + case Subscribe: + cp = &SubscribePacket{FixedHeader: fh} + case Suback: + cp = &SubackPacket{FixedHeader: fh} + case Unsubscribe: + cp = &UnsubscribePacket{FixedHeader: fh} + case Unsuback: + cp = &UnsubackPacket{FixedHeader: fh} + case Pingreq: + cp = &PingreqPacket{FixedHeader: fh} + case Pingresp: + cp = &PingrespPacket{FixedHeader: fh} + default: + return nil + } + return cp +} + +//Details struct returned by the Details() function called on +//ControlPackets to present details of the Qos and MessageID +//of the ControlPacket +type Details struct { + Qos byte + MessageID uint16 +} + +//FixedHeader is a struct to hold the decoded information from +//the fixed header of an MQTT ControlPacket +type FixedHeader struct { + MessageType byte + Dup bool + Qos byte + Retain bool + RemainingLength int +} + +func (fh FixedHeader) String() string { + return fmt.Sprintf("%s: dup: %t qos: %d retain: %t rLength: %d", PacketNames[fh.MessageType], fh.Dup, fh.Qos, fh.Retain, fh.RemainingLength) +} + +func boolToByte(b bool) byte { + switch b { + case true: + return 1 + default: + return 0 + } +} + +func (fh *FixedHeader) pack() bytes.Buffer { + var header bytes.Buffer + header.WriteByte(fh.MessageType<<4 | boolToByte(fh.Dup)<<3 | fh.Qos<<1 | boolToByte(fh.Retain)) + header.Write(encodeLength(fh.RemainingLength)) + return header +} + +func (fh *FixedHeader) unpack(typeAndFlags byte, r io.Reader) { + fh.MessageType = typeAndFlags >> 4 + fh.Dup = (typeAndFlags>>3)&0x01 > 0 + fh.Qos = (typeAndFlags >> 1) & 0x03 + fh.Retain = typeAndFlags&0x01 > 0 + fh.RemainingLength = decodeLength(r) +} + +func decodeByte(b io.Reader) byte { + num := make([]byte, 1) + b.Read(num) + return num[0] +} + +func decodeUint16(b io.Reader) uint16 { + num := make([]byte, 2) + b.Read(num) + return binary.BigEndian.Uint16(num) +} + +func encodeUint16(num uint16) []byte { + bytes := make([]byte, 2) + binary.BigEndian.PutUint16(bytes, num) + return bytes +} + +func encodeString(field string) []byte { + fieldLength := make([]byte, 2) + binary.BigEndian.PutUint16(fieldLength, uint16(len(field))) + return append(fieldLength, []byte(field)...) +} + +func decodeString(b io.Reader) string { + fieldLength := decodeUint16(b) + field := make([]byte, fieldLength) + b.Read(field) + return string(field) +} + +func decodeBytes(b io.Reader) []byte { + fieldLength := decodeUint16(b) + field := make([]byte, fieldLength) + b.Read(field) + return field +} + +func encodeBytes(field []byte) []byte { + fieldLength := make([]byte, 2) + binary.BigEndian.PutUint16(fieldLength, uint16(len(field))) + return append(fieldLength, field...) +} + +func encodeLength(length int) []byte { + var encLength []byte + for { + digit := byte(length % 128) + length /= 128 + if length > 0 { + digit |= 0x80 + } + encLength = append(encLength, digit) + if length == 0 { + break + } + } + return encLength +} + +func decodeLength(r io.Reader) int { + var rLength uint32 + var multiplier uint32 + b := make([]byte, 1) + for multiplier < 27 { //fix: Infinite '(digit & 128) == 1' will cause the dead loop + io.ReadFull(r, b) + digit := b[0] + rLength |= uint32(digit&127) << multiplier + if (digit & 128) == 0 { + break + } + multiplier += 7 + } + return int(rLength) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go new file mode 100644 index 00000000..51d887d0 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go @@ -0,0 +1,159 @@ +package packets + +import ( + "bytes" + "testing" +) + +func TestPacketNames(t *testing.T) { + if PacketNames[1] != "CONNECT" { + t.Errorf("PacketNames[1] is %s, should be %s", PacketNames[1], "CONNECT") + } + if PacketNames[2] != "CONNACK" { + t.Errorf("PacketNames[2] is %s, should be %s", PacketNames[2], "CONNACK") + } + if PacketNames[3] != "PUBLISH" { + t.Errorf("PacketNames[3] is %s, should be %s", PacketNames[3], "PUBLISH") + } + if PacketNames[4] != "PUBACK" { + t.Errorf("PacketNames[4] is %s, should be %s", PacketNames[4], "PUBACK") + } + if PacketNames[5] != "PUBREC" { + t.Errorf("PacketNames[5] is %s, should be %s", PacketNames[5], "PUBREC") + } + if PacketNames[6] != "PUBREL" { + t.Errorf("PacketNames[6] is %s, should be %s", PacketNames[6], "PUBREL") + } + if PacketNames[7] != "PUBCOMP" { + t.Errorf("PacketNames[7] is %s, should be %s", PacketNames[7], "PUBCOMP") + } + if PacketNames[8] != "SUBSCRIBE" { + t.Errorf("PacketNames[8] is %s, should be %s", PacketNames[8], "SUBSCRIBE") + } + if PacketNames[9] != "SUBACK" { + t.Errorf("PacketNames[9] is %s, should be %s", PacketNames[9], "SUBACK") + } + if PacketNames[10] != "UNSUBSCRIBE" { + t.Errorf("PacketNames[10] is %s, should be %s", PacketNames[10], "UNSUBSCRIBE") + } + if PacketNames[11] != "UNSUBACK" { + t.Errorf("PacketNames[11] is %s, should be %s", PacketNames[11], "UNSUBACK") + } + if PacketNames[12] != "PINGREQ" { + t.Errorf("PacketNames[12] is %s, should be %s", PacketNames[12], "PINGREQ") + } + if PacketNames[13] != "PINGRESP" { + t.Errorf("PacketNames[13] is %s, should be %s", PacketNames[13], "PINGRESP") + } + if PacketNames[14] != "DISCONNECT" { + t.Errorf("PacketNames[14] is %s, should be %s", PacketNames[14], "DISCONNECT") + } +} + +func TestPacketConsts(t *testing.T) { + if Connect != 1 { + t.Errorf("Const for Connect is %d, should be %d", Connect, 1) + } + if Connack != 2 { + t.Errorf("Const for Connack is %d, should be %d", Connack, 2) + } + if Publish != 3 { + t.Errorf("Const for Publish is %d, should be %d", Publish, 3) + } + if Puback != 4 { + t.Errorf("Const for Puback is %d, should be %d", Puback, 4) + } + if Pubrec != 5 { + t.Errorf("Const for Pubrec is %d, should be %d", Pubrec, 5) + } + if Pubrel != 6 { + t.Errorf("Const for Pubrel is %d, should be %d", Pubrel, 6) + } + if Pubcomp != 7 { + t.Errorf("Const for Pubcomp is %d, should be %d", Pubcomp, 7) + } + if Subscribe != 8 { + t.Errorf("Const for Subscribe is %d, should be %d", Subscribe, 8) + } + if Suback != 9 { + t.Errorf("Const for Suback is %d, should be %d", Suback, 9) + } + if Unsubscribe != 10 { + t.Errorf("Const for Unsubscribe is %d, should be %d", Unsubscribe, 10) + } + if Unsuback != 11 { + t.Errorf("Const for Unsuback is %d, should be %d", Unsuback, 11) + } + if Pingreq != 12 { + t.Errorf("Const for Pingreq is %d, should be %d", Pingreq, 12) + } + if Pingresp != 13 { + t.Errorf("Const for Pingresp is %d, should be %d", Pingresp, 13) + } + if Disconnect != 14 { + t.Errorf("Const for Disconnect is %d, should be %d", Disconnect, 14) + } +} + +func TestConnackConsts(t *testing.T) { + if Accepted != 0x00 { + t.Errorf("Const for Accepted is %d, should be %d", Accepted, 0) + } + if ErrRefusedBadProtocolVersion != 0x01 { + t.Errorf("Const for RefusedBadProtocolVersion is %d, should be %d", ErrRefusedBadProtocolVersion, 1) + } + if ErrRefusedIDRejected != 0x02 { + t.Errorf("Const for RefusedIDRejected is %d, should be %d", ErrRefusedIDRejected, 2) + } + if ErrRefusedServerUnavailable != 0x03 { + t.Errorf("Const for RefusedServerUnavailable is %d, should be %d", ErrRefusedServerUnavailable, 3) + } + if ErrRefusedBadUsernameOrPassword != 0x04 { + t.Errorf("Const for RefusedBadUsernameOrPassword is %d, should be %d", ErrRefusedBadUsernameOrPassword, 4) + } + if ErrRefusedNotAuthorised != 0x05 { + t.Errorf("Const for RefusedNotAuthorised is %d, should be %d", ErrRefusedNotAuthorised, 5) + } +} + +func TestConnectPacket(t *testing.T) { + connectPacketBytes := bytes.NewBuffer([]byte{16, 52, 0, 4, 77, 81, 84, 84, 4, 204, 0, 0, 0, 0, 0, 4, 116, 101, 115, 116, 0, 12, 84, 101, 115, 116, 32, 80, 97, 121, 108, 111, 97, 100, 0, 8, 116, 101, 115, 116, 117, 115, 101, 114, 0, 8, 116, 101, 115, 116, 112, 97, 115, 115}) + packet, err := ReadPacket(connectPacketBytes) + if err != nil { + t.Fatalf("Error reading packet: %s", err.Error()) + } + cp := packet.(*ConnectPacket) + if cp.ProtocolName != "MQTT" { + t.Errorf("Connect Packet ProtocolName is %s, should be %s", cp.ProtocolName, "MQTT") + } + if cp.ProtocolVersion != 4 { + t.Errorf("Connect Packet ProtocolVersion is %d, should be %d", cp.ProtocolVersion, 4) + } + if cp.UsernameFlag != true { + t.Errorf("Connect Packet UsernameFlag is %t, should be %t", cp.UsernameFlag, true) + } + if cp.Username != "testuser" { + t.Errorf("Connect Packet Username is %s, should be %s", cp.Username, "testuser") + } + if cp.PasswordFlag != true { + t.Errorf("Connect Packet PasswordFlag is %t, should be %t", cp.PasswordFlag, true) + } + if string(cp.Password) != "testpass" { + t.Errorf("Connect Packet Password is %s, should be %s", string(cp.Password), "testpass") + } + if cp.WillFlag != true { + t.Errorf("Connect Packet WillFlag is %t, should be %t", cp.WillFlag, true) + } + if cp.WillTopic != "test" { + t.Errorf("Connect Packet WillTopic is %s, should be %s", cp.WillTopic, "test") + } + if cp.WillQos != 1 { + t.Errorf("Connect Packet WillQos is %d, should be %d", cp.WillQos, 1) + } + if cp.WillRetain != false { + t.Errorf("Connect Packet WillRetain is %t, should be %t", cp.WillRetain, false) + } + if string(cp.WillMessage) != "Test Payload" { + t.Errorf("Connect Packet WillMessage is %s, should be %s", string(cp.WillMessage), "Test Payload") + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go new file mode 100644 index 00000000..5c3e88f9 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go @@ -0,0 +1,36 @@ +package packets + +import ( + "fmt" + "io" +) + +//PingreqPacket is an internal representation of the fields of the +//Pingreq MQTT packet +type PingreqPacket struct { + FixedHeader +} + +func (pr *PingreqPacket) String() string { + str := fmt.Sprintf("%s", pr.FixedHeader) + return str +} + +func (pr *PingreqPacket) Write(w io.Writer) error { + packet := pr.FixedHeader.pack() + _, err := packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pr *PingreqPacket) Unpack(b io.Reader) error { + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pr *PingreqPacket) Details() Details { + return Details{Qos: 0, MessageID: 0} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go new file mode 100644 index 00000000..39ebc001 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go @@ -0,0 +1,36 @@ +package packets + +import ( + "fmt" + "io" +) + +//PingrespPacket is an internal representation of the fields of the +//Pingresp MQTT packet +type PingrespPacket struct { + FixedHeader +} + +func (pr *PingrespPacket) String() string { + str := fmt.Sprintf("%s", pr.FixedHeader) + return str +} + +func (pr *PingrespPacket) Write(w io.Writer) error { + packet := pr.FixedHeader.pack() + _, err := packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pr *PingrespPacket) Unpack(b io.Reader) error { + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pr *PingrespPacket) Details() Details { + return Details{Qos: 0, MessageID: 0} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go new file mode 100644 index 00000000..e30402cd --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go @@ -0,0 +1,44 @@ +package packets + +import ( + "fmt" + "io" +) + +//PubackPacket is an internal representation of the fields of the +//Puback MQTT packet +type PubackPacket struct { + FixedHeader + MessageID uint16 +} + +func (pa *PubackPacket) String() string { + str := fmt.Sprintf("%s", pa.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", pa.MessageID) + return str +} + +func (pa *PubackPacket) Write(w io.Writer) error { + var err error + pa.FixedHeader.RemainingLength = 2 + packet := pa.FixedHeader.pack() + packet.Write(encodeUint16(pa.MessageID)) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pa *PubackPacket) Unpack(b io.Reader) error { + pa.MessageID = decodeUint16(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pa *PubackPacket) Details() Details { + return Details{Qos: pa.Qos, MessageID: pa.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go new file mode 100644 index 00000000..fb994ae7 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go @@ -0,0 +1,44 @@ +package packets + +import ( + "fmt" + "io" +) + +//PubcompPacket is an internal representation of the fields of the +//Pubcomp MQTT packet +type PubcompPacket struct { + FixedHeader + MessageID uint16 +} + +func (pc *PubcompPacket) String() string { + str := fmt.Sprintf("%s", pc.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", pc.MessageID) + return str +} + +func (pc *PubcompPacket) Write(w io.Writer) error { + var err error + pc.FixedHeader.RemainingLength = 2 + packet := pc.FixedHeader.pack() + packet.Write(encodeUint16(pc.MessageID)) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pc *PubcompPacket) Unpack(b io.Reader) error { + pc.MessageID = decodeUint16(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pc *PubcompPacket) Details() Details { + return Details{Qos: pc.Qos, MessageID: pc.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go new file mode 100644 index 00000000..b660ef4c --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go @@ -0,0 +1,80 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//PublishPacket is an internal representation of the fields of the +//Publish MQTT packet +type PublishPacket struct { + FixedHeader + TopicName string + MessageID uint16 + Payload []byte +} + +func (p *PublishPacket) String() string { + str := fmt.Sprintf("%s", p.FixedHeader) + str += " " + str += fmt.Sprintf("topicName: %s MessageID: %d", p.TopicName, p.MessageID) + str += " " + str += fmt.Sprintf("payload: %s", string(p.Payload)) + return str +} + +func (p *PublishPacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + + body.Write(encodeString(p.TopicName)) + if p.Qos > 0 { + body.Write(encodeUint16(p.MessageID)) + } + p.FixedHeader.RemainingLength = body.Len() + len(p.Payload) + packet := p.FixedHeader.pack() + packet.Write(body.Bytes()) + packet.Write(p.Payload) + _, err = w.Write(packet.Bytes()) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (p *PublishPacket) Unpack(b io.Reader) error { + var payloadLength = p.FixedHeader.RemainingLength + p.TopicName = decodeString(b) + if p.Qos > 0 { + p.MessageID = decodeUint16(b) + payloadLength -= len(p.TopicName) + 4 + } else { + payloadLength -= len(p.TopicName) + 2 + } + if payloadLength < 0 { + return fmt.Errorf("Error upacking publish, payload length < 0") + } + p.Payload = make([]byte, payloadLength) + _, err := b.Read(p.Payload) + + return err +} + +//Copy creates a new PublishPacket with the same topic and payload +//but an empty fixed header, useful for when you want to deliver +//a message with different properties such as Qos but the same +//content +func (p *PublishPacket) Copy() *PublishPacket { + newP := NewControlPacket(Publish).(*PublishPacket) + newP.TopicName = p.TopicName + newP.Payload = p.Payload + + return newP +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (p *PublishPacket) Details() Details { + return Details{Qos: p.Qos, MessageID: p.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go new file mode 100644 index 00000000..9874e641 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go @@ -0,0 +1,44 @@ +package packets + +import ( + "fmt" + "io" +) + +//PubrecPacket is an internal representation of the fields of the +//Pubrec MQTT packet +type PubrecPacket struct { + FixedHeader + MessageID uint16 +} + +func (pr *PubrecPacket) String() string { + str := fmt.Sprintf("%s", pr.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", pr.MessageID) + return str +} + +func (pr *PubrecPacket) Write(w io.Writer) error { + var err error + pr.FixedHeader.RemainingLength = 2 + packet := pr.FixedHeader.pack() + packet.Write(encodeUint16(pr.MessageID)) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pr *PubrecPacket) Unpack(b io.Reader) error { + pr.MessageID = decodeUint16(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pr *PubrecPacket) Details() Details { + return Details{Qos: pr.Qos, MessageID: pr.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go new file mode 100644 index 00000000..a7ecce75 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go @@ -0,0 +1,44 @@ +package packets + +import ( + "fmt" + "io" +) + +//PubrelPacket is an internal representation of the fields of the +//Pubrel MQTT packet +type PubrelPacket struct { + FixedHeader + MessageID uint16 +} + +func (pr *PubrelPacket) String() string { + str := fmt.Sprintf("%s", pr.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", pr.MessageID) + return str +} + +func (pr *PubrelPacket) Write(w io.Writer) error { + var err error + pr.FixedHeader.RemainingLength = 2 + packet := pr.FixedHeader.pack() + packet.Write(encodeUint16(pr.MessageID)) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (pr *PubrelPacket) Unpack(b io.Reader) error { + pr.MessageID = decodeUint16(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (pr *PubrelPacket) Details() Details { + return Details{Qos: pr.Qos, MessageID: pr.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go new file mode 100644 index 00000000..557a7dbe --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go @@ -0,0 +1,52 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//SubackPacket is an internal representation of the fields of the +//Suback MQTT packet +type SubackPacket struct { + FixedHeader + MessageID uint16 + ReturnCodes []byte +} + +func (sa *SubackPacket) String() string { + str := fmt.Sprintf("%s", sa.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", sa.MessageID) + return str +} + +func (sa *SubackPacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + body.Write(encodeUint16(sa.MessageID)) + body.Write(sa.ReturnCodes) + sa.FixedHeader.RemainingLength = body.Len() + packet := sa.FixedHeader.pack() + packet.Write(body.Bytes()) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (sa *SubackPacket) Unpack(b io.Reader) error { + var qosBuffer bytes.Buffer + sa.MessageID = decodeUint16(b) + qosBuffer.ReadFrom(b) + sa.ReturnCodes = qosBuffer.Bytes() + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (sa *SubackPacket) Details() Details { + return Details{Qos: 0, MessageID: sa.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go new file mode 100644 index 00000000..c418ef0f --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go @@ -0,0 +1,62 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//SubscribePacket is an internal representation of the fields of the +//Subscribe MQTT packet +type SubscribePacket struct { + FixedHeader + MessageID uint16 + Topics []string + Qoss []byte +} + +func (s *SubscribePacket) String() string { + str := fmt.Sprintf("%s", s.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics) + return str +} + +func (s *SubscribePacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + + body.Write(encodeUint16(s.MessageID)) + for i, topic := range s.Topics { + body.Write(encodeString(topic)) + body.WriteByte(s.Qoss[i]) + } + s.FixedHeader.RemainingLength = body.Len() + packet := s.FixedHeader.pack() + packet.Write(body.Bytes()) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (s *SubscribePacket) Unpack(b io.Reader) error { + s.MessageID = decodeUint16(b) + payloadLength := s.FixedHeader.RemainingLength - 2 + for payloadLength > 0 { + topic := decodeString(b) + s.Topics = append(s.Topics, topic) + qos := decodeByte(b) + s.Qoss = append(s.Qoss, qos) + payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos + } + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (s *SubscribePacket) Details() Details { + return Details{Qos: 1, MessageID: s.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go new file mode 100644 index 00000000..b3b91ce3 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go @@ -0,0 +1,44 @@ +package packets + +import ( + "fmt" + "io" +) + +//UnsubackPacket is an internal representation of the fields of the +//Unsuback MQTT packet +type UnsubackPacket struct { + FixedHeader + MessageID uint16 +} + +func (ua *UnsubackPacket) String() string { + str := fmt.Sprintf("%s", ua.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", ua.MessageID) + return str +} + +func (ua *UnsubackPacket) Write(w io.Writer) error { + var err error + ua.FixedHeader.RemainingLength = 2 + packet := ua.FixedHeader.pack() + packet.Write(encodeUint16(ua.MessageID)) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (ua *UnsubackPacket) Unpack(b io.Reader) error { + ua.MessageID = decodeUint16(b) + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (ua *UnsubackPacket) Details() Details { + return Details{Qos: 0, MessageID: ua.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go new file mode 100644 index 00000000..dc6a89ec --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go @@ -0,0 +1,55 @@ +package packets + +import ( + "bytes" + "fmt" + "io" +) + +//UnsubscribePacket is an internal representation of the fields of the +//Unsubscribe MQTT packet +type UnsubscribePacket struct { + FixedHeader + MessageID uint16 + Topics []string +} + +func (u *UnsubscribePacket) String() string { + str := fmt.Sprintf("%s", u.FixedHeader) + str += " " + str += fmt.Sprintf("MessageID: %d", u.MessageID) + return str +} + +func (u *UnsubscribePacket) Write(w io.Writer) error { + var body bytes.Buffer + var err error + body.Write(encodeUint16(u.MessageID)) + for _, topic := range u.Topics { + body.Write(encodeString(topic)) + } + u.FixedHeader.RemainingLength = body.Len() + packet := u.FixedHeader.pack() + packet.Write(body.Bytes()) + _, err = packet.WriteTo(w) + + return err +} + +//Unpack decodes the details of a ControlPacket after the fixed +//header has been read +func (u *UnsubscribePacket) Unpack(b io.Reader) error { + u.MessageID = decodeUint16(b) + var topic string + for topic = decodeString(b); topic != ""; topic = decodeString(b) { + u.Topics = append(u.Topics, topic) + } + + return nil +} + +//Details returns a Details struct containing the Qos and +//MessageID of this ControlPacket +func (u *UnsubscribePacket) Details() Details { + return Details{Qos: 1, MessageID: u.MessageID} +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go new file mode 100644 index 00000000..2558db2d --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "errors" + "time" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +func keepalive(c *client) { + DEBUG.Println(PNG, "keepalive starting") + + receiveInterval := c.options.KeepAlive + (1 * time.Second) + pingTimer := timer{Timer: time.NewTimer(c.options.KeepAlive)} + receiveTimer := timer{Timer: time.NewTimer(receiveInterval)} + pingRespTimer := timer{Timer: time.NewTimer(c.options.PingTimeout)} + + pingRespTimer.Stop() + + for { + select { + case <-c.stop: + DEBUG.Println(PNG, "keepalive stopped") + c.workers.Done() + return + case <-pingTimer.C: + sendPing(&pingTimer, &pingRespTimer, c) + case <-c.keepaliveReset: + DEBUG.Println(NET, "resetting ping timer") + pingTimer.Reset(c.options.KeepAlive) + case <-c.pingResp: + DEBUG.Println(NET, "resetting ping timeout timer") + pingRespTimer.Stop() + pingTimer.Reset(c.options.KeepAlive) + receiveTimer.Reset(receiveInterval) + case <-c.packetResp: + DEBUG.Println(NET, "resetting receive timer") + receiveTimer.Reset(receiveInterval) + case <-receiveTimer.C: + receiveTimer.SetRead(true) + receiveTimer.Reset(receiveInterval) + sendPing(&pingTimer, &pingRespTimer, c) + case <-pingRespTimer.C: + pingRespTimer.SetRead(true) + CRITICAL.Println(PNG, "pingresp not received, disconnecting") + c.workers.Done() + c.internalConnLost(errors.New("pingresp not received, disconnecting")) + pingTimer.Stop() + return + } + } +} + +type timer struct { + *time.Timer + readFrom bool +} + +func (t *timer) SetRead(v bool) { + t.readFrom = v +} + +func (t *timer) Stop() bool { + defer t.SetRead(true) + + if !t.Timer.Stop() && !t.readFrom { + <-t.C + return false + } + return true +} + +func (t *timer) Reset(d time.Duration) bool { + defer t.SetRead(false) + t.Stop() + return t.Timer.Reset(d) +} + +func sendPing(pt *timer, rt *timer, c *client) { + pt.SetRead(true) + DEBUG.Println(PNG, "keepalive sending ping") + ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) + //We don't want to wait behind large messages being sent, the Write call + //will block until it it able to send the packet. + ping.Write(c.conn) + + rt.Reset(c.options.PingTimeout) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go new file mode 100644 index 00000000..9e44b0f7 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "container/list" + "strings" + "sync" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +// route is a type which associates MQTT Topic strings with a +// callback to be executed upon the arrival of a message associated +// with a subscription to that topic. +type route struct { + topic string + callback MessageHandler +} + +// match takes a slice of strings which represent the route being tested having been split on '/' +// separators, and a slice of strings representing the topic string in the published message, similarly +// split. +// The function determines if the topic string matches the route according to the MQTT topic rules +// and returns a boolean of the outcome +func match(route []string, topic []string) bool { + if len(route) == 0 { + if len(topic) == 0 { + return true + } + return false + } + + if len(topic) == 0 { + if route[0] == "#" { + return true + } + return false + } + + if route[0] == "#" { + return true + } + + if (route[0] == "+") || (route[0] == topic[0]) { + return match(route[1:], topic[1:]) + } + + return false +} + +func routeIncludesTopic(route, topic string) bool { + return match(strings.Split(route, "/"), strings.Split(topic, "/")) +} + +// match takes the topic string of the published message and does a basic compare to the +// string of the current Route, if they match it returns true +func (r *route) match(topic string) bool { + return r.topic == topic || routeIncludesTopic(r.topic, topic) +} + +type router struct { + sync.RWMutex + routes *list.List + defaultHandler MessageHandler + messages chan *packets.PublishPacket + stop chan bool +} + +// newRouter returns a new instance of a Router and channel which can be used to tell the Router +// to stop +func newRouter() (*router, chan bool) { + router := &router{routes: list.New(), messages: make(chan *packets.PublishPacket), stop: make(chan bool)} + stop := router.stop + return router, stop +} + +// addRoute takes a topic string and MessageHandler callback. It looks in the current list of +// routes to see if there is already a matching Route. If there is it replaces the current +// callback with the new one. If not it add a new entry to the list of Routes. +func (r *router) addRoute(topic string, callback MessageHandler) { + r.Lock() + defer r.Unlock() + for e := r.routes.Front(); e != nil; e = e.Next() { + if e.Value.(*route).match(topic) { + r := e.Value.(*route) + r.callback = callback + return + } + } + r.routes.PushBack(&route{topic: topic, callback: callback}) +} + +// deleteRoute takes a route string, looks for a matching Route in the list of Routes. If +// found it removes the Route from the list. +func (r *router) deleteRoute(topic string) { + r.Lock() + defer r.Unlock() + for e := r.routes.Front(); e != nil; e = e.Next() { + if e.Value.(*route).match(topic) { + r.routes.Remove(e) + return + } + } +} + +// setDefaultHandler assigns a default callback that will be called if no matching Route +// is found for an incoming Publish. +func (r *router) setDefaultHandler(handler MessageHandler) { + r.Lock() + defer r.Unlock() + r.defaultHandler = handler +} + +// matchAndDispatch takes a channel of Message pointers as input and starts a go routine that +// takes messages off the channel, matches them against the internal route list and calls the +// associated callback (or the defaultHandler, if one exists and no other route matched). If +// anything is sent down the stop channel the function will end. +func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order bool, client *client) { + go func() { + for { + select { + case message := <-messages: + sent := false + r.RLock() + for e := r.routes.Front(); e != nil; e = e.Next() { + if e.Value.(*route).match(message.TopicName) { + if order { + e.Value.(*route).callback(client, messageFromPublish(message)) + } else { + go e.Value.(*route).callback(client, messageFromPublish(message)) + } + sent = true + } + } + if !sent && r.defaultHandler != nil { + if order { + r.defaultHandler(client, messageFromPublish(message)) + } else { + go r.defaultHandler(client, messageFromPublish(message)) + } + } + r.RUnlock() + case <-r.stop: + return + } + } + }() +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go new file mode 100644 index 00000000..1cc9e1d3 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "fmt" + "strconv" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +const ( + inboundPrefix = "i." + outboundPrefix = "o." +) + +// Store is an interface which can be used to provide implementations +// for message persistence. +// Because we may have to store distinct messages with the same +// message ID, we need a unique key for each message. This is +// possible by prepending "i." or "o." to each message id +type Store interface { + Open() + Put(key string, message packets.ControlPacket) + Get(key string) packets.ControlPacket + All() []string + Del(key string) + Close() + Reset() +} + +// A key MUST have the form "X.[messageid]" +// where X is 'i' or 'o' +func mIDFromKey(key string) uint16 { + s := key[2:] + i, err := strconv.Atoi(s) + chkerr(err) + return uint16(i) +} + +// Return a string of the form "i.[id]" +func inboundKeyFromMID(id uint16) string { + return fmt.Sprintf("%s%d", inboundPrefix, id) +} + +// Return a string of the form "o.[id]" +func outboundKeyFromMID(id uint16) string { + return fmt.Sprintf("%s%d", outboundPrefix, id) +} + +// govern which outgoing messages are persisted +func persistOutbound(s Store, m packets.ControlPacket) { + switch m.Details().Qos { + case 0: + switch m.(type) { + case *packets.PubackPacket, *packets.PubcompPacket: + // Sending puback. delete matching publish + // from ibound + s.Del(inboundKeyFromMID(m.Details().MessageID)) + } + case 1: + switch m.(type) { + case *packets.PublishPacket, *packets.PubrelPacket, *packets.SubscribePacket, *packets.UnsubscribePacket: + // Sending publish. store in obound + // until puback received + s.Put(outboundKeyFromMID(m.Details().MessageID), m) + default: + ERROR.Println(STR, "Asked to persist an invalid message type") + } + case 2: + switch m.(type) { + case *packets.PublishPacket: + // Sending publish. store in obound + // until pubrel received + s.Put(outboundKeyFromMID(m.Details().MessageID), m) + default: + ERROR.Println(STR, "Asked to persist an invalid message type") + } + } +} + +// govern which incoming messages are persisted +func persistInbound(s Store, m packets.ControlPacket) { + switch m.Details().Qos { + case 0: + switch m.(type) { + case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: + // Received a puback. delete matching publish + // from obound + s.Del(outboundKeyFromMID(m.Details().MessageID)) + case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: + default: + ERROR.Println(STR, "Asked to persist an invalid messages type") + } + case 1: + switch m.(type) { + case *packets.PublishPacket, *packets.PubrelPacket: + // Received a publish. store it in ibound + // until puback sent + s.Put(inboundKeyFromMID(m.Details().MessageID), m) + default: + ERROR.Println(STR, "Asked to persist an invalid messages type") + } + case 2: + switch m.(type) { + case *packets.PublishPacket: + // Received a publish. store it in ibound + // until pubrel received + s.Put(inboundKeyFromMID(m.Details().MessageID), m) + default: + ERROR.Println(STR, "Asked to persist an invalid messages type") + } + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go new file mode 100644 index 00000000..dc54d6d6 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Allan Stockdill-Mander + */ + +package mqtt + +import ( + "sync" + "time" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +//PacketAndToken is a struct that contains both a ControlPacket and a +//Token. This struct is passed via channels between the client interface +//code and the underlying code responsible for sending and receiving +//MQTT messages. +type PacketAndToken struct { + p packets.ControlPacket + t Token +} + +//Token defines the interface for the tokens used to indicate when +//actions have completed. +type Token interface { + Wait() bool + WaitTimeout(time.Duration) bool + flowComplete() + Error() error +} + +type baseToken struct { + m sync.RWMutex + complete chan struct{} + ready bool + err error +} + +// Wait will wait indefinitely for the Token to complete, ie the Publish +// to be sent and confirmed receipt from the broker +func (b *baseToken) Wait() bool { + b.m.Lock() + defer b.m.Unlock() + if !b.ready { + <-b.complete + b.ready = true + } + return b.ready +} + +// WaitTimeout takes a time in ms to wait for the flow associated with the +// Token to complete, returns true if it returned before the timeout or +// returns false if the timeout occurred. In the case of a timeout the Token +// does not have an error set in case the caller wishes to wait again +func (b *baseToken) WaitTimeout(d time.Duration) bool { + b.m.Lock() + defer b.m.Unlock() + if !b.ready { + select { + case <-b.complete: + b.ready = true + case <-time.After(d): + } + } + return b.ready +} + +func (b *baseToken) flowComplete() { + close(b.complete) +} + +func (b *baseToken) Error() error { + b.m.RLock() + defer b.m.RUnlock() + return b.err +} + +func newToken(tType byte) Token { + switch tType { + case packets.Connect: + return &ConnectToken{baseToken: baseToken{complete: make(chan struct{})}} + case packets.Subscribe: + return &SubscribeToken{baseToken: baseToken{complete: make(chan struct{})}, subResult: make(map[string]byte)} + case packets.Publish: + return &PublishToken{baseToken: baseToken{complete: make(chan struct{})}} + case packets.Unsubscribe: + return &UnsubscribeToken{baseToken: baseToken{complete: make(chan struct{})}} + case packets.Disconnect: + return &DisconnectToken{baseToken: baseToken{complete: make(chan struct{})}} + } + return nil +} + +//ConnectToken is an extension of Token containing the extra fields +//required to provide information about calls to Connect() +type ConnectToken struct { + baseToken + returnCode byte +} + +//ReturnCode returns the acknowlegement code in the connack sent +//in response to a Connect() +func (c *ConnectToken) ReturnCode() byte { + c.m.RLock() + defer c.m.RUnlock() + return c.returnCode +} + +//PublishToken is an extension of Token containing the extra fields +//required to provide information about calls to Publish() +type PublishToken struct { + baseToken + messageID uint16 +} + +//MessageID returns the MQTT message ID that was assigned to the +//Publish packet when it was sent to the broker +func (p *PublishToken) MessageID() uint16 { + return p.messageID +} + +//SubscribeToken is an extension of Token containing the extra fields +//required to provide information about calls to Subscribe() +type SubscribeToken struct { + baseToken + subs []string + subResult map[string]byte +} + +//Result returns a map of topics that were subscribed to along with +//the matching return code from the broker. This is either the Qos +//value of the subscription or an error code. +func (s *SubscribeToken) Result() map[string]byte { + s.m.RLock() + defer s.m.RUnlock() + return s.subResult +} + +//UnsubscribeToken is an extension of Token containing the extra fields +//required to provide information about calls to Unsubscribe() +type UnsubscribeToken struct { + baseToken +} + +//DisconnectToken is an extension of Token containing the extra fields +//required to provide information about calls to Disconnect() +type DisconnectToken struct { + baseToken +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go new file mode 100644 index 00000000..6fa3ad2a --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "errors" + "strings" +) + +//ErrInvalidQos is the error returned when an packet is to be sent +//with an invalid Qos value +var ErrInvalidQos = errors.New("Invalid QoS") + +//ErrInvalidTopicEmptyString is the error returned when a topic string +//is passed in that is 0 length +var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string") + +//ErrInvalidTopicMultilevel is the error returned when a topic string +//is passed in that has the multi level wildcard in any position but +//the last +var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level") + +// Topic Names and Topic Filters +// The MQTT v3.1.1 spec clarifies a number of ambiguities with regard +// to the validity of Topic strings. +// - A Topic must be between 1 and 65535 bytes. +// - A Topic is case sensitive. +// - A Topic may contain whitespace. +// - A Topic containing a leading forward slash is different than a Topic without. +// - A Topic may be "/" (two levels, both empty string). +// - A Topic must be UTF-8 encoded. +// - A Topic may contain any number of levels. +// - A Topic may contain an empty level (two forward slashes in a row). +// - A TopicName may not contain a wildcard. +// - A TopicFilter may only have a # (multi-level) wildcard as the last level. +// - A TopicFilter may contain any number of + (single-level) wildcards. +// - A TopicFilter with a # will match the absense of a level +// Example: a subscription to "foo/#" will match messages published to "foo". + +func validateSubscribeMap(subs map[string]byte) ([]string, []byte, error) { + var topics []string + var qoss []byte + for topic, qos := range subs { + if err := validateTopicAndQos(topic, qos); err != nil { + return nil, nil, err + } + topics = append(topics, topic) + qoss = append(qoss, qos) + } + + return topics, qoss, nil +} + +func validateTopicAndQos(topic string, qos byte) error { + if len(topic) == 0 { + return ErrInvalidTopicEmptyString + } + + levels := strings.Split(topic, "/") + for i, level := range levels { + if level == "#" && i != len(levels)-1 { + return ErrInvalidTopicMultilevel + } + } + + if qos < 0 || qos > 2 { + return ErrInvalidQos + } + return nil +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go new file mode 100644 index 00000000..2f5a0146 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "io/ioutil" + "log" +) + +// Internal levels of library output that are initialised to not print +// anything but can be overridden by programmer +var ( + ERROR *log.Logger + CRITICAL *log.Logger + WARN *log.Logger + DEBUG *log.Logger +) + +func init() { + ERROR = log.New(ioutil.Discard, "", 0) + CRITICAL = log.New(ioutil.Discard, "", 0) + WARN = log.New(ioutil.Discard, "", 0) + DEBUG = log.New(ioutil.Discard, "", 0) +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go new file mode 100644 index 00000000..0a57c6b8 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "log" + "net/http" + "os" + "testing" + + _ "net/http/pprof" +) + +func init() { + DEBUG = log.New(os.Stderr, "DEBUG ", log.Ltime) + WARN = log.New(os.Stderr, "WARNING ", log.Ltime) + CRITICAL = log.New(os.Stderr, "CRITICAL ", log.Ltime) + ERROR = log.New(os.Stderr, "ERROR ", log.Ltime) + + go func() { + log.Println(http.ListenAndServe("localhost:6060", nil)) + }() +} + +func Test_NewClient_simple(t *testing.T) { + ops := NewClientOptions().SetClientID("foo").AddBroker("tcp://10.10.0.1:1883") + c := NewClient(ops).(*client) + + if c == nil { + t.Fatalf("ops is nil") + } + + if c.options.ClientID != "foo" { + t.Fatalf("bad client id") + } + + if c.options.Servers[0].Scheme != "tcp" { + t.Fatalf("bad server scheme") + } + + if c.options.Servers[0].Host != "10.10.0.1:1883" { + t.Fatalf("bad server host") + } +} + +func Test_NewClient_optionsReader(t *testing.T) { + ops := NewClientOptions().SetClientID("foo").AddBroker("tcp://10.10.0.1:1883") + c := NewClient(ops).(*client) + + if c == nil { + t.Fatalf("ops is nil") + } + + rOps := c.OptionsReader() + cid := rOps.ClientID() + + if cid != "foo" { + t.Fatalf("unable to read client ID") + } + + servers := rOps.Servers() + broker := servers[0] + if broker.Hostname() != "10.10.0.1" { + t.Fatalf("unable to read hostname") + } + +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go new file mode 100644 index 00000000..9d941f69 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "fmt" + "testing" + "time" +) + +type DummyToken struct{} + +func (d *DummyToken) Wait() bool { + return true +} + +func (d *DummyToken) WaitTimeout(t time.Duration) bool { + return true +} + +func (d *DummyToken) flowComplete() {} + +func (d *DummyToken) Error() error { + return nil +} + +func Test_getID(t *testing.T) { + mids := &messageIds{index: make(map[uint16]Token)} + + i1 := mids.getID(&DummyToken{}) + + if i1 != 1 { + t.Fatalf("i1 was wrong: %v", i1) + } + + i2 := mids.getID(&DummyToken{}) + + if i2 != 2 { + t.Fatalf("i2 was wrong: %v", i2) + } + + for i := uint16(3); i < 100; i++ { + id := mids.getID(&DummyToken{}) + if id != i { + t.Fatalf("id was wrong expected %v got %v", i, id) + } + } +} + +func Test_freeID(t *testing.T) { + mids := &messageIds{index: make(map[uint16]Token)} + + i1 := mids.getID(&DummyToken{}) + mids.freeID(i1) + + if i1 != 1 { + t.Fatalf("i1 was wrong: %v", i1) + } + + i2 := mids.getID(&DummyToken{}) + fmt.Printf("i2: %v\n", i2) +} + +func Test_messageids_mix(t *testing.T) { + mids := &messageIds{index: make(map[uint16]Token)} + + done := make(chan bool) + a := make(chan uint16, 3) + b := make(chan uint16, 20) + c := make(chan uint16, 100) + + go func() { + for i := 0; i < 10000; i++ { + a <- mids.getID(&DummyToken{}) + mids.freeID(<-b) + } + done <- true + }() + + go func() { + for i := 0; i < 10000; i++ { + b <- mids.getID(&DummyToken{}) + mids.freeID(<-c) + } + done <- true + }() + + go func() { + for i := 0; i < 10000; i++ { + c <- mids.getID(&DummyToken{}) + mids.freeID(<-a) + } + done <- true + }() + + <-done + <-done + <-done +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go new file mode 100644 index 00000000..be6ad8b4 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "crypto/tls" + "crypto/x509" + "testing" + "time" +) + +func Test_NewClientOptions_default(t *testing.T) { + o := NewClientOptions() + + if o.ClientID != "" { + t.Fatalf("bad default client id") + } + + if o.Username != "" { + t.Fatalf("bad default username") + } + + if o.Password != "" { + t.Fatalf("bad default password") + } + + if o.KeepAlive != 30*time.Second { + t.Fatalf("bad default timeout") + } +} + +func Test_NewClientOptions_mix(t *testing.T) { + o := NewClientOptions() + o.AddBroker("tcp://192.168.1.2:9999") + o.SetClientID("myclientid") + o.SetUsername("myuser") + o.SetPassword("mypassword") + o.SetKeepAlive(88 * time.Second) + + if o.Servers[0].Scheme != "tcp" { + t.Fatalf("bad scheme") + } + + if o.Servers[0].Host != "192.168.1.2:9999" { + t.Fatalf("bad host") + } + + if o.ClientID != "myclientid" { + t.Fatalf("bad set clientid") + } + + if o.Username != "myuser" { + t.Fatalf("bad set username") + } + + if o.Password != "mypassword" { + t.Fatalf("bad set password") + } + + if o.KeepAlive != 88000000000 { + t.Fatalf("bad set timeout: %d", o.KeepAlive) + } +} + +func Test_ModifyOptions(t *testing.T) { + o := NewClientOptions() + o.AddBroker("tcp://3.3.3.3:12345") + c := NewClient(o).(*client) + o.AddBroker("ws://2.2.2.2:9999") + o.SetOrderMatters(false) + + if c.options.Servers[0].Scheme != "tcp" { + t.Fatalf("client options.server.Scheme was modified") + } + + // if c.options.server.Host != "2.2.2.2:9999" { + // t.Fatalf("client options.server.Host was modified") + // } + + if o.Order != false { + t.Fatalf("options.order was not modified") + } +} + +func Test_TLSConfig(t *testing.T) { + o := NewClientOptions().SetTLSConfig(&tls.Config{ + RootCAs: x509.NewCertPool(), + ClientAuth: tls.NoClientCert, + ClientCAs: x509.NewCertPool(), + InsecureSkipVerify: true}) + + c := NewClient(o).(*client) + + if c.options.TLSConfig.ClientAuth != tls.NoClientCert { + t.Fatalf("client options.tlsConfig ClientAuth incorrect") + } + + if c.options.TLSConfig.InsecureSkipVerify != true { + t.Fatalf("client options.tlsConfig InsecureSkipVerify incorrect") + } +} + +func Test_OnConnectionLost(t *testing.T) { + onconnlost := func(client Client, err error) { + panic(err) + } + o := NewClientOptions().SetConnectionLostHandler(onconnlost) + + c := NewClient(o).(*client) + + if c.options.OnConnectionLost == nil { + t.Fatalf("client options.onconnlost was nil") + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go new file mode 100644 index 00000000..70f9b664 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "bytes" + "testing" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +func Test_NewPingReqMessage(t *testing.T) { + pr := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) + if pr.MessageType != packets.Pingreq { + t.Errorf("NewPingReqMessage bad msg type: %v", pr.MessageType) + } + if pr.RemainingLength != 0 { + t.Errorf("NewPingReqMessage bad remlen, expected 0, got %d", pr.RemainingLength) + } + + exp := []byte{ + 0xC0, + 0x00, + } + + var buf bytes.Buffer + pr.Write(&buf) + bs := buf.Bytes() + + if len(bs) != 2 { + t.Errorf("NewPingReqMessage.Bytes() wrong length: %d", len(bs)) + } + + if exp[0] != bs[0] || exp[1] != bs[1] { + t.Errorf("NewPingMessage.Bytes() wrong") + } +} + +func Test_DecodeMessage_pingresp(t *testing.T) { + bs := bytes.NewBuffer([]byte{ + 0xD0, + 0x00, + }) + presp, _ := packets.ReadPacket(bs) + if presp.(*packets.PingrespPacket).MessageType != packets.Pingresp { + t.Errorf("DecodeMessage ping response wrong msg type: %v", presp.(*packets.PingrespPacket).MessageType) + } + if presp.(*packets.PingrespPacket).RemainingLength != 0 { + t.Errorf("DecodeMessage ping response wrong rem len: %d", presp.(*packets.PingrespPacket).RemainingLength) + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go new file mode 100644 index 00000000..b8f55c89 --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "testing" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +func Test_newRouter(t *testing.T) { + router, stop := newRouter() + if router == nil { + t.Fatalf("router is nil") + } + if stop == nil { + t.Fatalf("stop is nil") + } + if router.routes.Len() != 0 { + t.Fatalf("router.routes was not empty") + } +} + +func Test_AddRoute(t *testing.T) { + router, _ := newRouter() + calledback := false + cb := func(client Client, msg Message) { + calledback = true + } + router.addRoute("/alpha", cb) + + if router.routes.Len() != 1 { + t.Fatalf("router.routes was wrong") + } +} + +func Test_Match(t *testing.T) { + router, _ := newRouter() + router.addRoute("/alpha", nil) + + if !router.routes.Front().Value.(*route).match("/alpha") { + t.Fatalf("match function is bad") + } + + if router.routes.Front().Value.(*route).match("alpha") { + t.Fatalf("match function is bad") + } +} + +func Test_match(t *testing.T) { + + check := func(route, topic string, exp bool) { + result := routeIncludesTopic(route, topic) + if exp != result { + t.Errorf("match was bad R: %v, T: %v, EXP: %v", route, topic, exp) + } + } + + // ** Basic ** + R := "" + T := "" + check(R, T, true) + + R = "x" + T = "" + check(R, T, false) + + R = "" + T = "x" + check(R, T, false) + + R = "x" + T = "x" + check(R, T, true) + + R = "x" + T = "X" + check(R, T, false) + + R = "alpha" + T = "alpha" + check(R, T, true) + + R = "alpha" + T = "beta" + check(R, T, false) + + // ** / ** + R = "/" + T = "/" + check(R, T, true) + + R = "/one" + T = "/one" + check(R, T, true) + + R = "/" + T = "/two" + check(R, T, false) + + R = "/two" + T = "/" + check(R, T, false) + + R = "/two" + T = "two" + check(R, T, false) // a leading "/" creates a different topic + + R = "/a/" + T = "/a" + check(R, T, false) + + R = "/a/" + T = "/a/b" + check(R, T, false) + + R = "/a/b" + T = "/a/b" + check(R, T, true) + + R = "/a/b/" + T = "/a/b" + check(R, T, false) + + R = "/a/b" + T = "/R/b" + check(R, T, false) + + // ** + ** + R = "/a/+/c" + T = "/a/b/c" + check(R, T, true) + + R = "/+/b/c" + T = "/a/b/c" + check(R, T, true) + + R = "/a/b/+" + T = "/a/b/c" + check(R, T, true) + + R = "/a/+/+" + T = "/a/b/c" + check(R, T, true) + + R = "/+/+/+" + T = "/a/b/c" + check(R, T, true) + + R = "/+/+/c" + T = "/a/b/c" + check(R, T, true) + + R = "/a/b/c/+" // different number of levels + T = "/a/b/c" + check(R, T, false) + + R = "+" + T = "a" + check(R, T, true) + + R = "/+" + T = "a" + check(R, T, false) + + R = "+/+" + T = "/a" + check(R, T, true) + + R = "+/+" + T = "a" + check(R, T, false) + + // ** # ** + R = "#" + T = "/a/b/c" + check(R, T, true) + + R = "/#" + T = "/a/b/c" + check(R, T, true) + + // R = "/#/" // not valid + // T = "/a/b/c" + // check(R, T, true) + + R = "/#" + T = "/a/b/c" + check(R, T, true) + + R = "/a/#" + T = "/a/b/c" + check(R, T, true) + + R = "/a/#" + T = "/a/b/c" + check(R, T, true) + + R = "/a/b/#" + T = "/a/b/c" + check(R, T, true) + + // ** unicode ** + R = "☃" + T = "☃" + check(R, T, true) + + R = "✈" + T = "☃" + check(R, T, false) + + R = "/☃/✈" + T = "/☃/ッ" + check(R, T, false) + + R = "#" + T = "/☃/ッ" + check(R, T, true) + + R = "/☃/+" + T = "/☃/ッ/♫/ø/☹☹☹" + check(R, T, false) + + R = "/☃/#" + T = "/☃/ッ/♫/ø/☹☹☹" + check(R, T, true) + + R = "/☃/ッ/♫/ø/+" + T = "/☃/ッ/♫/ø/☹☹☹" + check(R, T, true) + + R = "/☃/ッ/+/ø/☹☹☹" + T = "/☃/ッ/♫/ø/☹☹☹" + check(R, T, true) + + R = "/+/a/ッ/+/ø/☹☹☹" + T = "/b/♫/ッ/♫/ø/☹☹☹" + check(R, T, false) + + R = "/+/♫/ッ/+/ø/☹☹☹" + T = "/b/♫/ッ/♫/ø/☹☹☹" + check(R, T, true) +} + +func Test_MatchAndDispatch(t *testing.T) { + calledback := make(chan bool) + + cb := func(c Client, m Message) { + calledback <- true + } + + pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pub.Qos = 2 + pub.TopicName = "a" + pub.Payload = []byte("foo") + + msgs := make(chan *packets.PublishPacket) + + router, stopper := newRouter() + router.addRoute("a", cb) + + router.matchAndDispatch(msgs, true, nil) + + msgs <- pub + + <-calledback + + stopper <- true + + select { + case msgs <- pub: + t.Errorf("msgs should not have a listener") + default: + } + +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go new file mode 100644 index 00000000..d8af064d --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go @@ -0,0 +1,579 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "fmt" + "io/ioutil" + "testing" + + "github.com/eclipse/paho.mqtt.golang/packets" +) + +func Test_fullpath(t *testing.T) { + p := fullpath("/tmp/store", "o.44324") + e := "/tmp/store/o.44324.msg" + if p != e { + t.Fatalf("full path expected %s, got %s", e, p) + } +} + +func Test_exists(t *testing.T) { + b := exists("/") + if !b { + t.Errorf("/proc/cpuinfo was not found") + } +} + +func Test_exists_no(t *testing.T) { + b := exists("/this/path/is/not/real/i/hope") + if b { + t.Errorf("you have some strange files") + } +} + +func isemptydir(dir string) bool { + if !exists(dir) { + panic(fmt.Errorf("Directory %s does not exist", dir)) + } + files, err := ioutil.ReadDir(dir) + chkerr(err) + return len(files) == 0 +} + +func Test_mIDFromKey(t *testing.T) { + key := "i.123" + exp := uint16(123) + res := mIDFromKey(key) + if exp != res { + t.Fatalf("mIDFromKey failed") + } +} + +func Test_inboundKeyFromMID(t *testing.T) { + id := uint16(9876) + exp := "i.9876" + res := inboundKeyFromMID(id) + if exp != res { + t.Fatalf("inboundKeyFromMID failed") + } +} + +func Test_outboundKeyFromMID(t *testing.T) { + id := uint16(7654) + exp := "o.7654" + res := outboundKeyFromMID(id) + if exp != res { + t.Fatalf("outboundKeyFromMID failed") + } +} + +/************************ + **** persistOutbound **** + ************************/ + +func Test_persistOutbound_connect(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket) + m.Qos = 0 + m.Username = "user" + m.Password = []byte("pass") + m.ClientIdentifier = "cid" + //m := newConnectMsg(false, false, QOS_ZERO, false, "", nil, "cid", "user", "pass", 10) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_publish_0(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 0 + m.TopicName = "/popub0" + m.Payload = []byte{0xBB, 0x00} + m.MessageID = 40 + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_publish_1(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 1 + m.TopicName = "/popub1" + m.Payload = []byte{0xBB, 0x00} + m.MessageID = 41 + persistOutbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 41 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_publish_2(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 2 + m.TopicName = "/popub2" + m.Payload = []byte{0xBB, 0x00} + m.MessageID = 42 + persistOutbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 42 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_puback(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 1 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_pubrec(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_pubrel(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) + m.MessageID = 43 + + persistOutbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 43 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_pubcomp(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 1 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_subscribe(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) + m.Topics = []string{"/posub"} + m.Qoss = []byte{1} + m.MessageID = 44 + persistOutbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 44 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_unsubscribe(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket) + m.Topics = []string{"/posub"} + m.MessageID = 45 + persistOutbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 45 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_pingreq(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Pingreq) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +func Test_persistOutbound_disconnect(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Disconnect) + persistOutbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistOutbound put message it should not have") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistOutbound get message it should not have") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistOutbound del message it should not have") + } +} + +/************************ + **** persistInbound **** + ************************/ + +func Test_persistInbound_connack(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Connack) + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_publish_0(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 0 + m.TopicName = "/pipub0" + m.Payload = []byte{0xCC, 0x01} + m.MessageID = 50 + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_publish_1(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 1 + m.TopicName = "/pipub1" + m.Payload = []byte{0xCC, 0x02} + m.MessageID = 51 + persistInbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 51 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_publish_2(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + m.Qos = 2 + m.TopicName = "/pipub2" + m.Payload = []byte{0xCC, 0x03} + m.MessageID = 52 + persistInbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 52 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_puback(t *testing.T) { + ts := &TestStore{} + pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pub.Qos = 1 + pub.TopicName = "/pub1" + pub.Payload = []byte{0xCC, 0x04} + pub.MessageID = 53 + publishKey := inboundKeyFromMID(pub.MessageID) + ts.Put(publishKey, pub) + + m := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) + m.MessageID = 53 + + persistInbound(ts, m) // "deletes" packets.Publish from store + + if len(ts.mput) != 1 { // not actually deleted in TestStore + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 1 || ts.mdel[0] != 53 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_pubrec(t *testing.T) { + ts := &TestStore{} + pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pub.Qos = 2 + pub.TopicName = "/pub2" + pub.Payload = []byte{0xCC, 0x05} + pub.MessageID = 54 + publishKey := inboundKeyFromMID(pub.MessageID) + ts.Put(publishKey, pub) + + m := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) + m.MessageID = 54 + + persistInbound(ts, m) + + if len(ts.mput) != 1 || ts.mput[0] != 54 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_pubrel(t *testing.T) { + ts := &TestStore{} + pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) + pub.Qos = 2 + pub.TopicName = "/pub2" + pub.Payload = []byte{0xCC, 0x06} + pub.MessageID = 55 + publishKey := inboundKeyFromMID(pub.MessageID) + ts.Put(publishKey, pub) + + m := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) + m.MessageID = 55 + + persistInbound(ts, m) // will overwrite publish + + if len(ts.mput) != 2 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_pubcomp(t *testing.T) { + ts := &TestStore{} + + m := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) + m.MessageID = 56 + + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 1 || ts.mdel[0] != 56 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_suback(t *testing.T) { + ts := &TestStore{} + + m := packets.NewControlPacket(packets.Suback).(*packets.SubackPacket) + m.MessageID = 57 + + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 1 || ts.mdel[0] != 57 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_unsuback(t *testing.T) { + ts := &TestStore{} + + m := packets.NewControlPacket(packets.Unsuback).(*packets.UnsubackPacket) + m.MessageID = 58 + + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 1 || ts.mdel[0] != 58 { + t.Fatalf("persistInbound in bad state") + } +} + +func Test_persistInbound_pingresp(t *testing.T) { + ts := &TestStore{} + m := packets.NewControlPacket(packets.Pingresp) + + persistInbound(ts, m) + + if len(ts.mput) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mget) != 0 { + t.Fatalf("persistInbound in bad state") + } + + if len(ts.mdel) != 0 { + t.Fatalf("persistInbound in bad state") + } +} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go new file mode 100644 index 00000000..da2b240e --- /dev/null +++ b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2013 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Seth Hoenig + * Allan Stockdill-Mander + * Mike Robertson + */ + +package mqtt + +import ( + "testing" +) + +func Test_ValidateTopicAndQos_qos3(t *testing.T) { + e := validateTopicAndQos("a", 3) + if e != ErrInvalidQos { + t.Fatalf("invalid error for invalid qos") + } +} + +func Test_ValidateTopicAndQos_ES(t *testing.T) { + e := validateTopicAndQos("", 0) + if e != ErrInvalidTopicEmptyString { + t.Fatalf("invalid error for empty topic name") + } +} + +func Test_ValidateTopicAndQos_a_0(t *testing.T) { + e := validateTopicAndQos("a", 0) + if e != nil { + t.Fatalf("error from valid NewTopicFilter") + } +} + +func Test_ValidateTopicAndQos_H(t *testing.T) { + e := validateTopicAndQos("a/#/c", 0) + if e != ErrInvalidTopicMultilevel { + t.Fatalf("invalid error for bad multilevel topic filter") + } +} From ba11537fb2011fe3fa0f60bdec6a3821864e7404 Mon Sep 17 00:00:00 2001 From: Matteo Suppo Date: Mon, 19 Jun 2017 10:42:54 +0200 Subject: [PATCH 2/3] Use glide for vendor Ran glide init and glide install and glide-vc clean Used the modified paho.mqtt repo --- glide.lock | 21 + glide.yaml | 10 + .../arduino-connector/main.go => main.go | 4 - .../eclipse/paho.mqtt.golang/.gitignore | 36 - .../eclipse/paho.mqtt.golang/CONTRIBUTING.md | 56 - .../eclipse/paho.mqtt.golang/DISTRIBUTION | 15 - .../eclipse/paho.mqtt.golang/README.md | 63 - .../eclipse/paho.mqtt.golang/about.html | 41 - .../eclipse/paho.mqtt.golang/cmd/build.sh | 11 - .../paho.mqtt.golang/cmd/custom_store/main.go | 96 -- .../paho.mqtt.golang/cmd/routing/main.go | 105 -- .../paho.mqtt.golang/cmd/sample/main.go | 130 -- .../paho.mqtt.golang/cmd/simple/main.go | 65 - .../eclipse/paho.mqtt.golang/cmd/ssl/main.go | 126 -- .../cmd/ssl/samplecerts/CAfile.pem | 150 --- .../cmd/ssl/samplecerts/README | 9 - .../cmd/ssl/samplecerts/client-crt.pem | 20 - .../cmd/ssl/samplecerts/client-key.pem | 27 - .../ssl/samplecerts/intermediateCA-crt.pem | 20 - .../ssl/samplecerts/intermediateCA-key.pem | 27 - .../cmd/ssl/samplecerts/mosquitto.org.crt | 18 - .../cmd/ssl/samplecerts/rootCA-crt.pem | 21 - .../cmd/ssl/samplecerts/rootCA-key.pem | 27 - .../cmd/ssl/samplecerts/server-crt.pem | 21 - .../cmd/ssl/samplecerts/server-key.pem | 27 - .../paho.mqtt.golang/cmd/stdinpub/main.go | 70 -- .../paho.mqtt.golang/cmd/stdoutsub/main.go | 85 -- .../eclipse/paho.mqtt.golang/edl-v10 | 15 - .../eclipse/paho.mqtt.golang/epl-v10 | 70 -- .../eclipse/paho.mqtt.golang/fvt/README.md | 74 -- .../paho.mqtt.golang/fvt/mosquitto.cfg | 17 - .../eclipse/paho.mqtt.golang/fvt/rsmb.cfg | 8 - .../eclipse/paho.mqtt.golang/fvt/setup_IMA.sh | 111 -- .../paho.mqtt.golang/fvt_client_test.go | 1041 ----------------- .../paho.mqtt.golang/fvt_store_test.go | 544 --------- .../eclipse/paho.mqtt.golang/fvt_test.go | 36 - .../paho.mqtt.golang/packets/packets_test.go | 159 --- .../paho.mqtt.golang/unit_client_test.go | 79 -- .../paho.mqtt.golang/unit_messageids_test.go | 111 -- .../paho.mqtt.golang/unit_options_test.go | 126 -- .../paho.mqtt.golang/unit_ping_test.go | 63 - .../paho.mqtt.golang/unit_router_test.go | 288 ----- .../paho.mqtt.golang/unit_store_test.go | 579 --------- .../paho.mqtt.golang/unit_topic_test.go | 47 - .../arduino-connector/status.go => status.go | 0 .../eclipse/paho.mqtt.golang/LICENSE | 0 .../eclipse/paho.mqtt.golang/client.go | 0 .../eclipse/paho.mqtt.golang/components.go | 0 .../eclipse/paho.mqtt.golang/filestore.go | 0 .../eclipse/paho.mqtt.golang/memstore.go | 0 .../eclipse/paho.mqtt.golang/message.go | 0 .../eclipse/paho.mqtt.golang/messageids.go | 0 .../eclipse/paho.mqtt.golang/net.go | 0 .../eclipse/paho.mqtt.golang/notice.html | 0 .../eclipse/paho.mqtt.golang/oops.go | 0 .../eclipse/paho.mqtt.golang/options.go | 0 .../paho.mqtt.golang/options_reader.go | 0 .../paho.mqtt.golang/packets/connack.go | 0 .../paho.mqtt.golang/packets/connect.go | 0 .../paho.mqtt.golang/packets/disconnect.go | 0 .../paho.mqtt.golang/packets/packets.go | 0 .../paho.mqtt.golang/packets/pingreq.go | 0 .../paho.mqtt.golang/packets/pingresp.go | 0 .../paho.mqtt.golang/packets/puback.go | 0 .../paho.mqtt.golang/packets/pubcomp.go | 0 .../paho.mqtt.golang/packets/publish.go | 0 .../paho.mqtt.golang/packets/pubrec.go | 0 .../paho.mqtt.golang/packets/pubrel.go | 0 .../paho.mqtt.golang/packets/suback.go | 0 .../paho.mqtt.golang/packets/subscribe.go | 0 .../paho.mqtt.golang/packets/unsuback.go | 0 .../paho.mqtt.golang/packets/unsubscribe.go | 0 .../eclipse/paho.mqtt.golang/ping.go | 0 .../eclipse/paho.mqtt.golang/router.go | 0 .../eclipse/paho.mqtt.golang/store.go | 0 .../eclipse/paho.mqtt.golang/token.go | 0 .../eclipse/paho.mqtt.golang/topic.go | 0 .../eclipse/paho.mqtt.golang/trace.go | 0 vendor/github.com/kardianos/osext/LICENSE | 27 + vendor/github.com/kardianos/osext/osext.go | 33 + .../github.com/kardianos/osext/osext_go18.go | 9 + .../github.com/kardianos/osext/osext_plan9.go | 22 + .../kardianos/osext/osext_procfs.go | 36 + .../kardianos/osext/osext_sysctl.go | 126 ++ .../kardianos/osext/osext_windows.go | 36 + vendor/github.com/pkg/errors/LICENSE | 23 + vendor/github.com/pkg/errors/errors.go | 269 +++++ vendor/github.com/pkg/errors/stack.go | 178 +++ vendor/github.com/satori/go.uuid/LICENSE | 20 + vendor/github.com/satori/go.uuid/uuid.go | 488 ++++++++ .../github.com/vharitonsky/iniflags/LICENSE | 23 + .../vharitonsky/iniflags/iniflags.go | 487 ++++++++ vendor/golang.org/x/net/LICENSE | 27 + vendor/golang.org/x/net/PATENTS | 22 + vendor/golang.org/x/net/proxy/direct.go | 18 + vendor/golang.org/x/net/proxy/per_host.go | 140 +++ vendor/golang.org/x/net/proxy/proxy.go | 94 ++ vendor/golang.org/x/net/proxy/socks5.go | 213 ++++ vendor/golang.org/x/net/websocket/client.go | 106 ++ vendor/golang.org/x/net/websocket/dial.go | 24 + vendor/golang.org/x/net/websocket/hybi.go | 583 +++++++++ vendor/golang.org/x/net/websocket/server.go | 113 ++ .../golang.org/x/net/websocket/websocket.go | 448 +++++++ 103 files changed, 3596 insertions(+), 4638 deletions(-) create mode 100644 glide.lock create mode 100644 glide.yaml rename src/github.com/bcmi-labs/arduino-connector/main.go => main.go (99%) delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html delete mode 100755 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go delete mode 100644 src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go rename src/github.com/bcmi-labs/arduino-connector/status.go => status.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/LICENSE (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/client.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/components.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/filestore.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/memstore.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/message.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/messageids.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/net.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/notice.html (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/oops.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/options.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/options_reader.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/connack.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/connect.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/packets.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/puback.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/publish.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/suback.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/ping.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/router.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/store.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/token.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/topic.go (100%) rename {src/github.com/bcmi-labs/arduino-connector/vendor => vendor}/github.com/eclipse/paho.mqtt.golang/trace.go (100%) create mode 100644 vendor/github.com/kardianos/osext/LICENSE create mode 100644 vendor/github.com/kardianos/osext/osext.go create mode 100644 vendor/github.com/kardianos/osext/osext_go18.go create mode 100644 vendor/github.com/kardianos/osext/osext_plan9.go create mode 100644 vendor/github.com/kardianos/osext/osext_procfs.go create mode 100644 vendor/github.com/kardianos/osext/osext_sysctl.go create mode 100644 vendor/github.com/kardianos/osext/osext_windows.go create mode 100644 vendor/github.com/pkg/errors/LICENSE create mode 100644 vendor/github.com/pkg/errors/errors.go create mode 100644 vendor/github.com/pkg/errors/stack.go create mode 100644 vendor/github.com/satori/go.uuid/LICENSE create mode 100644 vendor/github.com/satori/go.uuid/uuid.go create mode 100644 vendor/github.com/vharitonsky/iniflags/LICENSE create mode 100644 vendor/github.com/vharitonsky/iniflags/iniflags.go create mode 100644 vendor/golang.org/x/net/LICENSE create mode 100644 vendor/golang.org/x/net/PATENTS create mode 100644 vendor/golang.org/x/net/proxy/direct.go create mode 100644 vendor/golang.org/x/net/proxy/per_host.go create mode 100644 vendor/golang.org/x/net/proxy/proxy.go create mode 100644 vendor/golang.org/x/net/proxy/socks5.go create mode 100644 vendor/golang.org/x/net/websocket/client.go create mode 100644 vendor/golang.org/x/net/websocket/dial.go create mode 100644 vendor/golang.org/x/net/websocket/hybi.go create mode 100644 vendor/golang.org/x/net/websocket/server.go create mode 100644 vendor/golang.org/x/net/websocket/websocket.go diff --git a/glide.lock b/glide.lock new file mode 100644 index 00000000..371230fe --- /dev/null +++ b/glide.lock @@ -0,0 +1,21 @@ +hash: a50abbf0769838c3d94deba4c500a75d0367d7a65908fb329dee8ce1746d82f9 +updated: 2017-06-19T10:40:26.984867202+02:00 +imports: +- name: github.com/eclipse/paho.mqtt.golang + version: 45f9b18f4864c81d49c3ed01e5faec9eeb05de31 + subpackages: + - packets +- name: github.com/kardianos/osext + version: ae77be60afb1dcacde03767a8c37337fad28ac14 +- name: github.com/pkg/errors + version: 645ef00459ed84a119197bfb8d8205042c6df63d +- name: github.com/satori/go.uuid + version: 879c5887cd475cd7864858769793b2ceb0d44feb +- name: github.com/vharitonsky/iniflags + version: 643132d9585eb6cfdf0dd4d6651a0a94c729094c +- name: golang.org/x/net + version: dd2d9a67c97da0afa00d5726e28086007a0acce5 + subpackages: + - proxy + - websocket +testImports: [] diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 00000000..ce1fc4a7 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,10 @@ +package: github.com/bcmi-labs/arduino-connector +import: +- package: github.com/eclipse/paho.mqtt.golang + version: ^1.0.0 +- package: github.com/kardianos/osext +- package: github.com/pkg/errors + version: ^0.8.0 +- package: github.com/satori/go.uuid + version: ^1.1.0 +- package: github.com/vharitonsky/iniflags diff --git a/src/github.com/bcmi-labs/arduino-connector/main.go b/main.go similarity index 99% rename from src/github.com/bcmi-labs/arduino-connector/main.go rename to main.go index 5bd02a55..161ab46d 100644 --- a/src/github.com/bcmi-labs/arduino-connector/main.go +++ b/main.go @@ -17,7 +17,6 @@ import ( "syscall" "time" - "github.com/davecgh/go-spew/spew" mqtt "github.com/eclipse/paho.mqtt.golang" "github.com/kardianos/osext" "github.com/pkg/errors" @@ -107,9 +106,6 @@ func UploadCB(status *Status) mqtt.MessageHandler { return } - spew.Dump(msg.Payload()) - spew.Dump(info) - // create folder folder, err := osext.ExecutableFolder() if err != nil { diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore deleted file mode 100644 index 47bb0de4..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/.gitignore +++ /dev/null @@ -1,36 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -*.msg -*.lok - -samples/trivial -samples/trivial2 -samples/sample -samples/reconnect -samples/ssl -samples/custom_store -samples/simple -samples/stdinpub -samples/stdoutsub -samples/routing \ No newline at end of file diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md deleted file mode 100644 index 9791dc60..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/CONTRIBUTING.md +++ /dev/null @@ -1,56 +0,0 @@ -Contributing to Paho -==================== - -Thanks for your interest in this project. - -Project description: --------------------- - -The Paho project has been created to provide scalable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). -Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications. Paho is being kicked off with MQTT publish/subscribe client implementations for use on embedded platforms, along with corresponding server support as determined by the community. - -- https://projects.eclipse.org/projects/technology.paho - -Developer resources: --------------------- - -Information regarding source code management, builds, coding standards, and more. - -- https://projects.eclipse.org/projects/technology.paho/developer - -Contributor License Agreement: ------------------------------- - -Before your contribution can be accepted by the project, you need to create and electronically sign the Eclipse Foundation Contributor License Agreement (CLA). - -- http://www.eclipse.org/legal/CLA.php - -Contributing Code: ------------------- - -The Go client is developed in Github, see their documentation on the process of forking and pull requests; https://help.github.com/categories/collaborating-on-projects-using-pull-requests/ - -Git commit messages should follow the style described here; - -http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html - -Contact: --------- - -Contact the project developers via the project's "dev" list. - -- https://dev.eclipse.org/mailman/listinfo/paho-dev - -Search for bugs: ----------------- - -This project uses Github issues to track ongoing development and issues. - -- https://github.com/eclipse/paho.mqtt.golang/issues - -Create a new bug: ------------------ - -Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! - -- https://github.com/eclipse/paho.mqtt.golang/issues diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION deleted file mode 100644 index 34e49731..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/DISTRIBUTION +++ /dev/null @@ -1,15 +0,0 @@ - - -Eclipse Distribution License - v 1.0 - -Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md deleted file mode 100644 index 09e50072..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/README.md +++ /dev/null @@ -1,63 +0,0 @@ -Eclipse Paho MQTT Go client -=========================== - - -This repository contains the source code for the [Eclipse Paho](http://eclipse.org/paho) MQTT Go client library. - -This code builds a library which enable applications to connect to an [MQTT](http://mqtt.org) broker to publish messages, and to subscribe to topics and receive published messages. - -This library supports a fully asynchronous mode of operation. - - -Installation and Build ----------------------- - -This client is designed to work with the standard Go tools, so installation is as easy as: - -``` -go get github.com/eclipse/paho.mqtt.golang -``` - -The client depends on Google's [websockets](https://godoc.org/golang.org/x/net/websocket) and [proxy](https://godoc.org/golang.org/x/net/proxy) package, -also easily installed with the commands: - -``` -go get golang.org/x/net/websocket -go get golang.org/x/net/proxy -``` - - -Usage and API -------------- - -Detailed API documentation is available by using to godoc tool, or can be browsed online -using the [godoc.org](http://godoc.org/github.com/eclipse/paho.mqtt.golang) service. - -Make use of the library by importing it in your Go client source code. For example, -``` -import "github.com/eclipse/paho.mqtt.golang" -``` - -Samples are available in the `cmd` directory for reference. - - -Runtime tracing ---------------- - -Tracing is enabled by assigning logs (from the Go log package) to the logging endpoints, ERROR, CRITICAL, WARN and DEBUG - - -Reporting bugs --------------- - -Please report bugs by raising issues for this project in github https://github.com/eclipse/paho.mqtt.golang/issues - - -More information ----------------- - -Discussion of the Paho clients takes place on the [Eclipse paho-dev mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev). - -General questions about the MQTT protocol are discussed in the [MQTT Google Group](https://groups.google.com/forum/?hl=en-US&fromgroups#!forum/mqtt). - -There is much more information available via the [MQTT community site](http://mqtt.org). diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html deleted file mode 100644 index b183f417..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/about.html +++ /dev/null @@ -1,41 +0,0 @@ - - - -About - - -

About This Content

- -

December 9, 2013

-

License

- -

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). -A copy of the EPL is available at -http://www.eclipse.org/legal/epl-v10.html -and a copy of the EDL is available at -http://www.eclipse.org/org/documents/edl-v10.php. -For purposes of the EPL, "Program" will mean the Content.

- -

If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party ("Redistributor") and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at http://www.eclipse.org.

- - -

Third Party Content

-

The Content includes items that have been sourced from third parties as set out below. If you - did not receive this Content directly from the Eclipse Foundation, the following is provided - for informational purposes only, and you should look to the Redistributor's license for - terms and conditions of use.

-

- None

-

-

- - - - diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh deleted file mode 100755 index c9cec5a8..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/build.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh - -for dir in `ls -d */ | cut -f1 -d'/'` -do - echo "Compiling $dir ...\c" - cd $dir - go clean - go build - cd .. - echo " done." -done diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go deleted file mode 100644 index d5920b82..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/custom_store/main.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -// This demonstrates how to implement your own Store interface and provide -// it to the go-mqtt client. - -package main - -import ( - "fmt" - "time" - - MQTT "github.com/eclipse/paho.mqtt.golang" - "github.com/eclipse/paho.mqtt.golang/packets" -) - -// This NoOpStore type implements the go-mqtt/Store interface, which -// allows it to be used by the go-mqtt client library. However, it is -// highly recommended that you do not use this NoOpStore in production, -// because it will NOT provide any sort of guaruntee of message delivery. -type NoOpStore struct { - // Contain nothing -} - -func (store *NoOpStore) Open() { - // Do nothing -} - -func (store *NoOpStore) Put(string, packets.ControlPacket) { - // Do nothing -} - -func (store *NoOpStore) Get(string) packets.ControlPacket { - // Do nothing - return nil -} - -func (store *NoOpStore) Del(string) { - // Do nothing -} - -func (store *NoOpStore) All() []string { - return nil -} - -func (store *NoOpStore) Close() { - // Do Nothing -} - -func (store *NoOpStore) Reset() { - // Do Nothing -} - -func main() { - myNoOpStore := &NoOpStore{} - - opts := MQTT.NewClientOptions() - opts.AddBroker("tcp://iot.eclipse.org:1883") - opts.SetClientID("custom-store") - opts.SetStore(myNoOpStore) - - var callback MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - } - - c := MQTT.NewClient(opts) - if token := c.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - - c.Subscribe("/go-mqtt/sample", 0, callback) - - for i := 0; i < 5; i++ { - text := fmt.Sprintf("this is msg #%d!", i) - token := c.Publish("/go-mqtt/sample", 0, false, text) - token.Wait() - } - - for i := 1; i < 5; i++ { - time.Sleep(1 * time.Second) - } - - c.Disconnect(250) -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go deleted file mode 100644 index de708cc5..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/routing/main.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -/*---------------------------------------------------------------------- -This sample is designed to demonstrate the ability to set individual -callbacks on a per-subscription basis. There are three handlers in use: - brokerLoadHandler - $SYS/broker/load/# - brokerConnectionHandler - $SYS/broker/connection/# - brokerClientHandler - $SYS/broker/clients/# -The client will receive 100 messages total from those subscriptions, -and then print the total number of messages received from each. -It may take a few moments for the sample to complete running, as it -must wait for messages to be published. ------------------------------------------------------------------------*/ - -package main - -import ( - "fmt" - "os" - - MQTT "github.com/eclipse/paho.mqtt.golang" -) - -var brokerLoad = make(chan bool) -var brokerConnection = make(chan bool) -var brokerClients = make(chan bool) - -func brokerLoadHandler(client MQTT.Client, msg MQTT.Message) { - brokerLoad <- true - fmt.Printf("BrokerLoadHandler ") - fmt.Printf("[%s] ", msg.Topic()) - fmt.Printf("%s\n", msg.Payload()) -} - -func brokerConnectionHandler(client MQTT.Client, msg MQTT.Message) { - brokerConnection <- true - fmt.Printf("BrokerConnectionHandler ") - fmt.Printf("[%s] ", msg.Topic()) - fmt.Printf("%s\n", msg.Payload()) -} - -func brokerClientsHandler(client MQTT.Client, msg MQTT.Message) { - brokerClients <- true - fmt.Printf("BrokerClientsHandler ") - fmt.Printf("[%s] ", msg.Topic()) - fmt.Printf("%s\n", msg.Payload()) -} - -func main() { - opts := MQTT.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("router-sample") - opts.SetCleanSession(true) - - c := MQTT.NewClient(opts) - if token := c.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - - if token := c.Subscribe("$SYS/broker/load/#", 0, brokerLoadHandler); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - if token := c.Subscribe("$SYS/broker/connection/#", 0, brokerConnectionHandler); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - if token := c.Subscribe("$SYS/broker/clients/#", 0, brokerClientsHandler); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - loadCount := 0 - connectionCount := 0 - clientsCount := 0 - - for i := 0; i < 100; i++ { - select { - case <-brokerLoad: - loadCount++ - case <-brokerConnection: - connectionCount++ - case <-brokerClients: - clientsCount++ - } - } - - fmt.Printf("Received %3d Broker Load messages\n", loadCount) - fmt.Printf("Received %3d Broker Connection messages\n", connectionCount) - fmt.Printf("Received %3d Broker Clients messages\n", clientsCount) - - c.Disconnect(250) -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go deleted file mode 100644 index f144fe02..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/sample/main.go +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package main - -import ( - "flag" - "fmt" - "os" - - MQTT "github.com/eclipse/paho.mqtt.golang" -) - -/* -Options: - [-help] Display help - [-a pub|sub] Action pub (publish) or sub (subscribe) - [-m ] Payload to send - [-n ] Number of messages to send or receive - [-q 0|1|2] Quality of Service - [-clean] CleanSession (true if -clean is present) - [-id ] CliendID - [-user ] User - [-password ] Password - [-broker ] Broker URI - [-topic ] Topic - [-store ] Store Directory - -*/ - -func main() { - topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe") - broker := flag.String("broker", "tcp://iot.eclipse.org:1883", "The broker URI. ex: tcp://10.10.1.1:1883") - password := flag.String("password", "", "The password (optional)") - user := flag.String("user", "", "The User (optional)") - id := flag.String("id", "testgoid", "The ClientID (optional)") - cleansess := flag.Bool("clean", false, "Set Clean Session (default false)") - qos := flag.Int("qos", 0, "The Quality of Service 0,1,2 (default 0)") - num := flag.Int("num", 1, "The number of messages to publish or subscribe (default 1)") - payload := flag.String("message", "", "The message text to publish (default empty)") - action := flag.String("action", "", "Action publish or subscribe (required)") - store := flag.String("store", ":memory:", "The Store Directory (default use memory store)") - flag.Parse() - - if *action != "pub" && *action != "sub" { - fmt.Println("Invalid setting for -action, must be pub or sub") - return - } - - if *topic == "" { - fmt.Println("Invalid setting for -topic, must not be empty") - return - } - - fmt.Printf("Sample Info:\n") - fmt.Printf("\taction: %s\n", *action) - fmt.Printf("\tbroker: %s\n", *broker) - fmt.Printf("\tclientid: %s\n", *id) - fmt.Printf("\tuser: %s\n", *user) - fmt.Printf("\tpassword: %s\n", *password) - fmt.Printf("\ttopic: %s\n", *topic) - fmt.Printf("\tmessage: %s\n", *payload) - fmt.Printf("\tqos: %d\n", *qos) - fmt.Printf("\tcleansess: %v\n", *cleansess) - fmt.Printf("\tnum: %d\n", *num) - fmt.Printf("\tstore: %s\n", *store) - - opts := MQTT.NewClientOptions() - opts.AddBroker(*broker) - opts.SetClientID(*id) - opts.SetUsername(*user) - opts.SetPassword(*password) - opts.SetCleanSession(*cleansess) - if *store != ":memory:" { - opts.SetStore(MQTT.NewFileStore(*store)) - } - - if *action == "pub" { - client := MQTT.NewClient(opts) - if token := client.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - fmt.Println("Sample Publisher Started") - for i := 0; i < *num; i++ { - fmt.Println("---- doing publish ----") - token := client.Publish(*topic, byte(*qos), false, *payload) - token.Wait() - } - - client.Disconnect(250) - fmt.Println("Sample Publisher Disconnected") - } else { - receiveCount := 0 - choke := make(chan [2]string) - - opts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) { - choke <- [2]string{msg.Topic(), string(msg.Payload())} - }) - - client := MQTT.NewClient(opts) - if token := client.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - - if token := client.Subscribe(*topic, byte(*qos), nil); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - for receiveCount < *num { - incoming := <-choke - fmt.Printf("RECEIVED TOPIC: %s MESSAGE: %s\n", incoming[0], incoming[1]) - receiveCount++ - } - - client.Disconnect(250) - fmt.Println("Sample Subscriber Disconnected") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go deleted file mode 100644 index 96459353..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/simple/main.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package main - -import ( - "fmt" - "log" - "os" - "time" - - "github.com/eclipse/paho.mqtt.golang" -) - -var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) -} - -func main() { - mqtt.DEBUG = log.New(os.Stdout, "", 0) - mqtt.ERROR = log.New(os.Stdout, "", 0) - opts := mqtt.NewClientOptions().AddBroker("tcp://iot.eclipse.org:1883").SetClientID("gotrivial") - opts.SetKeepAlive(2 * time.Second) - opts.SetDefaultPublishHandler(f) - opts.SetPingTimeout(1 * time.Second) - - c := mqtt.NewClient(opts) - if token := c.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - - if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - for i := 0; i < 5; i++ { - text := fmt.Sprintf("this is msg #%d!", i) - token := c.Publish("go-mqtt/sample", 0, false, text) - token.Wait() - } - - time.Sleep(6 * time.Second) - - if token := c.Unsubscribe("go-mqtt/sample"); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - os.Exit(1) - } - - c.Disconnect(250) - - time.Sleep(1 * time.Second) -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go deleted file mode 100644 index 99d4eae8..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/main.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -/* -To run this sample, The following certificates -must be created: - - rootCA-crt.pem - root certificate authority that is used - to sign and verify the client and server - certificates. - rootCA-key.pem - keyfile for the rootCA. - - server-crt.pem - server certificate signed by the CA. - server-key.pem - keyfile for the server certificate. - - client-crt.pem - client certificate signed by the CA. - client-key.pem - keyfile for the client certificate. - - CAfile.pem - file containing concatenated CA certificates - if there is more than 1 in the chain. - (e.g. root CA -> intermediate CA -> server cert) - - Instead of creating CAfile.pem, rootCA-crt.pem can be added - to the default openssl CA certificate bundle. To find the - default CA bundle used, check: - $GO_ROOT/src/pks/crypto/x509/root_unix.go - To use this CA bundle, just set tls.Config.RootCAs = nil. -*/ - -package main - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "time" - - MQTT "github.com/eclipse/paho.mqtt.golang" -) - -func NewTLSConfig() *tls.Config { - // Import trusted certificates from CAfile.pem. - // Alternatively, manually add CA certificates to - // default openssl CA bundle. - certpool := x509.NewCertPool() - pemCerts, err := ioutil.ReadFile("samplecerts/CAfile.pem") - if err == nil { - certpool.AppendCertsFromPEM(pemCerts) - } - - // Import client certificate/key pair - cert, err := tls.LoadX509KeyPair("samplecerts/client-crt.pem", "samplecerts/client-key.pem") - if err != nil { - panic(err) - } - - // Just to print out the client certificate.. - cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - panic(err) - } - fmt.Println(cert.Leaf) - - // Create tls.Config with desired tls properties - return &tls.Config{ - // RootCAs = certs used to verify server cert. - RootCAs: certpool, - // ClientAuth = whether to request cert from server. - // Since the server is set up for SSL, this happens - // anyways. - ClientAuth: tls.NoClientCert, - // ClientCAs = certs used to validate client cert. - ClientCAs: nil, - // InsecureSkipVerify = verify that cert contents - // match server. IP matches what is in cert etc. - InsecureSkipVerify: true, - // Certificates = list of certs client sends to server. - Certificates: []tls.Certificate{cert}, - } -} - -var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) -} - -func main() { - tlsconfig := NewTLSConfig() - - opts := MQTT.NewClientOptions() - opts.AddBroker("ssl://iot.eclipse.org:8883") - opts.SetClientID("ssl-sample").SetTLSConfig(tlsconfig) - opts.SetDefaultPublishHandler(f) - - // Start the connection - c := MQTT.NewClient(opts) - if token := c.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - - c.Subscribe("/go-mqtt/sample", 0, nil) - - i := 0 - for _ = range time.Tick(time.Duration(1) * time.Second) { - if i == 5 { - break - } - text := fmt.Sprintf("this is msg #%d!", i) - c.Publish("/go-mqtt/sample", 0, false, text) - i++ - } - - c.Disconnect(250) -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem deleted file mode 100644 index 16c664a4..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/CAfile.pem +++ /dev/null @@ -1,150 +0,0 @@ -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA - Validity - Not Before: Oct 21 19:24:23 2013 GMT - Not After : Sep 25 19:24:23 2018 GMT - Subject: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c2:d1:d0:31:dc:93:c3:ad:88:0d:f8:93:fe:cc: - aa:04:1d:85:aa:c3:bb:bd:87:04:f0:42:67:14:34: - 4a:56:94:2b:bf:d0:6b:72:30:38:39:35:20:8c:e3: - 7e:65:82:b0:7e:3e:1d:f1:18:82:b7:d6:19:59:43: - ed:81:be:eb:51:44:fc:77:9e:37:ad:e1:a0:18:b9: - 4b:59:79:90:81:a4:e4:52:2f:fc:e2:ff:98:10:5e: - d5:13:9a:16:62:1a:e0:cb:ab:1d:ae:da:d1:40:d4: - 97:b1:e6:e3:f1:97:2c:2a:52:73:ab:d0:a2:15:f3: - 1e:9a:b0:67:d0:62:67:4b:74:b0:bb:8f:ef:9e:32: - 6a:4c:27:4e:82:7c:16:66:ce:06:e9:a3:d9:36:4f: - f4:3e:bc:80:00:93:c1:ca:31:cf:03:68:d4:e5:8b: - 38:45:b6:1b:35:b0:c0:e9:4a:62:75:83:01:aa:b9: - c1:0b:c0:ee:97:c0:73:23:cd:34:ec:bb:3c:95:35: - c8:2d:69:ff:86:d8:1f:c8:04:7e:18:de:62:c2:4b: - 37:c6:aa:8e:03:bf:2b:0d:97:20:2a:75:47:ec:98: - 29:3c:64:52:ef:91:8b:63:0f:6a:f8:c2:9d:08:6a: - 61:68:6f:64:9a:56:b2:0a:bc:7b:59:3d:7f:fd:ba: - 12:4b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 5B:BB:3E:8E:2D:90:AD:AE:58:07:FF:53:00:18:98:FF:44:84:4C:BA - X509v3 Authority Key Identifier: - keyid:5B:BB:3E:8E:2D:90:AD:AE:58:07:FF:53:00:18:98:FF:44:84:4C:BA - - X509v3 Basic Constraints: - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 3c:89:0b:bd:49:10:a6:1a:f6:2a:4b:5f:02:3d:ee:f3:19:4f: - c9:10:79:9c:01:ef:88:22:3d:03:5b:1a:14:46:b6:7f:9b:af: - a5:99:1a:d4:d4:9b:d6:6f:c1:fe:96:8f:9a:9e:47:42:b4:ee: - 21:56:6a:c4:92:38:6c:81:cd:8e:31:43:86:7c:97:15:90:80: - d8:21:f0:46:be:2a:2f:f2:96:07:85:74:a8:fa:1b:78:8f:80: - c1:5e:bc:d9:06:c2:33:9e:8e:f9:08:dd:43:7b:6f:5a:22:67: - 46:78:5d:fb:4a:4e:c2:c6:29:94:17:53:a6:c5:a9:d6:67:06: - 4f:07:ef:da:5b:45:21:83:cb:31:b2:dc:dc:ac:13:19:98:3f: - 98:5f:2c:b4:b4:da:d4:43:d7:a9:1a:6e:b6:cf:be:85:a8:80: - 1f:8a:c1:95:8a:83:a4:af:d2:23:4a:b6:18:87:4e:28:31:36: - 03:2c:bf:e4:9e:b6:75:fd:c4:68:ed:4d:d5:a8:fa:a5:81:13: - 17:1c:43:67:02:1c:d0:e6:00:6e:8b:13:e6:60:1f:ba:40:78: - 93:25:ca:59:5a:71:cc:58:d4:52:63:1d:b3:3c:ce:37:f1:89: - 78:fc:13:fa:b3:ea:22:af:17:68:8a:a1:59:57:f5:1a:49:6e: - b9:f6:5f:b3 ------BEGIN CERTIFICATE----- -MIIDizCCAnOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO -MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO -MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy -M1oXDTE4MDkyNTE5MjQyM1owYDELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 -MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 -MREwDwYDVQQDDAhEdW1teSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAMLR0DHck8OtiA34k/7MqgQdharDu72HBPBCZxQ0SlaUK7/Qa3IwODk1IIzj -fmWCsH4+HfEYgrfWGVlD7YG+61FE/HeeN63hoBi5S1l5kIGk5FIv/OL/mBBe1ROa -FmIa4MurHa7a0UDUl7Hm4/GXLCpSc6vQohXzHpqwZ9BiZ0t0sLuP754yakwnToJ8 -FmbOBumj2TZP9D68gACTwcoxzwNo1OWLOEW2GzWwwOlKYnWDAaq5wQvA7pfAcyPN -NOy7PJU1yC1p/4bYH8gEfhjeYsJLN8aqjgO/Kw2XICp1R+yYKTxkUu+Ri2MPavjC -nQhqYWhvZJpWsgq8e1k9f/26EksCAwEAAaNQME4wHQYDVR0OBBYEFFu7Po4tkK2u -WAf/UwAYmP9EhEy6MB8GA1UdIwQYMBaAFFu7Po4tkK2uWAf/UwAYmP9EhEy6MAwG -A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADyJC71JEKYa9ipLXwI97vMZ -T8kQeZwB74giPQNbGhRGtn+br6WZGtTUm9Zvwf6Wj5qeR0K07iFWasSSOGyBzY4x -Q4Z8lxWQgNgh8Ea+Ki/ylgeFdKj6G3iPgMFevNkGwjOejvkI3UN7b1oiZ0Z4XftK -TsLGKZQXU6bFqdZnBk8H79pbRSGDyzGy3NysExmYP5hfLLS02tRD16kabrbPvoWo -gB+KwZWKg6Sv0iNKthiHTigxNgMsv+SetnX9xGjtTdWo+qWBExccQ2cCHNDmAG6L -E+ZgH7pAeJMlyllaccxY1FJjHbM8zjfxiXj8E/qz6iKvF2iKoVlX9RpJbrn2X7M= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy CA - Validity - Not Before: Oct 21 19:24:23 2013 GMT - Not After : Sep 25 19:24:23 2018 GMT - Subject: C=US, ST=Dummy, L=Dummy, O=Dummy, OU=Dummy, CN=Dummy Intermediate CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:cf:7d:92:07:a5:56:1b:6f:4c:f3:34:c2:12:c2: - 34:62:3b:69:aa:a6:0c:c6:70:5b:93:bc:dc:41:98: - 61:87:61:36:be:8c:08:dd:31:a9:33:76:d3:66:3e: - 77:60:1e:ed:9e:e1:e5:ef:bf:17:91:ac:0c:63:07: - 01:ab:30:67:bc:16:a6:2f:79:f0:61:8c:79:2d:3c: - 98:60:74:61:c4:5f:60:44:85:71:92:9d:cc:7b:14: - 39:74:aa:44:f9:9f:ae:f6:c7:8d:c3:01:47:53:24: - ac:7b:a2:f6:c5:7d:65:37:40:0b:20:c8:d4:14:cd: - f8:f4:57:ea:23:70:f4:e3:99:2b:1c:9a:67:37:ed: - 93:c7:a7:7c:86:90:f7:ae:fc:6f:4b:18:dc:d5:eb: - f3:68:33:d6:78:14:d1:ca:a7:06:7d:75:34:f6:c0: - d4:15:1b:21:2b:78:d9:76:24:a5:f0:c6:13:c8:1e: - 4a:c8:ca:77:34:4e:f8:fa:49:5f:6c:e1:66:a8:65: - f0:8c:bc:44:20:03:ac:af:4a:61:a5:39:48:51:1b: - cb:d8:22:29:60:27:47:42:fc:bf:6a:77:65:58:09: - 20:82:1c:d1:16:5e:5a:18:ea:99:61:8e:93:94:27: - 30:20:dd:44:03:50:43:b4:ec:a3:0f:ee:91:69:d7: - b1:5b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 39:a0:8d:2f:68:22:1d:4f:3e:db:f1:9b:29:20:77:23:f8:21: - 34:17:84:00:88:a8:3e:a1:4d:84:94:90:96:02:e6:6a:b4:20: - 51:a0:66:20:38:05:18:aa:2a:3e:9a:50:60:af:eb:4a:70:ac: - 9b:59:30:d5:17:14:9c:b4:91:6a:1b:c3:45:8a:dd:cd:2f:c6: - c5:8c:fe:d0:76:20:63:a4:97:db:e3:2a:8e:c1:3d:c8:b6:06: - 2d:49:7a:d9:8a:de:16:ea:5d:5f:fb:41:79:0d:8f:d2:23:00: - d9:b9:6f:93:45:bb:74:17:ea:6b:72:13:01:86:fe:8d:7e:8f: - 27:71:76:a9:37:6d:6c:90:5a:3f:d9:6d:4d:6c:a4:64:7a:ea: - 82:c9:87:ee:6a:d0:6e:30:05:7f:19:1d:19:31:a9:9a:ce:21: - 84:da:47:c7:a0:66:12:e8:7e:57:69:5d:9c:24:e5:46:3c:bf: - 37:f6:88:c3:b1:42:de:3b:81:ed:f5:ae:e2:23:9e:c2:89:a1: - e7:5c:1d:49:0f:ed:ae:55:60:0e:4e:4c:e9:8a:64:e6:ae:c5: - d1:99:a7:70:4c:7e:5d:53:ac:88:2c:0f:0b:21:94:1a:32:f9: - a1:cc:1e:67:98:6b:b6:e9:b1:b9:4b:46:02:b1:65:c9:49:83: - 80:bd:b9:70 ------BEGIN CERTIFICATE----- -MIIDWDCCAkCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO -MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO -MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy -M1oXDTE4MDkyNTE5MjQyM1owbTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 -MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 -MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDPfZIHpVYbb0zzNMISwjRiO2mqpgzGcFuTvNxBmGGH -YTa+jAjdMakzdtNmPndgHu2e4eXvvxeRrAxjBwGrMGe8FqYvefBhjHktPJhgdGHE -X2BEhXGSncx7FDl0qkT5n672x43DAUdTJKx7ovbFfWU3QAsgyNQUzfj0V+ojcPTj -mSscmmc37ZPHp3yGkPeu/G9LGNzV6/NoM9Z4FNHKpwZ9dTT2wNQVGyEreNl2JKXw -xhPIHkrIync0Tvj6SV9s4WaoZfCMvEQgA6yvSmGlOUhRG8vYIilgJ0dC/L9qd2VY -CSCCHNEWXloY6plhjpOUJzAg3UQDUEO07KMP7pFp17FbAgMBAAGjEDAOMAwGA1Ud -EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADmgjS9oIh1PPtvxmykgdyP4ITQX -hACIqD6hTYSUkJYC5mq0IFGgZiA4BRiqKj6aUGCv60pwrJtZMNUXFJy0kWobw0WK -3c0vxsWM/tB2IGOkl9vjKo7BPci2Bi1JetmK3hbqXV/7QXkNj9IjANm5b5NFu3QX -6mtyEwGG/o1+jydxdqk3bWyQWj/ZbU1spGR66oLJh+5q0G4wBX8ZHRkxqZrOIYTa -R8egZhLofldpXZwk5UY8vzf2iMOxQt47ge31ruIjnsKJoedcHUkP7a5VYA5OTOmK -ZOauxdGZp3BMfl1TrIgsDwshlBoy+aHMHmeYa7bpsblLRgKxZclJg4C9uXA= ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README deleted file mode 100644 index aa7c97d7..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/README +++ /dev/null @@ -1,9 +0,0 @@ -Certificate structure: - -Root CA - | - |-> Intermediate CA - | - |-> Server - | - |-> Client diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem deleted file mode 100644 index 5069e08e..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-crt.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDRzCCAi8CAQIwDQYJKoZIhvcNAQEFBQAwbTELMAkGA1UEBhMCVVMxDjAMBgNV -BAgMBUR1bW15MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNV -BAsMBUR1bW15MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwHhcNMTMx -MDIxMTkyNDIzWhcNMTgwOTI1MTkyNDIzWjBmMQswCQYDVQQGEwJVUzEOMAwGA1UE -CAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEOMAwGA1UE -CwwFRHVtbXkxFzAVBgNVBAMMDkR1bW15IChjbGllbnQpMIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA4J/+eKqsjK0QS+cSDa5Fh4XM4THy812JkWMySA5r -bFxHZ5ye36/IuwyRQ0Yn2DvhhsDR5K7yz8K+Yfp9A6WRBkyHK/sy/8vurQHeDH3y -lLtHCLi5nfyt2fDxWOYwFrS1giGn2IxJIHBAWu4cBODCkqwqAp92+Lqp3Sn+D+Fb -maHEU3LHua8OIJiSeAIHo/jPqfHFqZxK1bXhGCSQKvUZCaTftsqDtn+LZSElqj1y -5/cnc7XGsTf8ml/+FDMX1aSAHf+pu+UAp9JqOXOM60A5JIpYu3Lsejp1RppyPJYP -zC4nSN8R2LOdDChP2MB7f1/sXRGlLM/X3Vi4X+c6xQ85TQIDAQABMA0GCSqGSIb3 -DQEBBQUAA4IBAQAMWt9qMUOY5z1uyYcjUnconPHLM9MADCZI2sRbfdBOBHEnTVKv -Y63SWnCt8TRJb01LKLIEys6pW1NUlxr6b+FwicNmycR0L8b63cmNXg2NmSZsnK9C -fGT6BbbDdVPYjvmghpSd3soBGBLPsJvaFc6UL5tunm+hT7PxWjDxHZEiE18PTs05 -Vpp/ytILzhoXvJeFOWQHIdf4DLR5izGMNTKdQzgg1eBq2vKgjJIlEZ3j/AyHkJLE -qFip1tyc0PRzgKYFLWttaZzakCLJOGuxtvYB+GrixVM7U23p5LQbLE0KX7fe2Gql -xKMfSID5NUDNf1SuSrrGLD3gfnJEKVB8TVBk ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem deleted file mode 100644 index 7665fb65..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/client-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA4J/+eKqsjK0QS+cSDa5Fh4XM4THy812JkWMySA5rbFxHZ5ye -36/IuwyRQ0Yn2DvhhsDR5K7yz8K+Yfp9A6WRBkyHK/sy/8vurQHeDH3ylLtHCLi5 -nfyt2fDxWOYwFrS1giGn2IxJIHBAWu4cBODCkqwqAp92+Lqp3Sn+D+FbmaHEU3LH -ua8OIJiSeAIHo/jPqfHFqZxK1bXhGCSQKvUZCaTftsqDtn+LZSElqj1y5/cnc7XG -sTf8ml/+FDMX1aSAHf+pu+UAp9JqOXOM60A5JIpYu3Lsejp1RppyPJYPzC4nSN8R -2LOdDChP2MB7f1/sXRGlLM/X3Vi4X+c6xQ85TQIDAQABAoIBABosCiZdHIW3lHKD -leLqL0e/G0QR4dDhUSoTeMRUiceyaM91vD0r6iOBL1u7TOEw+PIOfWY7zCbQ9gXM -fcxy+hbVy9ogBq0vQbv+v7SM6DrUJ06o11fFHSyLmlNVXr0GiS+EZF4i2lJhQd5W -aAVZetJEJRDxK5eHiEswnV2UUGvx6VCpFILL0JVGxWY7oOPxiiBLl+cmfRZdTfGx -46VzQvBu7N8hGpCIsljuVFP/DxR7c+2oyrtFaFSMZBMNI8fICgkb2QeLk/XUBXtn -0bDttgmOP/BvnNAor7nIRoeer/7kbXc9jOsgXwnvDKPapltQddL+exycXzbIjLuY -Z2SFsDECgYEA+2A4QGV0biqdICAoKCHCHCU/CrdDUQiQDHqRU6/nhka7MFPSl4Wy -9oISRrYZhKIbSbaXwTW5ZcYq8Hpn/yGYIWlINP9sjprnOWPE7L74lac+PFWXNMUI -jNJOJkLK1IeppByXAt5ekGBrG556bhzRCJsTjYsyUR/r/bMEF1FD8WMCgYEA5MHM -hqmkDK5CbklVaPonNc251Lx+HSzzQ40WExC/PrCczRaZMKlhmyKZfWJCInQsUDln -w6Lqa5UnwZV2HYAF30VZYQsq84ulNnx1/36BEZyIimfAL1WHvKeGWjGsZqniXxxb -Os5wEMAvxk0SWVrR5v6YpBDv3t9+lLg/bzBOAY8CgYEAuZ0q7CH9/vroWrhj7n4+ -3pmCG1+HDWbNNumqNalFxBimT+EVN1058FvLMvtzjERG8f8pvzj0VPom6rr336Pm -uYUMFFYmyoYHBpFs74Nz+s0rX1Gz/PsgfRstKYNYUeZ6lPunZi7clK8dZ591t6j/ -kOMxZOrLlKuFjieJdc5D5RECgYAVTzxXOwxOJhmIHoq3Sb5HU8/A0oJJA3vxyf3J -buDx3Q/uRvGkR9MQ2YtE09dnUD0kiARzhASkWvOmI98p5lglsVcfJCQvJc4RIkz3 -rPgnBNbvVbTgc+4+E7j/Q+tUcPTmeUTCWKK13MFWjq1r53rwMr1TY0SFFXq8LeGy -4OQTXwKBgQDCuPN3Q+EJusYy7TXt0WicY/xyu15s1216N7PmRKFr/WAn2JdAfjbD -JKDwVqo0AQiEDAobJk0JMPs+ENK2d58GsybCK4QGAh6z5FGunb5T432YfnoXtL3J -ZKVvkf7eowvokTIeiDf3XrCPajLDBpo88Xax+RH03US7XRdu/fVzMA== ------END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem deleted file mode 100644 index 6b2658ae..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-crt.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDWDCCAkCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO -MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO -MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy -M1oXDTE4MDkyNTE5MjQyM1owbTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 -MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 -MR4wHAYDVQQDDBVEdW1teSBJbnRlcm1lZGlhdGUgQ0EwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDPfZIHpVYbb0zzNMISwjRiO2mqpgzGcFuTvNxBmGGH -YTa+jAjdMakzdtNmPndgHu2e4eXvvxeRrAxjBwGrMGe8FqYvefBhjHktPJhgdGHE -X2BEhXGSncx7FDl0qkT5n672x43DAUdTJKx7ovbFfWU3QAsgyNQUzfj0V+ojcPTj -mSscmmc37ZPHp3yGkPeu/G9LGNzV6/NoM9Z4FNHKpwZ9dTT2wNQVGyEreNl2JKXw -xhPIHkrIync0Tvj6SV9s4WaoZfCMvEQgA6yvSmGlOUhRG8vYIilgJ0dC/L9qd2VY -CSCCHNEWXloY6plhjpOUJzAg3UQDUEO07KMP7pFp17FbAgMBAAGjEDAOMAwGA1Ud -EwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADmgjS9oIh1PPtvxmykgdyP4ITQX -hACIqD6hTYSUkJYC5mq0IFGgZiA4BRiqKj6aUGCv60pwrJtZMNUXFJy0kWobw0WK -3c0vxsWM/tB2IGOkl9vjKo7BPci2Bi1JetmK3hbqXV/7QXkNj9IjANm5b5NFu3QX -6mtyEwGG/o1+jydxdqk3bWyQWj/ZbU1spGR66oLJh+5q0G4wBX8ZHRkxqZrOIYTa -R8egZhLofldpXZwk5UY8vzf2iMOxQt47ge31ruIjnsKJoedcHUkP7a5VYA5OTOmK -ZOauxdGZp3BMfl1TrIgsDwshlBoy+aHMHmeYa7bpsblLRgKxZclJg4C9uXA= ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem deleted file mode 100644 index 74773609..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/intermediateCA-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEogIBAAKCAQEAz32SB6VWG29M8zTCEsI0YjtpqqYMxnBbk7zcQZhhh2E2vowI -3TGpM3bTZj53YB7tnuHl778XkawMYwcBqzBnvBamL3nwYYx5LTyYYHRhxF9gRIVx -kp3MexQ5dKpE+Z+u9seNwwFHUySse6L2xX1lN0ALIMjUFM349FfqI3D045krHJpn -N+2Tx6d8hpD3rvxvSxjc1evzaDPWeBTRyqcGfXU09sDUFRshK3jZdiSl8MYTyB5K -yMp3NE74+klfbOFmqGXwjLxEIAOsr0phpTlIURvL2CIpYCdHQvy/andlWAkgghzR -Fl5aGOqZYY6TlCcwIN1EA1BDtOyjD+6RadexWwIDAQABAoIBAEs6OsS85DBENUEE -QszsTnPDGLd/Rqh3uiwhUDYUGmAsFd4WBWy1AaSgE1tBkKRv8jUlr+kxfkkZeNA6 -jRdVEHc4Ov6Blm63sIN/Mbve1keNUOjm/NtsjOOe3In45dMfWx8sELC/+O0jIcod -tpy5rwXOGXrEdWgpmXZ1nXVGEfOmQH3eGEPkqbY1I4YlAoXD0mc5fNQQrn7qrogH -M5USCnC44yIIF0Yube2Fg0Cem41vzIvENAlZC273gyW+pQwez0uma2LaCWmkEz1N -sESrNSQ4yeQnDQYlgX2w3RRpqql4GDzAdISL2WJcNhW6KJ72B0SQ1ny/TmQgZePG -Ojv1T0ECgYEA9CXqKyXBSPF+Wdc/fNagrIi6tcNkLAN2/p5J3Z6TtbZGjItoMlDX -c+hwHobcI3GZLMlxlBx7ePc7cKgaMDXrl8BZZjFoyEV9OHOLicfNkLFmBIZ14gtX -bGZYDuCcal46r7IKRjT8lcYWCoLJnI9vLEII7Q7P/eBgcntw3+h/ziECgYEA2ZAa -bp9d0xBaOXq/E341guxNG49R09/DeZ/2CEM+V1pMD8OVH9cvxrBdDLUmAnrqeGTh -Djoi1UEbOVAV6/dXbTQHrla+HF4Uq+t9tV+mt68TEa54PQ/ERt5ih3nZGBiqZ6rX -SGeyZmIXMLIZEs2dIbJ2DmLcZj6Tjxkd/PxPt/sCgYBGczZaEv/uK3k5NWplfI1K -m/28e1BJfwp0OHq6D4sx8RH0djmv4zH4iUbpGCMnuxznFo3Gnl1mr3igbnF4HecI -mAF0AqfoulyC0JygOl5v9TCp957Ghl1Is1OPn3KjIuOuVSKv1ZRZJ5qul8TTf3Qm -AjwPI6oS6Q8LmeEdSzqt4QKBgB5MglHboe5t/ZK5tHibgApOrGJlMEkohYmfrFz0 -OG9j5OnhHBiGGGI8V4kYhUWdJqBDtFAN6qH2Yjs2Gwd0t9k+gL9X1zwOIiTbM/OZ -cZdtK2Ov/5DJbFVOTTx+zKwda0Xqtfagcmjtyjr+4p0Kw5JYzzYrsHQQzO4F2nZM -ETIXAoGADskTzhgpPrC5/qfuLY4gBUtCfYIb8kaKN90AT8A/14lBrT4lSnmsEvKP -tRDmFjnc/ogDlHa5SRDijtT6UoyQPuauAt6DYrJ8G6qKJqiMwJcuLV1XFks7z1J8 -VzB8kso1pPAtcvVXBPklsjvZ10NdQOCqm4N3EVp69agbB1oco4I= ------END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt deleted file mode 100644 index b8535e88..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/mosquitto.org.crt +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC8DCCAlmgAwIBAgIJAOD63PlXjJi8MA0GCSqGSIb3DQEBBQUAMIGQMQswCQYD -VQQGEwJHQjEXMBUGA1UECAwOVW5pdGVkIEtpbmdkb20xDjAMBgNVBAcMBURlcmJ5 -MRIwEAYDVQQKDAlNb3NxdWl0dG8xCzAJBgNVBAsMAkNBMRYwFAYDVQQDDA1tb3Nx -dWl0dG8ub3JnMR8wHQYJKoZIhvcNAQkBFhByb2dlckBhdGNob28ub3JnMB4XDTEy -MDYyOTIyMTE1OVoXDTIyMDYyNzIyMTE1OVowgZAxCzAJBgNVBAYTAkdCMRcwFQYD -VQQIDA5Vbml0ZWQgS2luZ2RvbTEOMAwGA1UEBwwFRGVyYnkxEjAQBgNVBAoMCU1v -c3F1aXR0bzELMAkGA1UECwwCQ0ExFjAUBgNVBAMMDW1vc3F1aXR0by5vcmcxHzAd -BgkqhkiG9w0BCQEWEHJvZ2VyQGF0Y2hvby5vcmcwgZ8wDQYJKoZIhvcNAQEBBQAD -gY0AMIGJAoGBAMYkLmX7SqOT/jJCZoQ1NWdCrr/pq47m3xxyXcI+FLEmwbE3R9vM -rE6sRbP2S89pfrCt7iuITXPKycpUcIU0mtcT1OqxGBV2lb6RaOT2gC5pxyGaFJ+h -A+GIbdYKO3JprPxSBoRponZJvDGEZuM3N7p3S/lRoi7G5wG5mvUmaE5RAgMBAAGj -UDBOMB0GA1UdDgQWBBTad2QneVztIPQzRRGj6ZHKqJTv5jAfBgNVHSMEGDAWgBTa -d2QneVztIPQzRRGj6ZHKqJTv5jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUA -A4GBAAqw1rK4NlRUCUBLhEFUQasjP7xfFqlVbE2cRy0Rs4o3KS0JwzQVBwG85xge -REyPOFdGdhBY2P1FNRy0MDr6xr+D2ZOwxs63dG1nnAnWZg7qwoLgpZ4fESPD3PkA -1ZgKJc2zbSQ9fCPxt2W3mdVav66c6fsb7els2W2Iz7gERJSX ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem deleted file mode 100644 index 1ddb0d49..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-crt.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDizCCAnOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJVUzEO -MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO -MAwGA1UECwwFRHVtbXkxETAPBgNVBAMMCER1bW15IENBMB4XDTEzMTAyMTE5MjQy -M1oXDTE4MDkyNTE5MjQyM1owYDELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBUR1bW15 -MQ4wDAYDVQQHDAVEdW1teTEOMAwGA1UECgwFRHVtbXkxDjAMBgNVBAsMBUR1bW15 -MREwDwYDVQQDDAhEdW1teSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAMLR0DHck8OtiA34k/7MqgQdharDu72HBPBCZxQ0SlaUK7/Qa3IwODk1IIzj -fmWCsH4+HfEYgrfWGVlD7YG+61FE/HeeN63hoBi5S1l5kIGk5FIv/OL/mBBe1ROa -FmIa4MurHa7a0UDUl7Hm4/GXLCpSc6vQohXzHpqwZ9BiZ0t0sLuP754yakwnToJ8 -FmbOBumj2TZP9D68gACTwcoxzwNo1OWLOEW2GzWwwOlKYnWDAaq5wQvA7pfAcyPN -NOy7PJU1yC1p/4bYH8gEfhjeYsJLN8aqjgO/Kw2XICp1R+yYKTxkUu+Ri2MPavjC -nQhqYWhvZJpWsgq8e1k9f/26EksCAwEAAaNQME4wHQYDVR0OBBYEFFu7Po4tkK2u -WAf/UwAYmP9EhEy6MB8GA1UdIwQYMBaAFFu7Po4tkK2uWAf/UwAYmP9EhEy6MAwG -A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADyJC71JEKYa9ipLXwI97vMZ -T8kQeZwB74giPQNbGhRGtn+br6WZGtTUm9Zvwf6Wj5qeR0K07iFWasSSOGyBzY4x -Q4Z8lxWQgNgh8Ea+Ki/ylgeFdKj6G3iPgMFevNkGwjOejvkI3UN7b1oiZ0Z4XftK -TsLGKZQXU6bFqdZnBk8H79pbRSGDyzGy3NysExmYP5hfLLS02tRD16kabrbPvoWo -gB+KwZWKg6Sv0iNKthiHTigxNgMsv+SetnX9xGjtTdWo+qWBExccQ2cCHNDmAG6L -E+ZgH7pAeJMlyllaccxY1FJjHbM8zjfxiXj8E/qz6iKvF2iKoVlX9RpJbrn2X7M= ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem deleted file mode 100644 index 27828768..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/rootCA-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAwtHQMdyTw62IDfiT/syqBB2FqsO7vYcE8EJnFDRKVpQrv9Br -cjA4OTUgjON+ZYKwfj4d8RiCt9YZWUPtgb7rUUT8d543reGgGLlLWXmQgaTkUi/8 -4v+YEF7VE5oWYhrgy6sdrtrRQNSXsebj8ZcsKlJzq9CiFfMemrBn0GJnS3Swu4/v -njJqTCdOgnwWZs4G6aPZNk/0PryAAJPByjHPA2jU5Ys4RbYbNbDA6UpidYMBqrnB -C8Dul8BzI8007Ls8lTXILWn/htgfyAR+GN5iwks3xqqOA78rDZcgKnVH7JgpPGRS -75GLYw9q+MKdCGphaG9kmlayCrx7WT1//boSSwIDAQABAoIBAGphOzge5Cjzdtl6 -JQX7J9M7c6O9YaSqN44iFDs6GmWQXxtMaX9eyTSjx/RmvLwdUtZ8gMkHw0kzBYBy -0RwJ7mDgNKP0px6xl0Qo2fYvpTLFoU8nmQUy4AwAXIVpnFNRrfJIq9qw7ZZi/7pL -A6kGDT3G7Bajw/4MVWfOb8GgGhte1ZhZgXFEZNjGkhwi3Na1/6slOQIfnkkhco0X -ru1Cw82nXNPHqu6K+pbHP9ucYdUNZWRh+yQS3p92lr5tB3/IL/lD0Cl3+xP8JFl+ -5NMSISOKGb3ld0rzrJd1ncgLgv/XlHu8DqvcFs9QwXbaUlG0U/0GrorGYqFaZYaH -R1rkZjECgYEA9mAarVAeL7IOeEIg28f/qyp//5+pMzRpVhnI+xscHB5QUO9WH+uE -nOXwcGvcRME134H4o/0j75aMhVs7sGfMOQ+enAwOxRC5h4MCClDSWysWftU8Ihhf -Sm6eZ0kYLZNqXt/TxTs124NiF1Bb5pekzEr9fTj//vP4meuAQ/D0JoUCgYEAym4f -BCm5tLwYYxZM4tko0g9BHxy4aAPfyshuLed1JjkK4JCFp368GBoknj5rUNewTun2 -1zkQF9b5Mi3k5qWkboP5rpp7DuG3PJdWypV6b/btUeqcyG1gteQwTAwebfqeM0vH -QvpuAoRMtEcSBQBl2s9zgmObXUpDlLwuIlL+to8CgYEAyJBtxx8Mo9k4jE+Q/jnu -+QFtF8R68jM9eRkeksR7+qv2yBw+KVgKKcvKE0rLErGS0LO2nJELexQ8qqcdjTrC -dsUvYmsybtxxnE5bD9jBlfQaqP+fp0Xd9PLeQsivRRLXqgpeFBZifqOS69XAKpTS -VHjLqPAI/hzQCUU8spJpvx0CgYAePgt2NMGgxcUi8I72CRl3IH5LJqBKMeH6Sq1j -QEQZPMZqPE0rc9yoASfdWFfyEPcvIvcUulq0JRK/s2mSJ8cEF8Vyl3OxCnm0nKuD -woczOQHFjjZ0HxsmsXuhsOHO7nU6FqUjVYSf7aIEAOYpRyDwarPIFBd+/XxROTfv -OtUA8wKBgAOiGXRxycb4rAtJBDqPAgdAAwNgvQHyVgn32ArWtgu8ermuZW5h1y45 -hULFvCbLSCpo+I7QhRhw4y2DoB1DgIw04BeFUIcE+az7HH3euAyCLQ0caaA8Xk/6 -bpPfUMe1SNi51f345QlOPvvwGllTC6DeBhZ730k7VNB32dOCV3kE ------END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem deleted file mode 100644 index f3de3caa..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-crt.pem +++ /dev/null @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDYTCCAkmgAwIBAgIBATANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJVUzEO -MAwGA1UECAwFRHVtbXkxDjAMBgNVBAcMBUR1bW15MQ4wDAYDVQQKDAVEdW1teTEO -MAwGA1UECwwFRHVtbXkxHjAcBgNVBAMMFUR1bW15IEludGVybWVkaWF0ZSBDQTAe -Fw0xMzEwMjExOTI0MjNaFw0xODA5MjUxOTI0MjNaMGYxCzAJBgNVBAYTAlVTMQ4w -DAYDVQQIDAVEdW1teTEOMAwGA1UEBwwFRHVtbXkxDjAMBgNVBAoMBUR1bW15MQ4w -DAYDVQQLDAVEdW1teTEXMBUGA1UEAwwORHVtbXkgKHNlcnZlcikwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0fQCRUWXt+i7JMR55Zuo6wBRxG7RnPutN -2L7J/18io52vxjm8AZDiC0JFkCHh72ZzvbgVA+e+WxAIYfioRis4JWw4jK8v5m8q -cZzS0GJNTMROPiZQi7A81tAbrV00XN7d5PsmIJ2Bf4XbJWMy31CsmoFloeRMd7bR -LxwDIb0qqRawhKsWdfZB/c9wGKmHlei50B7PXk+koKnVdsLwXxtCZDvc/3fNRHEK -lZs4m0N05G38FdrnczPm/0pie87nK9rnklL7u1sYOukOznnOtW5h7+A4M+DxzME0 -HRU6k4d+6QvukxBlsE93gHhwRsejIuDGlqD+DRxk2PdmmgsmPH59AgMBAAGjEzAR -MA8GA1UdEQQIMAaHBAoKBOQwDQYJKoZIhvcNAQEFBQADggEBAJ3bKs2b4cAJWTZj -69dMEfYZKcQIXs7euwtKlP7H8m5c+X5KmZPi1Puq4Z0gtvLu/z7J9UjZjG0CoylV -q15Zp5svryJ7XzcsZs7rwyo1JtngW1z54wr9MezqIOF2w12dTwEAINFsW7TxAsH7 -bfqkzZjuCbbsww5q4eHuZp0yaMHc3hOGaUot27OTlxlIMhv7VBBqWAj0jmvAfTKf -la0SiL/Mc8rD8D5C0SXGcCL6li/kqtinAxzhokuyyPf+hQX35kcZxEPu6WxtYVLv -hMzrokOZP2FrGbCnhaNT8gw4Aa0RXV1JgonRWYSbkeaCzvr2bJ0OuJiDdwdRKvOo -raKLlfY= ------END CERTIFICATE----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem deleted file mode 100644 index 951ad0ef..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/ssl/samplecerts/server-key.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAtH0AkVFl7fouyTEeeWbqOsAUcRu0Zz7rTdi+yf9fIqOdr8Y5 -vAGQ4gtCRZAh4e9mc724FQPnvlsQCGH4qEYrOCVsOIyvL+ZvKnGc0tBiTUzETj4m -UIuwPNbQG61dNFze3eT7JiCdgX+F2yVjMt9QrJqBZaHkTHe20S8cAyG9KqkWsISr -FnX2Qf3PcBiph5XoudAez15PpKCp1XbC8F8bQmQ73P93zURxCpWbOJtDdORt/BXa -53Mz5v9KYnvO5yva55JS+7tbGDrpDs55zrVuYe/gODPg8czBNB0VOpOHfukL7pMQ -ZbBPd4B4cEbHoyLgxpag/g0cZNj3ZpoLJjx+fQIDAQABAoIBAG0UfxtUTn4dDdma -TgihIj6Ph8s0Kzua0yshK215YU3WBJ8O9iWh7KYwl8Ti7xdVUF3y8yYATjbFYlMu -otFQVx5/v4ANxnL0mYrVTyo5tq9xDdMbzJwxUDn0uaGAjSvwVOFWWlMYsxhoscVY -OzOrs14dosaBqTBtyZdzGULrSSBWPCBlucRcvTV/eZwgYrYJ3bG66ZTfdc930KPj -nfkWrsAWmPz8irHoWQ2OX+ZJTprVYRYIZXqpFn3zuwmhpJkZUVULMMk6LFBKDmBT -F2+b4h49P+oNJ+6CRoOERHYq2k1MmYBcu1z8lMjdfRGUDdK4vS9pcqhBXJJg1vU9 -APRtfiECgYEA6Y3LqQJLkUI0w6g/9T+XyzUoi0aUfH6PT81XnGYqJxTBHinZvgML -mF3qtZ0bHGwEoAsyhSgDkeCawE/E7Phd+B6aku2QMVm8GHygZg0Pbao4cxXv+CF3 -i1Lo7n3zY0kTVrjsvDRsDDESmRK4Ea48fJwOfUEtfG6VDtwmZAe8chcCgYEAxdWd -sWcc45ARi2vY6yb5Ysgt/g0z26KyQydF+GMWIz1FDfUxXJ/axdCovd3VIHDvItJE -n9LjFiobkyOKX99ou1foWwsmhn11duVrF7hsVrE0nsbd4RX3sTbqXa9x3GN/ujFr -0xHUTmiXt3Qyn/076jBiLGnbtzSxJ/IZIEI9VIsCgYEAketHnTaT5BOLR9ss6ptq -yUlTJYFZcFbaTy+qV0r1dyleZuwa4L6iVfYHmKSptZ4/XYbhb5RKdq/vv8uW679Z -ZpYoWTgX6N15yYrD5D6wrwG09yJzpYGzYNbSNX93u0aC0KIFNqlCAHQAfKbXXiSQ -IgKWgudf9ehZNMmTKtgygs0CgYAoTV9Fr7Lj7QqV84+KQDNX2137PmdNHDTil1Ka -ylzNKwMxV70JmIsx91MY8uMjK76bwmg2gvi+IC/j5r6ez11/pOXx/jCH/3D5mr0Z -ZPm1I36LxgmXfCkskfpmwYIZmq9/l+fWZPByVL5roiFaFHWrPNYTJDGdff+FGr3h -o3zpBwKBgDY1sih/nY+6rwOP+DcabGK9KFFKLXsoJrXobEniLxp7oFaGN2GkmKvN -NajCs5pr3wfb4LrVrsNvERnUsUXWg6ReLqfWbT4bmjzE2iJ3IbtVQ5M4kl6YrbdZ -PMgWoLCqnoo8NoGBtmVMWhaXNJvVZPgZHk33T5F0Cg6PKNdHDchH ------END RSA PRIVATE KEY----- diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go deleted file mode 100644 index 2fdcb407..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdinpub/main.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package main - -import ( - "bufio" - "crypto/tls" - "flag" - "fmt" - "io" - //"log" - "os" - "strconv" - "time" - - MQTT "github.com/eclipse/paho.mqtt.golang" -) - -func main() { - //MQTT.DEBUG = log.New(os.Stdout, "", 0) - //MQTT.ERROR = log.New(os.Stdout, "", 0) - stdin := bufio.NewReader(os.Stdin) - hostname, _ := os.Hostname() - - server := flag.String("server", "tcp://127.0.0.1:1883", "The full URL of the MQTT server to connect to") - topic := flag.String("topic", hostname, "Topic to publish the messages on") - qos := flag.Int("qos", 0, "The QoS to send the messages at") - retained := flag.Bool("retained", false, "Are the messages sent with the retained flag") - clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection") - username := flag.String("username", "", "A username to authenticate to the MQTT server") - password := flag.String("password", "", "Password to match username") - flag.Parse() - - connOpts := MQTT.NewClientOptions().AddBroker(*server).SetClientID(*clientid).SetCleanSession(true) - if *username != "" { - connOpts.SetUsername(*username) - if *password != "" { - connOpts.SetPassword(*password) - } - } - tlsConfig := &tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert} - connOpts.SetTLSConfig(tlsConfig) - - client := MQTT.NewClient(connOpts) - if token := client.Connect(); token.Wait() && token.Error() != nil { - fmt.Println(token.Error()) - return - } - fmt.Printf("Connected to %s\n", *server) - - for { - message, err := stdin.ReadString('\n') - if err == io.EOF { - os.Exit(0) - } - client.Publish(*topic, byte(*qos), *retained, message) - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go deleted file mode 100644 index 235b477a..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/cmd/stdoutsub/main.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package main - -import ( - "crypto/tls" - "flag" - "fmt" - //"log" - "os" - "os/signal" - "strconv" - "syscall" - "time" - - MQTT "github.com/eclipse/paho.mqtt.golang" -) - -func onMessageReceived(client MQTT.Client, message MQTT.Message) { - fmt.Printf("Received message on topic: %s\nMessage: %s\n", message.Topic(), message.Payload()) -} - -var i int64 - -func main() { - //MQTT.DEBUG = log.New(os.Stdout, "", 0) - //MQTT.ERROR = log.New(os.Stdout, "", 0) - c := make(chan os.Signal, 1) - i = 0 - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - go func() { - <-c - fmt.Println("signal received, exiting") - os.Exit(0) - }() - - hostname, _ := os.Hostname() - - server := flag.String("server", "tcp://127.0.0.1:1883", "The full url of the MQTT server to connect to ex: tcp://127.0.0.1:1883") - topic := flag.String("topic", "#", "Topic to subscribe to") - qos := flag.Int("qos", 0, "The QoS to subscribe to messages at") - clientid := flag.String("clientid", hostname+strconv.Itoa(time.Now().Second()), "A clientid for the connection") - username := flag.String("username", "", "A username to authenticate to the MQTT server") - password := flag.String("password", "", "Password to match username") - flag.Parse() - - connOpts := &MQTT.ClientOptions{ - ClientID: *clientid, - CleanSession: true, - Username: *username, - Password: *password, - MaxReconnectInterval: 1 * time.Second, - KeepAlive: 30 * time.Second, - TLSConfig: tls.Config{InsecureSkipVerify: true, ClientAuth: tls.NoClientCert}, - } - connOpts.AddBroker(*server) - connOpts.OnConnect = func(c MQTT.Client) { - if token := c.Subscribe(*topic, byte(*qos), onMessageReceived); token.Wait() && token.Error() != nil { - panic(token.Error()) - } - } - - client := MQTT.NewClient(connOpts) - if token := client.Connect(); token.Wait() && token.Error() != nil { - panic(token.Error()) - } else { - fmt.Printf("Connected to %s\n", *server) - } - - for { - time.Sleep(1 * time.Second) - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 deleted file mode 100644 index cf989f14..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/edl-v10 +++ /dev/null @@ -1,15 +0,0 @@ - -Eclipse Distribution License - v 1.0 - -Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 deleted file mode 100644 index 79e486c3..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/epl-v10 +++ /dev/null @@ -1,70 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: -i) changes to the Program, and -ii) additions to the Program; -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS - -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: - -a) it complies with the terms and conditions of this Agreement; and -b) its license agreement: -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and -b) a copy of this Agreement must be included with each copy of the Program. -Contributors may not remove or alter any copyright notices contained within the Program. - -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md deleted file mode 100644 index 17790426..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/README.md +++ /dev/null @@ -1,74 +0,0 @@ -FVT Instructions -================ - -The FVT tests are currenly only supported by [IBM MessageSight](http://www-03.ibm.com/software/products/us/en/messagesight/). - -Support for [mosquitto](http://mosquitto.org/) and [IBM Really Small Message Broker](https://www.ibm.com/developerworks/community/groups/service/html/communityview?communityUuid=d5bedadd-e46f-4c97-af89-22d65ffee070) might be added in the future. - - -IBM MessageSight Configuration ------------------------------- - -The IBM MessageSight Virtual Appliance can be downloaded here: -[Download](http://www-933.ibm.com/support/fixcentral/swg/selectFixes?parent=ibm~Other+software&product=ibm/Other+software/MessageSight&function=fixId&fixids=1.0.0.1-IMA-DeveloperImage&includeSupersedes=0 "IBM MessageSight") - -There is a nice blog post about it here: -[Blog](https://www.ibm.com/developerworks/community/blogs/c565c720-fe84-4f63-873f-607d87787327/entry/ibm_messagesight_for_developers_is_here?lang=en "Blog") - - -The virtual appliance must be installed into a virtual machine like -Oracle VirtualBox or VMWare Player. (Follow the instructions that come -with the download). - -Next, copy your authorized keys (basically a file containing the public -rsa key of your own computer) onto the appliance to enable passwordless ssh. - -For example, - - Console> user sshkey add "scp://user@host:~/.ssh/authorized_keys" - -More information can be found in the IBM MessageSight InfoCenter: -[InfoCenter](https://infocenters.hursley.ibm.com/ism/v1/help/index.jsp "InfoCenter") - -Now, execute the script setup_IMA.sh to create the objects necessary -to configure the server for the unit test cases provided. - -For example, - - ./setup_IMA.sh - -You should now be able to view the objects on your server: - - Console> imaserver show Endpoint Name=GoMqttEP1 - Name = GoMqttEP1 - Enabled = True - Port = 17001 - Protocol = MQTT - Interface = all - SecurityProfile = - ConnectionPolicies = GoMqttCP1 - MessagingPolicies = GoMqttMP1 - MaxMessageSize = 1024KB - MessageHub = GoMqttTestHub - Description = - - - -RSMB Configuration ------------------- -Wait for SSL support? - - -Mosquitto Configuration ------------------------ -Launch mosquitto from the fvt directory, specifiying mosquitto.cfg as config file - -``ex: /usr/bin/mosquitto -c ./mosquitto.cfg`` - -Note: Mosquitto requires SSL 1.1 or better, while Go 1.1.2 supports -only SSL v1.0. However, Go 1.2+ supports SSL v1.1 and SSL v1.2. - - -Other Notes ------------ -Go 1.1.2 does not support intermediate certificates, however Go 1.2+ does. diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg deleted file mode 100644 index cddb94f3..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/mosquitto.cfg +++ /dev/null @@ -1,17 +0,0 @@ -allow_anonymous true -allow_duplicate_messages false -connection_messages true -log_dest stdout -log_timestamp true -log_type all -persistence false -bind_address 127.0.0.1 - -listener 17001 -listener 17002 -listener 17003 -listener 17004 - -#capath ../samples/samplecerts -#certfile ../samples/samplecerts/server-crt.pem -#keyfile ../samples/samplecerts/server-key.pem diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg deleted file mode 100644 index 1dd77547..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/rsmb.cfg +++ /dev/null @@ -1,8 +0,0 @@ -allow_anonymous false -bind_address 127.0.0.1 -connection_messages true -log_level detail - -listener 17001 -#listener 17003 -#listener 17004 \ No newline at end of file diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh deleted file mode 100644 index 6ebdda3c..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt/setup_IMA.sh +++ /dev/null @@ -1,111 +0,0 @@ -#!/bin/bash - -####################################################################### -# This script is for configuring your IBM Messaging Appliance for use # -# as an mqtt test server for testing the go-mqtt open source client. # -# It creates the Policies and Endpoints necessary to test particular # -# features of the client, such as IPv6, SSL, and other things # -# # -# You do not need this script for any other purpose. # -####################################################################### - -# Edit options to match your configuration -IMA_HOST=9.41.55.184 -IMA_USER=admin -HOST=9.41.55.146 -USER=root -CERTDIR=~/GO/src/github.com/shoenig/go-mqtt/samples/samplecerts - -echo 'Configuring your IBM Messaging Appliance for testing go-mqtt' -echo 'IMA_HOST: ' $IMA_HOST - - -function ima { - reply=`ssh $IMA_USER@$IMA_HOST imaserver $@` -} - -function imp { - reply=`ssh $IMA_USER@$IMA_HOST file get $@` -} - -ima create MessageHub Name=GoMqttTestHub - -# Config "1" is a basic, open endpoint, port 17001 -ima create MessagingPolicy \ - Name=GoMqttMP1 \ - Protocol=MQTT \ - ActionList=Publish,Subscribe \ - MaxMessages=100000 \ - DestinationType=Topic \ - Destination=* - -ima create ConnectionPolicy \ - Name=GoMqttCP1 \ - Protocol=MQTT - -ima create Endpoint \ - Name=GoMqttEP1 \ - Protocol=MQTT \ - MessageHub=GoMqttTestHub \ - ConnectionPolicies=GoMqttCP1 \ - MessagingPolicies=GoMqttMP1 \ - Port=17001 - -# Config "2" is IPv6 only , port 17002 - -# Config "3" is for authorization failures, port 17003 -ima create ConnectionPolicy \ - Name=GoMqttCP2 \ - Protocol=MQTT \ - ClientID=GoMqttClient - -ima create Endpoint \ - Name=GoMqttEP3 \ - Protocol=MQTT \ - MessageHub=GoMqttTestHub \ - ConnectionPolicies=GoMqttCP2 \ - MessagingPolicies=GoMqttMP1 \ - Port=17003 - -# Config "4" is secure connections, port 17004 -imp scp://$USER@$HOST:${CERTDIR}/server-crt.pem . -imp scp://$USER@$HOST:${CERTDIR}/server-key.pem . -imp scp://$USER@$HOST:${CERTDIR}/rootCA-crt.pem . -imp scp://$USER@$HOST:${CERTDIR}/intermediateCA-crt.pem . - -ima apply Certificate \ - CertFileName=server-crt.pem \ - "CertFilePassword=" \ - KeyFileName=server-key.pem \ - "KeyFilePassword=" - -ima create CertificateProfile \ - Name=GoMqttCertProf \ - Certificate=server-crt.pem \ - Key=server-key.pem - -ima create SecurityProfile \ - Name=GoMqttSecProf \ - MinimumProtocolMethod=SSLv3 \ - UseClientCertificate=True \ - UsePasswordAuthentication=False \ - Ciphers=Fast \ - CertificateProfile=GoMqttCertProf - -ima apply Certificate \ - TrustedCertificate=rootCA-crt.pem \ - SecurityProfileName=GoMqttSecProf - -ima apply Certificate \ - TrustedCertificate=intermediateCA-crt.pem \ - SecurityProfileName=GoMqttSecProf - -ima create Endpoint \ - Name=GoMqttEP4 \ - Port=17004 \ - MessageHub=GoMqttTestHub \ - ConnectionPolicies=GoMqttCP1 \ - MessagingPolicies=GoMqttMP1 \ - SecurityProfile=GoMqttSecProf \ - Protocol=MQTT - diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go deleted file mode 100644 index 9cf46cd1..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_client_test.go +++ /dev/null @@ -1,1041 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "bytes" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "testing" - "time" -) - -func Test_Start(t *testing.T) { - ops := NewClientOptions().SetClientID("Start").AddBroker(FVTTCP) - c := NewClient(ops) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.Disconnect(250) -} - -/* uncomment this if you have connection policy disallowing FailClientID -func Test_InvalidConnRc(t *testing.T) { - ops := NewClientOptions().SetClientID("FailClientID"). - AddBroker("tcp://" + FVT_IP + ":17003"). - SetStore(NewFileStore("/tmp/fvt/InvalidConnRc")) - - c := NewClient(ops) - _, err := c.Connect() - if err != ErrNotAuthorized { - t.Fatalf("Did not receive error as expected, got %v", err) - } - c.Disconnect(250) -} -*/ - -// Helper function for Test_Start_Ssl -func NewTLSConfig() *tls.Config { - certpool := x509.NewCertPool() - pemCerts, err := ioutil.ReadFile("samples/samplecerts/CAfile.pem") - if err == nil { - certpool.AppendCertsFromPEM(pemCerts) - } - - cert, err := tls.LoadX509KeyPair("samples/samplecerts/client-crt.pem", "samples/samplecerts/client-key.pem") - if err != nil { - panic(err) - } - - return &tls.Config{ - RootCAs: certpool, - ClientAuth: tls.NoClientCert, - ClientCAs: nil, - InsecureSkipVerify: true, - Certificates: []tls.Certificate{cert}, - } -} - -/* uncomment this if you have ssl setup -func Test_Start_Ssl(t *testing.T) { - tlsconfig := NewTlsConfig() - ops := NewClientOptions().SetClientID("StartSsl"). - AddBroker(FVT_SSL). - SetStore(NewFileStore("/tmp/fvt/Start_Ssl")). - SetTlsConfig(tlsconfig) - - c := NewClient(ops) - - _, err := c.Connect() - if err != nil { - t.Fatalf("Error on Client.Connect(): %v", err) - } - - c.Disconnect(250) -} -*/ - -func Test_Publish_1(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("Publish_1") - - c := NewClient(ops) - token := c.Connect() - if token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.Publish("test/Publish", 0, false, "Publish qo0") - - c.Disconnect(250) -} - -func Test_Publish_2(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("Publish_2") - - c := NewClient(ops) - token := c.Connect() - if token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.Publish("/test/Publish", 0, false, "Publish1 qos0") - c.Publish("/test/Publish", 0, false, "Publish2 qos0") - - c.Disconnect(250) -} - -func Test_Publish_3(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("Publish_3") - - c := NewClient(ops) - token := c.Connect() - if token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.Publish("/test/Publish", 0, false, "Publish1 qos0") - c.Publish("/test/Publish", 1, false, "Publish2 qos1") - c.Publish("/test/Publish", 2, false, "Publish2 qos2") - - c.Disconnect(250) -} - -func Test_Subscribe(t *testing.T) { - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("Subscribe_tx") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("Subscribe_rx") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - } - sops.SetDefaultPublishHandler(f) - s := NewClient(sops) - - sToken := s.Connect() - if sToken.Wait() && sToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) - } - - s.Subscribe("/test/sub", 0, nil) - - pToken := p.Connect() - if pToken.Wait() && pToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) - } - - p.Publish("/test/sub", 0, false, "Publish qos0") - - p.Disconnect(250) - s.Disconnect(250) -} - -func Test_Will(t *testing.T) { - willmsgc := make(chan string, 1) - - sops := NewClientOptions().AddBroker(FVTTCP) - sops.SetClientID("will-giver") - sops.SetWill("/wills", "good-byte!", 0, false) - sops.SetConnectionLostHandler(func(client Client, err error) { - fmt.Println("OnConnectionLost!") - }) - sops.SetAutoReconnect(false) - c := NewClient(sops).(*client) - - wops := NewClientOptions() - wops.AddBroker(FVTTCP) - wops.SetClientID("will-subscriber") - wops.SetDefaultPublishHandler(func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - willmsgc <- string(msg.Payload()) - }) - wops.SetAutoReconnect(false) - wsub := NewClient(wops) - - if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) - } - - if wsubToken := wsub.Subscribe("/wills", 0, nil); wsubToken.Wait() && wsubToken.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", wsubToken.Error()) - } - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.forceDisconnect() - - if <-willmsgc != "good-byte!" { - t.Fatalf("will message did not have correct payload") - } - - wsub.Disconnect(250) -} - -func Test_CleanSession(t *testing.T) { - clsnc := make(chan string, 1) - - sops := NewClientOptions().AddBroker(FVTTCP) - sops.SetClientID("clsn-sender") - sops.SetConnectionLostHandler(func(client Client, err error) { - fmt.Println("OnConnectionLost!") - }) - sops.SetAutoReconnect(false) - c := NewClient(sops).(*client) - - wops := NewClientOptions() - wops.AddBroker(FVTTCP) - wops.SetClientID("clsn-tester") - wops.SetCleanSession(false) - wops.SetDefaultPublishHandler(func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - clsnc <- string(msg.Payload()) - }) - wops.SetAutoReconnect(false) - wsub := NewClient(wops) - - if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) - } - - if wsubToken := wsub.Subscribe("clean", 1, nil); wsubToken.Wait() && wsubToken.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", wsubToken.Error()) - } - - wsub.Disconnect(250) - time.Sleep(2 * time.Second) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if pToken := c.Publish("clean", 1, false, "clean!"); pToken.Wait() && pToken.Error() != nil { - t.Fatalf("Error on Client.Publish(): %v", pToken.Error()) - } - - c.Disconnect(250) - - wsub = NewClient(wops) - if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) - } - - select { - case msg := <-clsnc: - if msg != "clean!" { - t.Fatalf("will message did not have correct payload") - } - case <-time.NewTicker(5 * time.Second).C: - t.Fatalf("failed to receive publish") - } - - wsub.Disconnect(250) - - wops.SetCleanSession(true) - - wsub = NewClient(wops) - if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) - } - - wsub.Disconnect(250) -} - -func Test_Binary_Will(t *testing.T) { - willmsgc := make(chan []byte, 1) - will := []byte{ - 0xDE, - 0xAD, - 0xBE, - 0xEF, - } - - sops := NewClientOptions().AddBroker(FVTTCP) - sops.SetClientID("will-giver") - sops.SetBinaryWill("/wills", will, 0, false) - sops.SetConnectionLostHandler(func(client Client, err error) { - }) - sops.SetAutoReconnect(false) - c := NewClient(sops).(*client) - - wops := NewClientOptions().AddBroker(FVTTCP) - wops.SetClientID("will-subscriber") - wops.SetDefaultPublishHandler(func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %v\n", msg.Payload()) - willmsgc <- msg.Payload() - }) - wops.SetAutoReconnect(false) - wsub := NewClient(wops) - - if wToken := wsub.Connect(); wToken.Wait() && wToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", wToken.Error()) - } - - if wsubToken := wsub.Subscribe("/wills", 0, nil); wsubToken.Wait() && wsubToken.Error() != nil { - t.Fatalf("Error on Client.Subscribe() %v", wsubToken.Error()) - } - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - c.forceDisconnect() - - if !bytes.Equal(<-willmsgc, will) { - t.Fatalf("will message did not have correct payload") - } - - wsub.Disconnect(250) -} - -/** -"[...] a publisher is responsible for determining the maximum QoS a -message can be delivered at, but a subscriber is able to downgrade -the QoS to one more suitable for its usage. -The QoS of a message is never upgraded." -**/ - -/*********************************** - * Tests to cover the 9 QoS combos * - ***********************************/ - -func wait(c chan bool) { - fmt.Println("choke is waiting") - <-c -} - -// Pub 0, Sub 0 - -func Test_p0s0(t *testing.T) { - topic := "/test/p0s0" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p0s0-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p0s0-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 0, false, "p0s0 payload 1") - p.Publish(topic, 0, false, "p0s0 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 0, false, "p0s0 payload 3") - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 0, Sub 1 - -func Test_p0s1(t *testing.T) { - topic := "/test/p0s1" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p0s1-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p0s1-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 0, false, "p0s1 payload 1") - p.Publish(topic, 0, false, "p0s1 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 0, false, "p0s1 payload 3") - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 0, Sub 2 - -func Test_p0s2(t *testing.T) { - topic := "/test/p0s2" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p0s2-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p0s2-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 0, false, "p0s2 payload 1") - p.Publish(topic, 0, false, "p0s2 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 0, false, "p0s2 payload 3") - - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 1, Sub 0 - -func Test_p1s0(t *testing.T) { - topic := "/test/p1s0" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p1s0-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p1s0-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 1, false, "p1s0 payload 1") - p.Publish(topic, 1, false, "p1s0 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 1, false, "p1s0 payload 3") - - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 1, Sub 1 - -func Test_p1s1(t *testing.T) { - topic := "/test/p1s1" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p1s1-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p1s1-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 1, false, "p1s1 payload 1") - p.Publish(topic, 1, false, "p1s1 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 1, false, "p1s1 payload 3") - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 1, Sub 2 - -func Test_p1s2(t *testing.T) { - topic := "/test/p1s2" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p1s2-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p1s2-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 1, false, "p1s2 payload 1") - p.Publish(topic, 1, false, "p1s2 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 1, false, "p1s2 payload 3") - - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 2, Sub 0 - -func Test_p2s0(t *testing.T) { - topic := "/test/p2s0" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p2s0-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p2s0-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 2, false, "p2s0 payload 1") - p.Publish(topic, 2, false, "p2s0 payload 2") - wait(choke) - wait(choke) - - p.Publish(topic, 2, false, "p2s0 payload 3") - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 2, Sub 1 - -func Test_p2s1(t *testing.T) { - topic := "/test/p2s1" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p2s1-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p2s1-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 2, false, "p2s1 payload 1") - p.Publish(topic, 2, false, "p2s1 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 2, false, "p2s1 payload 3") - - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -// Pub 2, Sub 2 - -func Test_p2s2(t *testing.T) { - topic := "/test/p2s2" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("p2s2-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("p2s2-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - p.Publish(topic, 2, false, "p2s2 payload 1") - p.Publish(topic, 2, false, "p2s2 payload 2") - - wait(choke) - wait(choke) - - p.Publish(topic, 2, false, "p2s2 payload 3") - - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -func Test_PublishMessage(t *testing.T) { - topic := "/test/pubmsg" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("pubmsg-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("pubmsg-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - if string(msg.Payload()) != "pubmsg payload" { - fmt.Println("Message payload incorrect", msg.Payload(), len("pubmsg payload")) - t.Fatalf("Message payload incorrect") - } - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if token := s.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if token := s.Subscribe(topic, 2, nil); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", token.Error()) - } - - if token := p.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - text := "pubmsg payload" - p.Publish(topic, 0, false, text) - p.Publish(topic, 0, false, text) - wait(choke) - wait(choke) - - p.Publish(topic, 0, false, text) - wait(choke) - - p.Disconnect(250) - s.Disconnect(250) -} - -func Test_PublishEmptyMessage(t *testing.T) { - topic := "/test/pubmsgempty" - choke := make(chan bool) - - pops := NewClientOptions() - pops.AddBroker(FVTTCP) - pops.SetClientID("pubmsgempty-pub") - p := NewClient(pops) - - sops := NewClientOptions() - sops.AddBroker(FVTTCP) - sops.SetClientID("pubmsgempty-sub") - var f MessageHandler = func(client Client, msg Message) { - fmt.Printf("TOPIC: %s\n", msg.Topic()) - fmt.Printf("MSG: %s\n", msg.Payload()) - if string(msg.Payload()) != "" { - t.Fatalf("Message payload incorrect") - } - choke <- true - } - sops.SetDefaultPublishHandler(f) - - s := NewClient(sops) - if sToken := s.Connect(); sToken.Wait() && sToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) - } - - if sToken := s.Subscribe(topic, 2, nil); sToken.Wait() && sToken.Error() != nil { - t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error()) - } - - if pToken := p.Connect(); pToken.Wait() && pToken.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) - } - - p.Publish(topic, 0, false, "") - p.Publish(topic, 0, false, "") - wait(choke) - wait(choke) - - p.Publish(topic, 0, false, "") - wait(choke) - - p.Disconnect(250) -} - -// func Test_Cleanstore(t *testing.T) { -// store := "/tmp/fvt/cleanstore" -// topic := "/test/cleanstore" - -// pops := NewClientOptions() -// pops.AddBroker(FVTTCP) -// pops.SetClientID("cleanstore-pub") -// pops.SetStore(NewFileStore(store + "/p")) -// p := NewClient(pops) - -// var s *Client -// sops := NewClientOptions() -// sops.AddBroker(FVTTCP) -// sops.SetClientID("cleanstore-sub") -// sops.SetCleanSession(false) -// sops.SetStore(NewFileStore(store + "/s")) -// var f MessageHandler = func(client Client, msg Message) { -// fmt.Printf("TOPIC: %s\n", msg.Topic()) -// fmt.Printf("MSG: %s\n", msg.Payload()) -// // Close the connection after receiving -// // the first message so that hopefully -// // there is something in the store to be -// // cleaned. -// s.ForceDisconnect() -// } -// sops.SetDefaultPublishHandler(f) - -// s = NewClient(sops) -// sToken := s.Connect() -// if sToken.Wait() && sToken.Error() != nil { -// t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) -// } - -// sToken = s.Subscribe(topic, 2, nil) -// if sToken.Wait() && sToken.Error() != nil { -// t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error()) -// } - -// pToken := p.Connect() -// if pToken.Wait() && pToken.Error() != nil { -// t.Fatalf("Error on Client.Connect(): %v", pToken.Error()) -// } - -// text := "test message" -// p.Publish(topic, 0, false, text) -// p.Publish(topic, 0, false, text) -// p.Publish(topic, 0, false, text) - -// p.Disconnect(250) - -// s2ops := NewClientOptions() -// s2ops.AddBroker(FVTTCP) -// s2ops.SetClientID("cleanstore-sub") -// s2ops.SetCleanSession(true) -// s2ops.SetStore(NewFileStore(store + "/s")) -// s2ops.SetDefaultPublishHandler(f) - -// s2 := NewClient(s2ops) -// sToken = s2.Connect() -// if sToken.Wait() && sToken.Error() != nil { -// t.Fatalf("Error on Client.Connect(): %v", sToken.Error()) -// } - -// // at this point existing state should be cleared... -// // how to check? -// } - -func Test_MultipleURLs(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker("tcp://127.0.0.1:10000") - ops.AddBroker(FVTTCP) - ops.SetClientID("MultiURL") - - c := NewClient(ops) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - if pToken := c.Publish("/test/MultiURL", 0, false, "Publish qo0"); pToken.Wait() && pToken.Error() != nil { - t.Fatalf("Error on Client.Publish(): %v", pToken.Error()) - } - - c.Disconnect(250) -} - -// A test to make sure ping mechanism is working -func Test_ping1_idle5(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("p3i10") - ops.SetConnectionLostHandler(func(c Client, err error) { - t.Fatalf("Connection-lost handler was called: %s", err) - }) - ops.SetKeepAlive(2 * time.Second) - - c := NewClient(ops) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - time.Sleep(5 * time.Second) - c.Disconnect(250) -} - -func Test_autoreconnect(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("auto_reconnect") - ops.SetAutoReconnect(true) - ops.SetOnConnectHandler(func(c Client) { - t.Log("Connected") - }) - ops.SetKeepAlive(2 * time.Second) - - c := NewClient(ops) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - time.Sleep(5 * time.Second) - - fmt.Println("Breaking connection") - c.(*client).internalConnLost(fmt.Errorf("Autoreconnect test")) - - time.Sleep(5 * time.Second) - if !c.IsConnected() { - t.Fail() - } - - c.Disconnect(250) -} - -func Test_cleanUpMids(t *testing.T) { - ops := NewClientOptions() - ops.AddBroker(FVTTCP) - ops.SetClientID("auto_reconnect") - ops.SetCleanSession(true) - ops.SetAutoReconnect(true) - ops.SetKeepAlive(10 * time.Second) - - c := NewClient(ops) - - if token := c.Connect(); token.Wait() && token.Error() != nil { - t.Fatalf("Error on Client.Connect(): %v", token.Error()) - } - - token := c.Publish("/test/cleanUP", 2, false, "cleanup test") - time.Sleep(10 * time.Millisecond) - fmt.Println("Breaking connection", len(c.(*client).messageIds.index)) - if len(c.(*client).messageIds.index) == 0 { - t.Fatalf("Should be a token in the messageIDs, none found") - } - c.(*client).internalConnLost(fmt.Errorf("cleanup test")) - - time.Sleep(5 * time.Second) - if !c.IsConnected() { - t.Fail() - } - - if len(c.(*client).messageIds.index) > 0 { - t.Fatalf("Should have cleaned up messageIDs, have %d left", len(c.(*client).messageIds.index)) - } - if token.Error() == nil { - t.Fatal("token should have received an error on connection loss") - } - fmt.Println(token.Error()) - - c.Disconnect(250) -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go deleted file mode 100644 index f0aa39cd..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_store_test.go +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "bytes" - "io/ioutil" - "os" - "testing" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -/********************************************** - **** A mock store implementation for test **** - **********************************************/ - -type TestStore struct { - mput []uint16 - mget []uint16 - mdel []uint16 -} - -func (ts *TestStore) Open() { -} - -func (ts *TestStore) Close() { -} - -func (ts *TestStore) Put(key string, m packets.ControlPacket) { - ts.mput = append(ts.mput, m.Details().MessageID) -} - -func (ts *TestStore) Get(key string) packets.ControlPacket { - mid := mIDFromKey(key) - ts.mget = append(ts.mget, mid) - return nil -} - -func (ts *TestStore) All() []string { - return nil -} - -func (ts *TestStore) Del(key string) { - mid := mIDFromKey(key) - ts.mdel = append(ts.mdel, mid) -} - -func (ts *TestStore) Reset() { -} - -/******************* - **** FileStore **** - *******************/ - -func Test_NewFileStore(t *testing.T) { - storedir := "/tmp/TestStore/_new" - f := NewFileStore(storedir) - if f.opened { - t.Fatalf("filestore was opened without opening it") - } - if f.directory != storedir { - t.Fatalf("filestore directory is wrong") - } - // storedir might exist or might not, just like with a real client - // the point is, we don't care, we just want it to exist after it is - // opened -} - -func Test_FileStore_Open(t *testing.T) { - storedir := "/tmp/TestStore/_open" - - f := NewFileStore(storedir) - f.Open() - if !f.opened { - t.Fatalf("filestore was not set open") - } - if f.directory != storedir { - t.Fatalf("filestore directory is wrong") - } - if !exists(storedir) { - t.Fatalf("filestore directory does not exst after opening it") - } -} - -func Test_FileStore_Close(t *testing.T) { - storedir := "/tmp/TestStore/_unopen" - f := NewFileStore(storedir) - f.Open() - if !f.opened { - t.Fatalf("filestore was not set open") - } - if f.directory != storedir { - t.Fatalf("filestore directory is wrong") - } - if !exists(storedir) { - t.Fatalf("filestore directory does not exst after opening it") - } - - f.Close() - if f.opened { - t.Fatalf("filestore was still open after unopen") - } - if !exists(storedir) { - t.Fatalf("filestore was deleted after unopen") - } -} - -func Test_FileStore_write(t *testing.T) { - storedir := "/tmp/TestStore/_write" - f := NewFileStore(storedir) - f.Open() - - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 91 - - key := inboundKeyFromMID(pm.MessageID) - f.Put(key, pm) - - if !exists(storedir + "/i.91.msg") { - t.Fatalf("message not in store") - } - -} - -func Test_FileStore_Get(t *testing.T) { - storedir := "/tmp/TestStore/_get" - f := NewFileStore(storedir) - f.Open() - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "/a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 120 - - key := outboundKeyFromMID(pm.MessageID) - f.Put(key, pm) - - if !exists(storedir + "/o.120.msg") { - t.Fatalf("message not in store") - } - - exp := []byte{ - /* msg type */ - 0x32, // qos 1 - - /* remlen */ - 0x0d, - - /* topic, msg id in varheader */ - 0x00, // length of topic - 0x06, - 0x2F, // / - 0x61, // a - 0x2F, // / - 0x62, // b - 0x2F, // / - 0x63, // c - - /* msg id (is always 2 bytes) */ - 0x00, - 0x78, - - /*payload */ - 0xBE, - 0xEF, - 0xED, - } - - m := f.Get(key) - - if m == nil { - t.Fatalf("message not retreived from store") - } - - var msg bytes.Buffer - m.Write(&msg) - if !bytes.Equal(exp, msg.Bytes()) { - t.Fatal("message from store not same as what went in", msg.Bytes()) - } -} - -func Test_FileStore_Get_Corrupted(t *testing.T) { - storedir := "/tmp/TestStore/_get_error" - f := NewFileStore(storedir) - f.Open() - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "/a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 120 - - key := outboundKeyFromMID(pm.MessageID) - - exp := []byte{ - /* msg type */ - 0x32, // qos 1 - - /* remlen */ - 0x0d, - - /* topic, msg id in varheader */ - 0x00, // length of topic - 0x06, - // Oh no the rest is gone! - } - - file, err := os.Create(storedir + "/o.120.msg") - chkerr(err) - _, err = file.Write(exp) - chkerr(err) - chkerr(file.Close()) - - if !exists(storedir + "/o.120.msg") { - t.Fatalf("corrupt message not in store") - } - - m := f.Get(key) - - if m != nil { - t.Fatalf("corrupted message retrieved from store") - } - - if exists(storedir + "/o.120.msg") { - t.Fatalf("corrupt message left in store") - } - - if !exists(storedir + "/o.120.CORRUPT") { - t.Fatalf("corrupt message not archived") - } - - contents, err := ioutil.ReadFile(storedir + "/o.120.CORRUPT") - chkerr(err) - - if !bytes.Equal(exp, contents) { - t.Fatal("archived corrupted bytes not the same as those saved", exp, contents) - } -} - -func Test_FileStore_All(t *testing.T) { - storedir := "/tmp/TestStore/_all" - f := NewFileStore(storedir) - f.Open() - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 2 - pm.TopicName = "/t/r/v" - pm.Payload = []byte{0x01, 0x02} - pm.MessageID = 121 - - key := outboundKeyFromMID(pm.MessageID) - f.Put(key, pm) - - keys := f.All() - if len(keys) != 1 { - t.Logf("Keys: %s", keys) - t.Fatalf("FileStore.All does not have the messages") - } - - if keys[0] != "o.121" { - t.Fatalf("FileStore.All has wrong key") - } -} - -func Test_FileStore_Del(t *testing.T) { - storedir := "/tmp/TestStore/_del" - f := NewFileStore(storedir) - f.Open() - - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 17 - - key := inboundKeyFromMID(pm.MessageID) - f.Put(key, pm) - - if !exists(storedir + "/i.17.msg") { - t.Fatalf("message not in store") - } - - f.Del(key) - - if exists(storedir + "/i.17.msg") { - t.Fatalf("message still exists after deletion") - } -} - -func Test_FileStore_Reset(t *testing.T) { - storedir := "/tmp/TestStore/_reset" - f := NewFileStore(storedir) - f.Open() - - pm1 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm1.Qos = 1 - pm1.TopicName = "/q/w/e" - pm1.Payload = []byte{0xBB} - pm1.MessageID = 71 - key1 := inboundKeyFromMID(pm1.MessageID) - f.Put(key1, pm1) - - pm2 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm2.Qos = 1 - pm2.TopicName = "/q/w/e" - pm2.Payload = []byte{0xBB} - pm2.MessageID = 72 - key2 := inboundKeyFromMID(pm2.MessageID) - f.Put(key2, pm2) - - pm3 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm3.Qos = 1 - pm3.TopicName = "/q/w/e" - pm3.Payload = []byte{0xBB} - pm3.MessageID = 73 - key3 := inboundKeyFromMID(pm3.MessageID) - f.Put(key3, pm3) - - pm4 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm4.Qos = 1 - pm4.TopicName = "/q/w/e" - pm4.Payload = []byte{0xBB} - pm4.MessageID = 74 - key4 := inboundKeyFromMID(pm4.MessageID) - f.Put(key4, pm4) - - pm5 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm5.Qos = 1 - pm5.TopicName = "/q/w/e" - pm5.Payload = []byte{0xBB} - pm5.MessageID = 75 - key5 := inboundKeyFromMID(pm5.MessageID) - f.Put(key5, pm5) - - if !exists(storedir + "/i.71.msg") { - t.Fatalf("message not in store") - } - - if !exists(storedir + "/i.72.msg") { - t.Fatalf("message not in store") - } - - if !exists(storedir + "/i.73.msg") { - t.Fatalf("message not in store") - } - - if !exists(storedir + "/i.74.msg") { - t.Fatalf("message not in store") - } - - if !exists(storedir + "/i.75.msg") { - t.Fatalf("message not in store") - } - - f.Reset() - - if exists(storedir + "/i.71.msg") { - t.Fatalf("message still exists after reset") - } - - if exists(storedir + "/i.72.msg") { - t.Fatalf("message still exists after reset") - } - - if exists(storedir + "/i.73.msg") { - t.Fatalf("message still exists after reset") - } - - if exists(storedir + "/i.74.msg") { - t.Fatalf("message still exists after reset") - } - - if exists(storedir + "/i.75.msg") { - t.Fatalf("message still exists after reset") - } -} - -/******************* - *** MemoryStore *** - *******************/ - -func Test_NewMemoryStore(t *testing.T) { - m := NewMemoryStore() - if m == nil { - t.Fatalf("MemoryStore could not be created") - } -} - -func Test_MemoryStore_Open(t *testing.T) { - m := NewMemoryStore() - m.Open() - if !m.opened { - t.Fatalf("MemoryStore was not set open") - } -} - -func Test_MemoryStore_Close(t *testing.T) { - m := NewMemoryStore() - m.Open() - if !m.opened { - t.Fatalf("MemoryStore was not set open") - } - - m.Close() - if m.opened { - t.Fatalf("MemoryStore was still open after unopen") - } -} - -func Test_MemoryStore_Reset(t *testing.T) { - m := NewMemoryStore() - m.Open() - - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 2 - pm.TopicName = "/f/r/s" - pm.Payload = []byte{0xAB} - pm.MessageID = 81 - - key := outboundKeyFromMID(pm.MessageID) - m.Put(key, pm) - - if len(m.messages) != 1 { - t.Fatalf("message not in memstore") - } - - m.Reset() - - if len(m.messages) != 0 { - t.Fatalf("reset did not clear memstore") - } -} - -func Test_MemoryStore_write(t *testing.T) { - m := NewMemoryStore() - m.Open() - - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "/a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 91 - key := inboundKeyFromMID(pm.MessageID) - m.Put(key, pm) - - if len(m.messages) != 1 { - t.Fatalf("message not in store") - } -} - -func Test_MemoryStore_Get(t *testing.T) { - m := NewMemoryStore() - m.Open() - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "/a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 120 - - key := outboundKeyFromMID(pm.MessageID) - m.Put(key, pm) - - if len(m.messages) != 1 { - t.Fatalf("message not in store") - } - - exp := []byte{ - /* msg type */ - 0x32, // qos 1 - - /* remlen */ - 0x0d, - - /* topic, msg id in varheader */ - 0x00, // length of topic - 0x06, - 0x2F, // / - 0x61, // a - 0x2F, // / - 0x62, // b - 0x2F, // / - 0x63, // c - - /* msg id (is always 2 bytes) */ - 0x00, - 0x78, - - /*payload */ - 0xBE, - 0xEF, - 0xED, - } - - msg := m.Get(key) - - if msg == nil { - t.Fatalf("message not retreived from store") - } - - var buf bytes.Buffer - msg.Write(&buf) - if !bytes.Equal(exp, buf.Bytes()) { - t.Fatalf("message from store not same as what went in") - } -} - -func Test_MemoryStore_Del(t *testing.T) { - m := NewMemoryStore() - m.Open() - - pm := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pm.Qos = 1 - pm.TopicName = "/a/b/c" - pm.Payload = []byte{0xBE, 0xEF, 0xED} - pm.MessageID = 17 - - key := outboundKeyFromMID(pm.MessageID) - - m.Put(key, pm) - - if len(m.messages) != 1 { - t.Fatalf("message not in store") - } - - m.Del(key) - - if len(m.messages) != 1 { - t.Fatalf("message still exists after deletion") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go deleted file mode 100644 index cb3a4545..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/fvt_test.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import "os" - -// Use setup_IMA.sh for IBM's MessageSight -// Use fvt/rsmb.cfg for IBM's Really Small Message Broker -// Use fvt/mosquitto.cfg for the open source Mosquitto project - -var ( - FVTAddr string - FVTTCP string - FVTSSL string -) - -func init() { - FVTAddr := os.Getenv("TEST_FVT_ADDR") - if FVTAddr == "" { - FVTAddr = "iot.eclipse.org" - } - FVTTCP = "tcp://" + FVTAddr + ":1883" - FVTSSL = "ssl://" + FVTAddr + ":8883" -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go deleted file mode 100644 index 51d887d0..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets_test.go +++ /dev/null @@ -1,159 +0,0 @@ -package packets - -import ( - "bytes" - "testing" -) - -func TestPacketNames(t *testing.T) { - if PacketNames[1] != "CONNECT" { - t.Errorf("PacketNames[1] is %s, should be %s", PacketNames[1], "CONNECT") - } - if PacketNames[2] != "CONNACK" { - t.Errorf("PacketNames[2] is %s, should be %s", PacketNames[2], "CONNACK") - } - if PacketNames[3] != "PUBLISH" { - t.Errorf("PacketNames[3] is %s, should be %s", PacketNames[3], "PUBLISH") - } - if PacketNames[4] != "PUBACK" { - t.Errorf("PacketNames[4] is %s, should be %s", PacketNames[4], "PUBACK") - } - if PacketNames[5] != "PUBREC" { - t.Errorf("PacketNames[5] is %s, should be %s", PacketNames[5], "PUBREC") - } - if PacketNames[6] != "PUBREL" { - t.Errorf("PacketNames[6] is %s, should be %s", PacketNames[6], "PUBREL") - } - if PacketNames[7] != "PUBCOMP" { - t.Errorf("PacketNames[7] is %s, should be %s", PacketNames[7], "PUBCOMP") - } - if PacketNames[8] != "SUBSCRIBE" { - t.Errorf("PacketNames[8] is %s, should be %s", PacketNames[8], "SUBSCRIBE") - } - if PacketNames[9] != "SUBACK" { - t.Errorf("PacketNames[9] is %s, should be %s", PacketNames[9], "SUBACK") - } - if PacketNames[10] != "UNSUBSCRIBE" { - t.Errorf("PacketNames[10] is %s, should be %s", PacketNames[10], "UNSUBSCRIBE") - } - if PacketNames[11] != "UNSUBACK" { - t.Errorf("PacketNames[11] is %s, should be %s", PacketNames[11], "UNSUBACK") - } - if PacketNames[12] != "PINGREQ" { - t.Errorf("PacketNames[12] is %s, should be %s", PacketNames[12], "PINGREQ") - } - if PacketNames[13] != "PINGRESP" { - t.Errorf("PacketNames[13] is %s, should be %s", PacketNames[13], "PINGRESP") - } - if PacketNames[14] != "DISCONNECT" { - t.Errorf("PacketNames[14] is %s, should be %s", PacketNames[14], "DISCONNECT") - } -} - -func TestPacketConsts(t *testing.T) { - if Connect != 1 { - t.Errorf("Const for Connect is %d, should be %d", Connect, 1) - } - if Connack != 2 { - t.Errorf("Const for Connack is %d, should be %d", Connack, 2) - } - if Publish != 3 { - t.Errorf("Const for Publish is %d, should be %d", Publish, 3) - } - if Puback != 4 { - t.Errorf("Const for Puback is %d, should be %d", Puback, 4) - } - if Pubrec != 5 { - t.Errorf("Const for Pubrec is %d, should be %d", Pubrec, 5) - } - if Pubrel != 6 { - t.Errorf("Const for Pubrel is %d, should be %d", Pubrel, 6) - } - if Pubcomp != 7 { - t.Errorf("Const for Pubcomp is %d, should be %d", Pubcomp, 7) - } - if Subscribe != 8 { - t.Errorf("Const for Subscribe is %d, should be %d", Subscribe, 8) - } - if Suback != 9 { - t.Errorf("Const for Suback is %d, should be %d", Suback, 9) - } - if Unsubscribe != 10 { - t.Errorf("Const for Unsubscribe is %d, should be %d", Unsubscribe, 10) - } - if Unsuback != 11 { - t.Errorf("Const for Unsuback is %d, should be %d", Unsuback, 11) - } - if Pingreq != 12 { - t.Errorf("Const for Pingreq is %d, should be %d", Pingreq, 12) - } - if Pingresp != 13 { - t.Errorf("Const for Pingresp is %d, should be %d", Pingresp, 13) - } - if Disconnect != 14 { - t.Errorf("Const for Disconnect is %d, should be %d", Disconnect, 14) - } -} - -func TestConnackConsts(t *testing.T) { - if Accepted != 0x00 { - t.Errorf("Const for Accepted is %d, should be %d", Accepted, 0) - } - if ErrRefusedBadProtocolVersion != 0x01 { - t.Errorf("Const for RefusedBadProtocolVersion is %d, should be %d", ErrRefusedBadProtocolVersion, 1) - } - if ErrRefusedIDRejected != 0x02 { - t.Errorf("Const for RefusedIDRejected is %d, should be %d", ErrRefusedIDRejected, 2) - } - if ErrRefusedServerUnavailable != 0x03 { - t.Errorf("Const for RefusedServerUnavailable is %d, should be %d", ErrRefusedServerUnavailable, 3) - } - if ErrRefusedBadUsernameOrPassword != 0x04 { - t.Errorf("Const for RefusedBadUsernameOrPassword is %d, should be %d", ErrRefusedBadUsernameOrPassword, 4) - } - if ErrRefusedNotAuthorised != 0x05 { - t.Errorf("Const for RefusedNotAuthorised is %d, should be %d", ErrRefusedNotAuthorised, 5) - } -} - -func TestConnectPacket(t *testing.T) { - connectPacketBytes := bytes.NewBuffer([]byte{16, 52, 0, 4, 77, 81, 84, 84, 4, 204, 0, 0, 0, 0, 0, 4, 116, 101, 115, 116, 0, 12, 84, 101, 115, 116, 32, 80, 97, 121, 108, 111, 97, 100, 0, 8, 116, 101, 115, 116, 117, 115, 101, 114, 0, 8, 116, 101, 115, 116, 112, 97, 115, 115}) - packet, err := ReadPacket(connectPacketBytes) - if err != nil { - t.Fatalf("Error reading packet: %s", err.Error()) - } - cp := packet.(*ConnectPacket) - if cp.ProtocolName != "MQTT" { - t.Errorf("Connect Packet ProtocolName is %s, should be %s", cp.ProtocolName, "MQTT") - } - if cp.ProtocolVersion != 4 { - t.Errorf("Connect Packet ProtocolVersion is %d, should be %d", cp.ProtocolVersion, 4) - } - if cp.UsernameFlag != true { - t.Errorf("Connect Packet UsernameFlag is %t, should be %t", cp.UsernameFlag, true) - } - if cp.Username != "testuser" { - t.Errorf("Connect Packet Username is %s, should be %s", cp.Username, "testuser") - } - if cp.PasswordFlag != true { - t.Errorf("Connect Packet PasswordFlag is %t, should be %t", cp.PasswordFlag, true) - } - if string(cp.Password) != "testpass" { - t.Errorf("Connect Packet Password is %s, should be %s", string(cp.Password), "testpass") - } - if cp.WillFlag != true { - t.Errorf("Connect Packet WillFlag is %t, should be %t", cp.WillFlag, true) - } - if cp.WillTopic != "test" { - t.Errorf("Connect Packet WillTopic is %s, should be %s", cp.WillTopic, "test") - } - if cp.WillQos != 1 { - t.Errorf("Connect Packet WillQos is %d, should be %d", cp.WillQos, 1) - } - if cp.WillRetain != false { - t.Errorf("Connect Packet WillRetain is %t, should be %t", cp.WillRetain, false) - } - if string(cp.WillMessage) != "Test Payload" { - t.Errorf("Connect Packet WillMessage is %s, should be %s", string(cp.WillMessage), "Test Payload") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go deleted file mode 100644 index 0a57c6b8..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_client_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "log" - "net/http" - "os" - "testing" - - _ "net/http/pprof" -) - -func init() { - DEBUG = log.New(os.Stderr, "DEBUG ", log.Ltime) - WARN = log.New(os.Stderr, "WARNING ", log.Ltime) - CRITICAL = log.New(os.Stderr, "CRITICAL ", log.Ltime) - ERROR = log.New(os.Stderr, "ERROR ", log.Ltime) - - go func() { - log.Println(http.ListenAndServe("localhost:6060", nil)) - }() -} - -func Test_NewClient_simple(t *testing.T) { - ops := NewClientOptions().SetClientID("foo").AddBroker("tcp://10.10.0.1:1883") - c := NewClient(ops).(*client) - - if c == nil { - t.Fatalf("ops is nil") - } - - if c.options.ClientID != "foo" { - t.Fatalf("bad client id") - } - - if c.options.Servers[0].Scheme != "tcp" { - t.Fatalf("bad server scheme") - } - - if c.options.Servers[0].Host != "10.10.0.1:1883" { - t.Fatalf("bad server host") - } -} - -func Test_NewClient_optionsReader(t *testing.T) { - ops := NewClientOptions().SetClientID("foo").AddBroker("tcp://10.10.0.1:1883") - c := NewClient(ops).(*client) - - if c == nil { - t.Fatalf("ops is nil") - } - - rOps := c.OptionsReader() - cid := rOps.ClientID() - - if cid != "foo" { - t.Fatalf("unable to read client ID") - } - - servers := rOps.Servers() - broker := servers[0] - if broker.Hostname() != "10.10.0.1" { - t.Fatalf("unable to read hostname") - } - -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go deleted file mode 100644 index 9d941f69..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_messageids_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "fmt" - "testing" - "time" -) - -type DummyToken struct{} - -func (d *DummyToken) Wait() bool { - return true -} - -func (d *DummyToken) WaitTimeout(t time.Duration) bool { - return true -} - -func (d *DummyToken) flowComplete() {} - -func (d *DummyToken) Error() error { - return nil -} - -func Test_getID(t *testing.T) { - mids := &messageIds{index: make(map[uint16]Token)} - - i1 := mids.getID(&DummyToken{}) - - if i1 != 1 { - t.Fatalf("i1 was wrong: %v", i1) - } - - i2 := mids.getID(&DummyToken{}) - - if i2 != 2 { - t.Fatalf("i2 was wrong: %v", i2) - } - - for i := uint16(3); i < 100; i++ { - id := mids.getID(&DummyToken{}) - if id != i { - t.Fatalf("id was wrong expected %v got %v", i, id) - } - } -} - -func Test_freeID(t *testing.T) { - mids := &messageIds{index: make(map[uint16]Token)} - - i1 := mids.getID(&DummyToken{}) - mids.freeID(i1) - - if i1 != 1 { - t.Fatalf("i1 was wrong: %v", i1) - } - - i2 := mids.getID(&DummyToken{}) - fmt.Printf("i2: %v\n", i2) -} - -func Test_messageids_mix(t *testing.T) { - mids := &messageIds{index: make(map[uint16]Token)} - - done := make(chan bool) - a := make(chan uint16, 3) - b := make(chan uint16, 20) - c := make(chan uint16, 100) - - go func() { - for i := 0; i < 10000; i++ { - a <- mids.getID(&DummyToken{}) - mids.freeID(<-b) - } - done <- true - }() - - go func() { - for i := 0; i < 10000; i++ { - b <- mids.getID(&DummyToken{}) - mids.freeID(<-c) - } - done <- true - }() - - go func() { - for i := 0; i < 10000; i++ { - c <- mids.getID(&DummyToken{}) - mids.freeID(<-a) - } - done <- true - }() - - <-done - <-done - <-done -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go deleted file mode 100644 index be6ad8b4..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_options_test.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "crypto/tls" - "crypto/x509" - "testing" - "time" -) - -func Test_NewClientOptions_default(t *testing.T) { - o := NewClientOptions() - - if o.ClientID != "" { - t.Fatalf("bad default client id") - } - - if o.Username != "" { - t.Fatalf("bad default username") - } - - if o.Password != "" { - t.Fatalf("bad default password") - } - - if o.KeepAlive != 30*time.Second { - t.Fatalf("bad default timeout") - } -} - -func Test_NewClientOptions_mix(t *testing.T) { - o := NewClientOptions() - o.AddBroker("tcp://192.168.1.2:9999") - o.SetClientID("myclientid") - o.SetUsername("myuser") - o.SetPassword("mypassword") - o.SetKeepAlive(88 * time.Second) - - if o.Servers[0].Scheme != "tcp" { - t.Fatalf("bad scheme") - } - - if o.Servers[0].Host != "192.168.1.2:9999" { - t.Fatalf("bad host") - } - - if o.ClientID != "myclientid" { - t.Fatalf("bad set clientid") - } - - if o.Username != "myuser" { - t.Fatalf("bad set username") - } - - if o.Password != "mypassword" { - t.Fatalf("bad set password") - } - - if o.KeepAlive != 88000000000 { - t.Fatalf("bad set timeout: %d", o.KeepAlive) - } -} - -func Test_ModifyOptions(t *testing.T) { - o := NewClientOptions() - o.AddBroker("tcp://3.3.3.3:12345") - c := NewClient(o).(*client) - o.AddBroker("ws://2.2.2.2:9999") - o.SetOrderMatters(false) - - if c.options.Servers[0].Scheme != "tcp" { - t.Fatalf("client options.server.Scheme was modified") - } - - // if c.options.server.Host != "2.2.2.2:9999" { - // t.Fatalf("client options.server.Host was modified") - // } - - if o.Order != false { - t.Fatalf("options.order was not modified") - } -} - -func Test_TLSConfig(t *testing.T) { - o := NewClientOptions().SetTLSConfig(&tls.Config{ - RootCAs: x509.NewCertPool(), - ClientAuth: tls.NoClientCert, - ClientCAs: x509.NewCertPool(), - InsecureSkipVerify: true}) - - c := NewClient(o).(*client) - - if c.options.TLSConfig.ClientAuth != tls.NoClientCert { - t.Fatalf("client options.tlsConfig ClientAuth incorrect") - } - - if c.options.TLSConfig.InsecureSkipVerify != true { - t.Fatalf("client options.tlsConfig InsecureSkipVerify incorrect") - } -} - -func Test_OnConnectionLost(t *testing.T) { - onconnlost := func(client Client, err error) { - panic(err) - } - o := NewClientOptions().SetConnectionLostHandler(onconnlost) - - c := NewClient(o).(*client) - - if c.options.OnConnectionLost == nil { - t.Fatalf("client options.onconnlost was nil") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go deleted file mode 100644 index 70f9b664..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_ping_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "bytes" - "testing" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -func Test_NewPingReqMessage(t *testing.T) { - pr := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) - if pr.MessageType != packets.Pingreq { - t.Errorf("NewPingReqMessage bad msg type: %v", pr.MessageType) - } - if pr.RemainingLength != 0 { - t.Errorf("NewPingReqMessage bad remlen, expected 0, got %d", pr.RemainingLength) - } - - exp := []byte{ - 0xC0, - 0x00, - } - - var buf bytes.Buffer - pr.Write(&buf) - bs := buf.Bytes() - - if len(bs) != 2 { - t.Errorf("NewPingReqMessage.Bytes() wrong length: %d", len(bs)) - } - - if exp[0] != bs[0] || exp[1] != bs[1] { - t.Errorf("NewPingMessage.Bytes() wrong") - } -} - -func Test_DecodeMessage_pingresp(t *testing.T) { - bs := bytes.NewBuffer([]byte{ - 0xD0, - 0x00, - }) - presp, _ := packets.ReadPacket(bs) - if presp.(*packets.PingrespPacket).MessageType != packets.Pingresp { - t.Errorf("DecodeMessage ping response wrong msg type: %v", presp.(*packets.PingrespPacket).MessageType) - } - if presp.(*packets.PingrespPacket).RemainingLength != 0 { - t.Errorf("DecodeMessage ping response wrong rem len: %d", presp.(*packets.PingrespPacket).RemainingLength) - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go deleted file mode 100644 index b8f55c89..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_router_test.go +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "testing" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -func Test_newRouter(t *testing.T) { - router, stop := newRouter() - if router == nil { - t.Fatalf("router is nil") - } - if stop == nil { - t.Fatalf("stop is nil") - } - if router.routes.Len() != 0 { - t.Fatalf("router.routes was not empty") - } -} - -func Test_AddRoute(t *testing.T) { - router, _ := newRouter() - calledback := false - cb := func(client Client, msg Message) { - calledback = true - } - router.addRoute("/alpha", cb) - - if router.routes.Len() != 1 { - t.Fatalf("router.routes was wrong") - } -} - -func Test_Match(t *testing.T) { - router, _ := newRouter() - router.addRoute("/alpha", nil) - - if !router.routes.Front().Value.(*route).match("/alpha") { - t.Fatalf("match function is bad") - } - - if router.routes.Front().Value.(*route).match("alpha") { - t.Fatalf("match function is bad") - } -} - -func Test_match(t *testing.T) { - - check := func(route, topic string, exp bool) { - result := routeIncludesTopic(route, topic) - if exp != result { - t.Errorf("match was bad R: %v, T: %v, EXP: %v", route, topic, exp) - } - } - - // ** Basic ** - R := "" - T := "" - check(R, T, true) - - R = "x" - T = "" - check(R, T, false) - - R = "" - T = "x" - check(R, T, false) - - R = "x" - T = "x" - check(R, T, true) - - R = "x" - T = "X" - check(R, T, false) - - R = "alpha" - T = "alpha" - check(R, T, true) - - R = "alpha" - T = "beta" - check(R, T, false) - - // ** / ** - R = "/" - T = "/" - check(R, T, true) - - R = "/one" - T = "/one" - check(R, T, true) - - R = "/" - T = "/two" - check(R, T, false) - - R = "/two" - T = "/" - check(R, T, false) - - R = "/two" - T = "two" - check(R, T, false) // a leading "/" creates a different topic - - R = "/a/" - T = "/a" - check(R, T, false) - - R = "/a/" - T = "/a/b" - check(R, T, false) - - R = "/a/b" - T = "/a/b" - check(R, T, true) - - R = "/a/b/" - T = "/a/b" - check(R, T, false) - - R = "/a/b" - T = "/R/b" - check(R, T, false) - - // ** + ** - R = "/a/+/c" - T = "/a/b/c" - check(R, T, true) - - R = "/+/b/c" - T = "/a/b/c" - check(R, T, true) - - R = "/a/b/+" - T = "/a/b/c" - check(R, T, true) - - R = "/a/+/+" - T = "/a/b/c" - check(R, T, true) - - R = "/+/+/+" - T = "/a/b/c" - check(R, T, true) - - R = "/+/+/c" - T = "/a/b/c" - check(R, T, true) - - R = "/a/b/c/+" // different number of levels - T = "/a/b/c" - check(R, T, false) - - R = "+" - T = "a" - check(R, T, true) - - R = "/+" - T = "a" - check(R, T, false) - - R = "+/+" - T = "/a" - check(R, T, true) - - R = "+/+" - T = "a" - check(R, T, false) - - // ** # ** - R = "#" - T = "/a/b/c" - check(R, T, true) - - R = "/#" - T = "/a/b/c" - check(R, T, true) - - // R = "/#/" // not valid - // T = "/a/b/c" - // check(R, T, true) - - R = "/#" - T = "/a/b/c" - check(R, T, true) - - R = "/a/#" - T = "/a/b/c" - check(R, T, true) - - R = "/a/#" - T = "/a/b/c" - check(R, T, true) - - R = "/a/b/#" - T = "/a/b/c" - check(R, T, true) - - // ** unicode ** - R = "☃" - T = "☃" - check(R, T, true) - - R = "✈" - T = "☃" - check(R, T, false) - - R = "/☃/✈" - T = "/☃/ッ" - check(R, T, false) - - R = "#" - T = "/☃/ッ" - check(R, T, true) - - R = "/☃/+" - T = "/☃/ッ/♫/ø/☹☹☹" - check(R, T, false) - - R = "/☃/#" - T = "/☃/ッ/♫/ø/☹☹☹" - check(R, T, true) - - R = "/☃/ッ/♫/ø/+" - T = "/☃/ッ/♫/ø/☹☹☹" - check(R, T, true) - - R = "/☃/ッ/+/ø/☹☹☹" - T = "/☃/ッ/♫/ø/☹☹☹" - check(R, T, true) - - R = "/+/a/ッ/+/ø/☹☹☹" - T = "/b/♫/ッ/♫/ø/☹☹☹" - check(R, T, false) - - R = "/+/♫/ッ/+/ø/☹☹☹" - T = "/b/♫/ッ/♫/ø/☹☹☹" - check(R, T, true) -} - -func Test_MatchAndDispatch(t *testing.T) { - calledback := make(chan bool) - - cb := func(c Client, m Message) { - calledback <- true - } - - pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pub.Qos = 2 - pub.TopicName = "a" - pub.Payload = []byte("foo") - - msgs := make(chan *packets.PublishPacket) - - router, stopper := newRouter() - router.addRoute("a", cb) - - router.matchAndDispatch(msgs, true, nil) - - msgs <- pub - - <-calledback - - stopper <- true - - select { - case msgs <- pub: - t.Errorf("msgs should not have a listener") - default: - } - -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go deleted file mode 100644 index d8af064d..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_store_test.go +++ /dev/null @@ -1,579 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "fmt" - "io/ioutil" - "testing" - - "github.com/eclipse/paho.mqtt.golang/packets" -) - -func Test_fullpath(t *testing.T) { - p := fullpath("/tmp/store", "o.44324") - e := "/tmp/store/o.44324.msg" - if p != e { - t.Fatalf("full path expected %s, got %s", e, p) - } -} - -func Test_exists(t *testing.T) { - b := exists("/") - if !b { - t.Errorf("/proc/cpuinfo was not found") - } -} - -func Test_exists_no(t *testing.T) { - b := exists("/this/path/is/not/real/i/hope") - if b { - t.Errorf("you have some strange files") - } -} - -func isemptydir(dir string) bool { - if !exists(dir) { - panic(fmt.Errorf("Directory %s does not exist", dir)) - } - files, err := ioutil.ReadDir(dir) - chkerr(err) - return len(files) == 0 -} - -func Test_mIDFromKey(t *testing.T) { - key := "i.123" - exp := uint16(123) - res := mIDFromKey(key) - if exp != res { - t.Fatalf("mIDFromKey failed") - } -} - -func Test_inboundKeyFromMID(t *testing.T) { - id := uint16(9876) - exp := "i.9876" - res := inboundKeyFromMID(id) - if exp != res { - t.Fatalf("inboundKeyFromMID failed") - } -} - -func Test_outboundKeyFromMID(t *testing.T) { - id := uint16(7654) - exp := "o.7654" - res := outboundKeyFromMID(id) - if exp != res { - t.Fatalf("outboundKeyFromMID failed") - } -} - -/************************ - **** persistOutbound **** - ************************/ - -func Test_persistOutbound_connect(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket) - m.Qos = 0 - m.Username = "user" - m.Password = []byte("pass") - m.ClientIdentifier = "cid" - //m := newConnectMsg(false, false, QOS_ZERO, false, "", nil, "cid", "user", "pass", 10) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_publish_0(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 0 - m.TopicName = "/popub0" - m.Payload = []byte{0xBB, 0x00} - m.MessageID = 40 - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_publish_1(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 1 - m.TopicName = "/popub1" - m.Payload = []byte{0xBB, 0x00} - m.MessageID = 41 - persistOutbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 41 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_publish_2(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 2 - m.TopicName = "/popub2" - m.Payload = []byte{0xBB, 0x00} - m.MessageID = 42 - persistOutbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 42 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_puback(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 1 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_pubrec(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_pubrel(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) - m.MessageID = 43 - - persistOutbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 43 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_pubcomp(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 1 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_subscribe(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Subscribe).(*packets.SubscribePacket) - m.Topics = []string{"/posub"} - m.Qoss = []byte{1} - m.MessageID = 44 - persistOutbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 44 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_unsubscribe(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket) - m.Topics = []string{"/posub"} - m.MessageID = 45 - persistOutbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 45 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_pingreq(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Pingreq) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -func Test_persistOutbound_disconnect(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Disconnect) - persistOutbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistOutbound put message it should not have") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistOutbound get message it should not have") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistOutbound del message it should not have") - } -} - -/************************ - **** persistInbound **** - ************************/ - -func Test_persistInbound_connack(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Connack) - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_publish_0(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 0 - m.TopicName = "/pipub0" - m.Payload = []byte{0xCC, 0x01} - m.MessageID = 50 - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_publish_1(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 1 - m.TopicName = "/pipub1" - m.Payload = []byte{0xCC, 0x02} - m.MessageID = 51 - persistInbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 51 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_publish_2(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - m.Qos = 2 - m.TopicName = "/pipub2" - m.Payload = []byte{0xCC, 0x03} - m.MessageID = 52 - persistInbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 52 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_puback(t *testing.T) { - ts := &TestStore{} - pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pub.Qos = 1 - pub.TopicName = "/pub1" - pub.Payload = []byte{0xCC, 0x04} - pub.MessageID = 53 - publishKey := inboundKeyFromMID(pub.MessageID) - ts.Put(publishKey, pub) - - m := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) - m.MessageID = 53 - - persistInbound(ts, m) // "deletes" packets.Publish from store - - if len(ts.mput) != 1 { // not actually deleted in TestStore - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 1 || ts.mdel[0] != 53 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_pubrec(t *testing.T) { - ts := &TestStore{} - pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pub.Qos = 2 - pub.TopicName = "/pub2" - pub.Payload = []byte{0xCC, 0x05} - pub.MessageID = 54 - publishKey := inboundKeyFromMID(pub.MessageID) - ts.Put(publishKey, pub) - - m := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) - m.MessageID = 54 - - persistInbound(ts, m) - - if len(ts.mput) != 1 || ts.mput[0] != 54 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_pubrel(t *testing.T) { - ts := &TestStore{} - pub := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket) - pub.Qos = 2 - pub.TopicName = "/pub2" - pub.Payload = []byte{0xCC, 0x06} - pub.MessageID = 55 - publishKey := inboundKeyFromMID(pub.MessageID) - ts.Put(publishKey, pub) - - m := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) - m.MessageID = 55 - - persistInbound(ts, m) // will overwrite publish - - if len(ts.mput) != 2 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_pubcomp(t *testing.T) { - ts := &TestStore{} - - m := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) - m.MessageID = 56 - - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 1 || ts.mdel[0] != 56 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_suback(t *testing.T) { - ts := &TestStore{} - - m := packets.NewControlPacket(packets.Suback).(*packets.SubackPacket) - m.MessageID = 57 - - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 1 || ts.mdel[0] != 57 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_unsuback(t *testing.T) { - ts := &TestStore{} - - m := packets.NewControlPacket(packets.Unsuback).(*packets.UnsubackPacket) - m.MessageID = 58 - - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 1 || ts.mdel[0] != 58 { - t.Fatalf("persistInbound in bad state") - } -} - -func Test_persistInbound_pingresp(t *testing.T) { - ts := &TestStore{} - m := packets.NewControlPacket(packets.Pingresp) - - persistInbound(ts, m) - - if len(ts.mput) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mget) != 0 { - t.Fatalf("persistInbound in bad state") - } - - if len(ts.mdel) != 0 { - t.Fatalf("persistInbound in bad state") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go b/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go deleted file mode 100644 index da2b240e..00000000 --- a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/unit_topic_test.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "testing" -) - -func Test_ValidateTopicAndQos_qos3(t *testing.T) { - e := validateTopicAndQos("a", 3) - if e != ErrInvalidQos { - t.Fatalf("invalid error for invalid qos") - } -} - -func Test_ValidateTopicAndQos_ES(t *testing.T) { - e := validateTopicAndQos("", 0) - if e != ErrInvalidTopicEmptyString { - t.Fatalf("invalid error for empty topic name") - } -} - -func Test_ValidateTopicAndQos_a_0(t *testing.T) { - e := validateTopicAndQos("a", 0) - if e != nil { - t.Fatalf("error from valid NewTopicFilter") - } -} - -func Test_ValidateTopicAndQos_H(t *testing.T) { - e := validateTopicAndQos("a/#/c", 0) - if e != ErrInvalidTopicMultilevel { - t.Fatalf("invalid error for bad multilevel topic filter") - } -} diff --git a/src/github.com/bcmi-labs/arduino-connector/status.go b/status.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/status.go rename to status.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE b/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/LICENSE rename to vendor/github.com/eclipse/paho.mqtt.golang/LICENSE diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go b/vendor/github.com/eclipse/paho.mqtt.golang/client.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/client.go rename to vendor/github.com/eclipse/paho.mqtt.golang/client.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go b/vendor/github.com/eclipse/paho.mqtt.golang/components.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/components.go rename to vendor/github.com/eclipse/paho.mqtt.golang/components.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go b/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go rename to vendor/github.com/eclipse/paho.mqtt.golang/filestore.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go b/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go rename to vendor/github.com/eclipse/paho.mqtt.golang/memstore.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go b/vendor/github.com/eclipse/paho.mqtt.golang/message.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/message.go rename to vendor/github.com/eclipse/paho.mqtt.golang/message.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go b/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go rename to vendor/github.com/eclipse/paho.mqtt.golang/messageids.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go b/vendor/github.com/eclipse/paho.mqtt.golang/net.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/net.go rename to vendor/github.com/eclipse/paho.mqtt.golang/net.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html b/vendor/github.com/eclipse/paho.mqtt.golang/notice.html similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/notice.html rename to vendor/github.com/eclipse/paho.mqtt.golang/notice.html diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go b/vendor/github.com/eclipse/paho.mqtt.golang/oops.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/oops.go rename to vendor/github.com/eclipse/paho.mqtt.golang/oops.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go b/vendor/github.com/eclipse/paho.mqtt.golang/options.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options.go rename to vendor/github.com/eclipse/paho.mqtt.golang/options.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go b/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go rename to vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go rename to vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go b/vendor/github.com/eclipse/paho.mqtt.golang/ping.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/ping.go rename to vendor/github.com/eclipse/paho.mqtt.golang/ping.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go b/vendor/github.com/eclipse/paho.mqtt.golang/router.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/router.go rename to vendor/github.com/eclipse/paho.mqtt.golang/router.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go b/vendor/github.com/eclipse/paho.mqtt.golang/store.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/store.go rename to vendor/github.com/eclipse/paho.mqtt.golang/store.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go b/vendor/github.com/eclipse/paho.mqtt.golang/token.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/token.go rename to vendor/github.com/eclipse/paho.mqtt.golang/token.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go b/vendor/github.com/eclipse/paho.mqtt.golang/topic.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/topic.go rename to vendor/github.com/eclipse/paho.mqtt.golang/topic.go diff --git a/src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go b/vendor/github.com/eclipse/paho.mqtt.golang/trace.go similarity index 100% rename from src/github.com/bcmi-labs/arduino-connector/vendor/github.com/eclipse/paho.mqtt.golang/trace.go rename to vendor/github.com/eclipse/paho.mqtt.golang/trace.go diff --git a/vendor/github.com/kardianos/osext/LICENSE b/vendor/github.com/kardianos/osext/LICENSE new file mode 100644 index 00000000..74487567 --- /dev/null +++ b/vendor/github.com/kardianos/osext/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/kardianos/osext/osext.go b/vendor/github.com/kardianos/osext/osext.go new file mode 100644 index 00000000..17f380f0 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext.go @@ -0,0 +1,33 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Extensions to the standard "os" package. +package osext // import "github.com/kardianos/osext" + +import "path/filepath" + +var cx, ce = executableClean() + +func executableClean() (string, error) { + p, err := executable() + return filepath.Clean(p), err +} + +// Executable returns an absolute path that can be used to +// re-invoke the current program. +// It may not be valid after the current program exits. +func Executable() (string, error) { + return cx, ce +} + +// Returns same path as Executable, returns just the folder +// path. Excludes the executable name and any trailing slash. +func ExecutableFolder() (string, error) { + p, err := Executable() + if err != nil { + return "", err + } + + return filepath.Dir(p), nil +} diff --git a/vendor/github.com/kardianos/osext/osext_go18.go b/vendor/github.com/kardianos/osext/osext_go18.go new file mode 100644 index 00000000..009d8a92 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext_go18.go @@ -0,0 +1,9 @@ +//+build go1.8,!openbsd + +package osext + +import "os" + +func executable() (string, error) { + return os.Executable() +} diff --git a/vendor/github.com/kardianos/osext/osext_plan9.go b/vendor/github.com/kardianos/osext/osext_plan9.go new file mode 100644 index 00000000..95e23713 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext_plan9.go @@ -0,0 +1,22 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//+build !go1.8 + +package osext + +import ( + "os" + "strconv" + "syscall" +) + +func executable() (string, error) { + f, err := os.Open("/proc/" + strconv.Itoa(os.Getpid()) + "/text") + if err != nil { + return "", err + } + defer f.Close() + return syscall.Fd2path(int(f.Fd())) +} diff --git a/vendor/github.com/kardianos/osext/osext_procfs.go b/vendor/github.com/kardianos/osext/osext_procfs.go new file mode 100644 index 00000000..e1f16f88 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext_procfs.go @@ -0,0 +1,36 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.8,android !go1.8,linux !go1.8,netbsd !go1.8,solaris !go1.8,dragonfly + +package osext + +import ( + "errors" + "fmt" + "os" + "runtime" + "strings" +) + +func executable() (string, error) { + switch runtime.GOOS { + case "linux", "android": + const deletedTag = " (deleted)" + execpath, err := os.Readlink("/proc/self/exe") + if err != nil { + return execpath, err + } + execpath = strings.TrimSuffix(execpath, deletedTag) + execpath = strings.TrimPrefix(execpath, deletedTag) + return execpath, nil + case "netbsd": + return os.Readlink("/proc/curproc/exe") + case "dragonfly": + return os.Readlink("/proc/curproc/file") + case "solaris": + return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid())) + } + return "", errors.New("ExecPath not implemented for " + runtime.GOOS) +} diff --git a/vendor/github.com/kardianos/osext/osext_sysctl.go b/vendor/github.com/kardianos/osext/osext_sysctl.go new file mode 100644 index 00000000..33cee252 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext_sysctl.go @@ -0,0 +1,126 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.8,darwin !go1.8,freebsd openbsd + +package osext + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "syscall" + "unsafe" +) + +var initCwd, initCwdErr = os.Getwd() + +func executable() (string, error) { + var mib [4]int32 + switch runtime.GOOS { + case "freebsd": + mib = [4]int32{1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1} + case "darwin": + mib = [4]int32{1 /* CTL_KERN */, 38 /* KERN_PROCARGS */, int32(os.Getpid()), -1} + case "openbsd": + mib = [4]int32{1 /* CTL_KERN */, 55 /* KERN_PROC_ARGS */, int32(os.Getpid()), 1 /* KERN_PROC_ARGV */} + } + + n := uintptr(0) + // Get length. + _, _, errNum := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, 0, uintptr(unsafe.Pointer(&n)), 0, 0) + if errNum != 0 { + return "", errNum + } + if n == 0 { // This shouldn't happen. + return "", nil + } + buf := make([]byte, n) + _, _, errNum = syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(unsafe.Pointer(&mib[0])), 4, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&n)), 0, 0) + if errNum != 0 { + return "", errNum + } + if n == 0 { // This shouldn't happen. + return "", nil + } + + var execPath string + switch runtime.GOOS { + case "openbsd": + // buf now contains **argv, with pointers to each of the C-style + // NULL terminated arguments. + var args []string + argv := uintptr(unsafe.Pointer(&buf[0])) + Loop: + for { + argp := *(**[1 << 20]byte)(unsafe.Pointer(argv)) + if argp == nil { + break + } + for i := 0; uintptr(i) < n; i++ { + // we don't want the full arguments list + if string(argp[i]) == " " { + break Loop + } + if argp[i] != 0 { + continue + } + args = append(args, string(argp[:i])) + n -= uintptr(i) + break + } + if n < unsafe.Sizeof(argv) { + break + } + argv += unsafe.Sizeof(argv) + n -= unsafe.Sizeof(argv) + } + execPath = args[0] + // There is no canonical way to get an executable path on + // OpenBSD, so check PATH in case we are called directly + if execPath[0] != '/' && execPath[0] != '.' { + execIsInPath, err := exec.LookPath(execPath) + if err == nil { + execPath = execIsInPath + } + } + default: + for i, v := range buf { + if v == 0 { + buf = buf[:i] + break + } + } + execPath = string(buf) + } + + var err error + // execPath will not be empty due to above checks. + // Try to get the absolute path if the execPath is not rooted. + if execPath[0] != '/' { + execPath, err = getAbs(execPath) + if err != nil { + return execPath, err + } + } + // For darwin KERN_PROCARGS may return the path to a symlink rather than the + // actual executable. + if runtime.GOOS == "darwin" { + if execPath, err = filepath.EvalSymlinks(execPath); err != nil { + return execPath, err + } + } + return execPath, nil +} + +func getAbs(execPath string) (string, error) { + if initCwdErr != nil { + return execPath, initCwdErr + } + // The execPath may begin with a "../" or a "./" so clean it first. + // Join the two paths, trailing and starting slashes undetermined, so use + // the generic Join function. + return filepath.Join(initCwd, filepath.Clean(execPath)), nil +} diff --git a/vendor/github.com/kardianos/osext/osext_windows.go b/vendor/github.com/kardianos/osext/osext_windows.go new file mode 100644 index 00000000..074b3b38 --- /dev/null +++ b/vendor/github.com/kardianos/osext/osext_windows.go @@ -0,0 +1,36 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//+build !go1.8 + +package osext + +import ( + "syscall" + "unicode/utf16" + "unsafe" +) + +var ( + kernel = syscall.MustLoadDLL("kernel32.dll") + getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW") +) + +// GetModuleFileName() with hModule = NULL +func executable() (exePath string, err error) { + return getModuleFileName() +} + +func getModuleFileName() (string, error) { + var n uint32 + b := make([]uint16, syscall.MAX_PATH) + size := uint32(len(b)) + + r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size)) + n = uint32(r0) + if n == 0 { + return "", e1 + } + return string(utf16.Decode(b[0:n])), nil +} diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 00000000..835ba3e7 --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 00000000..842ee804 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,269 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// and the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required the errors.WithStack and errors.WithMessage +// functions destructure errors.Wrap into its component operations of annotating +// an error with a stack trace and an a message, respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// causer interface is not exported by this package, but is considered a part +// of stable public API. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported +// +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface. +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// Where errors.StackTrace is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d", f) +// } +// } +// +// stackTracer interface is not exported by this package, but is considered a part +// of stable public API. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 00000000..6b1f2891 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,178 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strings" +) + +// Frame represents a program counter inside a stack frame. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + pc := f.pc() + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, _ := fn.FileLine(pc) + fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) + } + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + fmt.Fprintf(s, "%d", f.line()) + case 'n': + name := runtime.FuncForPC(f.pc()).Name() + io.WriteString(s, funcname(name)) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + fmt.Fprintf(s, "\n%+v", f) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + fmt.Fprintf(s, "%v", []Frame(st)) + } + case 's': + fmt.Fprintf(s, "%s", []Frame(st)) + } +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} + +func trimGOPATH(name, file string) string { + // Here we want to get the source file path relative to the compile time + // GOPATH. As of Go 1.6.x there is no direct way to know the compiled + // GOPATH at runtime, but we can infer the number of path segments in the + // GOPATH. We note that fn.Name() returns the function name qualified by + // the import path, which does not include the GOPATH. Thus we can trim + // segments from the beginning of the file path until the number of path + // separators remaining is one more than the number of path separators in + // the function name. For example, given: + // + // GOPATH /home/user + // file /home/user/src/pkg/sub/file.go + // fn.Name() pkg/sub.Type.Method + // + // We want to produce: + // + // pkg/sub/file.go + // + // From this we can easily see that fn.Name() has one less path separator + // than our desired output. We count separators from the end of the file + // path until it finds two more than in the function name and then move + // one character forward to preserve the initial path segment without a + // leading separator. + const sep = "/" + goal := strings.Count(name, sep) + 2 + i := len(file) + for n := 0; n < goal; n++ { + i = strings.LastIndex(file[:i], sep) + if i == -1 { + // not enough separators found, set i so that the slice expression + // below leaves file unmodified + i = -len(sep) + break + } + } + // get back to 0 or trim the leading separator + file = file[i+len(sep):] + return file +} diff --git a/vendor/github.com/satori/go.uuid/LICENSE b/vendor/github.com/satori/go.uuid/LICENSE new file mode 100644 index 00000000..488357b8 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/LICENSE @@ -0,0 +1,20 @@ +Copyright (C) 2013-2016 by Maxim Bublis + +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/github.com/satori/go.uuid/uuid.go b/vendor/github.com/satori/go.uuid/uuid.go new file mode 100644 index 00000000..9c7fbaa5 --- /dev/null +++ b/vendor/github.com/satori/go.uuid/uuid.go @@ -0,0 +1,488 @@ +// Copyright (C) 2013-2015 by Maxim Bublis +// +// 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. + +// Package uuid provides implementation of Universally Unique Identifier (UUID). +// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and +// version 2 (as specified in DCE 1.1). +package uuid + +import ( + "bytes" + "crypto/md5" + "crypto/rand" + "crypto/sha1" + "database/sql/driver" + "encoding/binary" + "encoding/hex" + "fmt" + "hash" + "net" + "os" + "sync" + "time" +) + +// UUID layout variants. +const ( + VariantNCS = iota + VariantRFC4122 + VariantMicrosoft + VariantFuture +) + +// UUID DCE domains. +const ( + DomainPerson = iota + DomainGroup + DomainOrg +) + +// Difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970). +const epochStart = 122192928000000000 + +// Used in string method conversion +const dash byte = '-' + +// UUID v1/v2 storage. +var ( + storageMutex sync.Mutex + storageOnce sync.Once + epochFunc = unixTimeFunc + clockSequence uint16 + lastTime uint64 + hardwareAddr [6]byte + posixUID = uint32(os.Getuid()) + posixGID = uint32(os.Getgid()) +) + +// String parse helpers. +var ( + urnPrefix = []byte("urn:uuid:") + byteGroups = []int{8, 4, 4, 4, 12} +) + +func initClockSequence() { + buf := make([]byte, 2) + safeRandom(buf) + clockSequence = binary.BigEndian.Uint16(buf) +} + +func initHardwareAddr() { + interfaces, err := net.Interfaces() + if err == nil { + for _, iface := range interfaces { + if len(iface.HardwareAddr) >= 6 { + copy(hardwareAddr[:], iface.HardwareAddr) + return + } + } + } + + // Initialize hardwareAddr randomly in case + // of real network interfaces absence + safeRandom(hardwareAddr[:]) + + // Set multicast bit as recommended in RFC 4122 + hardwareAddr[0] |= 0x01 +} + +func initStorage() { + initClockSequence() + initHardwareAddr() +} + +func safeRandom(dest []byte) { + if _, err := rand.Read(dest); err != nil { + panic(err) + } +} + +// Returns difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and current time. +// This is default epoch calculation function. +func unixTimeFunc() uint64 { + return epochStart + uint64(time.Now().UnixNano()/100) +} + +// UUID representation compliant with specification +// described in RFC 4122. +type UUID [16]byte + +// NullUUID can be used with the standard sql package to represent a +// UUID value that can be NULL in the database +type NullUUID struct { + UUID UUID + Valid bool +} + +// The nil UUID is special form of UUID that is specified to have all +// 128 bits set to zero. +var Nil = UUID{} + +// Predefined namespace UUIDs. +var ( + NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") + NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8") + NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8") + NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8") +) + +// And returns result of binary AND of two UUIDs. +func And(u1 UUID, u2 UUID) UUID { + u := UUID{} + for i := 0; i < 16; i++ { + u[i] = u1[i] & u2[i] + } + return u +} + +// Or returns result of binary OR of two UUIDs. +func Or(u1 UUID, u2 UUID) UUID { + u := UUID{} + for i := 0; i < 16; i++ { + u[i] = u1[i] | u2[i] + } + return u +} + +// Equal returns true if u1 and u2 equals, otherwise returns false. +func Equal(u1 UUID, u2 UUID) bool { + return bytes.Equal(u1[:], u2[:]) +} + +// Version returns algorithm version used to generate UUID. +func (u UUID) Version() uint { + return uint(u[6] >> 4) +} + +// Variant returns UUID layout variant. +func (u UUID) Variant() uint { + switch { + case (u[8] & 0x80) == 0x00: + return VariantNCS + case (u[8]&0xc0)|0x80 == 0x80: + return VariantRFC4122 + case (u[8]&0xe0)|0xc0 == 0xc0: + return VariantMicrosoft + } + return VariantFuture +} + +// Bytes returns bytes slice representation of UUID. +func (u UUID) Bytes() []byte { + return u[:] +} + +// Returns canonical string representation of UUID: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. +func (u UUID) String() string { + buf := make([]byte, 36) + + hex.Encode(buf[0:8], u[0:4]) + buf[8] = dash + hex.Encode(buf[9:13], u[4:6]) + buf[13] = dash + hex.Encode(buf[14:18], u[6:8]) + buf[18] = dash + hex.Encode(buf[19:23], u[8:10]) + buf[23] = dash + hex.Encode(buf[24:], u[10:]) + + return string(buf) +} + +// SetVersion sets version bits. +func (u *UUID) SetVersion(v byte) { + u[6] = (u[6] & 0x0f) | (v << 4) +} + +// SetVariant sets variant bits as described in RFC 4122. +func (u *UUID) SetVariant() { + u[8] = (u[8] & 0xbf) | 0x80 +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The encoding is the same as returned by String. +func (u UUID) MarshalText() (text []byte, err error) { + text = []byte(u.String()) + return +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// Following formats are supported: +// "6ba7b810-9dad-11d1-80b4-00c04fd430c8", +// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", +// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" +func (u *UUID) UnmarshalText(text []byte) (err error) { + if len(text) < 32 { + err = fmt.Errorf("uuid: UUID string too short: %s", text) + return + } + + t := text[:] + braced := false + + if bytes.Equal(t[:9], urnPrefix) { + t = t[9:] + } else if t[0] == '{' { + braced = true + t = t[1:] + } + + b := u[:] + + for i, byteGroup := range byteGroups { + if i > 0 && t[0] == '-' { + t = t[1:] + } else if i > 0 && t[0] != '-' { + err = fmt.Errorf("uuid: invalid string format") + return + } + + if i == 2 { + if !bytes.Contains([]byte("012345"), []byte{t[0]}) { + err = fmt.Errorf("uuid: invalid version number: %s", t[0]) + return + } + } + + if len(t) < byteGroup { + err = fmt.Errorf("uuid: UUID string too short: %s", text) + return + } + + if i == 4 && len(t) > byteGroup && + ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) { + err = fmt.Errorf("uuid: UUID string too long: %s", t) + return + } + + _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup]) + + if err != nil { + return + } + + t = t[byteGroup:] + b = b[byteGroup/2:] + } + + return +} + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (u UUID) MarshalBinary() (data []byte, err error) { + data = u.Bytes() + return +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// It will return error if the slice isn't 16 bytes long. +func (u *UUID) UnmarshalBinary(data []byte) (err error) { + if len(data) != 16 { + err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data)) + return + } + copy(u[:], data) + + return +} + +// Value implements the driver.Valuer interface. +func (u UUID) Value() (driver.Value, error) { + return u.String(), nil +} + +// Scan implements the sql.Scanner interface. +// A 16-byte slice is handled by UnmarshalBinary, while +// a longer byte slice or a string is handled by UnmarshalText. +func (u *UUID) Scan(src interface{}) error { + switch src := src.(type) { + case []byte: + if len(src) == 16 { + return u.UnmarshalBinary(src) + } + return u.UnmarshalText(src) + + case string: + return u.UnmarshalText([]byte(src)) + } + + return fmt.Errorf("uuid: cannot convert %T to UUID", src) +} + +// Value implements the driver.Valuer interface. +func (u NullUUID) Value() (driver.Value, error) { + if !u.Valid { + return nil, nil + } + // Delegate to UUID Value function + return u.UUID.Value() +} + +// Scan implements the sql.Scanner interface. +func (u *NullUUID) Scan(src interface{}) error { + if src == nil { + u.UUID, u.Valid = Nil, false + return nil + } + + // Delegate to UUID Scan function + u.Valid = true + return u.UUID.Scan(src) +} + +// FromBytes returns UUID converted from raw byte slice input. +// It will return error if the slice isn't 16 bytes long. +func FromBytes(input []byte) (u UUID, err error) { + err = u.UnmarshalBinary(input) + return +} + +// FromBytesOrNil returns UUID converted from raw byte slice input. +// Same behavior as FromBytes, but returns a Nil UUID on error. +func FromBytesOrNil(input []byte) UUID { + uuid, err := FromBytes(input) + if err != nil { + return Nil + } + return uuid +} + +// FromString returns UUID parsed from string input. +// Input is expected in a form accepted by UnmarshalText. +func FromString(input string) (u UUID, err error) { + err = u.UnmarshalText([]byte(input)) + return +} + +// FromStringOrNil returns UUID parsed from string input. +// Same behavior as FromString, but returns a Nil UUID on error. +func FromStringOrNil(input string) UUID { + uuid, err := FromString(input) + if err != nil { + return Nil + } + return uuid +} + +// Returns UUID v1/v2 storage state. +// Returns epoch timestamp, clock sequence, and hardware address. +func getStorage() (uint64, uint16, []byte) { + storageOnce.Do(initStorage) + + storageMutex.Lock() + defer storageMutex.Unlock() + + timeNow := epochFunc() + // Clock changed backwards since last UUID generation. + // Should increase clock sequence. + if timeNow <= lastTime { + clockSequence++ + } + lastTime = timeNow + + return timeNow, clockSequence, hardwareAddr[:] +} + +// NewV1 returns UUID based on current timestamp and MAC address. +func NewV1() UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := getStorage() + + binary.BigEndian.PutUint32(u[0:], uint32(timeNow)) + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + + copy(u[10:], hardwareAddr) + + u.SetVersion(1) + u.SetVariant() + + return u +} + +// NewV2 returns DCE Security UUID based on POSIX UID/GID. +func NewV2(domain byte) UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := getStorage() + + switch domain { + case DomainPerson: + binary.BigEndian.PutUint32(u[0:], posixUID) + case DomainGroup: + binary.BigEndian.PutUint32(u[0:], posixGID) + } + + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + u[9] = domain + + copy(u[10:], hardwareAddr) + + u.SetVersion(2) + u.SetVariant() + + return u +} + +// NewV3 returns UUID based on MD5 hash of namespace UUID and name. +func NewV3(ns UUID, name string) UUID { + u := newFromHash(md5.New(), ns, name) + u.SetVersion(3) + u.SetVariant() + + return u +} + +// NewV4 returns random generated UUID. +func NewV4() UUID { + u := UUID{} + safeRandom(u[:]) + u.SetVersion(4) + u.SetVariant() + + return u +} + +// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name. +func NewV5(ns UUID, name string) UUID { + u := newFromHash(sha1.New(), ns, name) + u.SetVersion(5) + u.SetVariant() + + return u +} + +// Returns UUID based on hashing of namespace UUID and name. +func newFromHash(h hash.Hash, ns UUID, name string) UUID { + u := UUID{} + h.Write(ns[:]) + h.Write([]byte(name)) + copy(u[:], h.Sum(nil)) + + return u +} diff --git a/vendor/github.com/vharitonsky/iniflags/LICENSE b/vendor/github.com/vharitonsky/iniflags/LICENSE new file mode 100644 index 00000000..1d12d162 --- /dev/null +++ b/vendor/github.com/vharitonsky/iniflags/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2014 vharitonsky, valyala. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/vendor/github.com/vharitonsky/iniflags/iniflags.go b/vendor/github.com/vharitonsky/iniflags/iniflags.go new file mode 100644 index 00000000..10a91353 --- /dev/null +++ b/vendor/github.com/vharitonsky/iniflags/iniflags.go @@ -0,0 +1,487 @@ +package iniflags + +import ( + "bufio" + "flag" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "os/signal" + "path" + "strings" + "syscall" + "time" +) + +var ( + allowUnknownFlags = flag.Bool("allowUnknownFlags", false, "Don't terminate the app if ini file contains unknown flags.") + config = flag.String("config", "", "Path to ini config for using in go flags. May be relative to the current executable path.") + configUpdateInterval = flag.Duration("configUpdateInterval", 0, "Update interval for re-reading config file set via -config flag. Zero disables config file re-reading.") + dumpflags = flag.Bool("dumpflags", false, "Dumps values for all flags defined in the app into stdout in ini-compatible syntax and terminates the app.") +) + +var ( + flagChangeCallbacks = make(map[string][]FlagChangeCallback) + importStack []string + parsed bool +) + +// Generation is flags' generation number. +// +// It is modified on each flags' modification +// via either -configUpdateInterval or SIGHUP. +var Generation int + +// Parse obtains flag values from config file set via -config. +// +// It obtains flag values from command line like flag.Parse(), then overrides +// them by values parsed from config file set via -config. +// +// Path to config file can also be set via SetConfigFile() before Parse() call. +func Parse() { + if parsed { + logger.Panicf("iniflags: duplicate call to iniflags.Parse() detected") + } + + parsed = true + flag.Parse() + _, ok := parseConfigFlags() + if !ok { + os.Exit(1) + } + + if *dumpflags { + dumpFlags() + os.Exit(0) + } + + for flagName := range flagChangeCallbacks { + verifyFlagChangeFlagName(flagName) + } + Generation++ + issueAllFlagChangeCallbacks() + + ch := make(chan os.Signal) + signal.Notify(ch, syscall.SIGHUP) + go sighupHandler(ch) + + go configUpdater() +} + +func configUpdater() { + if *configUpdateInterval != 0 { + for { + // Use time.Sleep() instead of time.Tick() for the sake of dynamic flag update. + time.Sleep(*configUpdateInterval) + updateConfig() + } + } +} + +func updateConfig() { + if oldFlagValues, ok := parseConfigFlags(); ok && len(oldFlagValues) > 0 { + modifiedFlags := make(map[string]string) + for k := range oldFlagValues { + modifiedFlags[k] = flag.Lookup(k).Value.String() + } + logger.Printf("iniflags: read updated config. Modified flags are: %v", modifiedFlags) + Generation++ + issueFlagChangeCallbacks(oldFlagValues) + } +} + +// FlagChangeCallback is called when the given flag is changed. +// +// The callback may be registered for any flag via OnFlagChange(). +type FlagChangeCallback func() + +// OnFlagChange registers the callback, which is called after the given flag +// value is initialized and/or changed. +// +// Flag values are initialized during iniflags.Parse() call. +// Flag value can be changed on config re-read after obtaining SIGHUP signal +// or if periodic config re-read is enabled with -configUpdateInterval flag. +// +// Note that flags set via command-line cannot be overriden via config file modifications. +func OnFlagChange(flagName string, callback FlagChangeCallback) { + if parsed { + verifyFlagChangeFlagName(flagName) + } + flagChangeCallbacks[flagName] = append(flagChangeCallbacks[flagName], callback) +} + +func verifyFlagChangeFlagName(flagName string) { + if flag.Lookup(flagName) == nil { + logger.Fatalf("iniflags: cannot register FlagChangeCallback for non-existing flag [%s]", flagName) + } +} + +func issueFlagChangeCallbacks(oldFlagValues map[string]string) { + for flagName := range oldFlagValues { + if fs, ok := flagChangeCallbacks[flagName]; ok { + for _, f := range fs { + f() + } + } + } +} + +func issueAllFlagChangeCallbacks() { + for _, fs := range flagChangeCallbacks { + for _, f := range fs { + f() + } + } +} + +func sighupHandler(ch <-chan os.Signal) { + for _ = range ch { + updateConfig() + } +} + +func parseConfigFlags() (oldFlagValues map[string]string, ok bool) { + configPath := *config + if !strings.HasPrefix(configPath, "./") { + if configPath, ok = combinePath(os.Args[0], *config); !ok { + return nil, false + } + } + if configPath == "" { + return nil, true + } + parsedArgs, ok := getArgsFromConfig(configPath) + if !ok { + return nil, false + } + missingFlags := getMissingFlags() + + ok = true + oldFlagValues = make(map[string]string) + for _, arg := range parsedArgs { + f := flag.Lookup(arg.Key) + if f == nil { + logger.Printf("iniflags: unknown flag name=[%s] found at line [%d] of file [%s]", arg.Key, arg.LineNum, arg.FilePath) + if !*allowUnknownFlags { + ok = false + } + continue + } + + if _, found := missingFlags[f.Name]; found { + oldValue := f.Value.String() + if oldValue == arg.Value { + continue + } + if err := f.Value.Set(arg.Value); err != nil { + logger.Printf("iniflags: error when parsing flag [%s] value [%s] at line [%d] of file [%s]: [%s]", arg.Key, arg.Value, arg.LineNum, arg.FilePath, err) + ok = false + continue + } + if oldValue != f.Value.String() { + oldFlagValues[arg.Key] = oldValue + } + } + } + + if !ok { + // restore old flag values + for k, v := range oldFlagValues { + flag.Set(k, v) + } + oldFlagValues = nil + } + + return oldFlagValues, ok +} + +func checkImportRecursion(configPath string) bool { + for _, path := range importStack { + if path == configPath { + logger.Printf("iniflags: import recursion found for [%s]: %v", configPath, importStack) + return false + } + } + return true +} + +type flagArg struct { + Key string + Value string + FilePath string + LineNum int +} + +func stripBOM(s string) string { + if len(s) < 3 { + return s + } + bom := s[:3] + if bom == "\ufeff" || bom == "\ufffe" { + return s[3:] + } + return s +} + +func getArgsFromConfig(configPath string) (args []flagArg, ok bool) { + if !checkImportRecursion(configPath) { + return nil, false + } + importStack = append(importStack, configPath) + defer func() { + importStack = importStack[:len(importStack)-1] + }() + + file := openConfigFile(configPath) + if file == nil { + return nil, false + } + defer file.Close() + r := bufio.NewReader(file) + + var lineNum int + var multilineFA flagArg + for { + lineNum++ + line, err := r.ReadString('\n') + if err != nil && line == "" { + if err == io.EOF { + if len(multilineFA.Key) > 0 { + // flush the last multiline arg + args = append(args, multilineFA) + } + break + } + logger.Printf("iniflags: error when reading file [%s] at line %d: [%s]", configPath, lineNum, err) + return nil, false + } + if lineNum == 1 { + line = stripBOM(line) + } + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "#import ") { + importPath, ok := unquoteValue(line[7:], lineNum, configPath) + if !ok { + return nil, false + } + if importPath, ok = combinePath(configPath, importPath); !ok { + return nil, false + } + importArgs, ok := getArgsFromConfig(importPath) + if !ok { + return nil, false + } + args = append(args, importArgs...) + continue + } + if line == "" || line[0] == ';' || line[0] == '#' || line[0] == '[' { + continue + } + parts := strings.SplitN(line, "=", 2) + if len(parts) != 2 { + logger.Printf("iniflags: cannot split [%s] at line %d into key and value in config file [%s]", line, lineNum, configPath) + return nil, false + } + key := strings.TrimSpace(parts[0]) + value, ok := unquoteValue(parts[1], lineNum, configPath) + if !ok { + return nil, false + } + + fa := flagArg{ + Key: key, + Value: value, + FilePath: configPath, + LineNum: lineNum, + } + + if !strings.HasSuffix(key, "}") { + if len(multilineFA.Key) > 0 { + // flush the last multiline arg + args = append(args, multilineFA) + multilineFA = flagArg{} + } + + args = append(args, fa) + continue + } + + // multiline arg + n := strings.LastIndex(key, "{") + if n < 0 { + log.Printf("iniflags: cannot find '{' in the multiline key [%s] at line %d, file [%s]", key, lineNum, configPath) + return nil, false + } + switch multilineFA.Key { + case "": + // the first line for multiline arg + multilineFA = fa + multilineFA.Key = key[:n] + case key[:n]: + // the subsequent line for multiline arg + delimiter := key[n+1 : len(key)-1] + multilineFA.Value += delimiter + multilineFA.Value += value + default: + // new multiline arg + args = append(args, multilineFA) + multilineFA = fa + multilineFA.Key = key[:n] + } + } + + return args, true +} + +func openConfigFile(path string) io.ReadCloser { + if isHTTP(path) { + resp, err := http.Get(path) + if err != nil { + logger.Printf("iniflags: cannot load config file at [%s]: [%s]\n", path, err) + return nil + } + if resp.StatusCode != http.StatusOK { + logger.Printf("iniflags: unexpected http status code when obtaining config file [%s]: %d. Expected %d", path, resp.StatusCode, http.StatusOK) + return nil + } + return resp.Body + } + + file, err := os.Open(path) + if err != nil { + logger.Printf("iniflags: cannot open config file at [%s]: [%s]", path, err) + return nil + } + return file +} + +func combinePath(basePath, relPath string) (string, bool) { + if isHTTP(basePath) { + base, err := url.Parse(basePath) + if err != nil { + logger.Printf("iniflags: error when parsing http base path [%s]: %s", basePath, err) + return "", false + } + rel, err := url.Parse(relPath) + if err != nil { + logger.Printf("iniflags: error when parsing http rel path [%s] for base [%s]: %s", relPath, basePath, err) + return "", false + } + return base.ResolveReference(rel).String(), true + } + + if relPath == "" || relPath[0] == '/' || isHTTP(relPath) { + return relPath, true + } + return path.Join(path.Dir(basePath), relPath), true +} + +func isHTTP(path string) bool { + return strings.HasPrefix(strings.ToLower(path), "http://") || strings.HasPrefix(strings.ToLower(path), "https://") +} + +func getMissingFlags() map[string]bool { + setFlags := make(map[string]bool) + flag.Visit(func(f *flag.Flag) { + setFlags[f.Name] = true + }) + + missingFlags := make(map[string]bool) + flag.VisitAll(func(f *flag.Flag) { + if _, ok := setFlags[f.Name]; !ok { + missingFlags[f.Name] = true + } + }) + return missingFlags +} + +func dumpFlags() { + flag.VisitAll(func(f *flag.Flag) { + if f.Name != "config" && f.Name != "dumpflags" { + fmt.Printf("%s = %s # %s\n", f.Name, quoteValue(f.Value.String()), escapeUsage(f.Usage)) + } + }) +} + +func escapeUsage(s string) string { + return strings.Replace(s, "\n", "\n # ", -1) +} + +func quoteValue(v string) string { + if !strings.ContainsAny(v, "\n#;") && strings.TrimSpace(v) == v { + return v + } + v = strings.Replace(v, "\\", "\\\\", -1) + v = strings.Replace(v, "\n", "\\n", -1) + v = strings.Replace(v, "\"", "\\\"", -1) + return fmt.Sprintf("\"%s\"", v) +} + +func unquoteValue(v string, lineNum int, configPath string) (string, bool) { + v = strings.TrimSpace(v) + if len(v) == 0 { + return "", true + } + if v[0] != '"' { + return removeTrailingComments(v), true + } + n := strings.LastIndex(v, "\"") + if n == -1 { + logger.Printf("iniflags: unclosed string found [%s] at line %d in config file [%s]", v, lineNum, configPath) + return "", false + } + v = v[1:n] + v = strings.Replace(v, "\\\"", "\"", -1) + v = strings.Replace(v, "\\n", "\n", -1) + return strings.Replace(v, "\\\\", "\\", -1), true +} + +func removeTrailingComments(v string) string { + v = strings.Split(v, "#")[0] + v = strings.Split(v, ";")[0] + return strings.TrimSpace(v) +} + +// SetConfigFile sets path to config file. +// +// Call this function before Parse() if you need default path to config file +// when -config command-line flag is not set. +func SetConfigFile(path string) { + if parsed { + logger.Panicf("iniflags: SetConfigFile() must be called before Parse()") + } + *config = path +} + +func SetAllowUnknownFlags(allowed bool) { + if parsed { + logger.Panicf("iniflags: SetAllowUnknownFlags() must be called before Parse()") + } + *allowUnknownFlags = allowed +} + +func SetConfigUpdateInterval(interval time.Duration) { + if parsed { + logger.Panicf("iniflags: SetConfigUpdateInterval() must be called before Parse()") + } + *configUpdateInterval = interval +} + +// Logger is a slimmed-down version of the log.Logger interface, which only includes the methods we use. +// This interface is accepted by SetLogger() to redirect log output to another destination. +type Logger interface { + Printf(format string, v ...interface{}) + Fatalf(format string, v ...interface{}) + Panicf(format string, v ...interface{}) +} + +// logger is the global Logger used to output log messages. By default, it outputs to the same place and with the same +// format as the standard libary log package calls. It can be changed via SetLogger(). +var logger Logger = log.New(os.Stderr, "", log.LstdFlags) + +func SetLogger(l Logger) { + logger = l +} diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE new file mode 100644 index 00000000..6a66aea5 --- /dev/null +++ b/vendor/golang.org/x/net/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/net/PATENTS b/vendor/golang.org/x/net/PATENTS new file mode 100644 index 00000000..73309904 --- /dev/null +++ b/vendor/golang.org/x/net/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/net/proxy/direct.go b/vendor/golang.org/x/net/proxy/direct.go new file mode 100644 index 00000000..4c5ad88b --- /dev/null +++ b/vendor/golang.org/x/net/proxy/direct.go @@ -0,0 +1,18 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proxy + +import ( + "net" +) + +type direct struct{} + +// Direct is a direct proxy: one that makes network connections directly. +var Direct = direct{} + +func (direct) Dial(network, addr string) (net.Conn, error) { + return net.Dial(network, addr) +} diff --git a/vendor/golang.org/x/net/proxy/per_host.go b/vendor/golang.org/x/net/proxy/per_host.go new file mode 100644 index 00000000..f540b196 --- /dev/null +++ b/vendor/golang.org/x/net/proxy/per_host.go @@ -0,0 +1,140 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proxy + +import ( + "net" + "strings" +) + +// A PerHost directs connections to a default Dialer unless the hostname +// requested matches one of a number of exceptions. +type PerHost struct { + def, bypass Dialer + + bypassNetworks []*net.IPNet + bypassIPs []net.IP + bypassZones []string + bypassHosts []string +} + +// NewPerHost returns a PerHost Dialer that directs connections to either +// defaultDialer or bypass, depending on whether the connection matches one of +// the configured rules. +func NewPerHost(defaultDialer, bypass Dialer) *PerHost { + return &PerHost{ + def: defaultDialer, + bypass: bypass, + } +} + +// Dial connects to the address addr on the given network through either +// defaultDialer or bypass. +func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + + return p.dialerForRequest(host).Dial(network, addr) +} + +func (p *PerHost) dialerForRequest(host string) Dialer { + if ip := net.ParseIP(host); ip != nil { + for _, net := range p.bypassNetworks { + if net.Contains(ip) { + return p.bypass + } + } + for _, bypassIP := range p.bypassIPs { + if bypassIP.Equal(ip) { + return p.bypass + } + } + return p.def + } + + for _, zone := range p.bypassZones { + if strings.HasSuffix(host, zone) { + return p.bypass + } + if host == zone[1:] { + // For a zone "example.com", we match "example.com" + // too. + return p.bypass + } + } + for _, bypassHost := range p.bypassHosts { + if bypassHost == host { + return p.bypass + } + } + return p.def +} + +// AddFromString parses a string that contains comma-separated values +// specifying hosts that should use the bypass proxy. Each value is either an +// IP address, a CIDR range, a zone (*.example.com) or a hostname +// (localhost). A best effort is made to parse the string and errors are +// ignored. +func (p *PerHost) AddFromString(s string) { + hosts := strings.Split(s, ",") + for _, host := range hosts { + host = strings.TrimSpace(host) + if len(host) == 0 { + continue + } + if strings.Contains(host, "/") { + // We assume that it's a CIDR address like 127.0.0.0/8 + if _, net, err := net.ParseCIDR(host); err == nil { + p.AddNetwork(net) + } + continue + } + if ip := net.ParseIP(host); ip != nil { + p.AddIP(ip) + continue + } + if strings.HasPrefix(host, "*.") { + p.AddZone(host[1:]) + continue + } + p.AddHost(host) + } +} + +// AddIP specifies an IP address that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match an IP. +func (p *PerHost) AddIP(ip net.IP) { + p.bypassIPs = append(p.bypassIPs, ip) +} + +// AddNetwork specifies an IP range that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match. +func (p *PerHost) AddNetwork(net *net.IPNet) { + p.bypassNetworks = append(p.bypassNetworks, net) +} + +// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of +// "example.com" matches "example.com" and all of its subdomains. +func (p *PerHost) AddZone(zone string) { + if strings.HasSuffix(zone, ".") { + zone = zone[:len(zone)-1] + } + if !strings.HasPrefix(zone, ".") { + zone = "." + zone + } + p.bypassZones = append(p.bypassZones, zone) +} + +// AddHost specifies a hostname that will use the bypass proxy. +func (p *PerHost) AddHost(host string) { + if strings.HasSuffix(host, ".") { + host = host[:len(host)-1] + } + p.bypassHosts = append(p.bypassHosts, host) +} diff --git a/vendor/golang.org/x/net/proxy/proxy.go b/vendor/golang.org/x/net/proxy/proxy.go new file mode 100644 index 00000000..78a8b7be --- /dev/null +++ b/vendor/golang.org/x/net/proxy/proxy.go @@ -0,0 +1,94 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package proxy provides support for a variety of protocols to proxy network +// data. +package proxy // import "golang.org/x/net/proxy" + +import ( + "errors" + "net" + "net/url" + "os" +) + +// A Dialer is a means to establish a connection. +type Dialer interface { + // Dial connects to the given address via the proxy. + Dial(network, addr string) (c net.Conn, err error) +} + +// Auth contains authentication parameters that specific Dialers may require. +type Auth struct { + User, Password string +} + +// FromEnvironment returns the dialer specified by the proxy related variables in +// the environment. +func FromEnvironment() Dialer { + allProxy := os.Getenv("all_proxy") + if len(allProxy) == 0 { + return Direct + } + + proxyURL, err := url.Parse(allProxy) + if err != nil { + return Direct + } + proxy, err := FromURL(proxyURL, Direct) + if err != nil { + return Direct + } + + noProxy := os.Getenv("no_proxy") + if len(noProxy) == 0 { + return proxy + } + + perHost := NewPerHost(proxy, Direct) + perHost.AddFromString(noProxy) + return perHost +} + +// proxySchemes is a map from URL schemes to a function that creates a Dialer +// from a URL with such a scheme. +var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error) + +// RegisterDialerType takes a URL scheme and a function to generate Dialers from +// a URL with that scheme and a forwarding Dialer. Registered schemes are used +// by FromURL. +func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) { + if proxySchemes == nil { + proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error)) + } + proxySchemes[scheme] = f +} + +// FromURL returns a Dialer given a URL specification and an underlying +// Dialer for it to make network requests. +func FromURL(u *url.URL, forward Dialer) (Dialer, error) { + var auth *Auth + if u.User != nil { + auth = new(Auth) + auth.User = u.User.Username() + if p, ok := u.User.Password(); ok { + auth.Password = p + } + } + + switch u.Scheme { + case "socks5": + return SOCKS5("tcp", u.Host, auth, forward) + } + + // If the scheme doesn't match any of the built-in schemes, see if it + // was registered by another package. + if proxySchemes != nil { + if f, ok := proxySchemes[u.Scheme]; ok { + return f(u, forward) + } + } + + return nil, errors.New("proxy: unknown scheme: " + u.Scheme) +} diff --git a/vendor/golang.org/x/net/proxy/socks5.go b/vendor/golang.org/x/net/proxy/socks5.go new file mode 100644 index 00000000..973f57f1 --- /dev/null +++ b/vendor/golang.org/x/net/proxy/socks5.go @@ -0,0 +1,213 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proxy + +import ( + "errors" + "io" + "net" + "strconv" +) + +// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address +// with an optional username and password. See RFC 1928. +func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) { + s := &socks5{ + network: network, + addr: addr, + forward: forward, + } + if auth != nil { + s.user = auth.User + s.password = auth.Password + } + + return s, nil +} + +type socks5 struct { + user, password string + network, addr string + forward Dialer +} + +const socks5Version = 5 + +const ( + socks5AuthNone = 0 + socks5AuthPassword = 2 +) + +const socks5Connect = 1 + +const ( + socks5IP4 = 1 + socks5Domain = 3 + socks5IP6 = 4 +) + +var socks5Errors = []string{ + "", + "general failure", + "connection forbidden", + "network unreachable", + "host unreachable", + "connection refused", + "TTL expired", + "command not supported", + "address type not supported", +} + +// Dial connects to the address addr on the network net via the SOCKS5 proxy. +func (s *socks5) Dial(network, addr string) (net.Conn, error) { + switch network { + case "tcp", "tcp6", "tcp4": + default: + return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) + } + + conn, err := s.forward.Dial(s.network, s.addr) + if err != nil { + return nil, err + } + if err := s.connect(conn, addr); err != nil { + conn.Close() + return nil, err + } + return conn, nil +} + +// connect takes an existing connection to a socks5 proxy server, +// and commands the server to extend that connection to target, +// which must be a canonical address with a host and port. +func (s *socks5) connect(conn net.Conn, target string) error { + host, portStr, err := net.SplitHostPort(target) + if err != nil { + return err + } + + port, err := strconv.Atoi(portStr) + if err != nil { + return errors.New("proxy: failed to parse port number: " + portStr) + } + if port < 1 || port > 0xffff { + return errors.New("proxy: port number out of range: " + portStr) + } + + // the size here is just an estimate + buf := make([]byte, 0, 6+len(host)) + + buf = append(buf, socks5Version) + if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { + buf = append(buf, 2 /* num auth methods */, socks5AuthNone, socks5AuthPassword) + } else { + buf = append(buf, 1 /* num auth methods */, socks5AuthNone) + } + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + if buf[0] != 5 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) + } + if buf[1] == 0xff { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") + } + + if buf[1] == socks5AuthPassword { + buf = buf[:0] + buf = append(buf, 1 /* password protocol version */) + buf = append(buf, uint8(len(s.user))) + buf = append(buf, s.user...) + buf = append(buf, uint8(len(s.password))) + buf = append(buf, s.password...) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if buf[1] != 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") + } + } + + buf = buf[:0] + buf = append(buf, socks5Version, socks5Connect, 0 /* reserved */) + + if ip := net.ParseIP(host); ip != nil { + if ip4 := ip.To4(); ip4 != nil { + buf = append(buf, socks5IP4) + ip = ip4 + } else { + buf = append(buf, socks5IP6) + } + buf = append(buf, ip...) + } else { + if len(host) > 255 { + return errors.New("proxy: destination hostname too long: " + host) + } + buf = append(buf, socks5Domain) + buf = append(buf, byte(len(host))) + buf = append(buf, host...) + } + buf = append(buf, byte(port>>8), byte(port)) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:4]); err != nil { + return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + failure := "unknown error" + if int(buf[1]) < len(socks5Errors) { + failure = socks5Errors[buf[1]] + } + + if len(failure) > 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) + } + + bytesToDiscard := 0 + switch buf[3] { + case socks5IP4: + bytesToDiscard = net.IPv4len + case socks5IP6: + bytesToDiscard = net.IPv6len + case socks5Domain: + _, err := io.ReadFull(conn, buf[:1]) + if err != nil { + return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + bytesToDiscard = int(buf[0]) + default: + return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) + } + + if cap(buf) < bytesToDiscard { + buf = make([]byte, bytesToDiscard) + } else { + buf = buf[:bytesToDiscard] + } + if _, err := io.ReadFull(conn, buf); err != nil { + return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + // Also need to discard the port number + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + return nil +} diff --git a/vendor/golang.org/x/net/websocket/client.go b/vendor/golang.org/x/net/websocket/client.go new file mode 100644 index 00000000..69a4ac7e --- /dev/null +++ b/vendor/golang.org/x/net/websocket/client.go @@ -0,0 +1,106 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "io" + "net" + "net/http" + "net/url" +) + +// DialError is an error that occurs while dialling a websocket server. +type DialError struct { + *Config + Err error +} + +func (e *DialError) Error() string { + return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() +} + +// NewConfig creates a new WebSocket config for client connection. +func NewConfig(server, origin string) (config *Config, err error) { + config = new(Config) + config.Version = ProtocolVersionHybi13 + config.Location, err = url.ParseRequestURI(server) + if err != nil { + return + } + config.Origin, err = url.ParseRequestURI(origin) + if err != nil { + return + } + config.Header = http.Header(make(map[string][]string)) + return +} + +// NewClient creates a new WebSocket client connection over rwc. +func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { + br := bufio.NewReader(rwc) + bw := bufio.NewWriter(rwc) + err = hybiClientHandshake(config, br, bw) + if err != nil { + return + } + buf := bufio.NewReadWriter(br, bw) + ws = newHybiClientConn(config, buf, rwc) + return +} + +// Dial opens a new client connection to a WebSocket. +func Dial(url_, protocol, origin string) (ws *Conn, err error) { + config, err := NewConfig(url_, origin) + if err != nil { + return nil, err + } + if protocol != "" { + config.Protocol = []string{protocol} + } + return DialConfig(config) +} + +var portMap = map[string]string{ + "ws": "80", + "wss": "443", +} + +func parseAuthority(location *url.URL) string { + if _, ok := portMap[location.Scheme]; ok { + if _, _, err := net.SplitHostPort(location.Host); err != nil { + return net.JoinHostPort(location.Host, portMap[location.Scheme]) + } + } + return location.Host +} + +// DialConfig opens a new client connection to a WebSocket with a config. +func DialConfig(config *Config) (ws *Conn, err error) { + var client net.Conn + if config.Location == nil { + return nil, &DialError{config, ErrBadWebSocketLocation} + } + if config.Origin == nil { + return nil, &DialError{config, ErrBadWebSocketOrigin} + } + dialer := config.Dialer + if dialer == nil { + dialer = &net.Dialer{} + } + client, err = dialWithDialer(dialer, config) + if err != nil { + goto Error + } + ws, err = NewClient(config, client) + if err != nil { + client.Close() + goto Error + } + return + +Error: + return nil, &DialError{config, err} +} diff --git a/vendor/golang.org/x/net/websocket/dial.go b/vendor/golang.org/x/net/websocket/dial.go new file mode 100644 index 00000000..2dab943a --- /dev/null +++ b/vendor/golang.org/x/net/websocket/dial.go @@ -0,0 +1,24 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "crypto/tls" + "net" +) + +func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { + switch config.Location.Scheme { + case "ws": + conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) + + case "wss": + conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) + + default: + err = ErrBadScheme + } + return +} diff --git a/vendor/golang.org/x/net/websocket/hybi.go b/vendor/golang.org/x/net/websocket/hybi.go new file mode 100644 index 00000000..8cffdd16 --- /dev/null +++ b/vendor/golang.org/x/net/websocket/hybi.go @@ -0,0 +1,583 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +// This file implements a protocol of hybi draft. +// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +const ( + websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + closeStatusNormal = 1000 + closeStatusGoingAway = 1001 + closeStatusProtocolError = 1002 + closeStatusUnsupportedData = 1003 + closeStatusFrameTooLarge = 1004 + closeStatusNoStatusRcvd = 1005 + closeStatusAbnormalClosure = 1006 + closeStatusBadMessageData = 1007 + closeStatusPolicyViolation = 1008 + closeStatusTooBigData = 1009 + closeStatusExtensionMismatch = 1010 + + maxControlFramePayloadLength = 125 +) + +var ( + ErrBadMaskingKey = &ProtocolError{"bad masking key"} + ErrBadPongMessage = &ProtocolError{"bad pong message"} + ErrBadClosingStatus = &ProtocolError{"bad closing status"} + ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"} + ErrNotImplemented = &ProtocolError{"not implemented"} + + handshakeHeader = map[string]bool{ + "Host": true, + "Upgrade": true, + "Connection": true, + "Sec-Websocket-Key": true, + "Sec-Websocket-Origin": true, + "Sec-Websocket-Version": true, + "Sec-Websocket-Protocol": true, + "Sec-Websocket-Accept": true, + } +) + +// A hybiFrameHeader is a frame header as defined in hybi draft. +type hybiFrameHeader struct { + Fin bool + Rsv [3]bool + OpCode byte + Length int64 + MaskingKey []byte + + data *bytes.Buffer +} + +// A hybiFrameReader is a reader for hybi frame. +type hybiFrameReader struct { + reader io.Reader + + header hybiFrameHeader + pos int64 + length int +} + +func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { + n, err = frame.reader.Read(msg) + if frame.header.MaskingKey != nil { + for i := 0; i < n; i++ { + msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4] + frame.pos++ + } + } + return n, err +} + +func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode } + +func (frame *hybiFrameReader) HeaderReader() io.Reader { + if frame.header.data == nil { + return nil + } + if frame.header.data.Len() == 0 { + return nil + } + return frame.header.data +} + +func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil } + +func (frame *hybiFrameReader) Len() (n int) { return frame.length } + +// A hybiFrameReaderFactory creates new frame reader based on its frame type. +type hybiFrameReaderFactory struct { + *bufio.Reader +} + +// NewFrameReader reads a frame header from the connection, and creates new reader for the frame. +// See Section 5.2 Base Framing protocol for detail. +// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2 +func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) { + hybiFrame := new(hybiFrameReader) + frame = hybiFrame + var header []byte + var b byte + // First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits) + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0 + for i := 0; i < 3; i++ { + j := uint(6 - i) + hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0 + } + hybiFrame.header.OpCode = header[0] & 0x0f + + // Second byte. Mask/Payload len(7bits) + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + mask := (b & 0x80) != 0 + b &= 0x7f + lengthFields := 0 + switch { + case b <= 125: // Payload length 7bits. + hybiFrame.header.Length = int64(b) + case b == 126: // Payload length 7+16bits + lengthFields = 2 + case b == 127: // Payload length 7+64bits + lengthFields = 8 + } + for i := 0; i < lengthFields; i++ { + b, err = buf.ReadByte() + if err != nil { + return + } + if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits + b &= 0x7f + } + header = append(header, b) + hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b) + } + if mask { + // Masking key. 4 bytes. + for i := 0; i < 4; i++ { + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b) + } + } + hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length) + hybiFrame.header.data = bytes.NewBuffer(header) + hybiFrame.length = len(header) + int(hybiFrame.header.Length) + return +} + +// A HybiFrameWriter is a writer for hybi frame. +type hybiFrameWriter struct { + writer *bufio.Writer + + header *hybiFrameHeader +} + +func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) { + var header []byte + var b byte + if frame.header.Fin { + b |= 0x80 + } + for i := 0; i < 3; i++ { + if frame.header.Rsv[i] { + j := uint(6 - i) + b |= 1 << j + } + } + b |= frame.header.OpCode + header = append(header, b) + if frame.header.MaskingKey != nil { + b = 0x80 + } else { + b = 0 + } + lengthFields := 0 + length := len(msg) + switch { + case length <= 125: + b |= byte(length) + case length < 65536: + b |= 126 + lengthFields = 2 + default: + b |= 127 + lengthFields = 8 + } + header = append(header, b) + for i := 0; i < lengthFields; i++ { + j := uint((lengthFields - i - 1) * 8) + b = byte((length >> j) & 0xff) + header = append(header, b) + } + if frame.header.MaskingKey != nil { + if len(frame.header.MaskingKey) != 4 { + return 0, ErrBadMaskingKey + } + header = append(header, frame.header.MaskingKey...) + frame.writer.Write(header) + data := make([]byte, length) + for i := range data { + data[i] = msg[i] ^ frame.header.MaskingKey[i%4] + } + frame.writer.Write(data) + err = frame.writer.Flush() + return length, err + } + frame.writer.Write(header) + frame.writer.Write(msg) + err = frame.writer.Flush() + return length, err +} + +func (frame *hybiFrameWriter) Close() error { return nil } + +type hybiFrameWriterFactory struct { + *bufio.Writer + needMaskingKey bool +} + +func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { + frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType} + if buf.needMaskingKey { + frameHeader.MaskingKey, err = generateMaskingKey() + if err != nil { + return nil, err + } + } + return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil +} + +type hybiFrameHandler struct { + conn *Conn + payloadType byte +} + +func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) { + if handler.conn.IsServerConn() { + // The client MUST mask all frames sent to the server. + if frame.(*hybiFrameReader).header.MaskingKey == nil { + handler.WriteClose(closeStatusProtocolError) + return nil, io.EOF + } + } else { + // The server MUST NOT mask all frames. + if frame.(*hybiFrameReader).header.MaskingKey != nil { + handler.WriteClose(closeStatusProtocolError) + return nil, io.EOF + } + } + if header := frame.HeaderReader(); header != nil { + io.Copy(ioutil.Discard, header) + } + switch frame.PayloadType() { + case ContinuationFrame: + frame.(*hybiFrameReader).header.OpCode = handler.payloadType + case TextFrame, BinaryFrame: + handler.payloadType = frame.PayloadType() + case CloseFrame: + return nil, io.EOF + case PingFrame, PongFrame: + b := make([]byte, maxControlFramePayloadLength) + n, err := io.ReadFull(frame, b) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return nil, err + } + io.Copy(ioutil.Discard, frame) + if frame.PayloadType() == PingFrame { + if _, err := handler.WritePong(b[:n]); err != nil { + return nil, err + } + } + return nil, nil + } + return frame, nil +} + +func (handler *hybiFrameHandler) WriteClose(status int) (err error) { + handler.conn.wio.Lock() + defer handler.conn.wio.Unlock() + w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame) + if err != nil { + return err + } + msg := make([]byte, 2) + binary.BigEndian.PutUint16(msg, uint16(status)) + _, err = w.Write(msg) + w.Close() + return err +} + +func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) { + handler.conn.wio.Lock() + defer handler.conn.wio.Unlock() + w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame) + if err != nil { + return 0, err + } + n, err = w.Write(msg) + w.Close() + return n, err +} + +// newHybiConn creates a new WebSocket connection speaking hybi draft protocol. +func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + if buf == nil { + br := bufio.NewReader(rwc) + bw := bufio.NewWriter(rwc) + buf = bufio.NewReadWriter(br, bw) + } + ws := &Conn{config: config, request: request, buf: buf, rwc: rwc, + frameReaderFactory: hybiFrameReaderFactory{buf.Reader}, + frameWriterFactory: hybiFrameWriterFactory{ + buf.Writer, request == nil}, + PayloadType: TextFrame, + defaultCloseStatus: closeStatusNormal} + ws.frameHandler = &hybiFrameHandler{conn: ws} + return ws +} + +// generateMaskingKey generates a masking key for a frame. +func generateMaskingKey() (maskingKey []byte, err error) { + maskingKey = make([]byte, 4) + if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil { + return + } + return +} + +// generateNonce generates a nonce consisting of a randomly selected 16-byte +// value that has been base64-encoded. +func generateNonce() (nonce []byte) { + key := make([]byte, 16) + if _, err := io.ReadFull(rand.Reader, key); err != nil { + panic(err) + } + nonce = make([]byte, 24) + base64.StdEncoding.Encode(nonce, key) + return +} + +// removeZone removes IPv6 zone identifer from host. +// E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" +func removeZone(host string) string { + if !strings.HasPrefix(host, "[") { + return host + } + i := strings.LastIndex(host, "]") + if i < 0 { + return host + } + j := strings.LastIndex(host[:i], "%") + if j < 0 { + return host + } + return host[:j] + host[i:] +} + +// getNonceAccept computes the base64-encoded SHA-1 of the concatenation of +// the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string. +func getNonceAccept(nonce []byte) (expected []byte, err error) { + h := sha1.New() + if _, err = h.Write(nonce); err != nil { + return + } + if _, err = h.Write([]byte(websocketGUID)); err != nil { + return + } + expected = make([]byte, 28) + base64.StdEncoding.Encode(expected, h.Sum(nil)) + return +} + +// Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17 +func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { + bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n") + + // According to RFC 6874, an HTTP client, proxy, or other + // intermediary must remove any IPv6 zone identifier attached + // to an outgoing URI. + bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n") + bw.WriteString("Upgrade: websocket\r\n") + bw.WriteString("Connection: Upgrade\r\n") + nonce := generateNonce() + if config.handshakeData != nil { + nonce = []byte(config.handshakeData["key"]) + } + bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n") + bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n") + + if config.Version != ProtocolVersionHybi13 { + return ErrBadProtocolVersion + } + + bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n") + if len(config.Protocol) > 0 { + bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n") + } + // TODO(ukai): send Sec-WebSocket-Extensions. + err = config.Header.WriteSubset(bw, handshakeHeader) + if err != nil { + return err + } + + bw.WriteString("\r\n") + if err = bw.Flush(); err != nil { + return err + } + + resp, err := http.ReadResponse(br, &http.Request{Method: "GET"}) + if err != nil { + return err + } + if resp.StatusCode != 101 { + return ErrBadStatus + } + if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" || + strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { + return ErrBadUpgrade + } + expectedAccept, err := getNonceAccept(nonce) + if err != nil { + return err + } + if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) { + return ErrChallengeResponse + } + if resp.Header.Get("Sec-WebSocket-Extensions") != "" { + return ErrUnsupportedExtensions + } + offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol") + if offeredProtocol != "" { + protocolMatched := false + for i := 0; i < len(config.Protocol); i++ { + if config.Protocol[i] == offeredProtocol { + protocolMatched = true + break + } + } + if !protocolMatched { + return ErrBadWebSocketProtocol + } + config.Protocol = []string{offeredProtocol} + } + + return nil +} + +// newHybiClientConn creates a client WebSocket connection after handshake. +func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn { + return newHybiConn(config, buf, rwc, nil) +} + +// A HybiServerHandshaker performs a server handshake using hybi draft protocol. +type hybiServerHandshaker struct { + *Config + accept []byte +} + +func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { + c.Version = ProtocolVersionHybi13 + if req.Method != "GET" { + return http.StatusMethodNotAllowed, ErrBadRequestMethod + } + // HTTP version can be safely ignored. + + if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" || + !strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") { + return http.StatusBadRequest, ErrNotWebSocket + } + + key := req.Header.Get("Sec-Websocket-Key") + if key == "" { + return http.StatusBadRequest, ErrChallengeResponse + } + version := req.Header.Get("Sec-Websocket-Version") + switch version { + case "13": + c.Version = ProtocolVersionHybi13 + default: + return http.StatusBadRequest, ErrBadWebSocketVersion + } + var scheme string + if req.TLS != nil { + scheme = "wss" + } else { + scheme = "ws" + } + c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI()) + if err != nil { + return http.StatusBadRequest, err + } + protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol")) + if protocol != "" { + protocols := strings.Split(protocol, ",") + for i := 0; i < len(protocols); i++ { + c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i])) + } + } + c.accept, err = getNonceAccept([]byte(key)) + if err != nil { + return http.StatusInternalServerError, err + } + return http.StatusSwitchingProtocols, nil +} + +// Origin parses the Origin header in req. +// If the Origin header is not set, it returns nil and nil. +func Origin(config *Config, req *http.Request) (*url.URL, error) { + var origin string + switch config.Version { + case ProtocolVersionHybi13: + origin = req.Header.Get("Origin") + } + if origin == "" { + return nil, nil + } + return url.ParseRequestURI(origin) +} + +func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { + if len(c.Protocol) > 0 { + if len(c.Protocol) != 1 { + // You need choose a Protocol in Handshake func in Server. + return ErrBadWebSocketProtocol + } + } + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n") + buf.WriteString("Upgrade: websocket\r\n") + buf.WriteString("Connection: Upgrade\r\n") + buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n") + if len(c.Protocol) > 0 { + buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n") + } + // TODO(ukai): send Sec-WebSocket-Extensions. + if c.Header != nil { + err := c.Header.WriteSubset(buf, handshakeHeader) + if err != nil { + return err + } + } + buf.WriteString("\r\n") + return buf.Flush() +} + +func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + return newHybiServerConn(c.Config, buf, rwc, request) +} + +// newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol. +func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + return newHybiConn(config, buf, rwc, request) +} diff --git a/vendor/golang.org/x/net/websocket/server.go b/vendor/golang.org/x/net/websocket/server.go new file mode 100644 index 00000000..0895dea1 --- /dev/null +++ b/vendor/golang.org/x/net/websocket/server.go @@ -0,0 +1,113 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "fmt" + "io" + "net/http" +) + +func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { + var hs serverHandshaker = &hybiServerHandshaker{Config: config} + code, err := hs.ReadHandshake(buf.Reader, req) + if err == ErrBadWebSocketVersion { + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) + buf.WriteString("\r\n") + buf.WriteString(err.Error()) + buf.Flush() + return + } + if err != nil { + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.WriteString(err.Error()) + buf.Flush() + return + } + if handshake != nil { + err = handshake(config, req) + if err != nil { + code = http.StatusForbidden + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.Flush() + return + } + } + err = hs.AcceptHandshake(buf.Writer) + if err != nil { + code = http.StatusBadRequest + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.Flush() + return + } + conn = hs.NewServerConn(buf, rwc, req) + return +} + +// Server represents a server of a WebSocket. +type Server struct { + // Config is a WebSocket configuration for new WebSocket connection. + Config + + // Handshake is an optional function in WebSocket handshake. + // For example, you can check, or don't check Origin header. + // Another example, you can select config.Protocol. + Handshake func(*Config, *http.Request) error + + // Handler handles a WebSocket connection. + Handler +} + +// ServeHTTP implements the http.Handler interface for a WebSocket +func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { + s.serveWebSocket(w, req) +} + +func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { + rwc, buf, err := w.(http.Hijacker).Hijack() + if err != nil { + panic("Hijack failed: " + err.Error()) + } + // The server should abort the WebSocket connection if it finds + // the client did not send a handshake that matches with protocol + // specification. + defer rwc.Close() + conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) + if err != nil { + return + } + if conn == nil { + panic("unexpected nil conn") + } + s.Handler(conn) +} + +// Handler is a simple interface to a WebSocket browser client. +// It checks if Origin header is valid URL by default. +// You might want to verify websocket.Conn.Config().Origin in the func. +// If you use Server instead of Handler, you could call websocket.Origin and +// check the origin in your Handshake func. So, if you want to accept +// non-browser clients, which do not send an Origin header, set a +// Server.Handshake that does not check the origin. +type Handler func(*Conn) + +func checkOrigin(config *Config, req *http.Request) (err error) { + config.Origin, err = Origin(config, req) + if err == nil && config.Origin == nil { + return fmt.Errorf("null origin") + } + return err +} + +// ServeHTTP implements the http.Handler interface for a WebSocket +func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { + s := Server{Handler: h, Handshake: checkOrigin} + s.serveWebSocket(w, req) +} diff --git a/vendor/golang.org/x/net/websocket/websocket.go b/vendor/golang.org/x/net/websocket/websocket.go new file mode 100644 index 00000000..e242c89a --- /dev/null +++ b/vendor/golang.org/x/net/websocket/websocket.go @@ -0,0 +1,448 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package websocket implements a client and server for the WebSocket protocol +// as specified in RFC 6455. +// +// This package currently lacks some features found in an alternative +// and more actively maintained WebSocket package: +// +// https://godoc.org/github.com/gorilla/websocket +// +package websocket // import "golang.org/x/net/websocket" + +import ( + "bufio" + "crypto/tls" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net" + "net/http" + "net/url" + "sync" + "time" +) + +const ( + ProtocolVersionHybi13 = 13 + ProtocolVersionHybi = ProtocolVersionHybi13 + SupportedProtocolVersion = "13" + + ContinuationFrame = 0 + TextFrame = 1 + BinaryFrame = 2 + CloseFrame = 8 + PingFrame = 9 + PongFrame = 10 + UnknownFrame = 255 + + DefaultMaxPayloadBytes = 32 << 20 // 32MB +) + +// ProtocolError represents WebSocket protocol errors. +type ProtocolError struct { + ErrorString string +} + +func (err *ProtocolError) Error() string { return err.ErrorString } + +var ( + ErrBadProtocolVersion = &ProtocolError{"bad protocol version"} + ErrBadScheme = &ProtocolError{"bad scheme"} + ErrBadStatus = &ProtocolError{"bad status"} + ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"} + ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"} + ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"} + ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"} + ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"} + ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"} + ErrBadFrame = &ProtocolError{"bad frame"} + ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"} + ErrNotWebSocket = &ProtocolError{"not websocket protocol"} + ErrBadRequestMethod = &ProtocolError{"bad method"} + ErrNotSupported = &ProtocolError{"not supported"} +) + +// ErrFrameTooLarge is returned by Codec's Receive method if payload size +// exceeds limit set by Conn.MaxPayloadBytes +var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit") + +// Addr is an implementation of net.Addr for WebSocket. +type Addr struct { + *url.URL +} + +// Network returns the network type for a WebSocket, "websocket". +func (addr *Addr) Network() string { return "websocket" } + +// Config is a WebSocket configuration +type Config struct { + // A WebSocket server address. + Location *url.URL + + // A Websocket client origin. + Origin *url.URL + + // WebSocket subprotocols. + Protocol []string + + // WebSocket protocol version. + Version int + + // TLS config for secure WebSocket (wss). + TlsConfig *tls.Config + + // Additional header fields to be sent in WebSocket opening handshake. + Header http.Header + + // Dialer used when opening websocket connections. + Dialer *net.Dialer + + handshakeData map[string]string +} + +// serverHandshaker is an interface to handle WebSocket server side handshake. +type serverHandshaker interface { + // ReadHandshake reads handshake request message from client. + // Returns http response code and error if any. + ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) + + // AcceptHandshake accepts the client handshake request and sends + // handshake response back to client. + AcceptHandshake(buf *bufio.Writer) (err error) + + // NewServerConn creates a new WebSocket connection. + NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn) +} + +// frameReader is an interface to read a WebSocket frame. +type frameReader interface { + // Reader is to read payload of the frame. + io.Reader + + // PayloadType returns payload type. + PayloadType() byte + + // HeaderReader returns a reader to read header of the frame. + HeaderReader() io.Reader + + // TrailerReader returns a reader to read trailer of the frame. + // If it returns nil, there is no trailer in the frame. + TrailerReader() io.Reader + + // Len returns total length of the frame, including header and trailer. + Len() int +} + +// frameReaderFactory is an interface to creates new frame reader. +type frameReaderFactory interface { + NewFrameReader() (r frameReader, err error) +} + +// frameWriter is an interface to write a WebSocket frame. +type frameWriter interface { + // Writer is to write payload of the frame. + io.WriteCloser +} + +// frameWriterFactory is an interface to create new frame writer. +type frameWriterFactory interface { + NewFrameWriter(payloadType byte) (w frameWriter, err error) +} + +type frameHandler interface { + HandleFrame(frame frameReader) (r frameReader, err error) + WriteClose(status int) (err error) +} + +// Conn represents a WebSocket connection. +// +// Multiple goroutines may invoke methods on a Conn simultaneously. +type Conn struct { + config *Config + request *http.Request + + buf *bufio.ReadWriter + rwc io.ReadWriteCloser + + rio sync.Mutex + frameReaderFactory + frameReader + + wio sync.Mutex + frameWriterFactory + + frameHandler + PayloadType byte + defaultCloseStatus int + + // MaxPayloadBytes limits the size of frame payload received over Conn + // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used. + MaxPayloadBytes int +} + +// Read implements the io.Reader interface: +// it reads data of a frame from the WebSocket connection. +// if msg is not large enough for the frame data, it fills the msg and next Read +// will read the rest of the frame data. +// it reads Text frame or Binary frame. +func (ws *Conn) Read(msg []byte) (n int, err error) { + ws.rio.Lock() + defer ws.rio.Unlock() +again: + if ws.frameReader == nil { + frame, err := ws.frameReaderFactory.NewFrameReader() + if err != nil { + return 0, err + } + ws.frameReader, err = ws.frameHandler.HandleFrame(frame) + if err != nil { + return 0, err + } + if ws.frameReader == nil { + goto again + } + } + n, err = ws.frameReader.Read(msg) + if err == io.EOF { + if trailer := ws.frameReader.TrailerReader(); trailer != nil { + io.Copy(ioutil.Discard, trailer) + } + ws.frameReader = nil + goto again + } + return n, err +} + +// Write implements the io.Writer interface: +// it writes data as a frame to the WebSocket connection. +func (ws *Conn) Write(msg []byte) (n int, err error) { + ws.wio.Lock() + defer ws.wio.Unlock() + w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType) + if err != nil { + return 0, err + } + n, err = w.Write(msg) + w.Close() + return n, err +} + +// Close implements the io.Closer interface. +func (ws *Conn) Close() error { + err := ws.frameHandler.WriteClose(ws.defaultCloseStatus) + err1 := ws.rwc.Close() + if err != nil { + return err + } + return err1 +} + +func (ws *Conn) IsClientConn() bool { return ws.request == nil } +func (ws *Conn) IsServerConn() bool { return ws.request != nil } + +// LocalAddr returns the WebSocket Origin for the connection for client, or +// the WebSocket location for server. +func (ws *Conn) LocalAddr() net.Addr { + if ws.IsClientConn() { + return &Addr{ws.config.Origin} + } + return &Addr{ws.config.Location} +} + +// RemoteAddr returns the WebSocket location for the connection for client, or +// the Websocket Origin for server. +func (ws *Conn) RemoteAddr() net.Addr { + if ws.IsClientConn() { + return &Addr{ws.config.Location} + } + return &Addr{ws.config.Origin} +} + +var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn") + +// SetDeadline sets the connection's network read & write deadlines. +func (ws *Conn) SetDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetDeadline(t) + } + return errSetDeadline +} + +// SetReadDeadline sets the connection's network read deadline. +func (ws *Conn) SetReadDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetReadDeadline(t) + } + return errSetDeadline +} + +// SetWriteDeadline sets the connection's network write deadline. +func (ws *Conn) SetWriteDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetWriteDeadline(t) + } + return errSetDeadline +} + +// Config returns the WebSocket config. +func (ws *Conn) Config() *Config { return ws.config } + +// Request returns the http request upgraded to the WebSocket. +// It is nil for client side. +func (ws *Conn) Request() *http.Request { return ws.request } + +// Codec represents a symmetric pair of functions that implement a codec. +type Codec struct { + Marshal func(v interface{}) (data []byte, payloadType byte, err error) + Unmarshal func(data []byte, payloadType byte, v interface{}) (err error) +} + +// Send sends v marshaled by cd.Marshal as single frame to ws. +func (cd Codec) Send(ws *Conn, v interface{}) (err error) { + data, payloadType, err := cd.Marshal(v) + if err != nil { + return err + } + ws.wio.Lock() + defer ws.wio.Unlock() + w, err := ws.frameWriterFactory.NewFrameWriter(payloadType) + if err != nil { + return err + } + _, err = w.Write(data) + w.Close() + return err +} + +// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores +// in v. The whole frame payload is read to an in-memory buffer; max size of +// payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds +// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire +// completely. The next call to Receive would read and discard leftover data of +// previous oversized frame before processing next frame. +func (cd Codec) Receive(ws *Conn, v interface{}) (err error) { + ws.rio.Lock() + defer ws.rio.Unlock() + if ws.frameReader != nil { + _, err = io.Copy(ioutil.Discard, ws.frameReader) + if err != nil { + return err + } + ws.frameReader = nil + } +again: + frame, err := ws.frameReaderFactory.NewFrameReader() + if err != nil { + return err + } + frame, err = ws.frameHandler.HandleFrame(frame) + if err != nil { + return err + } + if frame == nil { + goto again + } + maxPayloadBytes := ws.MaxPayloadBytes + if maxPayloadBytes == 0 { + maxPayloadBytes = DefaultMaxPayloadBytes + } + if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) { + // payload size exceeds limit, no need to call Unmarshal + // + // set frameReader to current oversized frame so that + // the next call to this function can drain leftover + // data before processing the next frame + ws.frameReader = frame + return ErrFrameTooLarge + } + payloadType := frame.PayloadType() + data, err := ioutil.ReadAll(frame) + if err != nil { + return err + } + return cd.Unmarshal(data, payloadType, v) +} + +func marshal(v interface{}) (msg []byte, payloadType byte, err error) { + switch data := v.(type) { + case string: + return []byte(data), TextFrame, nil + case []byte: + return data, BinaryFrame, nil + } + return nil, UnknownFrame, ErrNotSupported +} + +func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) { + switch data := v.(type) { + case *string: + *data = string(msg) + return nil + case *[]byte: + *data = msg + return nil + } + return ErrNotSupported +} + +/* +Message is a codec to send/receive text/binary data in a frame on WebSocket connection. +To send/receive text frame, use string type. +To send/receive binary frame, use []byte type. + +Trivial usage: + + import "websocket" + + // receive text frame + var message string + websocket.Message.Receive(ws, &message) + + // send text frame + message = "hello" + websocket.Message.Send(ws, message) + + // receive binary frame + var data []byte + websocket.Message.Receive(ws, &data) + + // send binary frame + data = []byte{0, 1, 2} + websocket.Message.Send(ws, data) + +*/ +var Message = Codec{marshal, unmarshal} + +func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) { + msg, err = json.Marshal(v) + return msg, TextFrame, err +} + +func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) { + return json.Unmarshal(msg, v) +} + +/* +JSON is a codec to send/receive JSON data in a frame from a WebSocket connection. + +Trivial usage: + + import "websocket" + + type T struct { + Msg string + Count int + } + + // receive JSON type T + var data T + websocket.JSON.Receive(ws, &data) + + // send JSON type T + websocket.JSON.Send(ws, data) +*/ +var JSON = Codec{jsonMarshal, jsonUnmarshal} From dd2f8dd1f5140468b325cc4fd30fb2097b02b53a Mon Sep 17 00:00:00 2001 From: Matteo Suppo Date: Mon, 3 Jul 2017 16:16:43 +0200 Subject: [PATCH 3/3] Patch has been merged --- glide.lock | 3 +- .../eclipse/paho.mqtt.golang/client.go | 147 +++++------- .../eclipse/paho.mqtt.golang/filestore.go | 30 +-- .../eclipse/paho.mqtt.golang/memstore.go | 28 +-- .../eclipse/paho.mqtt.golang/message.go | 2 +- .../eclipse/paho.mqtt.golang/messageids.go | 20 +- .../eclipse/paho.mqtt.golang/net.go | 152 ++++--------- .../eclipse/paho.mqtt.golang/oops.go | 6 + .../eclipse/paho.mqtt.golang/options.go | 6 +- .../paho.mqtt.golang/options_reader.go | 132 ----------- .../paho.mqtt.golang/packets/connack.go | 17 +- .../paho.mqtt.golang/packets/connect.go | 15 +- .../paho.mqtt.golang/packets/disconnect.go | 5 +- .../paho.mqtt.golang/packets/packets.go | 8 +- .../paho.mqtt.golang/packets/pingreq.go | 3 +- .../paho.mqtt.golang/packets/pingresp.go | 3 +- .../paho.mqtt.golang/packets/puback.go | 9 +- .../paho.mqtt.golang/packets/pubcomp.go | 7 +- .../paho.mqtt.golang/packets/publish.go | 17 +- .../paho.mqtt.golang/packets/pubrec.go | 7 +- .../paho.mqtt.golang/packets/pubrel.go | 7 +- .../paho.mqtt.golang/packets/suback.go | 13 +- .../paho.mqtt.golang/packets/subscribe.go | 5 +- .../paho.mqtt.golang/packets/unsuback.go | 7 +- .../paho.mqtt.golang/packets/unsubscribe.go | 7 +- .../eclipse/paho.mqtt.golang/ping.go | 75 +----- .../eclipse/paho.mqtt.golang/router.go | 8 +- .../eclipse/paho.mqtt.golang/store.go | 16 +- .../eclipse/paho.mqtt.golang/topic.go | 6 +- vendor/golang.org/x/net/proxy/direct.go | 18 -- vendor/golang.org/x/net/proxy/per_host.go | 140 ------------ vendor/golang.org/x/net/proxy/proxy.go | 94 -------- vendor/golang.org/x/net/proxy/socks5.go | 213 ------------------ 33 files changed, 201 insertions(+), 1025 deletions(-) delete mode 100644 vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go delete mode 100644 vendor/golang.org/x/net/proxy/direct.go delete mode 100644 vendor/golang.org/x/net/proxy/per_host.go delete mode 100644 vendor/golang.org/x/net/proxy/proxy.go delete mode 100644 vendor/golang.org/x/net/proxy/socks5.go diff --git a/glide.lock b/glide.lock index 371230fe..d1bff349 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ hash: a50abbf0769838c3d94deba4c500a75d0367d7a65908fb329dee8ce1746d82f9 -updated: 2017-06-19T10:40:26.984867202+02:00 +updated: 2017-07-03T16:14:42.072150388+02:00 imports: - name: github.com/eclipse/paho.mqtt.golang version: 45f9b18f4864c81d49c3ed01e5faec9eeb05de31 @@ -16,6 +16,5 @@ imports: - name: golang.org/x/net version: dd2d9a67c97da0afa00d5726e28086007a0acce5 subpackages: - - proxy - websocket testImports: [] diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/client.go b/vendor/github.com/eclipse/paho.mqtt.golang/client.go index 242344bf..44bdfc7f 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/client.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/client.go @@ -52,15 +52,15 @@ const ( // information can be found in their respective documentation. // Numerous connection options may be specified by configuring a // and then supplying a ClientOptions type. + type Client interface { IsConnected() bool Connect() Token - Disconnect(quiesce uint) - Publish(topic string, qos byte, retained bool, payload interface{}) Token - Subscribe(topic string, qos byte, callback MessageHandler) Token - SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token - Unsubscribe(topics ...string) Token - AddRoute(topic string, callback MessageHandler) + Disconnect(uint) + Publish(string, byte, bool, interface{}) Token + Subscribe(string, byte, MessageHandler) Token + SubscribeMultiple(map[string]byte, MessageHandler) Token + Unsubscribe(...string) Token } // client implements the Client interface @@ -78,9 +78,9 @@ type client struct { stop chan struct{} persist Store options ClientOptions + pingTimer *time.Timer + pingRespTimer *time.Timer pingResp chan struct{} - packetResp chan struct{} - keepaliveReset chan struct{} status connStatus workers sync.WaitGroup } @@ -114,12 +114,6 @@ func NewClient(o *ClientOptions) Client { return c } -func (c *client) AddRoute(topic string, callback MessageHandler) { - if callback != nil { - c.msgRouter.addRoute(topic, callback) - } -} - // IsConnected returns a bool signifying whether // the client is connected or not. func (c *client) IsConnected() bool { @@ -190,10 +184,8 @@ func (c *client) Connect() Token { rc = c.connect() if rc != packets.Accepted { - if c.conn != nil { - c.conn.Close() - c.conn = nil - } + c.conn.Close() + c.conn = nil //if the protocol version was explicitly set don't do any fallback if c.options.protocolVersionExplicit { ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc]) @@ -227,29 +219,34 @@ func (c *client) Connect() Token { return } - if c.options.KeepAlive != 0 { - c.workers.Add(1) - go keepalive(c) - } - c.obound = make(chan *PacketAndToken, c.options.MessageChannelDepth) c.oboundP = make(chan *PacketAndToken, c.options.MessageChannelDepth) c.ibound = make(chan packets.ControlPacket) c.errors = make(chan error, 1) c.stop = make(chan struct{}) + c.pingTimer = time.NewTimer(c.options.KeepAlive) + c.pingRespTimer = time.NewTimer(time.Duration(10) * time.Second) + c.pingRespTimer.Stop() c.pingResp = make(chan struct{}, 1) - c.packetResp = make(chan struct{}, 1) - c.keepaliveReset = make(chan struct{}, 1) c.incomingPubChan = make(chan *packets.PublishPacket, c.options.MessageChannelDepth) c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c) + c.workers.Add(1) + go outgoing(c) + go alllogic(c) + c.setConnected(connected) DEBUG.Println(CLI, "client is connected") if c.options.OnConnect != nil { go c.options.OnConnect(c) } + if c.options.KeepAlive != 0 { + c.workers.Add(1) + go keepalive(c) + } + // Take care of any messages in the store //var leftovers []Receipt if c.options.CleanSession == false { @@ -258,12 +255,8 @@ func (c *client) Connect() Token { c.persist.Reset() } - go errorWatch(c) - // Do not start incoming until resume has completed - c.workers.Add(3) - go alllogic(c) - go outgoing(c) + c.workers.Add(1) go incoming(c) DEBUG.Println(CLI, "exit startClient") @@ -275,14 +268,12 @@ func (c *client) Connect() Token { // internal function used to reconnect the client when it loses its connection func (c *client) reconnect() { DEBUG.Println(CLI, "enter reconnect") - var ( - err error - - rc = byte(1) - sleep = time.Duration(1 * time.Second) - ) + c.setConnected(reconnecting) + var rc byte = 1 + var sleep uint = 1 + var err error - for rc != 0 && c.status != disconnected { + for rc != 0 { cm := newConnectMsgFromOptions(&c.options) for _, broker := range c.options.Servers { @@ -327,41 +318,32 @@ func (c *client) reconnect() { } } if rc != 0 { - DEBUG.Println(CLI, "Reconnect failed, sleeping for", int(sleep.Seconds()), "seconds") - time.Sleep(sleep) - if sleep < c.options.MaxReconnectInterval { + DEBUG.Println(CLI, "Reconnect failed, sleeping for", sleep, "seconds") + time.Sleep(time.Duration(sleep) * time.Second) + if sleep <= uint(c.options.MaxReconnectInterval.Seconds()) { sleep *= 2 } - - if sleep > c.options.MaxReconnectInterval { - sleep = c.options.MaxReconnectInterval - } } } - // Disconnect() must have been called while we were trying to reconnect. - if c.status == disconnected { - DEBUG.Println(CLI, "Client moved to disconnected state while reconnecting, abandoning reconnect") - return - } - - if c.options.KeepAlive != 0 { - c.workers.Add(1) - go keepalive(c) - } + c.pingTimer.Reset(c.options.KeepAlive) c.stop = make(chan struct{}) + c.workers.Add(1) + go outgoing(c) + go alllogic(c) + c.setConnected(connected) DEBUG.Println(CLI, "client is reconnected") if c.options.OnConnect != nil { go c.options.OnConnect(c) } - go errorWatch(c) - - c.workers.Add(3) - go alllogic(c) - go outgoing(c) + if c.options.KeepAlive != 0 { + c.workers.Add(1) + go keepalive(c) + } + c.workers.Add(1) go incoming(c) } @@ -396,21 +378,19 @@ func (c *client) connect() byte { // the specified number of milliseconds to wait for existing work to be // completed. func (c *client) Disconnect(quiesce uint) { - if c.status == connected { - DEBUG.Println(CLI, "disconnecting") - c.setConnected(disconnected) - - dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket) - dt := newToken(packets.Disconnect) - c.oboundP <- &PacketAndToken{p: dm, t: dt} - - // wait for work to finish, or quiesce time consumed - dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond) - } else { - WARN.Println(CLI, "Disconnect() called but not connected (disconnected/reconnecting)") - c.setConnected(disconnected) + if !c.IsConnected() { + WARN.Println(CLI, "already disconnected") + return } + DEBUG.Println(CLI, "disconnecting") + c.setConnected(disconnected) + + dm := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket) + dt := newToken(packets.Disconnect) + c.oboundP <- &PacketAndToken{p: dm, t: dt} + // wait for work to finish, or quiesce time consumed + dt.WaitTimeout(time.Duration(quiesce) * time.Millisecond) c.disconnect() } @@ -434,18 +414,14 @@ func (c *client) internalConnLost(err error) { c.closeStop() c.conn.Close() c.workers.Wait() - if c.options.CleanSession { - c.messageIds.cleanUp() + if c.options.OnConnectionLost != nil { + go c.options.OnConnectionLost(c, err) } if c.options.AutoReconnect { - c.setConnected(reconnecting) go c.reconnect() } else { c.setConnected(disconnected) } - if c.options.OnConnectionLost != nil { - go c.options.OnConnectionLost(c, err) - } } } @@ -460,17 +436,9 @@ func (c *client) closeStop() { } } -func (c *client) closeConn() { - c.Lock() - defer c.Unlock() - if c.conn != nil { - c.conn.Close() - } -} - func (c *client) disconnect() { c.closeStop() - c.closeConn() + c.conn.Close() c.workers.Wait() close(c.stopRouter) DEBUG.Println(CLI, "disconnected") @@ -599,11 +567,6 @@ func (c *client) Unsubscribe(topics ...string) Token { return token } -func (c *client) OptionsReader() ClientOptionsReader { - r := ClientOptionsReader{options: &c.options} - return r -} - //DefaultConnectionLostHandler is a definition of a function that simply //reports to the DEBUG log the reason for the client losing a connection. func DefaultConnectionLostHandler(client Client, reason error) { diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go b/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go index daf3a9e4..2fedd40c 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/filestore.go @@ -75,7 +75,7 @@ func (store *FileStore) Close() { store.Lock() defer store.Unlock() store.opened = false - DEBUG.Println(STR, "store is closed") + WARN.Println(STR, "store is not open") } // Put will put a message into the store, associated with the provided @@ -83,15 +83,10 @@ func (store *FileStore) Close() { func (store *FileStore) Put(key string, m packets.ControlPacket) { store.Lock() defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use file store, but not open") - return - } + chkcond(store.opened) full := fullpath(store.directory, key) write(store.directory, key, m) - if !exists(full) { - ERROR.Println(STR, "file not created:", full) - } + chkcond(exists(full)) } // Get will retrieve a message from the store, the one associated with @@ -99,10 +94,7 @@ func (store *FileStore) Put(key string, m packets.ControlPacket) { func (store *FileStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use file store, but not open") - return nil - } + chkcond(store.opened) filepath := fullpath(store.directory, key) if !exists(filepath) { return nil @@ -150,10 +142,7 @@ func (store *FileStore) Reset() { // lockless func (store *FileStore) all() []string { - if !store.opened { - ERROR.Println(STR, "Trying to use file store, but not open") - return nil - } + chkcond(store.opened) keys := []string{} files, rderr := ioutil.ReadDir(store.directory) chkerr(rderr) @@ -172,10 +161,7 @@ func (store *FileStore) all() []string { // lockless func (store *FileStore) del(key string) { - if !store.opened { - ERROR.Println(STR, "Trying to use file store, but not open") - return - } + chkcond(store.opened) DEBUG.Println(STR, "store del filepath:", store.directory) DEBUG.Println(STR, "store delete key:", key) filepath := fullpath(store.directory, key) @@ -187,9 +173,7 @@ func (store *FileStore) del(key string) { rerr := os.Remove(filepath) chkerr(rerr) DEBUG.Println(STR, "del msg:", key) - if exists(filepath) { - ERROR.Println(STR, "file not deleted:", filepath) - } + chkcond(!exists(filepath)) } func fullpath(store string, key string) string { diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go b/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go index d3bfe084..580a7e02 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/memstore.go @@ -53,10 +53,7 @@ func (store *MemoryStore) Open() { func (store *MemoryStore) Put(key string, message packets.ControlPacket) { store.Lock() defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } + chkcond(store.opened) store.messages[key] = message } @@ -65,10 +62,7 @@ func (store *MemoryStore) Put(key string, message packets.ControlPacket) { func (store *MemoryStore) Get(key string) packets.ControlPacket { store.RLock() defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } + chkcond(store.opened) mid := mIDFromKey(key) m := store.messages[key] if m == nil { @@ -84,10 +78,7 @@ func (store *MemoryStore) Get(key string) packets.ControlPacket { func (store *MemoryStore) All() []string { store.RLock() defer store.RUnlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return nil - } + chkcond(store.opened) keys := []string{} for k := range store.messages { keys = append(keys, k) @@ -100,10 +91,6 @@ func (store *MemoryStore) All() []string { func (store *MemoryStore) Del(key string) { store.Lock() defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to use memory store, but not open") - return - } mid := mIDFromKey(key) m := store.messages[key] if m == nil { @@ -118,10 +105,7 @@ func (store *MemoryStore) Del(key string) { func (store *MemoryStore) Close() { store.Lock() defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to close memory store, but not open") - return - } + chkcond(store.opened) store.opened = false DEBUG.Println(STR, "memorystore closed") } @@ -130,9 +114,7 @@ func (store *MemoryStore) Close() { func (store *MemoryStore) Reset() { store.Lock() defer store.Unlock() - if !store.opened { - ERROR.Println(STR, "Trying to reset memory store, but not open") - } + chkcond(store.opened) store.messages = make(map[string]packets.ControlPacket) WARN.Println(STR, "memorystore wiped") } diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/message.go b/vendor/github.com/eclipse/paho.mqtt.golang/message.go index b1b71648..c8c9be23 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/message.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/message.go @@ -98,7 +98,7 @@ func newConnectMsgFromOptions(options *ClientOptions) *packets.ConnectPacket { } } - m.Keepalive = uint16(options.KeepAlive.Seconds()) + m.KeepaliveTimer = uint16(options.KeepAlive.Seconds()) return m } diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go b/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go index 9f4d0441..a6fc3ae4 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/messageids.go @@ -15,7 +15,6 @@ package mqtt import ( - "fmt" "sync" ) @@ -34,27 +33,10 @@ const ( midMax uint16 = 65535 ) -func (mids *messageIds) cleanUp() { - mids.Lock() - for _, token := range mids.index { - switch t := token.(type) { - case *PublishToken: - t.err = fmt.Errorf("Connection lost before Publish completed") - case *SubscribeToken: - t.err = fmt.Errorf("Connection lost before Subscribe completed") - case *UnsubscribeToken: - t.err = fmt.Errorf("Connection lost before Unsubscribe completed") - } - token.flowComplete() - } - mids.index = make(map[uint16]Token) - mids.Unlock() -} - func (mids *messageIds) freeID(id uint16) { mids.Lock() + defer mids.Unlock() delete(mids.index, id) - mids.Unlock() } func (mids *messageIds) getID(t Token) uint16 { diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/net.go b/vendor/github.com/eclipse/paho.mqtt.golang/net.go index bee0e4d0..5fca417b 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/net.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/net.go @@ -17,15 +17,12 @@ package mqtt import ( "crypto/tls" "errors" - "fmt" "net" "net/url" - "os" "reflect" "time" "github.com/eclipse/paho.mqtt.golang/packets" - "golang.org/x/net/proxy" "golang.org/x/net/websocket" ) @@ -39,14 +36,14 @@ func signalError(c chan<- error, err error) { func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration) (net.Conn, error) { switch uri.Scheme { case "ws": - conn, err := websocket.Dial(uri.String(), "mqtt", fmt.Sprintf("http://%s", uri.Host)) + conn, err := websocket.Dial(uri.String(), "mqtt", "ws://localhost") if err != nil { return nil, err } conn.PayloadType = websocket.BinaryFrame return conn, err case "wss": - config, _ := websocket.NewConfig(uri.String(), fmt.Sprintf("https://%s", uri.Host)) + config, _ := websocket.NewConfig(uri.String(), "ws://localhost") config.Protocol = []string{"mqtt"} config.TlsConfig = tlsc conn, err := websocket.DialConfig(config) @@ -56,52 +53,21 @@ func openConnection(uri *url.URL, tlsc *tls.Config, timeout time.Duration) (net. conn.PayloadType = websocket.BinaryFrame return conn, err case "tcp": - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - conn, err := net.DialTimeout("tcp", uri.Host, timeout) - if err != nil { - return nil, err - } - return conn, nil - } else { - proxyDialer := proxy.FromEnvironment() - - conn, err := proxyDialer.Dial("tcp", uri.Host) - if err != nil { - return nil, err - } - return conn, nil + conn, err := net.DialTimeout("tcp", uri.Host, timeout) + if err != nil { + return nil, err } + return conn, nil case "ssl": fallthrough case "tls": fallthrough case "tcps": - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc) - if err != nil { - return nil, err - } - return conn, nil - } else { - proxyDialer := proxy.FromEnvironment() - - conn, err := proxyDialer.Dial("tcp", uri.Host) - if err != nil { - return nil, err - } - - tlsConn := tls.Client(conn, tlsc) - - err = tlsConn.Handshake() - if err != nil { - conn.Close() - return nil, err - } - - return tlsConn, nil + conn, err := tls.DialWithDialer(&net.Dialer{Timeout: timeout}, "tcp", uri.Host, tlsc) + if err != nil { + return nil, err } + return conn, nil } return nil, errors.New("Unknown protocol") } @@ -121,18 +87,7 @@ func incoming(c *client) { break } DEBUG.Println(NET, "Received Message") - select { - case c.ibound <- cp: - // Notify keepalive logic that we recently received a packet - if c.options.KeepAlive != 0 { - c.packetResp <- struct{}{} - } - case <-c.stop: - // This avoids a deadlock should a message arrive while shutting down. - // In that case the "reader" of c.ibound might already be gone - WARN.Println(NET, "incoming dropped a received message during shutdown") - break - } + c.ibound <- cp } // We received an error on read. // If disconnect is in progress, swallow error and return @@ -204,13 +159,7 @@ func outgoing(c *client) { } } // Reset ping timer after sending control packet. - if c.options.KeepAlive != 0 { - select { - case c.keepaliveReset <- struct{}{}: - default: - DEBUG.Println(NET, "couldn't send keepalive signal in outbound as channel full") - } - } + c.pingTimer.Reset(c.options.KeepAlive) } } @@ -219,7 +168,7 @@ func outgoing(c *client) { // send replies on obound // delete messages from store if necessary func alllogic(c *client) { - defer c.workers.Done() + DEBUG.Println(NET, "logic started") for { @@ -229,90 +178,89 @@ func alllogic(c *client) { case msg := <-c.ibound: DEBUG.Println(NET, "logic got msg on ibound") persistInbound(c.persist, msg) - switch m := msg.(type) { + switch msg.(type) { case *packets.PingrespPacket: DEBUG.Println(NET, "received pingresp") c.pingResp <- struct{}{} case *packets.SubackPacket: - DEBUG.Println(NET, "received suback, id:", m.MessageID) - token := c.getToken(m.MessageID).(*SubscribeToken) - DEBUG.Println(NET, "granted qoss", m.ReturnCodes) - for i, qos := range m.ReturnCodes { + sa := msg.(*packets.SubackPacket) + DEBUG.Println(NET, "received suback, id:", sa.MessageID) + token := c.getToken(sa.MessageID).(*SubscribeToken) + DEBUG.Println(NET, "granted qoss", sa.GrantedQoss) + for i, qos := range sa.GrantedQoss { token.subResult[token.subs[i]] = qos } token.flowComplete() - c.freeID(m.MessageID) + go c.freeID(sa.MessageID) case *packets.UnsubackPacket: - DEBUG.Println(NET, "received unsuback, id:", m.MessageID) - token := c.getToken(m.MessageID).(*UnsubscribeToken) + ua := msg.(*packets.UnsubackPacket) + DEBUG.Println(NET, "received unsuback, id:", ua.MessageID) + token := c.getToken(ua.MessageID).(*UnsubscribeToken) token.flowComplete() - c.freeID(m.MessageID) + go c.freeID(ua.MessageID) case *packets.PublishPacket: - DEBUG.Println(NET, "received publish, msgId:", m.MessageID) + pp := msg.(*packets.PublishPacket) + DEBUG.Println(NET, "received publish, msgId:", pp.MessageID) DEBUG.Println(NET, "putting msg on onPubChan") - switch m.Qos { + switch pp.Qos { case 2: - c.incomingPubChan <- m + c.incomingPubChan <- pp DEBUG.Println(NET, "done putting msg on incomingPubChan") pr := packets.NewControlPacket(packets.Pubrec).(*packets.PubrecPacket) - pr.MessageID = m.MessageID + pr.MessageID = pp.MessageID DEBUG.Println(NET, "putting pubrec msg on obound") c.oboundP <- &PacketAndToken{p: pr, t: nil} DEBUG.Println(NET, "done putting pubrec msg on obound") case 1: - c.incomingPubChan <- m + c.incomingPubChan <- pp DEBUG.Println(NET, "done putting msg on incomingPubChan") pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket) - pa.MessageID = m.MessageID + pa.MessageID = pp.MessageID DEBUG.Println(NET, "putting puback msg on obound") c.oboundP <- &PacketAndToken{p: pa, t: nil} DEBUG.Println(NET, "done putting puback msg on obound") case 0: - c.incomingPubChan <- m + c.incomingPubChan <- pp DEBUG.Println(NET, "done putting msg on incomingPubChan") } case *packets.PubackPacket: - DEBUG.Println(NET, "received puback, id:", m.MessageID) + pa := msg.(*packets.PubackPacket) + DEBUG.Println(NET, "received puback, id:", pa.MessageID) // c.receipts.get(msg.MsgId()) <- Receipt{} // c.receipts.end(msg.MsgId()) - c.getToken(m.MessageID).flowComplete() - c.freeID(m.MessageID) + c.getToken(pa.MessageID).flowComplete() + c.freeID(pa.MessageID) case *packets.PubrecPacket: - DEBUG.Println(NET, "received pubrec, id:", m.MessageID) + prec := msg.(*packets.PubrecPacket) + DEBUG.Println(NET, "received pubrec, id:", prec.MessageID) prel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket) - prel.MessageID = m.MessageID + prel.MessageID = prec.MessageID select { case c.oboundP <- &PacketAndToken{p: prel, t: nil}: case <-time.After(time.Second): } case *packets.PubrelPacket: - DEBUG.Println(NET, "received pubrel, id:", m.MessageID) + pr := msg.(*packets.PubrelPacket) + DEBUG.Println(NET, "received pubrel, id:", pr.MessageID) pc := packets.NewControlPacket(packets.Pubcomp).(*packets.PubcompPacket) - pc.MessageID = m.MessageID + pc.MessageID = pr.MessageID select { case c.oboundP <- &PacketAndToken{p: pc, t: nil}: case <-time.After(time.Second): } case *packets.PubcompPacket: - DEBUG.Println(NET, "received pubcomp, id:", m.MessageID) - c.getToken(m.MessageID).flowComplete() - c.freeID(m.MessageID) + pc := msg.(*packets.PubcompPacket) + DEBUG.Println(NET, "received pubcomp, id:", pc.MessageID) + c.getToken(pc.MessageID).flowComplete() + c.freeID(pc.MessageID) } case <-c.stop: WARN.Println(NET, "logic stopped") return + case err := <-c.errors: + ERROR.Println(NET, "logic received from error channel, other components have errored, stopping") + c.internalConnLost(err) + return } } } - -func errorWatch(c *client) { - select { - case <-c.stop: - WARN.Println(NET, "errorWatch stopped") - return - case err := <-c.errors: - ERROR.Println(NET, "error triggered, stopping") - c.internalConnLost(err) - return - } -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/oops.go b/vendor/github.com/eclipse/paho.mqtt.golang/oops.go index 39630d7f..f15a9bae 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/oops.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/oops.go @@ -19,3 +19,9 @@ func chkerr(e error) { panic(e) } } + +func chkcond(b bool) { + if !b { + panic("oops") + } +} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/options.go b/vendor/github.com/eclipse/paho.mqtt.golang/options.go index 16129ceb..3e3f112c 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/options.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/options.go @@ -109,10 +109,8 @@ func NewClientOptions() *ClientOptions { // Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) // and "port" is the port on which the broker is accepting connections. func (o *ClientOptions) AddBroker(server string) *ClientOptions { - brokerURI, err := url.Parse(server) - if err == nil { - o.Servers = append(o.Servers, brokerURI) - } + brokerURI, _ := url.Parse(server) + o.Servers = append(o.Servers, brokerURI) return o } diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go b/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go deleted file mode 100644 index 85157d82..00000000 --- a/vendor/github.com/eclipse/paho.mqtt.golang/options_reader.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Seth Hoenig - * Allan Stockdill-Mander - * Mike Robertson - */ - -package mqtt - -import ( - "crypto/tls" - "net/url" - "time" -) - -// ClientOptionsReader provides an interface for reading ClientOptions after the client has been initialized. -type ClientOptionsReader struct { - options *ClientOptions -} - -func (r *ClientOptionsReader) Servers() []*url.URL { - s := make([]*url.URL, len(r.options.Servers)) - - for i, u := range r.options.Servers { - nu := *u - s[i] = &nu - } - - return s -} - -func (r *ClientOptionsReader) ClientID() string { - s := r.options.ClientID - return s -} - -func (r *ClientOptionsReader) Username() string { - s := r.options.Username - return s -} - -func (r *ClientOptionsReader) Password() string { - s := r.options.Password - return s -} - -func (r *ClientOptionsReader) CleanSession() bool { - s := r.options.CleanSession - return s -} - -func (r *ClientOptionsReader) Order() bool { - s := r.options.Order - return s -} - -func (r *ClientOptionsReader) WillEnabled() bool { - s := r.options.WillEnabled - return s -} - -func (r *ClientOptionsReader) WillTopic() string { - s := r.options.WillTopic - return s -} - -func (r *ClientOptionsReader) WillPayload() []byte { - s := r.options.WillPayload - return s -} - -func (r *ClientOptionsReader) WillQos() byte { - s := r.options.WillQos - return s -} - -func (r *ClientOptionsReader) WillRetained() bool { - s := r.options.WillRetained - return s -} - -func (r *ClientOptionsReader) ProtocolVersion() uint { - s := r.options.ProtocolVersion - return s -} - -func (r *ClientOptionsReader) TLSConfig() tls.Config { - s := r.options.TLSConfig - return s -} - -func (r *ClientOptionsReader) KeepAlive() time.Duration { - s := r.options.KeepAlive - return s -} - -func (r *ClientOptionsReader) PingTimeout() time.Duration { - s := r.options.PingTimeout - return s -} - -func (r *ClientOptionsReader) ConnectTimeout() time.Duration { - s := r.options.ConnectTimeout - return s -} - -func (r *ClientOptionsReader) MaxReconnectInterval() time.Duration { - s := r.options.MaxReconnectInterval - return s -} - -func (r *ClientOptionsReader) AutoReconnect() bool { - s := r.options.AutoReconnect - return s -} - -func (r *ClientOptionsReader) WriteTimeout() time.Duration { - s := r.options.WriteTimeout - return s -} - -func (r *ClientOptionsReader) MessageChannelDepth() uint { - s := r.options.MessageChannelDepth - return s -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go index a512ace0..d28b187f 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connack.go @@ -10,14 +10,13 @@ import ( //Connack MQTT packet type ConnackPacket struct { FixedHeader - SessionPresent bool - ReturnCode byte + TopicNameCompression byte + ReturnCode byte } func (ca *ConnackPacket) String() string { - str := fmt.Sprintf("%s", ca.FixedHeader) - str += " " - str += fmt.Sprintf("sessionpresent: %t returncode: %d", ca.SessionPresent, ca.ReturnCode) + str := fmt.Sprintf("%s\n", ca.FixedHeader) + str += fmt.Sprintf("returncode: %d", ca.ReturnCode) return str } @@ -25,7 +24,7 @@ func (ca *ConnackPacket) Write(w io.Writer) error { var body bytes.Buffer var err error - body.WriteByte(boolToByte(ca.SessionPresent)) + body.WriteByte(ca.TopicNameCompression) body.WriteByte(ca.ReturnCode) ca.FixedHeader.RemainingLength = 2 packet := ca.FixedHeader.pack() @@ -37,11 +36,9 @@ func (ca *ConnackPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (ca *ConnackPacket) Unpack(b io.Reader) error { - ca.SessionPresent = 1&decodeByte(b) > 0 +func (ca *ConnackPacket) Unpack(b io.Reader) { + ca.TopicNameCompression = decodeByte(b) ca.ReturnCode = decodeByte(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go index 378f0ed5..43adec5a 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/connect.go @@ -19,7 +19,7 @@ type ConnectPacket struct { UsernameFlag bool PasswordFlag bool ReservedBit byte - Keepalive uint16 + KeepaliveTimer uint16 ClientIdentifier string WillTopic string @@ -29,9 +29,8 @@ type ConnectPacket struct { } func (c *ConnectPacket) String() string { - str := fmt.Sprintf("%s", c.FixedHeader) - str += " " - str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password) + str := fmt.Sprintf("%s\n", c.FixedHeader) + str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalivetimer: %d\nclientId: %s\nwilltopic: %s\nwillmessage: %s\nUsername: %s\nPassword: %s\n", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.KeepaliveTimer, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password) return str } @@ -42,7 +41,7 @@ func (c *ConnectPacket) Write(w io.Writer) error { body.Write(encodeString(c.ProtocolName)) body.WriteByte(c.ProtocolVersion) body.WriteByte(boolToByte(c.CleanSession)<<1 | boolToByte(c.WillFlag)<<2 | c.WillQos<<3 | boolToByte(c.WillRetain)<<5 | boolToByte(c.PasswordFlag)<<6 | boolToByte(c.UsernameFlag)<<7) - body.Write(encodeUint16(c.Keepalive)) + body.Write(encodeUint16(c.KeepaliveTimer)) body.Write(encodeString(c.ClientIdentifier)) if c.WillFlag { body.Write(encodeString(c.WillTopic)) @@ -64,7 +63,7 @@ func (c *ConnectPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (c *ConnectPacket) Unpack(b io.Reader) error { +func (c *ConnectPacket) Unpack(b io.Reader) { c.ProtocolName = decodeString(b) c.ProtocolVersion = decodeByte(b) options := decodeByte(b) @@ -75,7 +74,7 @@ func (c *ConnectPacket) Unpack(b io.Reader) error { c.WillRetain = 1&(options>>5) > 0 c.PasswordFlag = 1&(options>>6) > 0 c.UsernameFlag = 1&(options>>7) > 0 - c.Keepalive = decodeUint16(b) + c.KeepaliveTimer = decodeUint16(b) c.ClientIdentifier = decodeString(b) if c.WillFlag { c.WillTopic = decodeString(b) @@ -87,8 +86,6 @@ func (c *ConnectPacket) Unpack(b io.Reader) error { if c.PasswordFlag { c.Password = decodeBytes(b) } - - return nil } //Validate performs validation of the fields of a Connect packet diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go index e5c18692..be08bc34 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/disconnect.go @@ -12,7 +12,7 @@ type DisconnectPacket struct { } func (d *DisconnectPacket) String() string { - str := fmt.Sprintf("%s", d.FixedHeader) + str := fmt.Sprintf("%s\n", d.FixedHeader) return str } @@ -25,8 +25,7 @@ func (d *DisconnectPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (d *DisconnectPacket) Unpack(b io.Reader) error { - return nil +func (d *DisconnectPacket) Unpack(b io.Reader) { } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go index cbc194a2..a7dcc5ed 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/packets.go @@ -13,7 +13,7 @@ import ( //written type ControlPacket interface { Write(io.Writer) error - Unpack(io.Reader) error + Unpack(io.Reader) String() string Details() Details } @@ -116,8 +116,8 @@ func ReadPacket(r io.Reader) (cp ControlPacket, err error) { if err != nil { return nil, err } - err = cp.Unpack(bytes.NewBuffer(packetBytes)) - return cp, err + cp.Unpack(bytes.NewBuffer(packetBytes)) + return cp, nil } //NewControlPacket is used to create a new ControlPacket of the type specified @@ -309,7 +309,7 @@ func decodeLength(r io.Reader) int { var rLength uint32 var multiplier uint32 b := make([]byte, 1) - for multiplier < 27 { //fix: Infinite '(digit & 128) == 1' will cause the dead loop + for { io.ReadFull(r, b) digit := b[0] rLength |= uint32(digit&127) << multiplier diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go index 5c3e88f9..3ecf0c6f 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingreq.go @@ -25,8 +25,7 @@ func (pr *PingreqPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pr *PingreqPacket) Unpack(b io.Reader) error { - return nil +func (pr *PingreqPacket) Unpack(b io.Reader) { } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go index 39ebc001..87e699e5 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pingresp.go @@ -25,8 +25,7 @@ func (pr *PingrespPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pr *PingrespPacket) Unpack(b io.Reader) error { - return nil +func (pr *PingrespPacket) Unpack(b io.Reader) { } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go index e30402cd..fb1399bb 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/puback.go @@ -13,9 +13,8 @@ type PubackPacket struct { } func (pa *PubackPacket) String() string { - str := fmt.Sprintf("%s", pa.FixedHeader) - str += " " - str += fmt.Sprintf("MessageID: %d", pa.MessageID) + str := fmt.Sprintf("%s\n", pa.FixedHeader) + str += fmt.Sprintf("messageID: %d", pa.MessageID) return str } @@ -31,10 +30,8 @@ func (pa *PubackPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pa *PubackPacket) Unpack(b io.Reader) error { +func (pa *PubackPacket) Unpack(b io.Reader) { pa.MessageID = decodeUint16(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go index fb994ae7..2cfb76fd 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubcomp.go @@ -13,8 +13,7 @@ type PubcompPacket struct { } func (pc *PubcompPacket) String() string { - str := fmt.Sprintf("%s", pc.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", pc.FixedHeader) str += fmt.Sprintf("MessageID: %d", pc.MessageID) return str } @@ -31,10 +30,8 @@ func (pc *PubcompPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pc *PubcompPacket) Unpack(b io.Reader) error { +func (pc *PubcompPacket) Unpack(b io.Reader) { pc.MessageID = decodeUint16(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go index b660ef4c..cab1e416 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/publish.go @@ -16,11 +16,9 @@ type PublishPacket struct { } func (p *PublishPacket) String() string { - str := fmt.Sprintf("%s", p.FixedHeader) - str += " " - str += fmt.Sprintf("topicName: %s MessageID: %d", p.TopicName, p.MessageID) - str += " " - str += fmt.Sprintf("payload: %s", string(p.Payload)) + str := fmt.Sprintf("%s\n", p.FixedHeader) + str += fmt.Sprintf("topicName: %s MessageID: %d\n", p.TopicName, p.MessageID) + str += fmt.Sprintf("payload: %s\n", string(p.Payload)) return str } @@ -43,7 +41,7 @@ func (p *PublishPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (p *PublishPacket) Unpack(b io.Reader) error { +func (p *PublishPacket) Unpack(b io.Reader) { var payloadLength = p.FixedHeader.RemainingLength p.TopicName = decodeString(b) if p.Qos > 0 { @@ -52,13 +50,8 @@ func (p *PublishPacket) Unpack(b io.Reader) error { } else { payloadLength -= len(p.TopicName) + 2 } - if payloadLength < 0 { - return fmt.Errorf("Error upacking publish, payload length < 0") - } p.Payload = make([]byte, payloadLength) - _, err := b.Read(p.Payload) - - return err + b.Read(p.Payload) } //Copy creates a new PublishPacket with the same topic and payload diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go index 9874e641..6579d4ec 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrec.go @@ -13,8 +13,7 @@ type PubrecPacket struct { } func (pr *PubrecPacket) String() string { - str := fmt.Sprintf("%s", pr.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", pr.FixedHeader) str += fmt.Sprintf("MessageID: %d", pr.MessageID) return str } @@ -31,10 +30,8 @@ func (pr *PubrecPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pr *PubrecPacket) Unpack(b io.Reader) error { +func (pr *PubrecPacket) Unpack(b io.Reader) { pr.MessageID = decodeUint16(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go index a7ecce75..7ffdbb82 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/pubrel.go @@ -13,8 +13,7 @@ type PubrelPacket struct { } func (pr *PubrelPacket) String() string { - str := fmt.Sprintf("%s", pr.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", pr.FixedHeader) str += fmt.Sprintf("MessageID: %d", pr.MessageID) return str } @@ -31,10 +30,8 @@ func (pr *PubrelPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (pr *PubrelPacket) Unpack(b io.Reader) error { +func (pr *PubrelPacket) Unpack(b io.Reader) { pr.MessageID = decodeUint16(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go index 557a7dbe..40db25f3 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/suback.go @@ -11,12 +11,11 @@ import ( type SubackPacket struct { FixedHeader MessageID uint16 - ReturnCodes []byte + GrantedQoss []byte } func (sa *SubackPacket) String() string { - str := fmt.Sprintf("%s", sa.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", sa.FixedHeader) str += fmt.Sprintf("MessageID: %d", sa.MessageID) return str } @@ -25,7 +24,7 @@ func (sa *SubackPacket) Write(w io.Writer) error { var body bytes.Buffer var err error body.Write(encodeUint16(sa.MessageID)) - body.Write(sa.ReturnCodes) + body.Write(sa.GrantedQoss) sa.FixedHeader.RemainingLength = body.Len() packet := sa.FixedHeader.pack() packet.Write(body.Bytes()) @@ -36,13 +35,11 @@ func (sa *SubackPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (sa *SubackPacket) Unpack(b io.Reader) error { +func (sa *SubackPacket) Unpack(b io.Reader) { var qosBuffer bytes.Buffer sa.MessageID = decodeUint16(b) qosBuffer.ReadFrom(b) - sa.ReturnCodes = qosBuffer.Bytes() - - return nil + sa.GrantedQoss = qosBuffer.Bytes() } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go index c418ef0f..12f0749f 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/subscribe.go @@ -17,7 +17,6 @@ type SubscribePacket struct { func (s *SubscribePacket) String() string { str := fmt.Sprintf("%s", s.FixedHeader) - str += " " str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics) return str } @@ -41,7 +40,7 @@ func (s *SubscribePacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (s *SubscribePacket) Unpack(b io.Reader) error { +func (s *SubscribePacket) Unpack(b io.Reader) { s.MessageID = decodeUint16(b) payloadLength := s.FixedHeader.RemainingLength - 2 for payloadLength > 0 { @@ -51,8 +50,6 @@ func (s *SubscribePacket) Unpack(b io.Reader) error { s.Qoss = append(s.Qoss, qos) payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos } - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go index b3b91ce3..4639c8d9 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsuback.go @@ -13,8 +13,7 @@ type UnsubackPacket struct { } func (ua *UnsubackPacket) String() string { - str := fmt.Sprintf("%s", ua.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", ua.FixedHeader) str += fmt.Sprintf("MessageID: %d", ua.MessageID) return str } @@ -31,10 +30,8 @@ func (ua *UnsubackPacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (ua *UnsubackPacket) Unpack(b io.Reader) error { +func (ua *UnsubackPacket) Unpack(b io.Reader) { ua.MessageID = decodeUint16(b) - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go index dc6a89ec..f52d4062 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/packets/unsubscribe.go @@ -15,8 +15,7 @@ type UnsubscribePacket struct { } func (u *UnsubscribePacket) String() string { - str := fmt.Sprintf("%s", u.FixedHeader) - str += " " + str := fmt.Sprintf("%s\n", u.FixedHeader) str += fmt.Sprintf("MessageID: %d", u.MessageID) return str } @@ -38,14 +37,12 @@ func (u *UnsubscribePacket) Write(w io.Writer) error { //Unpack decodes the details of a ControlPacket after the fixed //header has been read -func (u *UnsubscribePacket) Unpack(b io.Reader) error { +func (u *UnsubscribePacket) Unpack(b io.Reader) { u.MessageID = decodeUint16(b) var topic string for topic = decodeString(b); topic != ""; topic = decodeString(b) { u.Topics = append(u.Topics, topic) } - - return nil } //Details returns a Details struct containing the Qos and diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/ping.go b/vendor/github.com/eclipse/paho.mqtt.golang/ping.go index 2558db2d..a2176016 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/ping.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/ping.go @@ -16,7 +16,6 @@ package mqtt import ( "errors" - "time" "github.com/eclipse/paho.mqtt.golang/packets" ) @@ -24,79 +23,29 @@ import ( func keepalive(c *client) { DEBUG.Println(PNG, "keepalive starting") - receiveInterval := c.options.KeepAlive + (1 * time.Second) - pingTimer := timer{Timer: time.NewTimer(c.options.KeepAlive)} - receiveTimer := timer{Timer: time.NewTimer(receiveInterval)} - pingRespTimer := timer{Timer: time.NewTimer(c.options.PingTimeout)} - - pingRespTimer.Stop() - for { select { case <-c.stop: DEBUG.Println(PNG, "keepalive stopped") c.workers.Done() return - case <-pingTimer.C: - sendPing(&pingTimer, &pingRespTimer, c) - case <-c.keepaliveReset: - DEBUG.Println(NET, "resetting ping timer") - pingTimer.Reset(c.options.KeepAlive) + case <-c.pingTimer.C: + DEBUG.Println(PNG, "keepalive sending ping") + ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) + //We don't want to wait behind large messages being sent, the Write call + //will block until it it able to send the packet. + ping.Write(c.conn) + c.pingRespTimer.Reset(c.options.PingTimeout) case <-c.pingResp: - DEBUG.Println(NET, "resetting ping timeout timer") - pingRespTimer.Stop() - pingTimer.Reset(c.options.KeepAlive) - receiveTimer.Reset(receiveInterval) - case <-c.packetResp: - DEBUG.Println(NET, "resetting receive timer") - receiveTimer.Reset(receiveInterval) - case <-receiveTimer.C: - receiveTimer.SetRead(true) - receiveTimer.Reset(receiveInterval) - sendPing(&pingTimer, &pingRespTimer, c) - case <-pingRespTimer.C: - pingRespTimer.SetRead(true) + DEBUG.Println(NET, "resetting ping timers") + c.pingRespTimer.Stop() + c.pingTimer.Reset(c.options.KeepAlive) + case <-c.pingRespTimer.C: CRITICAL.Println(PNG, "pingresp not received, disconnecting") c.workers.Done() c.internalConnLost(errors.New("pingresp not received, disconnecting")) - pingTimer.Stop() + c.pingTimer.Stop() return } } } - -type timer struct { - *time.Timer - readFrom bool -} - -func (t *timer) SetRead(v bool) { - t.readFrom = v -} - -func (t *timer) Stop() bool { - defer t.SetRead(true) - - if !t.Timer.Stop() && !t.readFrom { - <-t.C - return false - } - return true -} - -func (t *timer) Reset(d time.Duration) bool { - defer t.SetRead(false) - t.Stop() - return t.Timer.Reset(d) -} - -func sendPing(pt *timer, rt *timer, c *client) { - pt.SetRead(true) - DEBUG.Println(PNG, "keepalive sending ping") - ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket) - //We don't want to wait behind large messages being sent, the Write call - //will block until it it able to send the packet. - ping.Write(c.conn) - - rt.Reset(c.options.PingTimeout) -} diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/router.go b/vendor/github.com/eclipse/paho.mqtt.golang/router.go index 9e44b0f7..842dba59 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/router.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/router.go @@ -119,8 +119,6 @@ func (r *router) deleteRoute(topic string) { // setDefaultHandler assigns a default callback that will be called if no matching Route // is found for an incoming Publish. func (r *router) setDefaultHandler(handler MessageHandler) { - r.Lock() - defer r.Unlock() r.defaultHandler = handler } @@ -138,21 +136,25 @@ func (r *router) matchAndDispatch(messages <-chan *packets.PublishPacket, order for e := r.routes.Front(); e != nil; e = e.Next() { if e.Value.(*route).match(message.TopicName) { if order { + r.RUnlock() e.Value.(*route).callback(client, messageFromPublish(message)) + r.RLock() } else { go e.Value.(*route).callback(client, messageFromPublish(message)) } sent = true } } + r.RUnlock() if !sent && r.defaultHandler != nil { if order { + r.RLock() r.defaultHandler(client, messageFromPublish(message)) + r.RUnlock() } else { go r.defaultHandler(client, messageFromPublish(message)) } } - r.RUnlock() case <-r.stop: return } diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/store.go b/vendor/github.com/eclipse/paho.mqtt.golang/store.go index 1cc9e1d3..a705d41c 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/store.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/store.go @@ -33,10 +33,10 @@ const ( // possible by prepending "i." or "o." to each message id type Store interface { Open() - Put(key string, message packets.ControlPacket) - Get(key string) packets.ControlPacket + Put(string, packets.ControlPacket) + Get(string) packets.ControlPacket All() []string - Del(key string) + Del(string) Close() Reset() } @@ -77,7 +77,7 @@ func persistOutbound(s Store, m packets.ControlPacket) { // until puback received s.Put(outboundKeyFromMID(m.Details().MessageID), m) default: - ERROR.Println(STR, "Asked to persist an invalid message type") + chkcond(false) } case 2: switch m.(type) { @@ -86,7 +86,7 @@ func persistOutbound(s Store, m packets.ControlPacket) { // until pubrel received s.Put(outboundKeyFromMID(m.Details().MessageID), m) default: - ERROR.Println(STR, "Asked to persist an invalid message type") + chkcond(false) } } } @@ -102,7 +102,7 @@ func persistInbound(s Store, m packets.ControlPacket) { s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: - ERROR.Println(STR, "Asked to persist an invalid messages type") + chkcond(false) } case 1: switch m.(type) { @@ -111,7 +111,7 @@ func persistInbound(s Store, m packets.ControlPacket) { // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: - ERROR.Println(STR, "Asked to persist an invalid messages type") + chkcond(false) } case 2: switch m.(type) { @@ -120,7 +120,7 @@ func persistInbound(s Store, m packets.ControlPacket) { // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: - ERROR.Println(STR, "Asked to persist an invalid messages type") + chkcond(false) } } } diff --git a/vendor/github.com/eclipse/paho.mqtt.golang/topic.go b/vendor/github.com/eclipse/paho.mqtt.golang/topic.go index 6fa3ad2a..ffe796d2 100644 --- a/vendor/github.com/eclipse/paho.mqtt.golang/topic.go +++ b/vendor/github.com/eclipse/paho.mqtt.golang/topic.go @@ -19,15 +19,15 @@ import ( "strings" ) -//ErrInvalidQos is the error returned when an packet is to be sent +//InvalidQos is the error returned when an packet is to be sent //with an invalid Qos value var ErrInvalidQos = errors.New("Invalid QoS") -//ErrInvalidTopicEmptyString is the error returned when a topic string +//InvalidTopicEmptyString is the error returned when a topic string //is passed in that is 0 length var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string") -//ErrInvalidTopicMultilevel is the error returned when a topic string +//InvalidTopicMultilevel is the error returned when a topic string //is passed in that has the multi level wildcard in any position but //the last var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level") diff --git a/vendor/golang.org/x/net/proxy/direct.go b/vendor/golang.org/x/net/proxy/direct.go deleted file mode 100644 index 4c5ad88b..00000000 --- a/vendor/golang.org/x/net/proxy/direct.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proxy - -import ( - "net" -) - -type direct struct{} - -// Direct is a direct proxy: one that makes network connections directly. -var Direct = direct{} - -func (direct) Dial(network, addr string) (net.Conn, error) { - return net.Dial(network, addr) -} diff --git a/vendor/golang.org/x/net/proxy/per_host.go b/vendor/golang.org/x/net/proxy/per_host.go deleted file mode 100644 index f540b196..00000000 --- a/vendor/golang.org/x/net/proxy/per_host.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proxy - -import ( - "net" - "strings" -) - -// A PerHost directs connections to a default Dialer unless the hostname -// requested matches one of a number of exceptions. -type PerHost struct { - def, bypass Dialer - - bypassNetworks []*net.IPNet - bypassIPs []net.IP - bypassZones []string - bypassHosts []string -} - -// NewPerHost returns a PerHost Dialer that directs connections to either -// defaultDialer or bypass, depending on whether the connection matches one of -// the configured rules. -func NewPerHost(defaultDialer, bypass Dialer) *PerHost { - return &PerHost{ - def: defaultDialer, - bypass: bypass, - } -} - -// Dial connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - - return p.dialerForRequest(host).Dial(network, addr) -} - -func (p *PerHost) dialerForRequest(host string) Dialer { - if ip := net.ParseIP(host); ip != nil { - for _, net := range p.bypassNetworks { - if net.Contains(ip) { - return p.bypass - } - } - for _, bypassIP := range p.bypassIPs { - if bypassIP.Equal(ip) { - return p.bypass - } - } - return p.def - } - - for _, zone := range p.bypassZones { - if strings.HasSuffix(host, zone) { - return p.bypass - } - if host == zone[1:] { - // For a zone "example.com", we match "example.com" - // too. - return p.bypass - } - } - for _, bypassHost := range p.bypassHosts { - if bypassHost == host { - return p.bypass - } - } - return p.def -} - -// AddFromString parses a string that contains comma-separated values -// specifying hosts that should use the bypass proxy. Each value is either an -// IP address, a CIDR range, a zone (*.example.com) or a hostname -// (localhost). A best effort is made to parse the string and errors are -// ignored. -func (p *PerHost) AddFromString(s string) { - hosts := strings.Split(s, ",") - for _, host := range hosts { - host = strings.TrimSpace(host) - if len(host) == 0 { - continue - } - if strings.Contains(host, "/") { - // We assume that it's a CIDR address like 127.0.0.0/8 - if _, net, err := net.ParseCIDR(host); err == nil { - p.AddNetwork(net) - } - continue - } - if ip := net.ParseIP(host); ip != nil { - p.AddIP(ip) - continue - } - if strings.HasPrefix(host, "*.") { - p.AddZone(host[1:]) - continue - } - p.AddHost(host) - } -} - -// AddIP specifies an IP address that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match an IP. -func (p *PerHost) AddIP(ip net.IP) { - p.bypassIPs = append(p.bypassIPs, ip) -} - -// AddNetwork specifies an IP range that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match. -func (p *PerHost) AddNetwork(net *net.IPNet) { - p.bypassNetworks = append(p.bypassNetworks, net) -} - -// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of -// "example.com" matches "example.com" and all of its subdomains. -func (p *PerHost) AddZone(zone string) { - if strings.HasSuffix(zone, ".") { - zone = zone[:len(zone)-1] - } - if !strings.HasPrefix(zone, ".") { - zone = "." + zone - } - p.bypassZones = append(p.bypassZones, zone) -} - -// AddHost specifies a hostname that will use the bypass proxy. -func (p *PerHost) AddHost(host string) { - if strings.HasSuffix(host, ".") { - host = host[:len(host)-1] - } - p.bypassHosts = append(p.bypassHosts, host) -} diff --git a/vendor/golang.org/x/net/proxy/proxy.go b/vendor/golang.org/x/net/proxy/proxy.go deleted file mode 100644 index 78a8b7be..00000000 --- a/vendor/golang.org/x/net/proxy/proxy.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package proxy provides support for a variety of protocols to proxy network -// data. -package proxy // import "golang.org/x/net/proxy" - -import ( - "errors" - "net" - "net/url" - "os" -) - -// A Dialer is a means to establish a connection. -type Dialer interface { - // Dial connects to the given address via the proxy. - Dial(network, addr string) (c net.Conn, err error) -} - -// Auth contains authentication parameters that specific Dialers may require. -type Auth struct { - User, Password string -} - -// FromEnvironment returns the dialer specified by the proxy related variables in -// the environment. -func FromEnvironment() Dialer { - allProxy := os.Getenv("all_proxy") - if len(allProxy) == 0 { - return Direct - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return Direct - } - proxy, err := FromURL(proxyURL, Direct) - if err != nil { - return Direct - } - - noProxy := os.Getenv("no_proxy") - if len(noProxy) == 0 { - return proxy - } - - perHost := NewPerHost(proxy, Direct) - perHost.AddFromString(noProxy) - return perHost -} - -// proxySchemes is a map from URL schemes to a function that creates a Dialer -// from a URL with such a scheme. -var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error) - -// RegisterDialerType takes a URL scheme and a function to generate Dialers from -// a URL with that scheme and a forwarding Dialer. Registered schemes are used -// by FromURL. -func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) { - if proxySchemes == nil { - proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error)) - } - proxySchemes[scheme] = f -} - -// FromURL returns a Dialer given a URL specification and an underlying -// Dialer for it to make network requests. -func FromURL(u *url.URL, forward Dialer) (Dialer, error) { - var auth *Auth - if u.User != nil { - auth = new(Auth) - auth.User = u.User.Username() - if p, ok := u.User.Password(); ok { - auth.Password = p - } - } - - switch u.Scheme { - case "socks5": - return SOCKS5("tcp", u.Host, auth, forward) - } - - // If the scheme doesn't match any of the built-in schemes, see if it - // was registered by another package. - if proxySchemes != nil { - if f, ok := proxySchemes[u.Scheme]; ok { - return f(u, forward) - } - } - - return nil, errors.New("proxy: unknown scheme: " + u.Scheme) -} diff --git a/vendor/golang.org/x/net/proxy/socks5.go b/vendor/golang.org/x/net/proxy/socks5.go deleted file mode 100644 index 973f57f1..00000000 --- a/vendor/golang.org/x/net/proxy/socks5.go +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package proxy - -import ( - "errors" - "io" - "net" - "strconv" -) - -// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address -// with an optional username and password. See RFC 1928. -func SOCKS5(network, addr string, auth *Auth, forward Dialer) (Dialer, error) { - s := &socks5{ - network: network, - addr: addr, - forward: forward, - } - if auth != nil { - s.user = auth.User - s.password = auth.Password - } - - return s, nil -} - -type socks5 struct { - user, password string - network, addr string - forward Dialer -} - -const socks5Version = 5 - -const ( - socks5AuthNone = 0 - socks5AuthPassword = 2 -) - -const socks5Connect = 1 - -const ( - socks5IP4 = 1 - socks5Domain = 3 - socks5IP6 = 4 -) - -var socks5Errors = []string{ - "", - "general failure", - "connection forbidden", - "network unreachable", - "host unreachable", - "connection refused", - "TTL expired", - "command not supported", - "address type not supported", -} - -// Dial connects to the address addr on the network net via the SOCKS5 proxy. -func (s *socks5) Dial(network, addr string) (net.Conn, error) { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) - } - - conn, err := s.forward.Dial(s.network, s.addr) - if err != nil { - return nil, err - } - if err := s.connect(conn, addr); err != nil { - conn.Close() - return nil, err - } - return conn, nil -} - -// connect takes an existing connection to a socks5 proxy server, -// and commands the server to extend that connection to target, -// which must be a canonical address with a host and port. -func (s *socks5) connect(conn net.Conn, target string) error { - host, portStr, err := net.SplitHostPort(target) - if err != nil { - return err - } - - port, err := strconv.Atoi(portStr) - if err != nil { - return errors.New("proxy: failed to parse port number: " + portStr) - } - if port < 1 || port > 0xffff { - return errors.New("proxy: port number out of range: " + portStr) - } - - // the size here is just an estimate - buf := make([]byte, 0, 6+len(host)) - - buf = append(buf, socks5Version) - if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { - buf = append(buf, 2 /* num auth methods */, socks5AuthNone, socks5AuthPassword) - } else { - buf = append(buf, 1 /* num auth methods */, socks5AuthNone) - } - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - if buf[0] != 5 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) - } - if buf[1] == 0xff { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") - } - - if buf[1] == socks5AuthPassword { - buf = buf[:0] - buf = append(buf, 1 /* password protocol version */) - buf = append(buf, uint8(len(s.user))) - buf = append(buf, s.user...) - buf = append(buf, uint8(len(s.password))) - buf = append(buf, s.password...) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if buf[1] != 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") - } - } - - buf = buf[:0] - buf = append(buf, socks5Version, socks5Connect, 0 /* reserved */) - - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - buf = append(buf, socks5IP4) - ip = ip4 - } else { - buf = append(buf, socks5IP6) - } - buf = append(buf, ip...) - } else { - if len(host) > 255 { - return errors.New("proxy: destination hostname too long: " + host) - } - buf = append(buf, socks5Domain) - buf = append(buf, byte(len(host))) - buf = append(buf, host...) - } - buf = append(buf, byte(port>>8), byte(port)) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:4]); err != nil { - return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - failure := "unknown error" - if int(buf[1]) < len(socks5Errors) { - failure = socks5Errors[buf[1]] - } - - if len(failure) > 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) - } - - bytesToDiscard := 0 - switch buf[3] { - case socks5IP4: - bytesToDiscard = net.IPv4len - case socks5IP6: - bytesToDiscard = net.IPv6len - case socks5Domain: - _, err := io.ReadFull(conn, buf[:1]) - if err != nil { - return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - bytesToDiscard = int(buf[0]) - default: - return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) - } - - if cap(buf) < bytesToDiscard { - buf = make([]byte, bytesToDiscard) - } else { - buf = buf[:bytesToDiscard] - } - if _, err := io.ReadFull(conn, buf); err != nil { - return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - // Also need to discard the port number - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - return nil -}