├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── cmd ├── ubnt-discovery │ ├── Makefile │ └── main.go └── ubnt-provisioner │ ├── Makefile │ └── main.go ├── discovery ├── auto_discovery.go ├── device.go ├── packet.go ├── packet_test.go ├── tag.go ├── tag_test.go └── testdata │ ├── edgerouter.dat │ ├── nanobeam-1a.dat │ ├── nanobeam-1b.dat │ └── nanobeam-2.dat ├── provisioner ├── configuration.go ├── device.go ├── device_cache.go ├── ssh │ └── ssh.go ├── ui │ ├── .babelrc │ ├── .bootstraprc │ ├── .eslintrc.json │ ├── .gitignore │ ├── Makefile │ ├── index.html │ ├── package.json │ ├── src │ │ ├── App.vue │ │ ├── components │ │ │ ├── DeviceNav.vue │ │ │ ├── DeviceView.vue │ │ │ └── UbntProvisioner.vue │ │ ├── main.js │ │ ├── provisioner.js │ │ └── utils │ │ │ └── filters.js │ ├── webpack.config.js │ └── yarn.lock └── web │ ├── ctrl_devices.go │ ├── ctrl_static.go │ ├── views.go │ └── web.go └── resources ├── config.yml └── provisioner.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Make targets 14 | /bin 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | include $(GOPATH)/src/github.com/digineo/goldflags/goldflags.mk 2 | 3 | RELEASE_PATTERN = bin/ubnt-tools_$(COMMIT_ID)_%.tar.bz2 4 | RELEASE_DIRS = $(shell find bin/ -mindepth 1 -maxdepth 1 -type d) 5 | RELEASE_ARCHIVES = $(patsubst bin/%,$(RELEASE_PATTERN),$(RELEASE_DIRS)) 6 | 7 | 8 | .PHONY: all 9 | all: discovery provisioner 10 | 11 | .PHONY: discovery 12 | discovery: 13 | cd cmd/ubnt-discovery && $(MAKE) 14 | 15 | .PHONY: provisioner 16 | provisioner: 17 | cd cmd/ubnt-provisioner && $(MAKE) 18 | 19 | .PHONY: clean 20 | clean: 21 | rm -f bin/*.tar.bz2 22 | 23 | .PHONY: clobber 24 | clobber: clean 25 | rm -rf $(RELEASE_DIRS) 26 | 27 | .PHONY: release 28 | release: $(RELEASE_ARCHIVES) 29 | cd bin && sha256sum $(notdir $(RELEASE_ARCHIVES)) 30 | 31 | $(RELEASE_PATTERN): bin/% 32 | cp resources/config.yml $= 1.8, 27 | - GNU Make, 28 | - Git, 29 | 30 | If you want to build the provisioning tool, you'll need additionally: 31 | 32 | - NodeJS >= 7 and NPM >= 3, 33 | - yarn, 34 | 35 | ### Getting the sources 36 | 37 | Clone this repository (assuming your `GOPATH` is setup properly): 38 | 39 | $ mkdir -p $GOPATH/src/github.com/digineo 40 | $ cd $GOPATH/src/github.com/digineo 41 | $ git clone https://github.com/digineo/ubnt-tools 42 | 43 | ### Building the binaries 44 | 45 | Run `make`: 46 | 47 | $ cd $GOPATH/src/github.com/digineo/ubnt-tools 48 | $ git pull # optionally 49 | $ make 50 | 51 | By default, this will build both the discovery and the provisioning tool. 52 | If you only need one of them, instead of `make` run one of the following 53 | suitable commands: 54 | 55 | $ make discovery 56 | $ make provisioner 57 | 58 | Note: Building the provisioner the for first time will try to download a 59 | bunch of NPM packages (the corresponding `node_modules` directory is, at 60 | the time of writing, around 100MB in size). 61 | 62 | ## Ubiquiti Device Discovery 63 | 64 | [![GoDoc](https://godoc.org/github.com/digineo/ubnt-tools/discovery?status.svg)](http://godoc.org/github.com/digineo/ubnt-tools/discovery) 65 | 66 | This is a standalone binary to detect Ubiquiti AirMax devices in your 67 | local network. It is basically a re-implementation of the Java tool 68 | [provided by Ubiquiti](https://www.ubnt.com/download/utilities/default/default/device-discovery-tool-java-all-platforms) 69 | in Go as a terminal application (i.e. it can easily be deployed on remote 70 | systems). 71 | 72 | ### Usage 73 | 74 | Simply invoke the discovery tool with an interface name: 75 | 76 | $ ubnt-discovery eth0 77 | 78 | This will broadcast the discovery packages (with exponential back-off), 79 | and report back the newly discovered devices: 80 | 81 | 2017/06/08 17:39:02 [discovery] listen on 172.16.1.7:49317 82 | 2017/06/08 17:39:02 [discovery] listen on 169.254.0.7:51705 83 | 2017/06/08 17:39:02 [discovery] sent broadcast, will send again in 4s 84 | 2017/06/08 17:39:02 [discovery] found new device: 85 | Device 86 | MAC: 80:2a:a8:64:7e:59 87 | Model: NanoBeam 5AC 19 88 | Platform: N5C 89 | Firmware: XC.qca955x.v8.0.2.33352.170327.1907 90 | Hostname: NanoBeam 5AC 19 91 | Booted at: 2017-06-08T16:08:50+02:00 92 | booted: 1h30m12.00001943s ago 93 | first seen: 24.031µs ago 94 | last seen: 24.031µs ago 95 | IP addresses on interface 80:2a:a8:64:7e:59 96 | - 192.168.1.20 97 | - 169.254.126.89 98 | ESSID: ubnt 99 | WMode: Station 100 | 2017/06/08 17:39:02 [discovery] found new device: 101 | Device 102 | MAC: 04:18:d6:83:f8:ec 103 | Model: 104 | Platform: ERLite-3 105 | Firmware: EdgeRouter.ER-e100.v1.9.1.4939093.161214.0705 106 | Hostname: digineo 107 | Booted at: 2017-04-10T10:36:11+02:00 108 | booted: 1423h2m51.000008187s ago 109 | first seen: 11.759µs ago 110 | last seen: 11.759µs ago 111 | IP addresses on interface 04:18:d6:83:f8:ec 112 | - 172.16.0.1 113 | - 172.16.2.1 114 | 115 | ## AirMax provisioning 116 | 117 | This provisioning tool helps managing a fleet of NanoBeam devices (it 118 | might work for other AirMax devices, but we haven't had the chance/need 119 | to try it with other devices). 120 | 121 | Given a directory with device configuration files, it can reconfigure 122 | ("provision") devices. 123 | 124 | If you also have a local copy of device firmwares, you can upgrade the 125 | devices with a single click. 126 | 127 | ### Usage 128 | 129 | First, create a config file. To get an example config file, run 130 | 131 | $ ubnt-provisioner -h 132 | 133 | and save the example to `config.yml` (the name can be arbitrary). 134 | Modify the content to your needs. See `resources/config.yml` for another 135 | sample. 136 | 137 | Then start the provisioner: 138 | 139 | $ ubnt-provisioner -c /path/to/config.yml 140 | ,____ __ __ 141 | | \|__|-----|__|-----.-----,-----. 142 | | - | | _ | | | .__| _ | 143 | |____/|__|___ |__|__|__|_____|_____| 144 | |_____| Digineo Ubnt provisioner 145 | Version 539be0b-dev (2017-06-09 12:57:02) 146 | Build 7 (2017-06-09 17:14:18) 147 | 2017/06/09 18:12:25 [discovery] listen on 172.16.1.7:33580 148 | 2017/06/09 18:12:25 [discovery] listen on 169.254.0.7:41207 149 | 2017/06/09 18:12:25 [discovery] sent broadcast, will send again in 4s 150 | 2017/06/09 18:12:25 [webui] Starting Web UI on http://127.0.0.1:8007 151 | 2017/06/09 18:12:25 [main] (re-) discovered NanoBeam 5AC 19 (80:2a:a8:64:7e:59) 152 | 2017/06/09 18:12:25 [main] (re-) discovered digineo (04:18:d6:83:f8:ec) 153 | 2017/06/09 18:12:29 [discovery] sent broadcast, will send again in 4.08s 154 | 155 | Finally, point your web browser with address given (in this case 156 | ): 157 | 158 | ![Screenshot provisioner](resources/provisioner.png) 159 | -------------------------------------------------------------------------------- /cmd/ubnt-discovery/Makefile: -------------------------------------------------------------------------------- 1 | include $(GOPATH)/src/github.com/digineo/goldflags/goldflags.mk 2 | 3 | NAME = ubnt-dicovery 4 | TARGET = ../../bin/$(NAME) 5 | DEPS = $(shell find ../../discovery -type f -name '*.go') 6 | DEPS += $(shell find . -type f -name '*.go') 7 | 8 | $(NAME): $(DEPS) 9 | $(call goldbuild,$(TARGET),linux,amd64) 10 | $(call goldbuild,$(TARGET),darwin,amd64) 11 | $(call goldbuild,$(TARGET),windows,amd64) 12 | -------------------------------------------------------------------------------- /cmd/ubnt-discovery/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | 11 | "github.com/digineo/goldflags" 12 | "github.com/digineo/ubnt-tools/discovery" 13 | ) 14 | 15 | const appName = "ubnt-discovery" 16 | 17 | var syslog = flag.Bool("syslog", false, "Disable log timestamps and redirect output to stdout") 18 | 19 | func main() { 20 | flag.Usage = func() { 21 | fmt.Fprintln(os.Stderr, goldflags.Banner(appName)) 22 | fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) 23 | flag.PrintDefaults() 24 | } 25 | flag.Parse() 26 | 27 | if *syslog { 28 | log.SetFlags(0) 29 | log.SetOutput(os.Stdout) 30 | } 31 | 32 | log.Println(goldflags.Banner("ubnt-discovery")) 33 | 34 | interfaces := []string{} 35 | for _, iface := range flag.Args() { 36 | interfaces = append(interfaces, iface) 37 | } 38 | 39 | discover, err := discovery.AutoDiscover(logDevice, interfaces...) 40 | if err != nil { 41 | log.Fatal(err) 42 | } 43 | defer discover.Close() 44 | 45 | sigs := make(chan os.Signal) 46 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 47 | <-sigs 48 | } 49 | 50 | func logDevice(device *discovery.Device) { 51 | log.Printf("[discovery] found new device:\n%s", device) 52 | } 53 | -------------------------------------------------------------------------------- /cmd/ubnt-provisioner/Makefile: -------------------------------------------------------------------------------- 1 | include $(GOPATH)/src/github.com/digineo/goldflags/goldflags.mk 2 | 3 | NAME = ubnt-provisioner 4 | TARGET = ../../bin/$(NAME) 5 | DEPS = $(shell find ../../discovery -type f -name '*.go') 6 | DEPS += $(shell find ../../provisioner -type f -name '*.go') 7 | DEPS += $(shell find . -type f -name '*.go') 8 | 9 | ASSETS = ../../provisioner/ui/bindata.go 10 | ASSET_DEPS = $(shell find ../../provisioner/ui/src -type f) 11 | 12 | .PHONY: $(NAME) 13 | $(NAME): $(DEPS) $(ASSETS) 14 | $(call goldbuild,$(TARGET),linux,amd64) 15 | $(call goldbuild,$(TARGET),darwin,amd64) 16 | $(call goldbuild,$(TARGET),windows,amd64) 17 | 18 | $(ASSETS): $(ASSET_DEPS) 19 | cd ../../provisioner/ui && $(MAKE) 20 | -------------------------------------------------------------------------------- /cmd/ubnt-provisioner/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | 11 | "github.com/digineo/goldflags" 12 | "github.com/digineo/ubnt-tools/discovery" 13 | "github.com/digineo/ubnt-tools/provisioner" 14 | "github.com/digineo/ubnt-tools/provisioner/web" 15 | ) 16 | 17 | const appName = "Digineo Ubnt provisioner" 18 | 19 | var ( 20 | configFile = flag.String("c", "./config.yml", "(optional) `path` to config.yml configuration file") 21 | syslog = flag.Bool("syslog", false, "Disable log timestamps and redirect output to stdout") 22 | 23 | configuration *provisioner.Configuration 24 | ) 25 | 26 | func main() { 27 | flag.Usage = func() { 28 | fmt.Fprintln(os.Stderr, goldflags.Banner(appName)) 29 | fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) 30 | printExampleConfig() 31 | flag.PrintDefaults() 32 | } 33 | 34 | fmt.Println(goldflags.Banner(appName)) 35 | flag.Parse() 36 | 37 | if *syslog { 38 | log.SetFlags(0) 39 | log.SetOutput(os.Stdout) 40 | } 41 | 42 | if configFile == nil || *configFile == "" { 43 | flag.Usage() 44 | printExampleConfig() 45 | os.Exit(1) 46 | } 47 | 48 | if config, errs := provisioner.LoadConfig(*configFile); len(errs) == 0 { 49 | configuration = config 50 | } else { 51 | log.Printf("Found %d error(s) loading the config file:", len(errs)) 52 | for i, e := range errs { 53 | log.Printf("Error %d: %s", i, e.Error()) 54 | } 55 | os.Exit(1) 56 | } 57 | 58 | discover, err := configuration.StartAutoDiscover(logDevice) 59 | if err != nil { 60 | log.Fatal(err) 61 | } 62 | defer discover.Close() 63 | go web.StartWeb(configuration) 64 | 65 | sigs := make(chan os.Signal) 66 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) 67 | <-sigs 68 | } 69 | 70 | func logDevice(device *discovery.Device) { 71 | log.Printf("[main] (re-) discovered %s (%s)", device.Hostname, device.MacAddress) 72 | } 73 | 74 | func printExampleConfig() { 75 | out := os.Stderr 76 | if *syslog { 77 | out = os.Stdout 78 | } 79 | fmt.Fprintf(out, "Example config file:\n\n%s\n", provisioner.ExampleYAML) 80 | } 81 | -------------------------------------------------------------------------------- /discovery/auto_discovery.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "log" 7 | "net" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | const ( 13 | discoveryPort = 10001 14 | discoveryBroadcast = "255.255.255.255" 15 | discoveryMulticast = "233.89.188.1" 16 | 17 | backoff = 1.02 18 | minDuration = 4 * time.Second 19 | maxDuration = 15 * time.Second 20 | ) 21 | 22 | var ( 23 | helloPacket = map[int][]byte{ 24 | 1: {0x01, 0x00, 0x00, 0x00}, 25 | 2: {0x02, 0x0a, 0x00, 0x00}, 26 | } 27 | ) 28 | 29 | type NotifyHandler func(*Device) 30 | 31 | type Discover struct { 32 | NotifyHandler NotifyHandler 33 | connections []*net.UDPConn 34 | incoming chan *Packet 35 | stop chan interface{} 36 | devices map[string]*Device // discovered devices 37 | mutex sync.RWMutex 38 | wg sync.WaitGroup 39 | } 40 | 41 | // AutoDiscover starts the UBNT auto discovery mechanism. It returns a 42 | // notifier channel which receives newly discovered devices (i.e. a 43 | // device already seen won't be send again). You can stop the discovery 44 | // by closing the quit channel. 45 | func AutoDiscover(notify NotifyHandler, interfaceNames ...string) (d *Discover, err error) { 46 | var locals []*net.UDPAddr 47 | 48 | for _, interfaceName := range interfaceNames { 49 | for _, addr := range interfaceAddresses(interfaceName) { 50 | locals = append(locals, &net.UDPAddr{IP: addr}) 51 | } 52 | } 53 | 54 | if len(locals) == 0 { 55 | err = fmt.Errorf("no local addresses on interface %v found", interfaceNames) 56 | return 57 | } 58 | 59 | d = &Discover{ 60 | devices: make(map[string]*Device), 61 | stop: make(chan interface{}), 62 | incoming: make(chan *Packet, 32), 63 | NotifyHandler: notify, 64 | } 65 | 66 | errs := d.listenMulticast(locals) 67 | if len(errs) > 0 { 68 | for i, e := range errs { 69 | log.Printf("Error %d: %s", i, e.Error()) 70 | } 71 | err = fmt.Errorf("Got errors, see log for details") 72 | return 73 | } 74 | 75 | go d.pingDevices() 76 | go d.handleIncoming() 77 | 78 | return d, nil 79 | } 80 | 81 | // Close closes ... 82 | func (d *Discover) Close() { 83 | close(d.stop) 84 | for _, conn := range d.connections { 85 | conn.Close() 86 | } 87 | d.wg.Wait() 88 | close(d.incoming) 89 | } 90 | 91 | func interfaceAddresses(ifaceName string) (result []net.IP) { 92 | iface, err := net.InterfaceByName(ifaceName) 93 | if err != nil { 94 | log.Fatal(err) 95 | } 96 | 97 | if iface.Flags&(net.FlagMulticast|net.FlagBroadcast) == 0 { 98 | // skip non-multicast/non-broadcast interfaces 99 | log.Fatalf("interface %s has no multicast/broadcast flags", ifaceName) 100 | } 101 | 102 | addresses, err := iface.Addrs() 103 | if err != nil { 104 | log.Fatal(err) 105 | } 106 | 107 | for _, addr := range addresses { 108 | ipnet, ok := addr.(*net.IPNet) 109 | if ok && ipnet.IP.To4() != nil { 110 | result = append(result, ipnet.IP) 111 | } 112 | } 113 | return 114 | } 115 | 116 | // pings devices and sleeps with exponential back-off (up to a maximum) 117 | func (d *Discover) pingDevices() { 118 | var duration time.Duration 119 | 120 | for { 121 | select { 122 | case <-d.stop: 123 | return 124 | case <-time.After(duration): 125 | d.pingMulticast(discoveryMulticast, helloPacket[1]) 126 | d.pingMulticast(discoveryBroadcast, helloPacket[1]) 127 | 128 | if duration.Nanoseconds() == 0 { 129 | duration = minDuration 130 | } else if duration < maxDuration { 131 | duration = time.Duration(backoff * float64(duration)) 132 | } 133 | log.Printf("[discovery] sent broadcast, will send again in %v", duration) 134 | } 135 | } 136 | } 137 | 138 | func (d *Discover) pingMulticast(addr string, msg []byte) { 139 | udpAddr := &net.UDPAddr{ 140 | IP: net.ParseIP(addr), 141 | Port: discoveryPort, 142 | } 143 | 144 | for _, conn := range d.connections { 145 | conn.WriteToUDP(msg, udpAddr) 146 | } 147 | } 148 | 149 | func (d *Discover) listenMulticast(addrs []*net.UDPAddr) (errs []error) { 150 | for _, addr := range addrs { 151 | if conn, err := net.ListenUDP("udp", addr); err != nil { 152 | errs = append(errs, err) 153 | } else { 154 | d.connections = append(d.connections, conn) 155 | } 156 | } 157 | if len(errs) == 0 { 158 | for _, conn := range d.connections { 159 | log.Printf("[discovery] listen on %s", conn.LocalAddr()) 160 | go d.packetHandler(conn) 161 | } 162 | } else { 163 | for _, conn := range d.connections { 164 | conn.Close() 165 | } 166 | } 167 | return errs 168 | } 169 | 170 | func (d *Discover) packetHandler(conn *net.UDPConn) { 171 | d.wg.Add(1) 172 | defer d.wg.Done() 173 | 174 | buf := make([]byte, 1500) 175 | for { 176 | n, _, err := conn.ReadFromUDP(buf) 177 | if err != nil { 178 | log.Print(err) 179 | return 180 | } 181 | 182 | if n <= 4 { 183 | continue // cannot possibly be a discovery response 184 | } 185 | 186 | cpy := make([]byte, 1500) 187 | copy(cpy, buf[:n]) 188 | 189 | if packet, err := ParsePacket(cpy[:n]); err == nil { 190 | d.incoming <- packet 191 | } else { 192 | log.Printf("Could not parse packet: %s\n%s\n", err.Error(), hex.Dump(cpy[:n])) 193 | } 194 | } 195 | } 196 | 197 | func (d *Discover) handleIncoming() { 198 | for packet := range d.incoming { 199 | dev := packet.Device() 200 | d.mutex.RLock() 201 | old, seen := d.devices[dev.MacAddress] 202 | d.mutex.RUnlock() 203 | 204 | if !seen || !old.RecentlySeen(1*time.Minute) { 205 | if handler := d.NotifyHandler; d != nil { 206 | handler(dev) 207 | } 208 | } 209 | 210 | d.mutex.Lock() 211 | if seen { 212 | old.Merge(dev) 213 | } else { 214 | d.devices[dev.MacAddress] = dev 215 | } 216 | d.mutex.Unlock() 217 | } 218 | } 219 | 220 | // List all discovered devices so far. Will create duplicates of the 221 | // actual device list, so that it'll be safe to work with the result. 222 | func (d *Discover) List() (list []*Device) { 223 | d.mutex.RLock() 224 | defer d.mutex.RUnlock() 225 | 226 | for _, dev := range d.devices { 227 | list = append(list, dev.Clone()) 228 | } 229 | return 230 | } 231 | 232 | // Find will search the list of discovered devices for an entry with 233 | // matching MAC address, and return a duplicate. 234 | func (d *Discover) Find(mac string) *Device { 235 | d.mutex.RLock() 236 | defer d.mutex.RUnlock() 237 | 238 | for _, dev := range d.devices { 239 | if mac == dev.MacAddress { 240 | return dev.Clone() 241 | } 242 | } 243 | return nil 244 | } 245 | -------------------------------------------------------------------------------- /discovery/device.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import "time" 4 | 5 | // Device descibes an UBNT device found on the local network 6 | type Device struct { 7 | Model string 8 | Platform string 9 | MacAddress string 10 | Hostname string 11 | Firmware string 12 | IPAddresses map[string][]string 13 | UpSince time.Time 14 | Essid string 15 | WirelessMode string 16 | LastSeenAt time.Time 17 | FirstSeenAt time.Time 18 | } 19 | 20 | // RecentlySeen tells you, whether you have seen this device in the 21 | // given time period 22 | func (d *Device) RecentlySeen(dur time.Duration) bool { 23 | return d.LastSeenAt.Add(dur).After(time.Now()) 24 | } 25 | 26 | // Merge updates this instance with the values of the other (by copying 27 | // the data), so that references to this instance are kept intact 28 | func (d *Device) Merge(other *Device) { 29 | d.Model = other.Model 30 | d.Platform = other.Platform 31 | d.MacAddress = other.MacAddress 32 | d.Hostname = other.Hostname 33 | d.Firmware = other.Firmware 34 | d.IPAddresses = make(map[string][]string) 35 | for mac, ips := range other.IPAddresses { 36 | d.IPAddresses[mac] = append(d.IPAddresses[mac], ips...) 37 | } 38 | d.UpSince = other.UpSince 39 | d.Essid = other.Essid 40 | d.WirelessMode = other.WirelessMode 41 | d.LastSeenAt = other.LastSeenAt 42 | if d.FirstSeenAt.After(other.FirstSeenAt) { 43 | d.FirstSeenAt = other.FirstSeenAt 44 | } 45 | } 46 | 47 | // Clone creates a deep-copy 48 | func (d *Device) Clone() *Device { 49 | other := &Device{FirstSeenAt: time.Now()} 50 | other.Merge(d) 51 | return other 52 | } 53 | 54 | func (d *Device) String() string { 55 | buf := "Device" 56 | buf += "\n MAC: " + d.MacAddress 57 | buf += "\n Model: " + d.Model 58 | buf += "\n Platform: " + d.Platform 59 | buf += "\n Firmware: " + d.Firmware 60 | buf += "\n Hostname: " + d.Hostname 61 | 62 | now := time.Now() 63 | if (d.UpSince != time.Time{}) { 64 | buf += "\n Booted at: " + d.UpSince.Format(time.RFC3339) 65 | buf += "\n booted: " + now.Sub(d.UpSince).String() + " ago" 66 | } 67 | 68 | buf += "\n first seen: " + now.Sub(d.FirstSeenAt).String() + " ago" 69 | buf += "\n last seen: " + now.Sub(d.FirstSeenAt).String() + " ago" 70 | 71 | for mac, ips := range d.IPAddresses { 72 | buf += "\n IP addresses on interface " + mac 73 | for _, ip := range ips { 74 | buf += "\n - " + ip 75 | } 76 | } 77 | 78 | if d.Essid != "" { 79 | buf += "\n ESSID: " + d.Essid 80 | } 81 | if d.WirelessMode != "" { 82 | buf += "\n WMode: " + d.WirelessMode 83 | } 84 | 85 | return buf 86 | } 87 | -------------------------------------------------------------------------------- /discovery/packet.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "log" 7 | "net" 8 | "time" 9 | ) 10 | 11 | // Packet holds information about a UBNT Discovery response 12 | type Packet struct { 13 | Version uint8 14 | Tags []*Tag 15 | timestamp time.Time 16 | } 17 | 18 | // ParsePacket tries to parse UPD packet data into a Packet 19 | func ParsePacket(raw []byte) (*Packet, error) { 20 | if len(raw) <= 4 { 21 | return nil, fmt.Errorf("packet data too short (%d bytes)", len(raw)) 22 | } 23 | 24 | ver := uint8(raw[0]) 25 | cmd := uint8(raw[1]) 26 | length := binary.BigEndian.Uint16(raw[2:4]) 27 | 28 | if int(length)+4 != len(raw) { 29 | return nil, fmt.Errorf("packet length mismatch (expected %d bytes, got %d)", length+4, len(raw)) 30 | } 31 | 32 | p := &Packet{ 33 | Version: ver, 34 | timestamp: time.Now(), 35 | } 36 | if err := p.parse(cmd, raw[4:length+4]); err != nil { 37 | return nil, err 38 | } 39 | return p, nil 40 | } 41 | 42 | func (p *Packet) parse(cmd uint8, data []byte) error { 43 | if !(p.Version == 1 && cmd == 0) && p.Version != 2 { 44 | return fmt.Errorf("unsupported packet ver=%d cmd=%d", p.Version, cmd) 45 | } 46 | 47 | for curr := 0; curr < len(data); { 48 | id := TagID(data[curr+0]) 49 | n := binary.BigEndian.Uint16(data[curr+1 : curr+3]) 50 | begin, end := curr+3, curr+3+int(n) 51 | 52 | tag, err := ParseTag(id, n, data[begin:end]) 53 | if err != nil { 54 | log.Print(err) 55 | } else { 56 | p.Tags = append(p.Tags, tag) 57 | } 58 | 59 | curr = end 60 | } 61 | 62 | return nil 63 | } 64 | 65 | // Device converts the packet information into a new device 66 | func (p *Packet) Device() *Device { 67 | dev := &Device{ 68 | IPAddresses: make(map[string][]string), 69 | LastSeenAt: p.timestamp, 70 | FirstSeenAt: time.Now(), 71 | } 72 | 73 | for _, t := range p.Tags { 74 | switch t.ID { 75 | case tagModelV1, tagModelV2: 76 | t.StringInto(&dev.Model) 77 | case tagPlatform: 78 | t.StringInto(&dev.Platform) 79 | case tagFirmware: 80 | t.StringInto(&dev.Firmware) 81 | case tagEssid: 82 | t.StringInto(&dev.Essid) 83 | case tagHostname: 84 | t.StringInto(&dev.Hostname) 85 | 86 | case tagMacAddress: 87 | if v, ok := t.value.(net.HardwareAddr); ok { 88 | dev.MacAddress = v.String() 89 | } 90 | case tagUptime: 91 | if v, ok := t.value.(uint32); ok { 92 | now := time.Now() 93 | dur := -1 * int(v) 94 | dev.UpSince = now.Add(time.Duration(dur) * time.Second) 95 | } 96 | case tagWmode: 97 | if v, ok := t.value.(uint8); ok { 98 | switch v { 99 | case 2: 100 | dev.WirelessMode = "Station" 101 | case 3: 102 | dev.WirelessMode = "AccessPoint" 103 | default: 104 | dev.WirelessMode = fmt.Sprintf("unknown (%#02x)", v) 105 | } 106 | } 107 | case tagIPInfo: 108 | if v, ok := t.value.(*ipInfo); ok { 109 | m := v.MacAddress.String() 110 | dev.IPAddresses[m] = append(dev.IPAddresses[m], v.IPAddress.String()) 111 | } 112 | } 113 | } 114 | return dev 115 | } 116 | -------------------------------------------------------------------------------- /discovery/packet_test.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func loadFixture(name string) []byte { 13 | fmt.Printf("Loading fixture 'testdata/%s'\n", name) 14 | buffer, err := ioutil.ReadFile("testdata/" + name) 15 | if err != nil { 16 | panic(err) 17 | } 18 | return buffer 19 | } 20 | 21 | func packetFromFixture(a *assert.Assertions, name string) *Packet { 22 | data := loadFixture(name) 23 | if !a.True(len(data) > 0, "fixture %s is empty", name) { 24 | return nil 25 | } 26 | 27 | pkt, err := ParsePacket(data) 28 | if a.Nil(err) && a.NotNil(pkt) { 29 | return pkt 30 | } 31 | return nil 32 | } 33 | 34 | func TestParsePacket(t *testing.T) { 35 | assert := assert.New(t) 36 | 37 | tt := map[string]string{ 38 | "edgerouter.dat": "04:18:d6:83:f8:ec", 39 | "nanobeam-2.dat": "80:2a:a8:64:a7:12", 40 | "nanobeam-1b.dat": "80:2a:a8:64:a7:22", 41 | "nanobeam-1a.dat": "80:2a:a8:64:a7:22", 42 | } 43 | 44 | for name, mac := range tt { 45 | dev := packetFromFixture(assert, name) 46 | for _, t := range dev.Tags { 47 | if t.ID == tagMacAddress { 48 | assert.Equal(mac, t.value.(net.HardwareAddr).String()) 49 | } 50 | } 51 | } 52 | } 53 | 54 | func TestPacketToDevice(t *testing.T) { 55 | assert := assert.New(t) 56 | 57 | dev := packetFromFixture(assert, "edgerouter.dat").Device() 58 | const mac = "04:18:d6:83:f8:ec" 59 | assert.Equal(mac, dev.MacAddress) 60 | assert.Equal("ERLite-3", dev.Platform) 61 | assert.Equal("digineo", dev.Hostname) 62 | 63 | if ips, ok := dev.IPAddresses[mac]; assert.True(ok, "expected mac %s to have IP addresses", mac) { 64 | assert.Contains(ips, "172.16.0.1") 65 | assert.Contains(ips, "172.16.2.1") 66 | assert.Contains(ips, "1.2.3.4") 67 | assert.Contains(ips, "66.66.66.66") 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /discovery/tag.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "net" 7 | ) 8 | 9 | // TagID identifies tags 10 | type TagID uint8 11 | 12 | const ( 13 | // common tags 14 | tagMacAddress = 0x01 // mac addr 15 | tagIPInfo = 0x02 // mac addr + ipv4 addr 16 | tagFirmware = 0x03 // string 17 | tagUptime = 0x0A // uint32 18 | tagHostname = 0x0B // string 19 | tagPlatform = 0x0C // string 20 | tagEssid = 0x0D // string 21 | tagWmode = 0x0E // uint8 22 | 23 | // v1 tags 24 | tagUsername = 0x06 // string 25 | tagSalt = 0x07 // ? 26 | tagRndChallenge = 0x08 // ? 27 | tagChallenge = 0x09 // ? 28 | tagWebui = 0x0F // string? 29 | tagModelV1 = 0x14 // string 30 | 31 | // v2 tags 32 | tagSequence = 0x12 // uint? 33 | tagSourceMac = 0x13 // string 34 | tagShortVersion = 0x16 // string 35 | tagDefault = 0x17 // uint8 (bool) 36 | tagLocating = 0x18 // uint8 (bool) 37 | tagDhcpc = 0x19 // uint8 (bool) 38 | tagDhcpcBound = 0x1A // uint8 (bool) 39 | tagReqFirmware = 0x1B // string 40 | tagSshdPort = 0x1C // uint32? 41 | tagModelV2 = 0x15 // string 42 | ) 43 | 44 | type tagParser func([]byte) (interface{}, error) 45 | 46 | // TagDescription annotates some meta information to a TagID 47 | type TagDescription struct { 48 | shortName string 49 | longName string 50 | byteLen int // 0 <= unspec, 0 < length < 2**16, 2**16 >= error 51 | converter tagParser 52 | } 53 | 54 | var ( 55 | tagDescriptions = map[TagID]TagDescription{ 56 | tagEssid: {"essid", "Wireless ESSID", -1, parseString}, 57 | tagFirmware: {"firmware", "Firmware", -1, parseString}, 58 | tagHostname: {"hostname", "Hostname", -1, parseString}, 59 | tagIPInfo: {"ipinfo", "MAC/IP mapping", 10, parseIPInfo}, 60 | tagMacAddress: {"hwaddr", "Hardware/MAC address", 6, parseMacAddress}, 61 | tagModelV1: {"model.v1", "Model name", -1, parseString}, 62 | tagModelV2: {"model.v2", "Model name", -1, parseString}, 63 | tagPlatform: {"platform", "Platform information", -1, parseString}, 64 | tagShortVersion: {"short-ver", "Short version", -1, parseString}, 65 | tagSshdPort: {"sshd-port", "SSH port", 2, parseUint16}, 66 | tagUptime: {"uptime", "Uptime", 4, parseUint32}, 67 | tagUsername: {"username", "Username", -1, parseString}, 68 | tagWebui: {"webui", "URL for Web-UI", -1, nil}, 69 | tagWmode: {"wmode", "Wireless mode", 1, parseUint8}, 70 | 71 | // unknown or not yet found in the wild 72 | tagChallenge: {"challenge", "(?)", -1, nil}, 73 | tagDefault: {"default", "(bool)", 1, parseBool}, 74 | tagDhcpc: {"dhcpc", "(bool)", 1, parseBool}, 75 | tagDhcpcBound: {"dhcpc-bound", "(bool)", 1, parseBool}, 76 | tagLocating: {"locating", "(bool)", 1, parseBool}, 77 | tagReqFirmware: {"req-firmware", "(string)", -1, parseString}, 78 | tagRndChallenge: {"rnd-challenge", "(?)", -1, nil}, 79 | tagSalt: {"salt", "(?)", -1, nil}, 80 | tagSequence: {"seq", "(uint?)", -1, nil}, 81 | tagSourceMac: {"source-mac", "(?)", -1, nil}, 82 | } 83 | ) 84 | 85 | // Tag describes a key value pair 86 | type Tag struct { 87 | ID TagID 88 | description *TagDescription 89 | value interface{} 90 | } 91 | 92 | type ipInfo struct { 93 | MacAddress net.HardwareAddr 94 | IPAddress net.IP 95 | } 96 | 97 | // ParseTag converts a byte stream (i.e. an UDP packet slice) into a Tag 98 | func ParseTag(id TagID, n uint16, raw []byte) (*Tag, error) { 99 | t := &Tag{ID: id} 100 | 101 | // check if known, unknown, or not yet seen 102 | if d, ok := tagDescriptions[t.ID]; ok { 103 | t.description = &d 104 | } else { 105 | t.description = &TagDescription{ 106 | shortName: "unknown", 107 | longName: fmt.Sprintf("unknown (%#x)", t.ID), 108 | } 109 | } 110 | 111 | if t.description.byteLen > 0 { 112 | if t.description.byteLen != int(n) { 113 | return nil, fmt.Errorf( 114 | "length mismatch for tag %s (expected %d bytes, got %d)", 115 | t.description.shortName, t.description.byteLen, n, 116 | ) 117 | } 118 | if len(raw) < int(n) { 119 | return nil, fmt.Errorf( 120 | "not enough data for tag %s (expected %d bytes, got %d)", 121 | t.description.shortName, n, len(raw), 122 | ) 123 | } 124 | } 125 | 126 | if val, err := t.description.convert(raw); err == nil { 127 | t.value = val 128 | } else { 129 | return nil, err 130 | } 131 | 132 | return t, nil 133 | } 134 | 135 | // Name returns the short tag name 136 | func (t *Tag) Name() string { 137 | return t.description.shortName 138 | } 139 | 140 | // Description returns the long tag name 141 | func (t *Tag) Description() string { 142 | return t.description.longName 143 | } 144 | 145 | // StringInto tries to update the given string reference with a type 146 | // asserted value (it doesn't perform an update, if the type assertion 147 | // fails) 148 | func (t *Tag) StringInto(ref *string) { 149 | if v, ok := t.value.(string); ok { 150 | *ref = v 151 | } 152 | } 153 | 154 | func (td *TagDescription) convert(data []byte) (interface{}, error) { 155 | if td.converter == nil { 156 | return fmt.Sprintf("len:%d<%x>", len(data), data), nil 157 | } 158 | return td.converter(data) 159 | } 160 | 161 | func parseString(data []byte) (interface{}, error) { 162 | return string(data), nil 163 | } 164 | 165 | func parseBool(data []byte) (interface{}, error) { 166 | return uint8(data[0]) != 0, nil 167 | } 168 | 169 | func parseUint8(data []byte) (interface{}, error) { 170 | return uint8(data[0]), nil 171 | } 172 | 173 | func parseUint16(data []byte) (interface{}, error) { 174 | return binary.BigEndian.Uint16(data[0:2]), nil 175 | } 176 | 177 | func parseUint32(data []byte) (interface{}, error) { 178 | return binary.BigEndian.Uint32(data[0:4]), nil 179 | } 180 | 181 | func parseMacAddress(data []byte) (interface{}, error) { 182 | return net.HardwareAddr(data[0:6]), nil 183 | } 184 | 185 | func parseIPInfo(data []byte) (interface{}, error) { 186 | return &ipInfo{ 187 | MacAddress: net.HardwareAddr(data[0:6]), 188 | IPAddress: net.IP(data[6:10]), 189 | }, nil 190 | } 191 | -------------------------------------------------------------------------------- /discovery/tag_test.go: -------------------------------------------------------------------------------- 1 | package discovery 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func prepareTestcase(a *assert.Assertions, id TagID, dataLen int, data []byte) *Tag { 10 | a.Equal(dataLen+3, len(data)) 11 | tag, err := ParseTag(id, uint16(dataLen), data[3:]) 12 | 13 | a.Nil(err) 14 | a.NotNil(tag) 15 | a.Equal(id, tag.ID) 16 | return tag 17 | } 18 | 19 | func TestParseUptimeTag(t *testing.T) { 20 | assert := assert.New(t) 21 | 22 | tag := prepareTestcase(assert, tagUptime, 4, []byte{ 23 | 0x0a, 0x00, 0x04, // header+len 24 | 0x01, 0x02, 0x03, 0x04, // uptime 25 | }) 26 | 27 | val, ok := tag.value.(uint32) 28 | assert.True(ok) 29 | assert.Equal(uint32(16909060), val) 30 | assert.Equal("uptime", tag.Name()) 31 | } 32 | 33 | func TestParseIPInfoTag(t *testing.T) { 34 | assert := assert.New(t) 35 | 36 | tag := prepareTestcase(assert, tagIPInfo, 6+4, []byte{ 37 | 0x02, 0x00, 0x0a, // header+len 38 | 0x04, 0x18, 0xd6, 0x83, 0xf8, 0xec, // mac 39 | 172, 16, 0, 1, // ip 40 | }) 41 | 42 | val, ok := tag.value.(*ipInfo) 43 | assert.True(ok) 44 | assert.Equal("04:18:d6:83:f8:ec", val.MacAddress.String()) 45 | assert.Equal("172.16.0.1", val.IPAddress.String()) 46 | } 47 | 48 | func TestParseUnknownTag(t *testing.T) { 49 | assert := assert.New(t) 50 | 51 | tag := prepareTestcase(assert, TagID(0x42), 3, []byte{ 52 | 0x02, 0x00, 0x01, // header+len 53 | 0xc0, 0xff, 0xee, // 0xC0FFEE 54 | }) 55 | 56 | val, ok := tag.value.(string) 57 | assert.True(ok) 58 | assert.Equal("len:3", val) 59 | assert.Equal("unknown", tag.Name()) 60 | assert.Equal("unknown (0x42)", tag.Description()) 61 | } 62 | -------------------------------------------------------------------------------- /discovery/testdata/edgerouter.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digineo/ubnt-tools/178e1e707a490fc4ec270eae29bafe0eb216ab16/discovery/testdata/edgerouter.dat -------------------------------------------------------------------------------- /discovery/testdata/nanobeam-1a.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digineo/ubnt-tools/178e1e707a490fc4ec270eae29bafe0eb216ab16/discovery/testdata/nanobeam-1a.dat -------------------------------------------------------------------------------- /discovery/testdata/nanobeam-1b.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digineo/ubnt-tools/178e1e707a490fc4ec270eae29bafe0eb216ab16/discovery/testdata/nanobeam-1b.dat -------------------------------------------------------------------------------- /discovery/testdata/nanobeam-2.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digineo/ubnt-tools/178e1e707a490fc4ec270eae29bafe0eb216ab16/discovery/testdata/nanobeam-2.dat -------------------------------------------------------------------------------- /provisioner/configuration.go: -------------------------------------------------------------------------------- 1 | package provisioner 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "math" 7 | "os" 8 | "path/filepath" 9 | 10 | "github.com/digineo/goldflags" 11 | "github.com/digineo/ubnt-tools/discovery" 12 | pssh "github.com/digineo/ubnt-tools/provisioner/ssh" 13 | "golang.org/x/crypto/ssh" 14 | "gopkg.in/yaml.v2" 15 | ) 16 | 17 | // ExampleYAML provides a complete set of config options in YAML format 18 | // and can be used for documentation purposes. 19 | const ExampleYAML = ` --- 20 | # Notes on path values (config_directory, firmware_directory, web.templates): 21 | # 22 | # - relative paths (i.e. those starting with "./") will be resolved relative 23 | # to the directory of this config file 24 | # - a "~/" prefix resolves to the home directory of the user running the 25 | # provisioner 26 | 27 | # Where do we find device specific system.cfg files? These files must be 28 | # named "aabbccddeeff.cfg", where aabbccddeeff is the MAC address of the 29 | # device (i.e. lowercase, without seperator). 30 | config_directory: /tmp/ubnt-config/configs 31 | 32 | # Where do we find the firmware images? 33 | firmware_directory: /tmp/ubnt-config/firmwares 34 | 35 | # This mapping describes safe upgrade paths. As key use the basename of the 36 | # firmware image (located in the firmware_directory) and as values provide 37 | # a list of firmware version identifiers found in the wild. 38 | safe_upgrade_paths: 39 | "XC.v7.2.4.31259.160714.1715.bin": 40 | - "XC.qca955x.v7.2.1.30741.160412.1342" 41 | 42 | # This must be a list of interface names with broadcast and multicast 43 | # capabilities. 44 | interfaces: 45 | - eth0 46 | 47 | # When accessing the devices via SSH, the authentication methods declared 48 | # here are tried in order. This sample lists all available types: 49 | ssh: 50 | - type: keyfile 51 | path: ~/.ssh/id_rsa 52 | password: foobar # required if keyfile is password protected 53 | - type: password 54 | password: super-secret 55 | - type: ssh-agent # try ssh-agent (needs SSH_AUTH_SOCK env var) 56 | 57 | web: 58 | # The internal webserver will bind to this address. You really should not 59 | # use a publicly accessible IP address. 60 | host: 127.0.0.1 61 | port: 8080 62 | ` 63 | 64 | type sshAuthMethod struct { 65 | Type string `yaml:"type"` 66 | Password string `yaml:"password"` 67 | Path string `yaml:"path"` 68 | } 69 | 70 | // Configuration maps config options to values 71 | type Configuration struct { 72 | ConfigDirectory string `yaml:"config_directory"` 73 | FirmwareDirectory string `yaml:"firmware_directory"` 74 | SafeUpgradePaths map[string][]string `yaml:"safe_upgrade_paths"` 75 | reverseUpgradePaths map[string]string // inferred from SafeUpgradePaths 76 | InterfaceNames []string `yaml:"interfaces"` 77 | 78 | SSHAuthMethods []sshAuthMethod `yaml:"ssh"` 79 | sshAuthMethods []ssh.AuthMethod 80 | 81 | Web struct { 82 | Host string `yaml:"host"` 83 | Port int `yaml:"port"` 84 | } `yaml:"web"` 85 | 86 | autoDiscoverer *discovery.Discover 87 | devices *deviceCache 88 | } 89 | 90 | // LoadConfig reads a YAML file and converts it to a config object 91 | func LoadConfig(fileName string) (c *Configuration, errs []error) { 92 | c = &Configuration{} 93 | 94 | file, err := ioutil.ReadFile(fileName) 95 | if err != nil { 96 | errs = append(errs, err) 97 | return 98 | } 99 | if err := yaml.Unmarshal(file, &c); err != nil { 100 | errs = append(errs, err) 101 | return 102 | } 103 | 104 | // the following errors are recoverable 105 | 106 | base := filepath.Dir(fileName) 107 | if dirErrs := checkDirectory("config_directory", base, &c.ConfigDirectory); len(dirErrs) > 0 { 108 | errs = append(errs, dirErrs...) 109 | } 110 | if dirErrs := checkDirectory("firmware_directory", base, &c.FirmwareDirectory); len(dirErrs) > 0 { 111 | errs = append(errs, dirErrs...) 112 | } 113 | 114 | c.reverseUpgradePaths = make(map[string]string) 115 | for target, sources := range c.SafeUpgradePaths { 116 | for _, source := range sources { 117 | if _, exists := c.reverseUpgradePaths[source]; exists { 118 | errs = append(errs, fmt.Errorf("multiple upgrade paths for %s detected", source)) 119 | continue 120 | } 121 | c.reverseUpgradePaths[source] = target 122 | } 123 | } 124 | 125 | if len(c.InterfaceNames) == 0 { 126 | errs = append(errs, fmt.Errorf("missing option interfaces, at least one name (or '*') must be given")) 127 | } 128 | 129 | if c.Web.Port <= 0 || c.Web.Port > math.MaxUint16 { 130 | errs = append(errs, fmt.Errorf("config option web.port out of range")) 131 | } 132 | 133 | c.sshAuthMethods = make([]ssh.AuthMethod, 0, len(c.SSHAuthMethods)) 134 | for _, m := range c.SSHAuthMethods { 135 | switch m.Type { 136 | case "", "password": // Type=="" is an alias for password 137 | if m.Password != "" { 138 | c.sshAuthMethods = append(c.sshAuthMethods, ssh.Password(m.Password)) 139 | } 140 | case "ssh-agent": 141 | if a := pssh.Agent(); a != nil { 142 | c.sshAuthMethods = append(c.sshAuthMethods, a) 143 | } 144 | case "keyfile": 145 | if key, ok := pssh.ReadPrivateKey(m.Path, m.Password); ok { 146 | c.sshAuthMethods = append(c.sshAuthMethods, key) 147 | } 148 | default: 149 | errs = append(errs, fmt.Errorf("unknown auth method %q", m.Type)) 150 | } 151 | } 152 | 153 | if len(errs) == 0 { 154 | c.devices = &deviceCache{ 155 | list: make(map[string]*Device), 156 | } 157 | } 158 | 159 | return 160 | } 161 | 162 | func checkDirectory(name string, baseDir string, dir *string) (errs []error) { 163 | deref := *dir 164 | if deref == "" { 165 | errs = append(errs, fmt.Errorf("missing %s config option", name)) 166 | return 167 | } 168 | 169 | if expanded, err := goldflags.ExpandPath(deref, baseDir); err == nil { 170 | deref = expanded 171 | } else { 172 | errs = append(errs, err) 173 | return 174 | } 175 | 176 | if _, err := os.Stat(deref); err != nil { 177 | if os.IsNotExist(err) { 178 | errs = append(errs, fmt.Errorf("directory %s (%s) doesn't exist", name, deref)) 179 | } else { 180 | errs = append(errs, err) 181 | } 182 | } 183 | 184 | *dir = deref 185 | return 186 | } 187 | 188 | // FirmwareImages prepares a list of firmware names 189 | func (c *Configuration) FirmwareImages() []string { 190 | return goldflags.ReadDir(c.FirmwareDirectory) 191 | } 192 | 193 | // DeviceConfigs prepares a list of device configuration names 194 | func (c *Configuration) DeviceConfigs() []string { 195 | return goldflags.ReadDir(c.ConfigDirectory) 196 | } 197 | -------------------------------------------------------------------------------- /provisioner/device.go: -------------------------------------------------------------------------------- 1 | package provisioner 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "reflect" 8 | "strings" 9 | "sync" 10 | "time" 11 | 12 | "github.com/digineo/ubnt-tools/discovery" 13 | pssh "github.com/digineo/ubnt-tools/provisioner/ssh" 14 | "golang.org/x/crypto/ssh" 15 | ) 16 | 17 | // Device is a wrapper around discovery.Device, and annotates a primary 18 | // IP address, the latest available Firmware and/or system config. 19 | // 20 | // It also knows how to communicate with the device. 21 | type Device struct { 22 | *discovery.Device 23 | IPAddress string 24 | firmwarePath string 25 | systemConfigPath string 26 | RebootedAt time.Time 27 | 28 | authMethods []ssh.AuthMethod 29 | 30 | busy bool 31 | busyMsg string 32 | busyMtx sync.RWMutex 33 | } 34 | 35 | // CanUpgrade indicates, whether new firmware image is available 36 | func (d *Device) CanUpgrade() bool { 37 | return d.firmwarePath != "" 38 | } 39 | 40 | // HasConfig indicates, whether system config is available 41 | func (d *Device) HasConfig() bool { 42 | return d.systemConfigPath != "" 43 | } 44 | 45 | // IsBusy states whether or not this Device is ready to receive commands. 46 | func (d *Device) IsBusy() bool { 47 | d.busyMtx.RLock() 48 | defer d.busyMtx.RUnlock() 49 | return d.busy 50 | } 51 | 52 | func (d *Device) setBusy(msg string) error { 53 | d.busyMtx.Lock() 54 | defer d.busyMtx.Unlock() 55 | if d.busy { 56 | return fmt.Errorf("Device is busy (%s)", d.busyMsg) 57 | } 58 | d.busy = true 59 | d.busyMsg = msg 60 | return nil 61 | } 62 | 63 | // Status gives a human-readable status information about this device. The 64 | // status may be "idle", "upgrading", "provisioning", or "rebooting". Note 65 | // that this status text only indicates a current event, when this device 66 | // is actually marked busy. Otherwise, you'll get the _last_ state. 67 | func (d *Device) Status() string { 68 | if d.IsBusy() { 69 | return d.busyMsg 70 | } 71 | if d.RebootedAt.After(d.LastSeenAt) { 72 | return "rebooting" 73 | } 74 | return "idle" 75 | } 76 | 77 | // Provision updates the system config on the remote device. 78 | func (d *Device) Provision() error { 79 | if !d.HasConfig() { 80 | return fmt.Errorf("No device configuration found for %s", d.MacAddress) 81 | } 82 | 83 | return d.withSSHClient("provisioning", d.doProvision) 84 | } 85 | 86 | // runs in background-goroutine 87 | func (d *Device) doProvision(c *ssh.Client) { 88 | d.log("Start provisioning...") 89 | var sessionError error 90 | 91 | remotePath := "/tmp/system.cfg" 92 | if sessionError = pssh.UploadFile(c, d.systemConfigPath, remotePath); sessionError != nil { 93 | d.log("Upload failed: %v", sessionError) 94 | return 95 | } 96 | d.log("local(%s) -> remote(%s) 100%%", d.systemConfigPath, remotePath) 97 | 98 | if _, sessionError = pssh.ExecuteCommand(c, "/usr/bin/cfgmtd -w -p /etc/"); sessionError != nil { 99 | d.log("Could not save configuration: %v", sessionError) 100 | return 101 | } 102 | d.log("Configuration saved") 103 | 104 | if _, sessionError = pssh.ExecuteCommand(c, "/usr/bin/reboot"); sessionError != nil { 105 | d.log("Reboot failed: %v", sessionError) 106 | return 107 | } 108 | d.markReboot(5 * time.Second) 109 | d.log("Reboot succeeded") 110 | } 111 | 112 | // Upgrade uploads the firmware image to the remote device and starts 113 | // the upgrade process. 114 | func (d *Device) Upgrade() error { 115 | if !d.CanUpgrade() { 116 | return fmt.Errorf("cannot safely upgrade device %s", d.MacAddress) 117 | } 118 | return d.withSSHClient("upgrading", d.doUpgrade) 119 | } 120 | 121 | func (d *Device) doUpgrade(c *ssh.Client) { 122 | d.log("Start upgrading...") 123 | var sessionError error 124 | 125 | remotePath := "/tmp/fwupdate.bin" 126 | if sessionError = pssh.UploadFile(c, d.firmwarePath, remotePath); sessionError != nil { 127 | d.log("Upload failed: %v", sessionError) 128 | return 129 | } 130 | d.log("local(%s) -> remote(%s) 100%%", d.firmwarePath, remotePath) 131 | 132 | _, sessionError = pssh.ExecuteCommand(c, "/usr/bin/ubntbox fwupdate.real -c "+remotePath) 133 | if sessionError != nil { 134 | d.log("Firmware check failed: %v", sessionError) 135 | return 136 | } 137 | d.log("Firmware check succeeded") 138 | 139 | sessionError = pssh.WithinSession(c, func(s *ssh.Session) error { 140 | reader, err := s.StderrPipe() 141 | if err != nil { 142 | return err 143 | } 144 | 145 | if err := s.Start("/usr/bin/ubntbox fwupdate.real -m " + remotePath); err != nil { 146 | return err 147 | } 148 | 149 | bufreader := bufio.NewReader(reader) 150 | for { 151 | line, err := bufreader.ReadString('\n') 152 | d.log("remote: |%s|", strings.TrimRight(line, "\n")) 153 | if err != nil { 154 | return err 155 | } 156 | 157 | if strings.HasPrefix(line, "Done") { 158 | time.Sleep(15 * time.Second) 159 | s.Close() 160 | return nil 161 | } 162 | } 163 | }) 164 | 165 | if sessionError != nil { 166 | d.log("Could not upgrade firmware: %v", sessionError) 167 | return 168 | } 169 | d.markReboot(30 * time.Second) 170 | d.log("Firmware upgrade succeeded") 171 | } 172 | 173 | // Reboot issues a reboot on the device. 174 | func (d *Device) Reboot() error { 175 | return d.withSSHClient("rebooting", func(c *ssh.Client) { 176 | if _, sessionError := pssh.ExecuteCommand(c, "/usr/bin/reboot"); sessionError != nil { 177 | d.log("Reboot failed: %v", sessionError) 178 | return 179 | } 180 | d.markReboot(5 * time.Second) 181 | d.log("Reboot succeeded") 182 | }) 183 | } 184 | 185 | func (d *Device) withSSHClient(msg string, callback func(*ssh.Client)) error { 186 | if err := d.setBusy(msg); err != nil { 187 | return err 188 | } 189 | 190 | client := d.getSSHClient() 191 | if client == nil { 192 | d.busy = false 193 | return fmt.Errorf("Could not obtain SSH client") 194 | } 195 | d.log("Got a client") 196 | 197 | go func() { 198 | callback(client) 199 | d.log("Callback succeeded") 200 | d.busy = false 201 | client.Close() 202 | }() 203 | 204 | return nil 205 | } 206 | 207 | func (d *Device) getSSHClient() *ssh.Client { 208 | clientConfig := &ssh.ClientConfig{ 209 | Timeout: 2 * time.Second, 210 | User: "ubnt", 211 | HostKeyCallback: ssh.InsecureIgnoreHostKey(), 212 | } 213 | 214 | for i, m := range d.authMethods { 215 | clientConfig.Auth = []ssh.AuthMethod{m} 216 | authType := reflect.TypeOf(m).String() 217 | 218 | client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", d.IPAddress), clientConfig) 219 | if err != nil { 220 | d.log("(try %d) %s authentication failed with %v", i+1, authType, err) 221 | continue 222 | } 223 | 224 | d.log("(try %d) %s authentication succeeded", i+1, authType) 225 | return client 226 | } 227 | 228 | return nil 229 | } 230 | 231 | // Prints a log message prefixed with "[Device aa:bb:cc:dd:ee:ff]". 232 | func (d *Device) log(message string, v ...interface{}) { 233 | log.Printf(fmt.Sprintf("[Device %s] %s", d.MacAddress, message), v...) 234 | } 235 | 236 | // markReboot sets the RebootedAt flat to a time in the future. This is 237 | // used to detect reboot cycles, which may not be effective immediately, 238 | // and hence makes the device misleadingly available/idle in the UI. 239 | func (d *Device) markReboot(inFuture time.Duration) { 240 | d.RebootedAt = time.Now().Add(inFuture) 241 | } 242 | -------------------------------------------------------------------------------- /provisioner/device_cache.go: -------------------------------------------------------------------------------- 1 | package provisioner 2 | 3 | import ( 4 | "log" 5 | "path/filepath" 6 | "strings" 7 | "sync" 8 | "time" 9 | 10 | "github.com/digineo/goldflags" 11 | "github.com/digineo/ubnt-tools/discovery" 12 | ) 13 | 14 | type deviceCache struct { 15 | list map[string]*Device 16 | updated time.Time 17 | sync.RWMutex 18 | } 19 | 20 | // StartAutoDiscover starts the UBNT auto discovery mechanism. See 21 | // discovery.AutoDiscover for details. 22 | func (c *Configuration) StartAutoDiscover(notify discovery.NotifyHandler) (d *discovery.Discover, err error) { 23 | d, err = discovery.AutoDiscover(notify, c.InterfaceNames...) 24 | if err == nil { 25 | c.autoDiscoverer = d 26 | } 27 | return 28 | } 29 | 30 | // GetDevices returns an array with all discovered devices. 31 | func (c *Configuration) GetDevices() (list []*Device) { 32 | c.updateCache() 33 | c.devices.RLock() 34 | for _, dev := range c.devices.list { 35 | list = append(list, dev) 36 | } 37 | c.devices.RUnlock() 38 | return 39 | } 40 | 41 | // FindDevice searches the list of discovered devices and returns a 42 | // pointer to it (or nil, if we can't find it). 43 | func (c *Configuration) FindDevice(mac string) *Device { 44 | c.updateCache() 45 | c.devices.RLock() 46 | defer c.devices.RUnlock() 47 | 48 | if dev, found := c.devices.list[mac]; found { 49 | return dev 50 | } 51 | return nil 52 | } 53 | 54 | func (c *Configuration) updateCache() { 55 | c.devices.Lock() 56 | defer c.devices.Unlock() 57 | 58 | if time.Since(c.devices.updated) < 1*time.Second { 59 | return 60 | } 61 | if c.autoDiscoverer == nil { 62 | log.Printf("[device cache] no auto-discoverer found") 63 | return 64 | } 65 | 66 | log.Printf("[device cache] updating") 67 | discovered := c.autoDiscoverer.List() 68 | seen := make(map[string]int) // IP address -> # of devices with this address 69 | list := c.devices.list // mac -> Device 70 | 71 | for _, dev := range discovered { 72 | for _, addrs := range dev.IPAddresses { 73 | for _, ip := range addrs { 74 | seen[ip]++ 75 | } 76 | } 77 | if old, found := list[dev.MacAddress]; found { 78 | old.Device.Merge(dev) 79 | old.firmwarePath = "" 80 | old.systemConfigPath = "" 81 | } else { 82 | list[dev.MacAddress] = &Device{Device: dev} 83 | } 84 | } 85 | 86 | // inject additional information 87 | for _, dev := range list { 88 | // unique IP addresses 89 | for _, addrs := range dev.IPAddresses { 90 | dev.IPAddress = "" 91 | for _, ip := range addrs { 92 | if ip == "192.168.1.20" { 93 | continue 94 | } 95 | if dev.IPAddress == "" && seen[ip] == 1 { 96 | dev.IPAddress = ip 97 | } 98 | } 99 | } 100 | 101 | // Path to system config 102 | if cfgPath := filepath.Join(c.ConfigDirectory, sanitizeMac(dev.MacAddress)+".cfg"); goldflags.PathExist(cfgPath) { 103 | dev.systemConfigPath = cfgPath 104 | } 105 | 106 | // Path to firmware 107 | if target, ok := c.reverseUpgradePaths[dev.Firmware]; ok { 108 | if fwPath := filepath.Join(c.FirmwareDirectory, target); goldflags.PathExist(fwPath) { 109 | dev.firmwarePath = fwPath 110 | } 111 | } 112 | 113 | // SSH auth methods 114 | dev.authMethods = c.sshAuthMethods 115 | } 116 | 117 | c.devices.updated = time.Now() 118 | return 119 | } 120 | 121 | func sanitizeMac(mac string) string { 122 | return strings.ToLower(strings.Replace(mac, ":", "", -1)) 123 | } 124 | -------------------------------------------------------------------------------- /provisioner/ssh/ssh.go: -------------------------------------------------------------------------------- 1 | package ssh 2 | 3 | import ( 4 | "bytes" 5 | "crypto/x509" 6 | "fmt" 7 | "io/ioutil" 8 | "log" 9 | "net" 10 | "os" 11 | "path/filepath" 12 | 13 | "encoding/pem" 14 | 15 | "strings" 16 | 17 | "github.com/digineo/goldflags" 18 | "golang.org/x/crypto/ssh" 19 | "golang.org/x/crypto/ssh/agent" 20 | ) 21 | 22 | type sshSessionCallback func(*ssh.Session) error 23 | 24 | // Agent tries to connect with the ssh-agent 25 | func Agent() ssh.AuthMethod { 26 | sock := os.Getenv("SSH_AUTH_SOCK") 27 | if sock == "" { 28 | log.Printf("[ssh.Agent] SSH_AUTH_SOCK is not defined or empty") 29 | return nil 30 | } 31 | 32 | sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) 33 | if err == nil { 34 | log.Printf("[ssh.Agent] Couldn't connect to SSH agent: %v", err) 35 | return nil 36 | } 37 | 38 | agent := agent.NewClient(sshAgent) 39 | keys, err := agent.List() 40 | if err != nil { 41 | log.Printf("[ssh.Agent] Listing keys error'ed: %v", err) 42 | } else { 43 | log.Printf("Keys: %v", keys) 44 | } 45 | return ssh.PublicKeysCallback(agent.Signers) 46 | } 47 | 48 | // ReadPrivateKey tries to read an SSH private key file. 49 | func ReadPrivateKey(keyPath, password string) (auth ssh.AuthMethod, ok bool) { 50 | keyFile, err := goldflags.ExpandPath(keyPath) 51 | if err != nil { 52 | log.Printf("[ssh.ReadPrivateKey] Could not expand %s: %v", keyPath, err) 53 | return 54 | } 55 | 56 | if !goldflags.PathExist(keyFile) { 57 | log.Printf("[ssh.ReadPrivateKey] Keyfile %s not found", keyFile) 58 | return 59 | } 60 | 61 | keyPEM, err := ioutil.ReadFile(keyFile) 62 | if err != nil { 63 | log.Printf("[ssh.ReadPrivateKey] Could not read %s: %v", keyFile, err) 64 | return 65 | } 66 | 67 | block, _ := pem.Decode(keyPEM) 68 | if block == nil { 69 | log.Printf("[ssh.ReadPrivateKey] No key found in %s", keyFile) 70 | return 71 | } 72 | 73 | keyFrom := block.Bytes 74 | if strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") { 75 | keyFrom, err = x509.DecryptPEMBlock(block, []byte(password)) 76 | if err != nil { 77 | log.Printf("[ssh.ReadPrivateKey] Error decrypting %s: %v", keyFile, err) 78 | return 79 | } 80 | } 81 | 82 | key, err := getKey(block.Type, keyFrom) 83 | if err != nil { 84 | log.Printf("[ssh.ReadPrivateKey] %s: %v", keyFile, err) 85 | return 86 | } 87 | 88 | sign, err := ssh.NewSignerFromKey(key) 89 | if err != nil { 90 | log.Printf("[ssh.ReadPrivateKey] %s: %v", keyFile, err) 91 | return 92 | } 93 | return ssh.PublicKeys(sign), true 94 | } 95 | 96 | func getKey(typ string, b []byte) (interface{}, error) { 97 | switch typ { 98 | case "RSA PRIVATE KEY": 99 | return x509.ParsePKCS1PrivateKey(b) 100 | case "EC PRIVATE KEY": 101 | return x509.ParseECPrivateKey(b) 102 | case "DSA PRIVATE KEY": 103 | return ssh.ParseDSAPrivateKey(b) 104 | default: 105 | return nil, fmt.Errorf("unsupported key type %q", typ) 106 | } 107 | } 108 | 109 | // WithinSession executes a callback function within a new SSH session of 110 | // the given client. 111 | func WithinSession(client *ssh.Client, callback sshSessionCallback) error { 112 | session, err := client.NewSession() 113 | if err != nil { 114 | return err 115 | } 116 | defer session.Close() 117 | return callback(session) 118 | } 119 | 120 | // UploadFile uploads a local file to the remote. Please avoid funky 121 | // remote file names, since there's no protection against command injection 122 | func UploadFile(client *ssh.Client, localName string, remoteName string) error { 123 | return WithinSession(client, func(s *ssh.Session) error { 124 | writer, err := s.StdinPipe() 125 | if err != nil { 126 | return err 127 | } 128 | defer writer.Close() 129 | 130 | buf, err := ioutil.ReadFile(localName) 131 | if err != nil { 132 | return err 133 | } 134 | log.Printf("[ssh.UploadFile local-file] %s, %d bytes", localName, len(buf)) 135 | 136 | rdir := filepath.Dir(remoteName) 137 | log.Printf("[ssh.UploadFile remote-dir] %s", rdir) 138 | 139 | rfile := filepath.Base(remoteName) 140 | log.Printf("[ssh.UploadFile remote-file] %s", rfile) 141 | 142 | var so, se bytes.Buffer 143 | s.Stdout = &so 144 | s.Stderr = &se 145 | 146 | cmd := fmt.Sprintf("/usr/bin/scp -t %s", rdir) // danger! 147 | log.Printf("[ssh.UploadFile command] %s", cmd) 148 | 149 | if err := s.Start(cmd); err != nil { 150 | return err 151 | } 152 | 153 | content := string(buf) 154 | log.Printf("[ssh.UploadFile uploading] %d bytes", len(content)) 155 | 156 | // https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works 157 | fmt.Fprintln(writer, "C0644", len(content), rfile) 158 | fmt.Fprint(writer, content) 159 | fmt.Fprint(writer, "\x00") 160 | writer.Close() 161 | 162 | if err := s.Wait(); err != nil { 163 | log.Println("[ssh.UploadFile] waiting failed") 164 | log.Printf("[ssh.UploadFile stderr] %s", se.String()) 165 | log.Printf("[ssh.UploadFile stdout] %s", so.String()) 166 | return err 167 | } 168 | 169 | return nil 170 | }) 171 | } 172 | 173 | // ExecuteCommand executes a command in a new SSH session. 174 | func ExecuteCommand(client *ssh.Client, cmd string) (string, error) { 175 | var output string 176 | sessionErr := WithinSession(client, func(s *ssh.Session) error { 177 | var so, se bytes.Buffer 178 | s.Stdout = &so 179 | s.Stderr = &se 180 | 181 | if err := s.Run(cmd); err != nil { 182 | log.Printf("[executeCommand] %s failed", cmd) 183 | log.Printf("[executeCommand stderr] %s", se.String()) 184 | log.Printf("[executeCommand stdout] %s", so.String()) 185 | return err 186 | } 187 | 188 | output = se.String() 189 | return nil 190 | }) 191 | 192 | return output, sessionErr 193 | } 194 | -------------------------------------------------------------------------------- /provisioner/ui/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["es2015", { "modules": false }] 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /provisioner/ui/.bootstraprc: -------------------------------------------------------------------------------- 1 | --- 2 | # Output debugging info 3 | # loglevel: debug 4 | 5 | # Major version of Bootstrap: 3 or 4 6 | bootstrapVersion: 3 7 | 8 | # If Bootstrap version 3 is used - turn on/off custom icon font path 9 | useCustomIconFontPath: false 10 | 11 | # Webpack loaders, order matters 12 | styleLoaders: 13 | - style 14 | - css 15 | - sass 16 | 17 | # Extract styles to stand-alone css file 18 | # Different settings for different environments can be used, 19 | # It depends on value of NODE_ENV environment variable 20 | # This param can also be set in webpack config: 21 | # entry: 'bootstrap-loader/extractStyles' 22 | extractStyles: false 23 | # env: 24 | # development: 25 | # extractStyles: false 26 | # production: 27 | # extractStyles: true 28 | 29 | 30 | # Customize Bootstrap variables that get imported before the original Bootstrap variables. 31 | # Thus, derived Bootstrap variables can depend on values from here. 32 | # See the Bootstrap _variables.scss file for examples of derived Bootstrap variables. 33 | # 34 | # preBootstrapCustomizations: ./path/to/bootstrap/pre-customizations.scss 35 | 36 | 37 | # This gets loaded after bootstrap/variables is loaded 38 | # Thus, you may customize Bootstrap variables 39 | # based on the values established in the Bootstrap _variables.scss file 40 | # 41 | # bootstrapCustomizations: ./path/to/bootstrap/customizations.scss 42 | 43 | 44 | # Import your custom styles here 45 | # Usually this endpoint-file contains list of @imports of your application styles 46 | # 47 | # appStyles: ./path/to/your/app/styles/endpoint.scss 48 | 49 | 50 | ### Bootstrap styles 51 | styles: 52 | 53 | # Mixins 54 | mixins: true 55 | 56 | # Reset and dependencies 57 | normalize: true 58 | print: false 59 | glyphicons: false 60 | 61 | # Core CSS 62 | scaffolding: true 63 | type: true 64 | code: true 65 | grid: true 66 | tables: true 67 | forms: true 68 | buttons: true 69 | 70 | # Components 71 | component-animations: false 72 | dropdowns: true 73 | button-groups: true 74 | input-groups: true 75 | navs: true 76 | navbar: true 77 | breadcrumbs: false 78 | pagination: false 79 | pager: false 80 | labels: true 81 | badges: true 82 | jumbotron: false 83 | thumbnails: false 84 | alerts: true 85 | progress-bars: true 86 | media: false 87 | list-group: true 88 | panels: true 89 | wells: true 90 | responsive-embed: false 91 | close: true 92 | 93 | # Components w/ JavaScript 94 | modals: false 95 | tooltip: false 96 | popovers: false 97 | carousel: false 98 | 99 | # Utility classes 100 | utilities: true 101 | responsive-utilities: true 102 | 103 | ### Bootstrap scripts 104 | scripts: 105 | transition: false 106 | alert: true 107 | button: true 108 | carousel: false 109 | collapse: true 110 | dropdown: true 111 | modal: false 112 | tooltip: false 113 | popover: false 114 | scrollspy: false 115 | tab: true 116 | affix: false 117 | -------------------------------------------------------------------------------- /provisioner/ui/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "commonjs": true, 5 | "es6": true, 6 | "node": true 7 | }, 8 | "parserOptions": { 9 | "ecmaFeatures": { 10 | "jsx": true 11 | }, 12 | "sourceType": "module" 13 | }, 14 | "rules": { 15 | "no-const-assign": "warn", 16 | "no-this-before-super": "warn", 17 | "no-undef": "warn", 18 | "no-unreachable": "warn", 19 | "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], 20 | "constructor-super": "warn", 21 | "valid-typeof": "warn" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /provisioner/ui/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log 5 | bindata.go 6 | -------------------------------------------------------------------------------- /provisioner/ui/Makefile: -------------------------------------------------------------------------------- 1 | DEPS = $(shell find src -type f) 2 | DEPS += index.html 3 | GOBINDATA = $(GOPATH)/bin/go-bindata 4 | 5 | ASSETS = \ 6 | dist/views/index.html \ 7 | dist/assets/application.js 8 | 9 | bindata.go: $(GOBINDATA) $(ASSETS) 10 | $(GOBINDATA) -pkg ui -prefix dist -o $@ dist/... 11 | 12 | $(GOBINDATA): 13 | go get -u github.com/jteeuwen/go-bindata/... 14 | 15 | dist/views/index.html: index.html 16 | mkdir -p ../../provisioner/ui/dist/views 17 | cp index.html dist/views/ 18 | 19 | dist/assets/application.js: $(DEPS) 20 | yarn install 21 | npm run build 22 | 23 | .PHONY: clean 24 | clean: 25 | rm -rf dist 26 | rm bindata.go 27 | 28 | .PHONY: clobber 29 | clobber: clean 30 | rm -rf node_modules 31 | -------------------------------------------------------------------------------- /provisioner/ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Digineo Ubnt Provisioner 8 | 9 | 10 |
Loading Provisioner...
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /provisioner/ui/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.0.1", 3 | "name": "ubnt-provisioner-ui", 4 | "description": "Digineo Ubnt Provisioner UI", 5 | "author": "Dominik Menke ", 6 | "private": true, 7 | "scripts": { 8 | "build": "NODE_ENV=production webpack --progress --hide-modules" 9 | }, 10 | "dependencies": { 11 | "bootstrap-sass": "^3.3.7", 12 | "jquery": "^3.1.1", 13 | "moment": "^2.15.2", 14 | "vue": "^2.0.1" 15 | }, 16 | "devDependencies": { 17 | "babel-core": "^6.0.0", 18 | "babel-loader": "^6.0.0", 19 | "babel-preset-es2015": "^6.0.0", 20 | "bootstrap-loader": "^2.1.0", 21 | "css-loader": "^0.25.0", 22 | "file-loader": "^0.9.0", 23 | "node-sass": "^4.5.3", 24 | "resolve-url-loader": "^1.6.0", 25 | "sass-loader": "^6.0.5", 26 | "style-loader": "^0.18.2", 27 | "url-loader": "^0.5.7", 28 | "vue-loader": "^9.7.0", 29 | "webpack": "^2.6.1", 30 | "webpack-dev-server": "^2.4.5", 31 | "extract-text-webpack-plugin": ">=2.1.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /provisioner/ui/src/App.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 25 | -------------------------------------------------------------------------------- /provisioner/ui/src/components/DeviceNav.vue: -------------------------------------------------------------------------------- 1 | 47 | 48 | 118 | 119 | 134 | -------------------------------------------------------------------------------- /provisioner/ui/src/components/DeviceView.vue: -------------------------------------------------------------------------------- 1 | 83 | 84 | 112 | 113 | 116 | -------------------------------------------------------------------------------- /provisioner/ui/src/components/UbntProvisioner.vue: -------------------------------------------------------------------------------- 1 | 55 | 56 | 104 | 105 | 111 | -------------------------------------------------------------------------------- /provisioner/ui/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from "vue" 2 | import jQuery from "jquery" 3 | import Provisioner from "./provisioner.js" 4 | import App from "./App.vue" 5 | 6 | const apiEndpoint = "/api" 7 | 8 | let directory = jQuery.getJSON(apiEndpoint) 9 | 10 | directory.done((data, _status, _xhr)=>{ 11 | let prov = new Provisioner(data) 12 | new Vue({ 13 | el: "#app", 14 | template: ``, 15 | data: { 16 | provisioner: prov, 17 | }, 18 | components: { 19 | App 20 | } 21 | }) 22 | }) 23 | 24 | directory.fail(()=>{ 25 | jQuery("#app").text("Failed to initialize Provisioner.") 26 | }) 27 | -------------------------------------------------------------------------------- /provisioner/ui/src/provisioner.js: -------------------------------------------------------------------------------- 1 | import jQuery from "jquery" 2 | import moment from "moment" 3 | 4 | const hasProp = Object.prototype.hasOwnProperty 5 | 6 | class Provisioner { 7 | constructor(urlDirectory) { 8 | this.urlDirectory = urlDirectory 9 | this.refreshRate = false 10 | this.numDevices = 0 11 | this.devices = {} 12 | this.alerts = [] 13 | 14 | this.getDevices() 15 | this.startRefresh() 16 | } 17 | 18 | get refreshRate() { return this._refreshRate } 19 | set refreshRate(rate) { 20 | if (rate === false) { 21 | this._refreshRate = false 22 | this.stopRefresh() 23 | return 24 | } 25 | if (!typeof rate === "Number") { 26 | throw "refresh rate must be false or a number" 27 | } 28 | if (rate < 1000) { 29 | throw "refresh rate must be at least 1000ms" 30 | } 31 | this._refreshRate = rate 32 | this.startRefresh() 33 | } 34 | 35 | refreshHuman() { 36 | if (!this.refreshRate) { 37 | return "off" 38 | } 39 | let r = this.refreshRate/1000 40 | if (r < 60) { 41 | return `${r} sec` 42 | } else { 43 | return `${Math.round(r/60)} min` 44 | } 45 | } 46 | 47 | url(name, args={}) { 48 | let url = this.urlDirectory[name] 49 | if (!url) { 50 | throw `Named URL ${name} not found.` 51 | } 52 | 53 | (url.match(/\{[-\w]+\}/g) || []).forEach((match)=> { 54 | let el = match.substring(1, match.length-1) // "{foo}" → "foo" 55 | if (!hasProp.call(args, el)) { 56 | throw `Missing parameter ${el}` 57 | } 58 | url = url.replace(match, args[el]) 59 | }) 60 | 61 | return url 62 | } 63 | 64 | getDevices() { 65 | let promise = jQuery.getJSON(this.url("devices")) 66 | promise.done((data, _status, _xhr)=>{ 67 | let devices = data 68 | devices.sort(function(a,b) { 69 | return +(a.mac_address < b.mac_address) || +(a.mac_address === b.mac_address) - 1 70 | }) 71 | 72 | this.numDevices = devices.length 73 | this.devices = devices.reduce(function(memo, d) { 74 | memo[d.mac_address] = d 75 | return memo 76 | }, {}) 77 | }) 78 | promise.fail((xhr, status, error)=>{ 79 | if (xhr.readyState === 0) { 80 | this.log("danger", "Could not connect to server.") 81 | } else { 82 | this.log("danger", `${status}: ${error}`) 83 | } 84 | }) 85 | return 86 | } 87 | 88 | log(type, message) { 89 | this.alerts.unshift({ t: moment().unix(), style: `alert-${type}`, message: message }) 90 | this.alerts.splice(5) // keep 5 91 | } 92 | 93 | startRefresh() { 94 | this.stopRefresh() 95 | if (this.refreshRate) { 96 | this._refreshID = setInterval(() => this.getDevices(), this.refreshRate) 97 | } 98 | } 99 | 100 | stopRefresh() { 101 | if (this._refreshID) { 102 | window.clearTimeout(this._refreshID) 103 | this._refreshID = null 104 | } 105 | } 106 | 107 | deviceAction(action, mac) { 108 | let dev = this.devices[mac] 109 | let url = null 110 | if (!dev) { 111 | this.log("danger", `Device ${mac} not found.`) 112 | return 113 | } 114 | if (["reboot", "provision", "upgrade"].indexOf(action) >= 0) { 115 | if (!(url = this.url(`${action}_device`, {mac: mac}))) { 116 | this.log("danger", `Don't know how to perform ${action} action: Missing route.`) 117 | return 118 | } 119 | } else { 120 | this.log("danger", `Unknown action: ${action}.`) 121 | return 122 | } 123 | if (action === "provision" && !dev.has_config) { 124 | this.log("danger", `No configuration found for device ${mac}.`) 125 | return 126 | } 127 | if (action === "upgrade" && !dev.can_upgrade) { 128 | this.log("danger", `No firmware upgrade found for device ${mac}.`) 129 | return 130 | } 131 | 132 | let promise = jQuery.ajax({ url: url, method: "POST" }) 133 | promise.done((data, _status, _xhr) => { 134 | this.log(data.type, data.message) 135 | }) 136 | promise.fail((xhr, status, error) => { 137 | let data = xhr.responseJSON 138 | if (data && data.type && data.message) { 139 | this.log(data.type, data.message) 140 | } else { 141 | this.log("danger", `Executing ${action} for device ${mac} failed (${status || error})`) 142 | } 143 | }) 144 | } 145 | } 146 | 147 | export default Provisioner 148 | -------------------------------------------------------------------------------- /provisioner/ui/src/utils/filters.js: -------------------------------------------------------------------------------- 1 | import moment from "moment" 2 | 3 | let filters = { 4 | timeAgo(value) { 5 | let unix = moment.unix(value), 6 | diff = moment().unix() - unix.unix() 7 | return diff < 60 ? `${diff} seconds ago` : unix.fromNow() 8 | }, 9 | 10 | fmtDate(value) { 11 | let unix = moment.unix(value), 12 | fmt = unix.format("YYYY-MM-DD, HH:mm"), 13 | diff = moment().unix() - unix.unix(), 14 | ago = diff < 60 ? `${diff} seconds ago` : unix.fromNow() 15 | return `${fmt} (${ago})` 16 | } 17 | } 18 | 19 | export default filters 20 | -------------------------------------------------------------------------------- /provisioner/ui/webpack.config.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var webpack = require('webpack') 3 | 4 | module.exports = { 5 | entry: [ 6 | 'bootstrap-loader', 7 | './src/main.js' 8 | ], 9 | output: { 10 | path: path.resolve(__dirname, './dist/assets'), 11 | publicPath: '/assets/', 12 | filename: 'application.js' 13 | }, 14 | module: { 15 | loaders: [ 16 | { test: /\.css$/, loaders: ['style', 'css', 'postcss'] }, 17 | { test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'] }, 18 | { 19 | test: /bootstrap-sass\/assets\/javascripts\//, 20 | loader: 'imports?jQuery=jquery' 21 | } 22 | ], 23 | rules: [ 24 | { 25 | test: /\.vue$/, 26 | loader: 'vue-loader', 27 | options: { 28 | // vue-loader options go here 29 | } 30 | }, 31 | { 32 | test: /\.js$/, 33 | loader: 'babel-loader', 34 | exclude: /node_modules/ 35 | }, 36 | { 37 | test: /\.(png|jpg|gif|svg)$/, 38 | loader: 'file-loader', 39 | options: { 40 | name: '[name].[ext]?[hash]' 41 | } 42 | } 43 | ] 44 | }, 45 | resolve: { 46 | alias: { 47 | "moment": "moment/moment.js", 48 | 'vue$': 'vue/dist/vue' 49 | } 50 | }, 51 | devServer: { 52 | historyApiFallback: true, 53 | noInfo: true 54 | }, 55 | devtool: '#eval-source-map', 56 | plugins: [ 57 | new webpack.NamedModulesPlugin(), 58 | new webpack.NoEmitOnErrorsPlugin(), 59 | new webpack.ProvidePlugin({ 60 | $: "jquery", 61 | jQuery: "jquery" 62 | }) 63 | ] 64 | } 65 | 66 | if (process.env.NODE_ENV === 'production') { 67 | module.exports.devtool = '#source-map' 68 | // http://vue-loader.vuejs.org/en/workflow/production.html 69 | module.exports.plugins = (module.exports.plugins || []).concat([ 70 | new webpack.DefinePlugin({ 71 | 'process.env': { 72 | NODE_ENV: '"production"' 73 | } 74 | }), 75 | new webpack.optimize.UglifyJsPlugin({ 76 | compress: { 77 | warnings: false 78 | } 79 | }), 80 | new webpack.LoaderOptionsPlugin({ 81 | minimize: true 82 | }) 83 | ]) 84 | } 85 | -------------------------------------------------------------------------------- /provisioner/web/ctrl_devices.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/digineo/ubnt-tools/provisioner" 7 | "github.com/gorilla/mux" 8 | ) 9 | 10 | // GET /api/devices 11 | func (g *goWeb) getDevices(w http.ResponseWriter, r *http.Request) { 12 | devices := WrapDeviceJSON(g.config.GetDevices()) 13 | g.responseJSON(w, http.StatusOK, devices) 14 | } 15 | 16 | // GET /api/devices/{mac} 17 | func (g *goWeb) getDevice(w http.ResponseWriter, r *http.Request) { 18 | if dev := g.findDevice(r); dev != nil { 19 | g.responseJSON(w, http.StatusOK, MakeDeviceJSON(dev)) 20 | } else { 21 | g.statusJSON(w, http.StatusNotFound, "Unknown device.") 22 | } 23 | } 24 | 25 | // POST /api/devices/{mac}/upgrade 26 | func (g *goWeb) upgradeDevice(w http.ResponseWriter, r *http.Request) { 27 | dev := g.findDevice(r) 28 | if dev == nil { 29 | g.statusJSON(w, http.StatusNotFound, "Unknown device.") 30 | return 31 | } 32 | if err := dev.Upgrade(); err != nil { 33 | g.statusJSON(w, http.StatusUnprocessableEntity, "%v", err) 34 | return 35 | } 36 | g.statusJSON(w, http.StatusOK, "Firmware upgrade for %s enqueued.", dev.MacAddress) 37 | } 38 | 39 | // POST /api/devices/{mac}/provision 40 | func (g *goWeb) provisionDevice(w http.ResponseWriter, r *http.Request) { 41 | dev := g.findDevice(r) 42 | if dev == nil { 43 | g.statusJSON(w, http.StatusNotFound, "Unknown device.") 44 | return 45 | } 46 | if err := dev.Provision(); err != nil { 47 | g.statusJSON(w, http.StatusUnprocessableEntity, "%v", err) 48 | return 49 | } 50 | g.statusJSON(w, http.StatusOK, "Provisioning for %s enqueued.", dev.MacAddress) 51 | } 52 | 53 | // POST /api/devices/{mac}/reboot 54 | func (g *goWeb) rebootDevice(w http.ResponseWriter, r *http.Request) { 55 | dev := g.findDevice(r) 56 | if dev == nil { 57 | g.statusJSON(w, http.StatusNotFound, "Unknown device.") 58 | return 59 | } 60 | if err := dev.Reboot(); err != nil { 61 | g.statusJSON(w, http.StatusUnprocessableEntity, "%v", err) 62 | return 63 | } 64 | g.statusJSON(w, http.StatusOK, "Rebooting device %s.", dev.MacAddress) 65 | } 66 | 67 | func (g *goWeb) findDevice(r *http.Request) *provisioner.Device { 68 | vars := mux.Vars(r) 69 | if mac, found := vars["mac"]; found { 70 | return g.config.FindDevice(mac) 71 | } 72 | return nil 73 | } 74 | -------------------------------------------------------------------------------- /provisioner/web/ctrl_static.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "mime" 7 | "net/http" 8 | "path/filepath" 9 | "strconv" 10 | "time" 11 | 12 | "github.com/digineo/ubnt-tools/provisioner/ui" 13 | ) 14 | 15 | // GET / 16 | func (g *goWeb) getRoot(w http.ResponseWriter, r *http.Request) { 17 | asset, err := ui.Asset("views/index.html") 18 | 19 | if err != nil { 20 | log.Println(err) 21 | http.NotFound(w, r) 22 | return 23 | } 24 | 25 | w.Header().Set(headerContentType, contentTypeHTML) 26 | w.Header().Set(headerContentLength, strconv.Itoa(len(asset))) 27 | w.WriteHeader(http.StatusOK) 28 | w.Write(asset) 29 | } 30 | 31 | // GET /assets/*file 32 | func (g *goWeb) getStaticAsset(w http.ResponseWriter, r *http.Request) { 33 | assetPath := r.URL.Path[1:] // remove leading slash 34 | asset, err := ui.Asset(assetPath) 35 | 36 | if err != nil { 37 | log.Print(err) 38 | http.NotFound(w, r) 39 | return 40 | } 41 | 42 | i, err := ui.AssetInfo(assetPath) 43 | if err != nil { 44 | log.Printf("Error reading static asset %s: %v", assetPath, err) 45 | http.Error(w, "500 internal server error", http.StatusInternalServerError) 46 | return 47 | } 48 | 49 | modTime := i.ModTime() 50 | contentType := "application/octed-stream" 51 | if ct := mime.TypeByExtension(filepath.Ext(assetPath)); ct != "" { 52 | contentType = ct 53 | } 54 | 55 | t, err := time.Parse(httpDateFormat, r.Header.Get(headerIfModifiedSince)) 56 | if err == nil && modTime.Before(t.Add(cacheDuration)) { 57 | w.Header().Del(headerContentType) 58 | w.Header().Del(headerContentLength) 59 | w.WriteHeader(http.StatusNotModified) 60 | return 61 | } 62 | 63 | w.Header().Set(headerContentType, contentType) 64 | w.Header().Set(headerLastModified, modTime.UTC().Format(httpDateFormat)) 65 | w.Header().Set(headerContentLength, fmt.Sprintf("%d", len(asset))) 66 | w.WriteHeader(http.StatusOK) 67 | w.Write(asset) 68 | } 69 | -------------------------------------------------------------------------------- /provisioner/web/views.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import "github.com/digineo/ubnt-tools/provisioner" 4 | 5 | // DeviceJSON wraps a provisioner.Device into JSON presentation 6 | type DeviceJSON struct { 7 | CanUpgrade bool `json:"can_upgrade"` 8 | Essid string `json:"essid"` 9 | Firmware string `json:"firmware"` 10 | FirstSeenAt int64 `json:"first_seen_at"` 11 | HasConfig bool `json:"has_config"` 12 | Hostname string `json:"hostname"` 13 | IPAddress string `json:"ip_address"` 14 | IPAddresses map[string][]string `json:"ip_addresses"` 15 | LastSeenAt int64 `json:"last_seen_at"` 16 | MacAddress string `json:"mac_address"` 17 | Model string `json:"model"` 18 | Platform string `json:"platform"` 19 | Status string `json:"status"` 20 | UpSince int64 `json:"up_since"` 21 | WirelessMode string `json:"wireless_mode"` 22 | } 23 | 24 | // MakeDeviceJSON transforms a Device into a DeviceJSON 25 | func MakeDeviceJSON(dev *provisioner.Device) *DeviceJSON { 26 | j := &DeviceJSON{ 27 | CanUpgrade: dev.CanUpgrade(), 28 | Essid: dev.Essid, 29 | Firmware: dev.Firmware, 30 | FirstSeenAt: dev.FirstSeenAt.Unix(), 31 | HasConfig: dev.HasConfig(), 32 | Hostname: dev.Hostname, 33 | IPAddress: dev.IPAddress, 34 | IPAddresses: make(map[string][]string), 35 | LastSeenAt: dev.LastSeenAt.Unix(), 36 | MacAddress: dev.MacAddress, 37 | Model: dev.Model, 38 | Platform: dev.Platform, 39 | Status: dev.Status(), 40 | UpSince: dev.UpSince.Unix(), 41 | WirelessMode: dev.WirelessMode, 42 | } 43 | 44 | for mac, ips := range dev.IPAddresses { 45 | // copy(j.IPAddresses[mac], ips) // doesn't work 46 | 47 | j.IPAddresses[mac] = make([]string, len(ips), len(ips)) 48 | for i, ip := range ips { 49 | j.IPAddresses[mac][i] = ip 50 | } 51 | } 52 | 53 | return j 54 | } 55 | 56 | // WrapDeviceJSON transforms a list of Devices into a list of DeviceJSONs 57 | func WrapDeviceJSON(devices []*provisioner.Device) []*DeviceJSON { 58 | list := make([]*DeviceJSON, len(devices)) 59 | for i, d := range devices { 60 | list[i] = MakeDeviceJSON(d) 61 | } 62 | return list 63 | } 64 | -------------------------------------------------------------------------------- /provisioner/web/web.go: -------------------------------------------------------------------------------- 1 | package web 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "os" 9 | "strconv" 10 | "time" 11 | 12 | "github.com/digineo/ubnt-tools/provisioner" 13 | "github.com/gorilla/handlers" 14 | "github.com/gorilla/mux" 15 | ) 16 | 17 | const ( 18 | headerContentLength = "Content-Length" 19 | headerContentType = "Content-Type" 20 | headerIfModifiedSince = "If-Modified-Since" 21 | headerLastModified = "Last-Modified" 22 | httpDateFormat = time.RFC1123 23 | cacheDuration = 20 * time.Second 24 | 25 | contentTypeHTML = "text/html; charset=UTF-8" 26 | contentTypeJSON = "application/json; charset=UTF-8" 27 | ) 28 | 29 | type goWeb struct { 30 | config *provisioner.Configuration 31 | router *mux.Router 32 | server *http.Server 33 | } 34 | 35 | // StartWeb initializes the web UI 36 | func StartWeb(c *provisioner.Configuration) { 37 | web := &goWeb{config: c} 38 | web.buildRoutes() 39 | 40 | cors := handlers.CORS(handlers.AllowedOrigins([]string{"*"})) 41 | handler := handlers.LoggingHandler(os.Stdout, cors(web.router)) 42 | 43 | web.server = &http.Server{ 44 | Addr: fmt.Sprintf("%s:%d", c.Web.Host, c.Web.Port), 45 | Handler: handler, 46 | ReadTimeout: 30 * time.Second, 47 | WriteTimeout: 30 * time.Second, 48 | } 49 | log.Printf("[webui] Starting Web UI on http://%s", web.server.Addr) 50 | web.server.ListenAndServe() 51 | } 52 | 53 | func (g *goWeb) buildRoutes() { 54 | g.router = mux.NewRouter() 55 | 56 | g.router.HandleFunc("/", g.getRoot).Methods("GET").Name("root") 57 | g.router.PathPrefix("/assets/").HandlerFunc(g.getStaticAsset).Name("asset") 58 | g.router.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { 59 | routes := make(map[string]string) 60 | for _, name := range []string{"api_directory", "device", "devices", "upgrade_device", "provision_device", "reboot_device"} { 61 | route := g.router.Get(name) 62 | if tpl, err := route.GetPathTemplate(); err == nil { 63 | routes[name] = fmt.Sprintf("//%s%s", g.server.Addr, tpl) 64 | } 65 | } 66 | g.responseJSON(w, http.StatusOK, routes) 67 | }).Methods("GET").Name("api_directory") 68 | 69 | g.router.HandleFunc("/api/devices", g.getDevices).Methods("GET").Name("devices") 70 | dev := g.router.PathPrefix("/api/devices").Subrouter() 71 | // dev.HandleFunc("", g.getDevices).Methods("GET").Name("devices") // doesn't work 72 | dev.HandleFunc("/{mac}", g.getDevice).Methods("GET").Name("device") 73 | dev.HandleFunc("/{mac}/upgrade", g.upgradeDevice).Methods("POST").Name("upgrade_device") 74 | dev.HandleFunc("/{mac}/provision", g.provisionDevice).Methods("POST").Name("provision_device") 75 | dev.HandleFunc("/{mac}/reboot", g.rebootDevice).Methods("POST").Name("reboot_device") 76 | } 77 | 78 | func (g *goWeb) statusJSON(w http.ResponseWriter, status int, message string, v ...interface{}) { 79 | json := map[string]interface{}{ 80 | "type": "info", 81 | "message": fmt.Sprintf(message, v...), 82 | } 83 | 84 | if 200 <= status && status < 300 { 85 | json["type"] = "success" 86 | } else if 400 <= status { 87 | json["type"] = "danger" 88 | } 89 | 90 | g.responseJSON(w, status, json) 91 | } 92 | 93 | func (g *goWeb) responseJSON(w http.ResponseWriter, status int, v interface{}) { 94 | if result, err := json.Marshal(v); err != nil { 95 | log.Printf("[responseJSON error] %v", err) 96 | http.Error(w, "500 internal server error", http.StatusInternalServerError) 97 | } else { 98 | w.Header().Set(headerContentType, contentTypeJSON) 99 | w.Header().Set(headerContentLength, strconv.Itoa(len(result))) 100 | w.WriteHeader(http.StatusOK) 101 | w.Write(result) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /resources/config.yml: -------------------------------------------------------------------------------- 1 | config_directory: /var/ubnt-tools/provisioner/configurations 2 | firmware_directory: /var/ubnt-tools/provisioner/firmwares 3 | 4 | safe_upgrade_paths: 5 | "XC.v7.2.4.31259.160714.1715.bin": 6 | - "XC.qca955x.v7.2.1.30741.160412.1342" 7 | 8 | "XC.v8.1.4.34481.170608.1728.bin": 9 | - "XC.qca955x.v7.2.1.30741.160412.1342" 10 | - "XC.qca955x.v8.0.2.33352.170327.1907" 11 | 12 | interfaces: 13 | - eth0.1007 14 | 15 | ssh: 16 | - type: keyfile 17 | path: /var/ubnt-tools/provisionoer/id_rsa_provisioner 18 | - password: ubnt 19 | 20 | web: 21 | host: 127.0.0.1 22 | port: 8007 23 | -------------------------------------------------------------------------------- /resources/provisioner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digineo/ubnt-tools/178e1e707a490fc4ec270eae29bafe0eb216ab16/resources/provisioner.png --------------------------------------------------------------------------------