├── .ci └── ci_build.go ├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── cmd ├── ttyc │ ├── cli_config.go │ ├── cli_config_incompatible.go │ ├── handlers │ │ ├── base.go │ │ ├── pty.go │ │ ├── pty_incompatible.go │ │ ├── shenanigans │ │ │ ├── winconsole.go │ │ │ ├── winconsole_darwin.go │ │ │ └── winconsole_windows.go │ │ └── stdfds.go │ └── main.go └── wistty │ └── main.go ├── common.go ├── debug.go ├── go.mod ├── go.sum ├── utils ├── copier.go └── httpAuth.go └── ws └── protocol.go /.ci/ci_build.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/Depau/ttyc" 6 | "os" 7 | "os/exec" 8 | "runtime" 9 | ) 10 | 11 | const JOBS = -1 // -1 => use number of usable CPUs 12 | 13 | type PlatformInfo struct { 14 | OS string 15 | Arch string 16 | ExtraEnv []string 17 | } 18 | 19 | var Platforms = []PlatformInfo{ 20 | {"linux", "386", []string{}}, 21 | {"linux", "amd64", []string{}}, 22 | {"linux", "arm", []string{}}, 23 | {"linux", "arm64", []string{}}, 24 | {"linux", "mips", []string{"GOMIPS=softfloat"}}, 25 | {"linux", "mips64", []string{"GOMIPS=softfloat"}}, 26 | {"linux", "mips64le", []string{"GOMIPS=softfloat"}}, 27 | {"linux", "mipsle", []string{"GOMIPS=softfloat"}}, 28 | {"linux", "ppc64", []string{}}, 29 | {"linux", "ppc64le", []string{}}, 30 | {"linux", "riscv64", []string{}}, 31 | {"linux", "s390x", []string{}}, 32 | //{"android", "386", []string{}}, 33 | //{"android", "amd64", []string{}}, 34 | //{"android", "arm", []string{}}, // CGO does not work 35 | {"android", "arm64", []string{}}, 36 | {"darwin", "amd64", []string{}}, 37 | {"darwin", "arm64", []string{}}, 38 | {"freebsd", "386", []string{}}, 39 | {"freebsd", "amd64", []string{}}, 40 | {"freebsd", "arm", []string{}}, 41 | {"freebsd", "arm64", []string{}}, 42 | {"netbsd", "386", []string{}}, 43 | {"netbsd", "amd64", []string{}}, 44 | {"netbsd", "arm", []string{}}, 45 | {"netbsd", "arm64", []string{}}, 46 | {"openbsd", "386", []string{}}, 47 | {"openbsd", "amd64", []string{}}, 48 | {"openbsd", "arm", []string{}}, 49 | {"openbsd", "arm64", []string{}}, 50 | {"openbsd", "mips64", []string{"GOMIPS=softfloat"}}, 51 | {"windows", "386", []string{}}, 52 | {"windows", "amd64", []string{}}, 53 | {"windows", "arm", []string{}}, 54 | {"dragonfly", "amd64", []string{}}, 55 | } 56 | 57 | func BuildPlatformExe(exe string, plat PlatformInfo, absoluteOutdir string, semaphore <-chan interface{}) { 58 | defer func() { <-semaphore }() 59 | 60 | fmt.Printf("Building %s for %s/%s\n", exe, plat.OS, plat.Arch) 61 | outname := absoluteOutdir + "/" + fmt.Sprintf("%s-%s-%s-%s", exe, ttyc.VERSION, plat.OS, plat.Arch) 62 | if plat.OS == "windows" { 63 | outname += ".exe" 64 | } 65 | command := exec.Command("go", "build", "-ldflags=-s -w", "-o", outname, "-trimpath") 66 | if runtime.GOOS == "linux" && runtime.GOOS == plat.OS && runtime.GOARCH == plat.Arch { 67 | command.Args = append(command.Args, "-ldflags", "-linkmode external -extldflags \"-fno-PIC -static\"") 68 | } 69 | 70 | command.Dir = "cmd/" + exe 71 | command.Env = os.Environ() 72 | command.Env = append(command.Env, "GOOS="+plat.OS, "GOARCH="+plat.Arch) 73 | command.Env = append(command.Env, plat.ExtraEnv...) 74 | command.Stdout = os.Stdout 75 | command.Stderr = os.Stderr 76 | command.Stdin = nil 77 | 78 | err := command.Run() 79 | if err != nil { 80 | fmt.Println("Build failed:", err) 81 | } 82 | } 83 | 84 | //goland:noinspection GoBoolExpressions // suppress check that jobs <= 0 is always true 85 | func BuildExes(exe string, plats []PlatformInfo, absoluteOutdir string) { 86 | jobs := JOBS 87 | if jobs <= 0 { 88 | jobs = runtime.NumCPU() 89 | } 90 | fmt.Println("Running", jobs, "jobs in parallel") 91 | 92 | semaphore := make(chan interface{}, jobs) 93 | 94 | for _, plat := range plats { 95 | semaphore <- nil 96 | go BuildPlatformExe(exe, plat, absoluteOutdir, semaphore) 97 | } 98 | } 99 | 100 | func main() { 101 | path, err := os.Getwd() 102 | if err != nil { 103 | panic(err) 104 | } 105 | BuildExes("ttyc", Platforms, path+"/build") 106 | BuildExes("wistty", Platforms, path+"/build") 107 | } 108 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Check program builds 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Set up Go 16 | uses: actions/setup-go@v2 17 | with: 18 | go-version: 1.16 19 | 20 | - name: Build ttyc 21 | run: go build -v ./cmd/ttyc 22 | 23 | - name: Build wistty 24 | run: go build -v ./cmd/wistty 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | 17 | .idea/ 18 | 19 | cmd/ttyc/ttyc 20 | cmd/wistty/wistty -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ttyc 2 | 3 | Command-line client for [ttyd](https://github.com/tsl0922/ttyd), [Wi-Se](https://github.com/Depau/wi-se-sw/) and 4 | anything else that uses a compatible protocol. 5 | 6 | Features: 7 | 8 | - Works on all major operating systems including Windows 9 | - Built-in terminal with a user interface similar to that of [tio](https://github.com/tio/tio) 10 | - Supports configuring remote UART parameters for Wi-Se 11 | 12 | Additionally, on all platforms except Windows and macOS: 13 | 14 | - Can expose the remote terminal as a pseudo-terminal, which you can connect to with any TTY program (screen, minicom, 15 | etc.) 16 | 17 | ## wistty 18 | 19 | Wistty is a utility to set remote terminal parameters for [Wi-Se](https://github.com/Depau/wi-se-sw/). 20 | 21 | Wistty is not compatible with ttyd. 22 | 23 | ## Installation 24 | 25 | ### Releases 26 | 27 | Head over to the [Releases](https://github.com/Depau/ttyc/releases) page and grab a prebuilt binary. 28 | 29 | ### Arch Linux 30 | 31 | Packages are available in the AUR: 32 | 33 | - `ttyc` - https://aur.archlinux.org/packages/ttyc/ 34 | - `wistty` - https://aur.archlinux.org/packages/wistty/ 35 | - `ttyc-git` - https://aur.archlinux.org/packages/ttyc-git/ (provides `wistty`) 36 | 37 | ## Building 38 | 39 | ### Quick way 40 | 41 | ```bash 42 | go get github.com/Depau/ttyc/cmd/ttyc 43 | go get github.com/Depau/ttyc/cmd/wistty 44 | ``` 45 | 46 | Binaries will be saved to `$GOHOME/bin/ttyc` and `$GOHOME/bin/wistty`, usually `~/go/bin/...` 47 | 48 | ### From local sources 49 | 50 | ```bash 51 | git clone https://github.com/Depau/ttyc.git 52 | cd ttyc/cmd/ttyc 53 | go build 54 | cd ../wistty 55 | go build 56 | ``` 57 | 58 | ### Build locally for all platforms 59 | 60 | ```bash 61 | git clone https://github.com/Depau/ttyc.git 62 | cd ttyc 63 | go run .ci/ci_build.go 64 | ``` 65 | 66 | Outputs will be placed in the `build/` directory. 67 | 68 | ## Usage 69 | 70 | ```bash 71 | ttyc --url http://localhost:7681 72 | ``` 73 | 74 | ``` 75 | -h, --help Show help 76 | -U, --url Server URL 77 | -w, --watchdog[=2] WebSocket ping interval in seconds, 0 to disable, default 2. 78 | -r, --reconnect[=2] Reconnection interval in seconds, -1 to disable, default 3. 79 | --backoff[=none] Backoff type, none, linear, exponential, defaults to linear 80 | --backoff-value[=2] For linear backoff, increase reconnect interval by this amount of seconds after each iteration. For exponential backoff, multiply reconnect interval by this amount. Default 2 81 | -u, --user Username for authentication 82 | -k, --pass Password for authentication 83 | -T, --tty Do not launch terminal, create terminal device at given location (i.e. /tmp/ttyd) 84 | -b, --baudrate[=-1] (Wi-Se only) Set remote baud rate [bps] 85 | -p, --parity (Wi-Se only) Set remote parity [odd|even|none] 86 | -d, --databits[=-1] (Wi-Se only) Set remote data bits [5|6|7|8] 87 | -s, --stopbits[=-1] (Wi-Se only) Set remote stop bits [1|2] 88 | -v, --version Show version 89 | ``` 90 | 91 | ```bash 92 | wistty (ttyc) - Manage Wi-Se remote terminal parameters 93 | 94 | Options: 95 | 96 | -h, --help Show help 97 | -U, --url Server URL 98 | -u, --user Username for authentication 99 | -k, --pass Password for authentication 100 | -j, --json Return machine-readable JSON output 101 | -b, --baudrate[=-1] Set remote baud rate [bps] 102 | -p, --parity Set remote parity [odd|even|none] 103 | -d, --databits[=-1] Set remote data bits [5|6|7|8] 104 | -s, --stopbits[=-1] Set remote stop bits [1|2] 105 | -v, --version Show version 106 | ``` 107 | 108 | ## Multiplatform notes 109 | 110 | ### GNU/Linux 111 | 112 | All functionality is available. This software is mainly tested on GNU/Linux so it should work well. 113 | 114 | ### Windows 115 | 116 | Occasionally tested. 117 | 118 | Raw terminal has been ported and workarounds have been implemented for missing system functionality. 119 | Everything should work perfectly except for TTY support, which is not supported by Windows itself (afaik). 120 | 121 | Text selection is disabled since it messes up the WebSocket communication. If you know workarounds, hit me up. 122 | 123 | ### macOS 124 | 125 | Occasionally tested, everything except for TTY support should work well., 126 | 127 | ### Android (with Bionic libc) 128 | 129 | It only seems to build for aarch64. Not tested. Other builds may work with with additional configuration tweaks. 130 | TTY support is likely to require additional permissions. 131 | 132 | ### OpenWRT (or other distros with uClibc) 133 | 134 | Tested on recent releases, it should work very well but huge 5MB binaries don't make it a very good fit on cheap routers. 135 | 136 | ### Other Non-GNU/Linux (i.e musl libc) 137 | 138 | Not tested, will likely work but YMMV. 139 | 140 | ### Other BSD 141 | 142 | Not tested, most things will likely work. TTY support may work or it may crash the program. 143 | 144 | ## License 145 | 146 | GNU General Public License v3.0 or later 147 | -------------------------------------------------------------------------------- /cmd/ttyc/cli_config.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | // +build !darwin 3 | 4 | package main 5 | 6 | type Config struct { 7 | Help bool `cli:"!h,help" usage:"Show help"` 8 | Url string `cli:"U,url" usage:"Server URL"` 9 | Watchdog int `cli:"w,watchdog" usage:"WebSocket ping interval in seconds, 0 to disable, default 2." dft:"2"` 10 | Reconnect int `cli:"r,reconnect" usage:"Reconnection interval in seconds, -1 to disable, default 3." dft:"2"` 11 | Backoff string `cli:"backoff" usage:"Backoff type, none, linear, exponential, defaults to linear" dft:"none"` 12 | BackoffValue uint `cli:"backoff-value" usage:"For linear backoff, increase reconnect interval by this amount of seconds after each iteration. For exponential backoff, multiply reconnect interval by this amount. Default 2" dft:"2"` 13 | User string `cli:"u,user" usage:"Username for authentication" dft:""` 14 | Pass string `cli:"k,pass" usage:"Password for authentication" dft:""` 15 | Tty string `cli:"T,tty" usage:"Do not launch terminal, create terminal device at given location (i.e. /tmp/ttyd)" dft:""` 16 | Baud int `cli:"b,baudrate" usage:"(Wi-Se only) Set remote baud rate [bps]" dft:"-1"` 17 | Parity string `cli:"p,parity" usage:"(Wi-Se only) Set remote parity [odd|even|none]" dft:""` 18 | Databits int `cli:"d,databits" usage:"(Wi-Se only) Set remote data bits [5|6|7|8]" dft:"-1"` 19 | Stopbits int `cli:"s,stopbits" usage:"(Wi-Se only) Set remote stop bits [1|2]" dft:"-1"` 20 | Version bool `cli:"!v,version" usage:"Show version"` 21 | } 22 | 23 | func (config *Config) GetTty() string { 24 | return (*config).Tty 25 | } 26 | 27 | func (config *Config) GetWaitDebugger() bool { 28 | return false 29 | } 30 | -------------------------------------------------------------------------------- /cmd/ttyc/cli_config_incompatible.go: -------------------------------------------------------------------------------- 1 | // +build windows darwin 2 | 3 | package main 4 | 5 | type Config struct { 6 | Help bool `cli:"!h,help" usage:"Show help"` 7 | Url string `cli:"U,url" usage:"Server URL"` 8 | Watchdog int `cli:"w,watchdog" usage:"WebSocket ping interval in seconds, 0 to disable, default 2." dft:"2"` 9 | Reconnect int `cli:"r,reconnect" usage:"Reconnection interval in seconds, -1 to disable, default 3." dft:"2"` 10 | Backoff string `cli:"backoff" usage:"Backoff type, none, linear, exponential, defaults to linear" dft:"none"` 11 | BackoffValue uint `cli:"backoff-value" usage:"For linear backoff, increase reconnect interval by this amount of seconds after each iteration. For exponential backoff, multiply reconnect interval by this amount. Default 2" dft:"2"` 12 | User string `cli:"u,user" usage:"Username for authentication" dft:""` 13 | Pass string `cli:"k,pass" usage:"Password for authentication" dft:""` 14 | Baud int `cli:"b,baudrate" usage:"(Wi-Se only) Set remote baud rate [bps]" dft:"-1"` 15 | Parity string `cli:"p,parity" usage:"(Wi-Se only) Set remote parity [odd|even|none]" dft:""` 16 | Databits int `cli:"d,databits" usage:"(Wi-Se only) Set remote data bits [5|6|7|8]" dft:"-1"` 17 | Stopbits int `cli:"s,stopbits" usage:"(Wi-Se only) Set remote stop bits [1|2]" dft:"-1"` 18 | WaitDebugger bool `cli:"D,debugger" usage:"Wait on start for a debugger connection" dft:"false"` 19 | Version bool `cli:"!v,version" usage:"Show version"` 20 | } 21 | 22 | func (config *Config) GetTty() string { 23 | return "" 24 | } 25 | 26 | func (config *Config) GetWaitDebugger() bool { 27 | return config.WaitDebugger 28 | } 29 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/base.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "io" 5 | ) 6 | 7 | type TtyHandler interface { 8 | io.Closer 9 | Run(errChan chan<- error) 10 | HandleDisconnect() error 11 | HandleReconnect() error 12 | } 13 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/pty.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | // +build !darwin 3 | 4 | // This module provides PTY emulation. It is only tested on Linux, tested not working on macOS. Windows does not support 5 | // this at all. 6 | 7 | package handlers 8 | 9 | import ( 10 | "fmt" 11 | "github.com/Depau/ttyc" 12 | "github.com/Depau/ttyc/utils" 13 | "github.com/Depau/ttyc/ws" 14 | "github.com/containerd/console" 15 | "os" 16 | ) 17 | 18 | type ptyHandler struct { 19 | client *ws.Client 20 | pty console.Console 21 | slavePath string 22 | } 23 | 24 | func NewPtyHandler(client *ws.Client, linkTo string) (tty TtyHandler, err error) { 25 | stat, statErr := os.Lstat(linkTo) 26 | if statErr == nil { 27 | if stat.Mode()&os.ModeSymlink != 0 { 28 | err = os.Remove(linkTo) 29 | if err != nil { 30 | ttyc.Trace() 31 | err = fmt.Errorf("tty filename exists and it can't be removed: %v", err) 32 | return nil, err 33 | } 34 | } else { 35 | err = fmt.Errorf("tty file exists: %s", linkTo) 36 | return nil, err 37 | } 38 | } 39 | 40 | pty, slavePath, err := console.NewPty() 41 | if err != nil { 42 | ttyc.Trace() 43 | return nil, err 44 | } 45 | if err = os.Symlink(slavePath, linkTo); err != nil { 46 | ttyc.TtycAngryPrintf("Warning: unaable to create link to %s as requested: %v\n", linkTo, err) 47 | ttyc.TtycAngryPrintf("You can still access it at %s\n", slavePath) 48 | } else { 49 | ttyc.TtycPrintf("TTY connected to remote terminal, available at %s\n", linkTo) 50 | } 51 | 52 | tty = &ptyHandler{ 53 | client: client, 54 | slavePath: slavePath, 55 | pty: pty, 56 | } 57 | 58 | return 59 | } 60 | 61 | func (p *ptyHandler) Run(errChan chan<- error) { 62 | go utils.CopyChanToWriter(p.client.CloseChan, p.client.Output, p.pty, errChan) 63 | go utils.CopyReaderToChan(p.client.CloseChan, p.pty, p.client.Input, errChan) 64 | for { 65 | select { 66 | case <-p.client.CloseChan: 67 | return 68 | case title := <-p.client.WinTitle: 69 | ttyc.TtycPrintf("Title: %s\n", title) 70 | case baudResult := <-p.client.DetectedBaudrate: 71 | approx := baudResult[0] 72 | measured := baudResult[1] 73 | if approx <= 0 { 74 | ttyc.TtycAngryPrintf("Baudrate detection was not successful (detection only works while input is received)\n") 75 | break 76 | } 77 | if measured > 0 { 78 | ttyc.TtycPrintf("Detected baudrate: likely %d bps (measured rate: %d bps)\n", approx, measured) 79 | } else { 80 | ttyc.TtycPrintf("Detected baudrate: likely %d bps\n", approx) 81 | } 82 | } 83 | } 84 | } 85 | 86 | func (p *ptyHandler) HandleDisconnect() error { 87 | return nil 88 | } 89 | 90 | func (p *ptyHandler) HandleReconnect() error { 91 | return nil 92 | } 93 | 94 | func (p *ptyHandler) Close() error { 95 | return p.pty.Close() 96 | } 97 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/pty_incompatible.go: -------------------------------------------------------------------------------- 1 | // +build windows darwin 2 | 3 | // This package provides mock implementations for Windows and macOS since PTY doesn't work 4 | 5 | package handlers 6 | 7 | import ( 8 | "fmt" 9 | "github.com/Depau/ttyc/ws" 10 | ) 11 | 12 | type ptyHandler struct{} 13 | 14 | func NewPtyHandler(client *ws.Client, linkTo string) (tty TtyHandler, err error) { 15 | err = fmt.Errorf("PTY backend is not available on Windows") 16 | return 17 | } 18 | 19 | func (p *ptyHandler) Run(errChan chan<- error) { 20 | errChan <- fmt.Errorf("PTY backend is not available on Windows") 21 | } 22 | 23 | func (p *ptyHandler) HandleDisconnect() error { 24 | return fmt.Errorf("PTY backend is not available on Windows") 25 | } 26 | 27 | func (p *ptyHandler) HandleReconnect() error { 28 | return fmt.Errorf("PTY backend is not available on Windows") 29 | } 30 | 31 | func (p *ptyHandler) Close() error { 32 | return fmt.Errorf("PTY backend is not available on Windows") 33 | } 34 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/shenanigans/winconsole.go: -------------------------------------------------------------------------------- 1 | // +build !windows 2 | // +build !darwin 3 | 4 | package shenanigans 5 | 6 | func ClearConsole() error { 7 | return nil 8 | } 9 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/shenanigans/winconsole_darwin.go: -------------------------------------------------------------------------------- 1 | package shenanigans 2 | 3 | import "os" 4 | 5 | // At least on iTerm2 it looks like launching a full-screen application such as tmux inside the emulated terminal 6 | // will result in a dirty screen on exit. 7 | // Clean it up with the ANSI \033c escape sequence. We don't need to clear the scrollback, just the current screen. 8 | 9 | func ClearConsole() (err error) { 10 | _, err = os.Stdout.Write([]byte{0x1b, 'c'}) 11 | return 12 | } 13 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/shenanigans/winconsole_windows.go: -------------------------------------------------------------------------------- 1 | package shenanigans 2 | 3 | import ( 4 | "golang.org/x/sys/windows" 5 | "os" 6 | ) 7 | 8 | // Terminal stays dirty if a full-screen application was launched. 9 | // We clear the terminal by temporarily forcing escape sequence parsing enabled, sending the escape sequence Windows 10 | // likes, then put everything back as it was. 11 | 12 | func ClearConsole() (err error) { 13 | stdout := windows.Handle(os.Stdout.Fd()) 14 | var outMode uint32 15 | if err = windows.GetConsoleMode(stdout, &outMode); err != nil { 16 | return 17 | } 18 | if err = windows.SetConsoleMode(stdout, outMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil { 19 | _ = windows.SetConsoleMode(stdout, outMode) 20 | return 21 | } 22 | _, err = os.Stdout.Write([]byte("\u001b[2J")) 23 | // ignore error but still return it 24 | err = windows.SetConsoleMode(stdout, outMode) 25 | return 26 | } 27 | -------------------------------------------------------------------------------- /cmd/ttyc/handlers/stdfds.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/Depau/switzerland" 8 | "github.com/Depau/ttyc" 9 | "github.com/Depau/ttyc/cmd/ttyc/handlers/shenanigans" 10 | "github.com/Depau/ttyc/utils" 11 | "github.com/Depau/ttyc/ws" 12 | "github.com/TwinProduction/go-color" 13 | "github.com/containerd/console" 14 | "io/ioutil" 15 | "net/http" 16 | "net/url" 17 | "os" 18 | "runtime" 19 | "sort" 20 | "time" 21 | ) 22 | 23 | // Tio-style (https://tio.github.io) console handler 24 | 25 | const ClearSequence = "\033c" 26 | const ( 27 | EscapeChar byte = 0x14 // Ctrl+T 28 | HelpChar byte = '?' 29 | QuitChar byte = 'q' 30 | ConfigChar byte = 'c' 31 | BreakChar byte = 'b' 32 | DetectBaudChar byte = 'B' 33 | ClearChar byte = 'l' 34 | CtrlTChar byte = 't' 35 | VersionChar byte = 'v' 36 | StatsChar byte = 's' 37 | LocalEchoChar byte = 'e' 38 | HexModeChar byte = 'h' 39 | TimestampsChar byte = 'T' 40 | ) 41 | 42 | type StatsDTO struct { 43 | Tx int64 `json:"tx"` 44 | Rx int64 `json:"rx"` 45 | TxRate int64 `json:"txRateBps"` 46 | RxRate int64 `json:"rxRateBps"` 47 | } 48 | 49 | type cmdInfo struct { 50 | HelpText string 51 | NonStandard bool 52 | } 53 | 54 | var cmdsInfo = map[byte]cmdInfo{ 55 | // Available for all implementations 56 | QuitChar: {"Quit", false}, 57 | ClearChar: {"Clear screen", false}, 58 | CtrlTChar: {"Send ctrl-t key code", false}, 59 | HelpChar: {"List available key commands", false}, 60 | ConfigChar: {"Show configuration", false}, 61 | VersionChar: {"Show version", false}, 62 | LocalEchoChar: {"Toggle local echo mode", false}, 63 | HexModeChar: {"Toggle hexadecimal mode", false}, 64 | TimestampsChar: {"Toggle timestamps", false}, 65 | // Available on Wi-Se server only 66 | BreakChar: {"Send break", true}, 67 | DetectBaudChar: {"Request baudrate detection", true}, 68 | StatsChar: {"Show statistics", true}, 69 | } 70 | 71 | type stdfdsHandler struct { 72 | client *ws.Client 73 | console *console.Console 74 | implementation ttyc.Implementation 75 | credentials *url.Userinfo 76 | server string 77 | expectingCommand bool 78 | localEchoMode bool 79 | hexMode bool 80 | showTimestamps bool 81 | nextIsTimestamp bool 82 | } 83 | 84 | func NewStdFdsHandler(client *ws.Client, implementation ttyc.Implementation, credentials *url.Userinfo, server string) (tty TtyHandler, err error) { 85 | tty = &stdfdsHandler{ 86 | client: client, 87 | implementation: implementation, 88 | credentials: credentials, 89 | server: server, 90 | console: nil, 91 | expectingCommand: false, 92 | localEchoMode: false, 93 | hexMode: false, 94 | showTimestamps: false, 95 | nextIsTimestamp: false, 96 | } 97 | return 98 | } 99 | 100 | func (s *stdfdsHandler) rawTtyPrintfLn(angry bool, format string, args ...interface{}) { 101 | var newLineFile *os.File 102 | if angry { 103 | ttyc.TtycAngryPrintf(format, args...) 104 | newLineFile = os.Stderr 105 | } else { 106 | ttyc.TtycPrintf(format, args...) 107 | newLineFile = os.Stdout 108 | } 109 | if s.console == nil { 110 | _, _ = newLineFile.WriteString("\n") 111 | } else { 112 | _, _ = newLineFile.WriteString("\r\n") 113 | } 114 | _ = newLineFile.Sync() 115 | } 116 | 117 | func (s *stdfdsHandler) handleStdin(closeChan <-chan interface{}, inChan <-chan []byte, outChan chan<- []byte, errChan chan<- error) { 118 | for { 119 | var input []byte 120 | 121 | //println("SELECT handleStdin") 122 | select { 123 | case <-closeChan: 124 | return 125 | case input = <-inChan: 126 | } 127 | //println("SELECTED handleStdin") 128 | 129 | // Check for new EscapeChars before handling any pending ones, since we may add one back that needs to be 130 | // passed through 131 | escapePos := bytes.Index(input, []byte{EscapeChar}) 132 | 133 | // Handle any pending commands, when EscapeChar was the last char of the previous buffer 134 | if s.expectingCommand { 135 | replacement := s.handleCommand(input[0], errChan) 136 | s.expectingCommand = false 137 | input = append(replacement, input[1:]...) 138 | 139 | if escapePos >= 0 { 140 | // Adjust the pre-existing escape char position based on the characters we added/removed to/from the 141 | // input buffer 142 | escapePos += 1 - len(replacement) 143 | } 144 | } 145 | 146 | // Handle new EscapeChars 147 | if escapePos >= 0 && escapePos == len(input)-1 { 148 | // Escape char is the last char, we need to handle it at the next iteration 149 | s.expectingCommand = true 150 | if len(input) == 1 { 151 | continue 152 | } 153 | input = input[:len(input)-1] 154 | } else if escapePos >= 0 { 155 | before := input[:escapePos] 156 | command := input[escapePos] 157 | after := input[escapePos+2:] 158 | replacement := s.handleCommand(command, errChan) 159 | input = bytes.Join([][]byte{before, after}, replacement) 160 | } 161 | // More than one escape char? I hope you're happy with your life. 162 | 163 | if s.localEchoMode { 164 | for _, char := range input { 165 | // If character is printable 166 | if (char >= 32 && char <= 126) || char == '\r' || char == '\n' { 167 | _, _ = os.Stdout.Write([]byte{char}) 168 | } 169 | } 170 | _ = os.Stdout.Sync() 171 | } 172 | 173 | outChan <- input 174 | } 175 | } 176 | 177 | func (s *stdfdsHandler) printStats() { 178 | statsUrl := ttyc.GetUrlFor(ttyc.UrlForStats, s.client.BaseUrl) 179 | res, err := http.Get(statsUrl.String()) 180 | if err != nil { 181 | ttyc.Trace() 182 | s.rawTtyPrintfLn(true, "Failed to get stats: %v", err) 183 | return 184 | } 185 | res, err = utils.EnsureAuth(res, s.credentials, nil) 186 | if err != nil { 187 | ttyc.Trace() 188 | s.rawTtyPrintfLn(true, "Failed to get stats: %v", err) 189 | return 190 | } 191 | buf, err := ioutil.ReadAll(res.Body) 192 | if err != nil { 193 | ttyc.Trace() 194 | s.rawTtyPrintfLn(true, "Failed to get stats: %v", err) 195 | return 196 | } 197 | stats := StatsDTO{} 198 | err = json.Unmarshal(buf, &stats) 199 | if err != nil { 200 | ttyc.Trace() 201 | s.rawTtyPrintfLn(true, "Failed to get stats: %v", err) 202 | return 203 | } 204 | s.rawTtyPrintfLn(false, "Statistics:") 205 | s.rawTtyPrintfLn(false, " Sent %d bytes, received %d bytes, tx %d bps, rx %d bps", stats.Tx, stats.Rx, stats.TxRate, stats.RxRate) 206 | } 207 | 208 | func (s *stdfdsHandler) handleCommand(command byte, errChan chan<- error) []byte { 209 | switch command { 210 | case QuitChar: 211 | println("") 212 | errChan <- fmt.Errorf("quitting") 213 | case ConfigChar: 214 | println("") 215 | s.rawTtyPrintfLn(false, "Configuration:") 216 | 217 | additionalServerInfo := "" 218 | if s.server != "" { 219 | additionalServerInfo = fmt.Sprintf(" (%s)", s.server) 220 | } 221 | wsUrl := ttyc.GetUrlFor(ttyc.UrlForWebSocket, s.client.BaseUrl) 222 | s.rawTtyPrintfLn(false, " Remote server: %s%s", wsUrl.String(), additionalServerInfo) 223 | 224 | if s.implementation == ttyc.ImplementationWiSe { 225 | sttyUrl := ttyc.GetUrlFor(ttyc.UrlForStty, s.client.BaseUrl) 226 | ttyConf, err := ttyc.GetStty(sttyUrl, s.credentials) 227 | if err == nil { 228 | s.rawTtyPrintfLn(false, " Baudrate: %d", *ttyConf.Baudrate) 229 | s.rawTtyPrintfLn(false, " Databits: %d", *ttyConf.Databits) 230 | s.rawTtyPrintfLn(false, " Flow: soft") 231 | s.rawTtyPrintfLn(false, " Stopbits: %d", *ttyConf.Stopbits) 232 | if ttyConf.Parity == nil { 233 | s.rawTtyPrintfLn(false, " Parity: none") 234 | } else { 235 | s.rawTtyPrintfLn(false, " Parity: %s", *ttyConf.Parity) 236 | } 237 | } else { 238 | s.rawTtyPrintfLn(false, "Failed to retrieve remote terminal configuration: %v", err) 239 | } 240 | } 241 | case DetectBaudChar: 242 | println("") 243 | if s.implementation == ttyc.ImplementationWiSe { 244 | s.rawTtyPrintfLn(false, "Requesting baud rate detection (it may take up to 10 seconds)") 245 | s.client.RequestBaudrateDetection() 246 | } else { 247 | s.rawTtyPrintfLn(true, "Baud rate detection is only available for Wi-Se") 248 | } 249 | case BreakChar: 250 | s.client.SendBreak() 251 | case ClearChar: 252 | // Clear screen using ANSI/VT100 escape code 253 | print(ClearSequence) 254 | _ = os.Stdout.Sync() 255 | case CtrlTChar: 256 | // Put back escape char into buffer 257 | return []byte{EscapeChar} 258 | case LocalEchoChar: 259 | s.localEchoMode = !s.localEchoMode 260 | case HexModeChar: 261 | s.hexMode = !s.hexMode 262 | case TimestampsChar: 263 | s.showTimestamps = !s.showTimestamps 264 | s.nextIsTimestamp = false 265 | case HelpChar: 266 | println("") 267 | s.rawTtyPrintfLn(false, "Key commands:") 268 | cmdsHelpOrder := make([]int, len(cmdsInfo)) 269 | i := 0 270 | for key := range cmdsInfo { 271 | cmdsHelpOrder[i] = int(key) 272 | i++ 273 | } 274 | // Sort chars with lowercase next to uppercase 275 | keyFn := func(index int) int { 276 | char := cmdsHelpOrder[index] 277 | ret := char * 2 278 | if char >= 'a' && char <= 'z' { 279 | ret = (char-32)*2 - 1 280 | } 281 | return ret 282 | } 283 | comparator := func(c1 int, c2 int) bool { return keyFn(c1) < keyFn(c2) } 284 | sort.Slice(cmdsHelpOrder, comparator) 285 | 286 | for _, key := range cmdsHelpOrder { 287 | info := cmdsInfo[byte(key)] 288 | if s.implementation != ttyc.ImplementationWiSe && info.NonStandard { 289 | continue 290 | } 291 | s.rawTtyPrintfLn(false, " ctrl-t %c %s", key, info.HelpText) 292 | } 293 | case StatsChar: 294 | s.printStats() 295 | case VersionChar: 296 | println() 297 | s.rawTtyPrintfLn(false, "ttyc %s", ttyc.VERSION) 298 | } 299 | 300 | return []byte{} 301 | } 302 | 303 | func bufferToHex(inBuf []byte) (outBuf []byte) { 304 | outBuf = []byte{} 305 | for _, value := range inBuf { 306 | if value == '\n' || value == '\r' { 307 | outBuf = append(outBuf, value) 308 | } else { 309 | byteStr := fmt.Sprintf("%02x ", value) 310 | outBuf = append(outBuf, []byte(byteStr)...) 311 | } 312 | } 313 | return 314 | } 315 | 316 | func (s *stdfdsHandler) injectTimestamps(inBuf []byte) (outBuf []byte) { 317 | outBuf = inBuf 318 | tstamp := []byte(fmt.Sprintf(ttyc.PlatformGray()+"[%s]"+color.Reset+" ", ttyc.Strftime.FormatString(time.Now()))) 319 | 320 | i := 0 321 | 322 | for i < len(outBuf) { 323 | if s.nextIsTimestamp && i != len(outBuf)-1 { 324 | end := append([]byte{}, outBuf[i:]...) 325 | outBuf = append(outBuf[:i], tstamp...) 326 | outBuf = append(outBuf, end...) 327 | i += len(tstamp) 328 | s.nextIsTimestamp = false 329 | } 330 | if outBuf[i] == '\n' { 331 | s.nextIsTimestamp = true 332 | } 333 | i++ 334 | } 335 | return 336 | } 337 | 338 | func (s *stdfdsHandler) printOutput(errChan chan<- error) { 339 | for { 340 | select { 341 | case <-s.client.CloseChan: 342 | return 343 | case buf := <-s.client.Output: 344 | if s.hexMode { 345 | buf = bufferToHex(buf) 346 | } 347 | if s.showTimestamps { 348 | buf = s.injectTimestamps(buf) 349 | } 350 | written := 0 351 | for written < len(buf) { 352 | bWritten, err := os.Stdout.Write(buf[written:]) 353 | if err != nil { 354 | errChan <- err 355 | return 356 | } 357 | written += bWritten 358 | } 359 | _ = os.Stdout.Sync() 360 | } 361 | } 362 | } 363 | 364 | func (s *stdfdsHandler) Run(errChan chan<- error) { 365 | if err := s.HandleReconnect(); err != nil { 366 | errChan <- err 367 | return 368 | } 369 | 370 | cmdHandlingChan := make(chan []byte, 1) 371 | go utils.CopyReaderToChan(s.client.CloseChan, os.Stdin, cmdHandlingChan, errChan) 372 | go s.handleStdin(s.client.CloseChan, cmdHandlingChan, s.client.Input, errChan) 373 | go s.printOutput(errChan) 374 | 375 | winch := make(chan switzerland.WinchSignal) 376 | switz := switzerland.GetSwitzerland() 377 | defer switz.Stop(winch) 378 | defer close(winch) 379 | switz.Notify(winch) 380 | 381 | for { 382 | select { 383 | case <-s.client.CloseChan: 384 | return 385 | case <-winch: 386 | if winSize, err := (*s.console).Size(); err != nil { 387 | ttyc.Trace() 388 | errChan <- err 389 | return 390 | } else { 391 | height := int(winSize.Height) 392 | // Windows seems to include the row below the bottom scrollbar 393 | if runtime.GOOS == "windows" { 394 | height -= 1 395 | } 396 | s.client.ResizeTerminal(int(winSize.Width), height) 397 | } 398 | case title := <-s.client.WinTitle: 399 | s.rawTtyPrintfLn(false, "Title: %s", title) 400 | case baudResult := <-s.client.DetectedBaudrate: 401 | approx := baudResult[0] 402 | measured := baudResult[1] 403 | if approx <= 0 { 404 | s.rawTtyPrintfLn(true, "Baudrate detection was not successful (detection only works while input is received)") 405 | break 406 | } 407 | if measured > 0 { 408 | s.rawTtyPrintfLn(false, "Detected baudrate: likely %d bps (measured %d bps)", approx, measured) 409 | } else { 410 | s.rawTtyPrintfLn(false, "Detected baudrate: likely %d bps", approx) 411 | } 412 | } 413 | } 414 | } 415 | 416 | func (s *stdfdsHandler) HandleDisconnect() error { 417 | if s.console != nil { 418 | if err := (*s.console).Reset(); err != nil { 419 | ttyc.Trace() 420 | return err 421 | } 422 | s.console = nil 423 | print("\r") 424 | 425 | if err := shenanigans.ClearConsole(); err != nil { 426 | ttyc.Trace() 427 | return err 428 | } 429 | } 430 | return nil 431 | } 432 | 433 | func (s *stdfdsHandler) HandleReconnect() error { 434 | current := console.Current() 435 | s.console = ¤t 436 | if err := current.SetRaw(); err != nil { 437 | ttyc.Trace() 438 | return err 439 | } 440 | winSize, err := current.Size() 441 | if err != nil { 442 | ttyc.Trace() 443 | return err 444 | } 445 | //println("RESIZE TERM") 446 | s.client.ResizeTerminal(int(winSize.Width), int(winSize.Height)) 447 | //println("TERM RESIZED") 448 | return nil 449 | } 450 | 451 | func (s *stdfdsHandler) Close() error { 452 | if err := s.HandleDisconnect(); err != nil { 453 | return err 454 | } 455 | return nil 456 | } 457 | -------------------------------------------------------------------------------- /cmd/ttyc/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "github.com/Depau/ttyc" 7 | "github.com/Depau/ttyc/cmd/ttyc/handlers" 8 | "github.com/Depau/ttyc/ws" 9 | "github.com/mattn/go-isatty" 10 | "github.com/mkideal/cli" 11 | "math" 12 | "net/http" 13 | "net/url" 14 | "os" 15 | "time" 16 | ) 17 | 18 | func (argv *Config) AutoHelp() bool { 19 | return argv.Help 20 | } 21 | 22 | func (argv *Config) Validate(ctx *cli.Context) error { 23 | // Windows bullshit 24 | if argv.GetWaitDebugger() { 25 | fmt.Print("Attach the debugger now, then press Enter to continue...") 26 | bufio.NewReader(os.Stdin).ReadBytes('\n') 27 | } 28 | 29 | if !(argv.User != "" && argv.Pass != "") && !(argv.User == "" && argv.Pass == "") { 30 | return fmt.Errorf("user and password must be both provided or not provided at all") 31 | } 32 | parsedUrl, err := url.Parse(argv.Url) 33 | if err != nil { 34 | return fmt.Errorf("invalid URL: %v", err) 35 | } 36 | if parsedUrl.Scheme != "http" && parsedUrl.Scheme != "https" { 37 | return fmt.Errorf("invalid URL, must be http or https") 38 | } 39 | if argv.GetTty() == "" && (!isatty.IsTerminal(os.Stdout.Fd()) || !isatty.IsTerminal(os.Stdin.Fd())) { 40 | return fmt.Errorf("cannot launch in terminal mode when standard file descriptors aren't terminals") 41 | } 42 | if !(argv.Backoff == "none" || argv.Backoff == "linear" || argv.Backoff == "exponential") { 43 | return fmt.Errorf("invalid backoff: %d", argv.Baud) 44 | } 45 | if argv.Baud != -1 && argv.Baud <= 0 { 46 | return fmt.Errorf("invalid baud rate: %d", argv.Baud) 47 | } 48 | if !(argv.Parity == "even" || argv.Parity == "odd" || argv.Parity == "none" || argv.Parity == "") { 49 | return fmt.Errorf("invalid parity: %s", argv.Parity) 50 | } 51 | if !(argv.Databits == -1 || (argv.Databits >= 5 && argv.Databits <= 8)) { 52 | return fmt.Errorf("invalid data bits: %d", argv.Databits) 53 | } 54 | if !(argv.Stopbits == -1 || argv.Stopbits == 1 || argv.Stopbits == 2) { 55 | return fmt.Errorf("invalid stop bits: %d", argv.Stopbits) 56 | } 57 | return nil 58 | } 59 | 60 | func stty(config *Config, sttyUrl *url.URL, credentials *url.Userinfo) error { 61 | dto := ttyc.SttyDTO{ 62 | Baudrate: nil, 63 | Databits: nil, 64 | Stopbits: nil, 65 | Parity: nil, 66 | } 67 | baud := uint(config.Baud) 68 | bits := uint8(config.Databits) 69 | stop := uint8(config.Stopbits) 70 | paramsToUpdate := 0 71 | if config.Baud > 0 { 72 | dto.Baudrate = &baud 73 | paramsToUpdate++ 74 | } 75 | if config.Databits > 0 { 76 | dto.Databits = &bits 77 | paramsToUpdate++ 78 | } 79 | if config.Stopbits > 0 { 80 | dto.Stopbits = &stop 81 | paramsToUpdate++ 82 | } 83 | if config.Parity != "" { 84 | dto.Parity = &config.Parity 85 | paramsToUpdate++ 86 | } 87 | if paramsToUpdate == 0 { 88 | return nil 89 | } 90 | 91 | _, err := ttyc.Stty(sttyUrl, credentials, &dto) 92 | if err != nil { 93 | ttyc.Trace() 94 | return err 95 | } 96 | return nil 97 | } 98 | 99 | func doHandshakeAndSetTerminal(baseUrl *url.URL, credentials *url.Userinfo, config *Config) (token string, implementation ttyc.Implementation, server string, err error) { 100 | tokenUrl := ttyc.GetUrlFor(ttyc.UrlForToken, baseUrl) 101 | sttyHttpUrl := ttyc.GetUrlFor(ttyc.UrlForStty, baseUrl) 102 | 103 | token, implementation, server, err = ttyc.Handshake(tokenUrl, credentials) 104 | if err != nil { 105 | err = fmt.Errorf("handshake failed (unable to connect or wrong user/pass): %v\n", err) 106 | return 107 | } 108 | 109 | if implementation == ttyc.ImplementationWiSe { 110 | if err := stty(config, sttyHttpUrl, credentials); err != nil { 111 | err = fmt.Errorf("unable to set remote UART parameters: %v\n", err) 112 | } 113 | } 114 | return 115 | } 116 | 117 | func nextBackoff(curBsckoff time.Duration, config *Config) time.Duration { 118 | if config.Backoff == "none" { 119 | return time.Duration(config.Reconnect) * time.Second 120 | } else if config.Backoff == "linear" { 121 | return curBsckoff + time.Duration(config.BackoffValue)*time.Second 122 | } else if config.Backoff == "exponential" { 123 | return curBsckoff * time.Duration(config.BackoffValue) 124 | } 125 | panic("fix command line argument validator") 126 | } 127 | 128 | func main() { 129 | config := Config{} 130 | 131 | ret := cli.Run(&config, func(ctx *cli.Context) error { 132 | return nil 133 | }, "ttyd protocol client") 134 | 135 | if ret != 0 || config.Help { 136 | os.Exit(ret) 137 | } 138 | if config.Version { 139 | fmt.Printf("ttyc %s\n", ttyc.VERSION) 140 | println(ttyc.COPYRIGHT) 141 | 142 | os.Exit(0) 143 | } 144 | 145 | //fmt.Printf("%+v\n", config); 146 | 147 | baseUrl, _ := url.Parse(config.Url) 148 | 149 | var credentials *url.Userinfo = nil 150 | if config.User != "" { 151 | credentials = url.UserPassword(config.User, config.Pass) 152 | } else if config.User == "" && baseUrl.User != nil { 153 | credentials = baseUrl.User 154 | } 155 | baseUrl.User = nil 156 | 157 | // Reduce HTTP timeout so that the client doesn't stall on reconnection when the server is down for a few seconds 158 | http.DefaultClient.Timeout = time.Duration(math.Max(math.Min(float64(config.Reconnect), 5.0), 2.0)) * time.Second 159 | 160 | token, implementation, server, err := doHandshakeAndSetTerminal(baseUrl, credentials, &config) 161 | if err != nil { 162 | ttyc.TtycAngryPrintf("%v\n", err) 163 | os.Exit(1) 164 | } 165 | 166 | client, err := ws.DialAndAuth(baseUrl, &token, config.Watchdog) 167 | if err != nil { 168 | ttyc.TtycAngryPrintf("unable to connect or authenticate to server: %v\n", err) 169 | os.Exit(1) 170 | } 171 | defer client.Close() 172 | go client.Run(config.Watchdog) 173 | 174 | handlerErrChan := make(chan error, 1) 175 | defer close(handlerErrChan) 176 | 177 | var handler handlers.TtyHandler 178 | if config.GetTty() == "" { 179 | handler, err = handlers.NewStdFdsHandler(client, implementation, credentials, server) 180 | if err != nil { 181 | ttyc.TtycAngryPrintf("Unable to launch console handler: %v\n", err) 182 | os.Exit(1) 183 | } 184 | ttyc.TtycPrintf("ttyc %s\n", ttyc.VERSION) 185 | ttyc.TtycPrintf("Press ctrl-t q to quit, ctrl-t ? for help\n") 186 | ttyc.TtycPrintf("Connected\n") 187 | } else { 188 | handler, err = handlers.NewPtyHandler(client, config.GetTty()) 189 | if err != nil { 190 | ttyc.TtycAngryPrintf("Unable to launch PTY handler: %v\n", err) 191 | os.Exit(1) 192 | } 193 | } 194 | defer handler.Close() 195 | go handler.Run(handlerErrChan) 196 | 197 | var fatalError error 198 | 199 | reconnect := time.Duration(config.Reconnect) * time.Second 200 | for { 201 | select { 202 | case fatalError = <-handlerErrChan: 203 | if err := handler.HandleDisconnect(); err != nil { 204 | ttyc.TtycAngryPrintf("Error while handling disconnection: %v\n", err) 205 | } 206 | ttyc.TtycAngryPrintf("%v\n", fatalError) 207 | return 208 | case fatalError = <-client.Error: 209 | // Restore terminal, if any 210 | if err := handler.HandleDisconnect(); err != nil { 211 | ttyc.TtycAngryPrintf("Error while handling disconnection: %v\n", err) 212 | return 213 | } 214 | 215 | println() 216 | ttyc.TtycAngryPrintf("Server disconnected: %v\n", fatalError) 217 | if err := client.SoftClose(); err != nil { 218 | ttyc.TtycAngryPrintf("Error while cleaning up the WebSocket: %v\n", err) 219 | } 220 | if config.Reconnect < 0 { 221 | return 222 | } 223 | 224 | for { 225 | if reconnect.Seconds() <= 0 { 226 | ttyc.TtycPrintf("Reconnecting\n") 227 | } else { 228 | ttyc.TtycPrintf("Reconnecting in %d seconds\n", int(reconnect.Seconds())) 229 | <-time.After(reconnect) 230 | } 231 | reconnect = nextBackoff(reconnect, &config) 232 | 233 | token, _, _, err := doHandshakeAndSetTerminal(baseUrl, credentials, &config) 234 | if err != nil { 235 | ttyc.TtycAngryPrintf("Unable to perform authentication: %v\n", err) 236 | continue 237 | } 238 | if err := client.Redial(&token); err != nil { 239 | ttyc.TtycAngryPrintf("Unable to connect or authenticate to server: %v\n", err) 240 | continue 241 | } 242 | break 243 | } 244 | ttyc.TtycPrintf("Reconnected\n") 245 | go client.Run(config.Watchdog) 246 | 247 | // Put back terminal into raw mode 248 | if err := handler.HandleReconnect(); err != nil { 249 | ttyc.TtycAngryPrintf("Error while handling reconnection: %v\n", err) 250 | return 251 | } 252 | } 253 | } 254 | 255 | } 256 | -------------------------------------------------------------------------------- /cmd/wistty/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/Depau/ttyc" 7 | "github.com/mkideal/cli" 8 | "log" 9 | "net/url" 10 | "os" 11 | ) 12 | 13 | type Config struct { 14 | Help bool `cli:"!h,help" usage:"Show help"` 15 | Url string `cli:"U,url" usage:"Server URL"` 16 | User string `cli:"u,user" usage:"Username for authentication" dft:""` 17 | Pass string `cli:"k,pass" usage:"Password for authentication" dft:""` 18 | Json bool `cli:"j,json" usage:"Return machine-readable JSON output"` 19 | Baud int `cli:"b,baudrate" usage:"Set remote baud rate [bps]" dft:"-1"` 20 | Parity string `cli:"p,parity" usage:"Set remote parity [odd|even|none]" dft:""` 21 | Databits int `cli:"d,databits" usage:"Set remote data bits [5|6|7|8]" dft:"-1"` 22 | Stopbits int `cli:"s,stopbits" usage:"Set remote stop bits [1|2]" dft:"-1"` 23 | Version bool `cli:"!v,version" usage:"Show version"` 24 | } 25 | 26 | func (argv *Config) AutoHelp() bool { 27 | return argv.Help 28 | } 29 | 30 | func (argv *Config) Validate(ctx *cli.Context) error { 31 | if !(argv.User != "" && argv.Pass != "") && !(argv.User == "" && argv.Pass == "") { 32 | return fmt.Errorf("user and password must be both provided or not provided at all") 33 | } 34 | parsedUrl, err := url.Parse(argv.Url) 35 | if err != nil { 36 | return fmt.Errorf("invalid URL: %v", err) 37 | } 38 | if parsedUrl.Scheme != "http" && parsedUrl.Scheme != "https" { 39 | return fmt.Errorf("invalid URL, must be http or https") 40 | } 41 | if argv.Baud != -1 && argv.Baud <= 0 { 42 | return fmt.Errorf("invalid baud rate: %d", argv.Baud) 43 | } 44 | if !(argv.Parity == "even" || argv.Parity == "odd" || argv.Parity == "none" || argv.Parity == "") { 45 | return fmt.Errorf("invalid parity: %s", argv.Parity) 46 | } 47 | if !(argv.Databits == -1 || (argv.Databits >= 5 && argv.Databits <= 8)) { 48 | return fmt.Errorf("invalid data bits: %d", argv.Databits) 49 | } 50 | if !(argv.Stopbits == -1 || argv.Stopbits == 1 || argv.Stopbits == 2) { 51 | return fmt.Errorf("invalid stop bits: %d", argv.Stopbits) 52 | } 53 | return nil 54 | } 55 | 56 | func stty(config *Config, sttyUrl *url.URL, credentials *url.Userinfo) (stty ttyc.SttyDTO, err error) { 57 | dto := ttyc.SttyDTO{ 58 | Baudrate: nil, 59 | Databits: nil, 60 | Stopbits: nil, 61 | Parity: nil, 62 | } 63 | baud := uint(config.Baud) 64 | bits := uint8(config.Databits) 65 | stop := uint8(config.Stopbits) 66 | 67 | paramsToUpdate := 0 68 | if config.Baud > 0 { 69 | dto.Baudrate = &baud 70 | paramsToUpdate++ 71 | } 72 | if config.Databits > 0 { 73 | dto.Databits = &bits 74 | paramsToUpdate++ 75 | } 76 | if config.Stopbits > 0 { 77 | dto.Stopbits = &stop 78 | paramsToUpdate++ 79 | } 80 | if config.Parity != "" { 81 | dto.Parity = &config.Parity 82 | paramsToUpdate++ 83 | } 84 | if paramsToUpdate == 0 { 85 | return ttyc.GetStty(sttyUrl, credentials) 86 | } 87 | 88 | stty, err = ttyc.Stty(sttyUrl, credentials, &dto) 89 | return 90 | } 91 | 92 | func main() { 93 | config := Config{} 94 | 95 | ret := cli.Run(&config, func(ctx *cli.Context) error { 96 | return nil 97 | }, "wistty (ttyc) - Manage Wi-Se remote terminal parameters") 98 | 99 | if ret != 0 || config.Help { 100 | os.Exit(ret) 101 | } 102 | if config.Version { 103 | fmt.Printf("wistty (ttyc) %s\n", ttyc.VERSION) 104 | println(ttyc.COPYRIGHT) 105 | 106 | os.Exit(0) 107 | } 108 | 109 | baseUrl, _ := url.Parse(config.Url) 110 | 111 | var credentials *url.Userinfo = nil 112 | if config.User != "" { 113 | credentials = url.UserPassword(config.User, config.Pass) 114 | } else if config.User == "" && baseUrl.User != nil { 115 | credentials = baseUrl.User 116 | } 117 | baseUrl.User = nil 118 | 119 | sttyHttpUrl := ttyc.GetUrlFor(ttyc.UrlForStty, baseUrl) 120 | stty, err := stty(&config, sttyHttpUrl, credentials) 121 | if err != nil { 122 | log.Fatalln("could not set terminal:", err) 123 | } 124 | 125 | if config.Json { 126 | strStty, err := json.Marshal(stty) 127 | if err != nil { 128 | log.Fatalln("could not parse stty output:", err) 129 | } 130 | println(string(strStty)) 131 | } else { 132 | var parityChar rune 133 | if stty.Parity == nil { 134 | parityChar = 'n' 135 | } else if *stty.Parity == "even" { 136 | parityChar = 'e' 137 | } else if *stty.Parity == "odd" { 138 | parityChar = 'o' 139 | } 140 | fmt.Printf("%d %d%c%d\n", *stty.Baudrate, *stty.Databits, parityChar, *stty.Stopbits) 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /common.go: -------------------------------------------------------------------------------- 1 | package ttyc 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/Depau/ttyc/utils" 8 | "github.com/TwinProduction/go-color" 9 | strftimeMod "github.com/lestrrat-go/strftime" 10 | "io" 11 | "io/ioutil" 12 | "net/http" 13 | "net/url" 14 | "os" 15 | "path" 16 | "runtime" 17 | "strings" 18 | "time" 19 | ) 20 | 21 | const VERSION = "v0.4" 22 | const COPYRIGHT = "Copyright (c) 2022 Davide Depau\n\n" + 23 | "License: GNU GPL version 3.0 or later .\n" + 24 | "This is free software; see the source for copying conditions. There is NO\n" + 25 | "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." 26 | 27 | var Strftime, _ = strftimeMod.New("%H:%M:%S") 28 | 29 | type TokenDTO struct { 30 | Token string `json:"token"` 31 | } 32 | 33 | type Implementation uint8 34 | 35 | const ( 36 | ImplementationTtyd = iota 37 | ImplementationWiSe 38 | ) 39 | 40 | type SttyDTO struct { 41 | Baudrate *uint `json:"baudrate"` 42 | Databits *uint8 `json:"databits"` 43 | Stopbits *uint8 `json:"stopbits"` 44 | Parity *string `json:"parity"` 45 | } 46 | 47 | type sttyInDTO struct { 48 | Baudrate uint `json:"baudrate"` 49 | Databits uint8 `json:"bits"` 50 | Stopbits uint8 `json:"stop"` 51 | Parity *int `json:"parity"` 52 | } 53 | 54 | const ( 55 | UrlForToken = iota 56 | UrlForWebSocket 57 | UrlForStty 58 | UrlForStats 59 | UrlForWhoami 60 | ) 61 | 62 | func GetUrlFor(urlFor int, baseURL *url.URL) (outUrl *url.URL) { 63 | outUrl, _ = url.Parse(baseURL.String()) 64 | 65 | switch urlFor { 66 | case UrlForToken: 67 | outUrl.Path = path.Join(baseURL.Path, "token") 68 | case UrlForStty: 69 | outUrl.Path = path.Join(baseURL.Path, "stty") 70 | case UrlForStats: 71 | outUrl.Path = path.Join(baseURL.Path, "stats") 72 | case UrlForWhoami: 73 | outUrl.Path = path.Join(baseURL.Path, "whoami") 74 | case UrlForWebSocket: 75 | if baseURL.Scheme == "https" { 76 | outUrl.Scheme = "wss" 77 | } else { 78 | outUrl.Scheme = "ws" 79 | } 80 | outUrl.Path = path.Join(baseURL.Path, "ws") 81 | default: 82 | panic("invalid urlfor\n") 83 | } 84 | 85 | return 86 | } 87 | 88 | func Handshake(url *url.URL, credentials *url.Userinfo) (token string, impl Implementation, server string, err error) { 89 | var resp *http.Response 90 | var body []byte 91 | 92 | if resp, err = http.Get(url.String()); err != nil { 93 | Trace() 94 | return 95 | } 96 | resp, err = utils.EnsureAuth(resp, credentials, nil) 97 | if err != nil { 98 | Trace() 99 | return 100 | } 101 | defer resp.Body.Close() 102 | 103 | impl = ImplementationTtyd 104 | server = "" 105 | if srv := resp.Header.Get("Server"); srv != "" { 106 | server = srv 107 | if strings.Contains(strings.ToLower(srv), "wi-se") { 108 | impl = ImplementationWiSe 109 | } 110 | } 111 | 112 | if body, err = ioutil.ReadAll(resp.Body); err != nil { 113 | Trace() 114 | return 115 | } 116 | dto := TokenDTO{} 117 | if err = json.Unmarshal(body, &dto); err != nil { 118 | Trace() 119 | return 120 | } 121 | token = dto.Token 122 | return 123 | } 124 | 125 | func parseStty(body []byte) (stty SttyDTO, err error) { 126 | sttyIn := sttyInDTO{} 127 | err = json.Unmarshal(body, &sttyIn) 128 | if err != nil { 129 | Trace() 130 | return 131 | } 132 | 133 | stty = SttyDTO{ 134 | Baudrate: &sttyIn.Baudrate, 135 | Databits: &sttyIn.Databits, 136 | Stopbits: &sttyIn.Stopbits, 137 | } 138 | if sttyIn.Parity == nil { 139 | stty.Parity = nil 140 | } else { 141 | var parity string 142 | if *sttyIn.Parity == 0 { 143 | parity = "even" 144 | } else { 145 | parity = "odd" 146 | } 147 | stty.Parity = &parity 148 | } 149 | return 150 | } 151 | 152 | func GetStty(url *url.URL, credentials *url.Userinfo) (stty SttyDTO, err error) { 153 | httpClient := http.Client{ 154 | Timeout: 3 * time.Second, 155 | } 156 | resp, err := httpClient.Get(url.String()) 157 | if err != nil { 158 | Trace() 159 | return 160 | } 161 | resp, err = utils.EnsureAuth(resp, credentials, nil) 162 | if err != nil { 163 | Trace() 164 | return 165 | } 166 | 167 | buf, err := ioutil.ReadAll(resp.Body) 168 | if err != nil { 169 | Trace() 170 | return 171 | } 172 | stty, err = parseStty(buf) 173 | return 174 | } 175 | 176 | func Stty(url *url.URL, credentials *url.Userinfo, dto *SttyDTO) (stty SttyDTO, err error) { 177 | // Generate json manually since golang can't generate it properly 178 | var jsonItems []string 179 | if dto.Baudrate != nil { 180 | jsonItems = append(jsonItems, fmt.Sprintf("\"baudrate\": %d", *dto.Baudrate)) 181 | } 182 | if dto.Stopbits != nil { 183 | jsonItems = append(jsonItems, fmt.Sprintf("\"stop\": %d", *dto.Stopbits)) 184 | } 185 | if dto.Databits != nil { 186 | jsonItems = append(jsonItems, fmt.Sprintf("\"bits\": %d", *dto.Databits)) 187 | } 188 | if dto.Parity != nil { 189 | if *dto.Parity == "none" { 190 | jsonItems = append(jsonItems, "\"parity\": null") 191 | } else if *dto.Parity == "even" { 192 | jsonItems = append(jsonItems, "\"parity\": 0") 193 | } else if *dto.Parity == "odd" { 194 | jsonItems = append(jsonItems, "\"parity\": 1") 195 | } 196 | } 197 | var sb strings.Builder 198 | sb.WriteString("{") 199 | sb.WriteString(strings.Join(jsonItems, ",")) 200 | sb.WriteString("}") 201 | 202 | resp, err := http.Post(url.String(), "application/json", bytes.NewBuffer([]byte(sb.String()))) 203 | if err != nil { 204 | Trace() 205 | return 206 | } 207 | resp, err = utils.EnsureAuth(resp, credentials, bytes.NewBuffer([]byte(sb.String()))) 208 | if err != nil { 209 | Trace() 210 | return 211 | } 212 | if resp.StatusCode != 200 { 213 | err = fmt.Errorf("HTTP status %d", resp.StatusCode) 214 | return 215 | } 216 | buf, err := ioutil.ReadAll(resp.Body) 217 | if err != nil { 218 | Trace() 219 | return 220 | } 221 | stty, err = parseStty(buf) 222 | return 223 | } 224 | 225 | func PlatformGray() string { 226 | if runtime.GOOS == "windows" { 227 | return color.Gray 228 | } 229 | return "\u001B[1;30m" 230 | } 231 | 232 | func PlatformYellow() string { 233 | if runtime.GOOS == "windows" { 234 | return color.Yellow 235 | } 236 | return "\u001B[31m" 237 | } 238 | 239 | func TtycErrFprintf(w io.Writer, format string, a ...interface{}) { 240 | // Ignore fprintf errors here since I wasn't planning to care anywhere else regardless 241 | _, _ = fmt.Fprintf(w, color.Red+"[ttyc %s] ", Strftime.FormatString(time.Now())) 242 | _, _ = fmt.Fprintf(w, format, a...) 243 | _, _ = fmt.Fprint(w, color.Reset) 244 | } 245 | 246 | func TtycFprintf(w io.Writer, format string, a ...interface{}) { 247 | // Ignore fprintf errors here since I wasn't planning to care anywhere else regardless 248 | _, _ = fmt.Fprintf(w, PlatformYellow()+"[ttyc %s] ", Strftime.FormatString(time.Now())) 249 | _, _ = fmt.Fprintf(w, format, a...) 250 | _, _ = fmt.Fprint(w, color.Reset) 251 | } 252 | 253 | func TtycErrPrintf(format string, args ...interface{}) { 254 | TtycErrFprintf(os.Stderr, format, args...) 255 | } 256 | 257 | // Cause why not 258 | func TtycAngryPrintf(format string, args ...interface{}) { 259 | TtycErrPrintf(format, args...) 260 | } 261 | 262 | func TtycPrintf(format string, args ...interface{}) { 263 | TtycFprintf(os.Stdout, format, args...) 264 | } 265 | -------------------------------------------------------------------------------- /debug.go: -------------------------------------------------------------------------------- 1 | package ttyc 2 | 3 | // https://stackoverflow.com/a/46289376/1124621 4 | func Trace() { 5 | //pc := make([]uintptr, 15) 6 | //n := runtime.Callers(2, pc) 7 | //frames := runtime.CallersFrames(pc[:n]) 8 | //frame, _ := frames.Next() 9 | //fmt.Printf("%s:%d %s\n", frame.File, frame.Line, frame.Function) 10 | } 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Depau/ttyc 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/Depau/switzerland v0.0.0-20210627232915-baff755487c4 7 | github.com/TwinProduction/go-color v1.0.0 8 | github.com/containerd/console v1.0.2 9 | github.com/lestrrat-go/strftime v1.0.4 10 | github.com/mattn/go-isatty v0.0.12 11 | github.com/mkideal/cli v0.2.5 12 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c 13 | nhooyr.io/websocket v1.8.6 14 | ) 15 | 16 | // Fork that does not enable OPOST on raw TTY 17 | replace github.com/containerd/console v1.0.2 => github.com/Depau/console v1.0.2-0.20210627210027-beeaa4cc766b 18 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Depau/console v1.0.2-0.20210627210027-beeaa4cc766b h1:x3WGdJm8V49ilx6TVZyEpAOXcS7Jv4Sgji/Vf7678yk= 2 | github.com/Depau/console v1.0.2-0.20210627210027-beeaa4cc766b/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= 3 | github.com/Depau/switzerland v0.0.0-20210627232915-baff755487c4 h1:JPjGZoEP6R422R13TJ4W+5z9iJgimHKbq9MoSJh/rLI= 4 | github.com/Depau/switzerland v0.0.0-20210627232915-baff755487c4/go.mod h1:ras8o9p1m6dTOnAs973YUrdob53MiZ8iBgRdSv8iegg= 5 | github.com/TwinProduction/go-color v1.0.0 h1:8n59tqmLmt8jyRsY44RPy2ixPDDw0FcVoAhlYeyz3Jw= 6 | github.com/TwinProduction/go-color v1.0.0/go.mod h1:5hWpSyT+mmKPjCwPNEruBW5Dkbs/2PwOuU468ntEXNQ= 7 | github.com/comail/colog v0.0.0-20160416085026-fba8e7b1f46c/go.mod h1:1WwgAwMKQLYG5I2FBhpVx94YTOAuB2W59IZ7REjSE6Y= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 12 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 13 | github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= 14 | github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= 15 | github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= 16 | github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 17 | github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= 18 | github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= 19 | github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= 20 | github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= 21 | github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= 22 | github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= 23 | github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= 24 | github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= 25 | github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= 26 | github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= 27 | github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= 28 | github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= 29 | github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 30 | github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= 31 | github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= 32 | github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= 33 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 34 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 35 | github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= 36 | github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 37 | github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= 38 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 39 | github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eTO0Q8= 40 | github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= 41 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 42 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 43 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 44 | github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= 45 | github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= 46 | github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= 47 | github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= 48 | github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= 49 | github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= 50 | github.com/lestrrat-go/strftime v1.0.4 h1:T1Rb9EPkAhgxKqbcMIPguPq8glqXTA1koF8n9BHElA8= 51 | github.com/lestrrat-go/strftime v1.0.4/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g= 52 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 53 | github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw= 54 | github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= 55 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 56 | github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= 57 | github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= 58 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 59 | github.com/mkideal/cli v0.2.5 h1:Lc2v2bijpYbl4TUAbstLx9X7o90agDWk7Z3I8AZTJ1Y= 60 | github.com/mkideal/cli v0.2.5/go.mod h1:XaQYNUpBxFxm15Gs9HILpG6bRuTKMWvuW3bSc+M8p0g= 61 | github.com/mkideal/expr v0.1.0 h1:fzborV9TeSUmLm0aEQWTWcexDURFFo4v5gHSc818Kl8= 62 | github.com/mkideal/expr v0.1.0/go.mod h1:vL1DsSb87ZtU6IEjOtUfxw98z0FQbzS8xlGtnPkKdzg= 63 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= 64 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 65 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= 66 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 67 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 68 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 69 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 70 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 71 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 72 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 73 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= 74 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 75 | github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= 76 | github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= 77 | github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= 78 | github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= 79 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 80 | github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= 81 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 82 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= 83 | golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= 84 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 85 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 86 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 87 | golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 88 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 89 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 90 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 91 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk= 92 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 93 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM= 94 | golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= 95 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 96 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 97 | golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 98 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 99 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 100 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 101 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 102 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 103 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 104 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 105 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 106 | nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= 107 | nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= 108 | -------------------------------------------------------------------------------- /utils/copier.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | // outChan should have len == 1, so writing to it blocks, there is no buffering and the buffer isn't overwritten 9 | func CopyReaderToChan(closeChan <-chan interface{}, fd io.Reader, outChan chan<- []byte, errChan chan<- error) { 10 | useBuf2 := false 11 | buffer1 := make([]byte, 4096) 12 | buffer2 := make([]byte, 4096) 13 | for { 14 | select { 15 | case <-closeChan: 16 | return 17 | default: 18 | } 19 | 20 | var buf []byte 21 | if useBuf2 { 22 | buf = buffer2 23 | } else { 24 | buf = buffer1 25 | } 26 | useBuf2 = !useBuf2 27 | 28 | //println("BLOCKING CopyReaderToChan") 29 | bRead, err := fd.Read(buf) 30 | //println("Unblocked CopyReaderToChan") 31 | 32 | if err != nil { 33 | errChan <- fmt.Errorf("tty error (usually terminal closed), shutting down: %v", err) 34 | return 35 | } 36 | outChan <- buf[0:bRead] 37 | } 38 | } 39 | 40 | func CopyChanToWriter(closeChan <-chan interface{}, inChan <-chan []byte, fd io.Writer, errChan chan<- error) { 41 | for { 42 | //println("SELECT CopyChanToWriter") 43 | select { 44 | case <-closeChan: 45 | return 46 | case buf := <-inChan: 47 | written := 0 48 | for written < len(buf) { 49 | bWritten, err := fd.Write(buf[written:]) 50 | if err != nil { 51 | errChan <- err 52 | return 53 | } 54 | written += bWritten 55 | } 56 | } 57 | //println("SELECTED CopyChanToWriter") 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /utils/httpAuth.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | // Adapted from https://github.com/ryanjdew/http-digest-auth-client 4 | // License: Apache 2.0 5 | 6 | import ( 7 | "crypto/md5" 8 | "crypto/rand" 9 | "encoding/base64" 10 | "fmt" 11 | "io" 12 | "net/http" 13 | "net/url" 14 | "strings" 15 | ) 16 | 17 | // DigestHeaders tracks the state of authentication 18 | type DigestHeaders struct { 19 | Realm string 20 | Qop string 21 | Method string 22 | Nonce string 23 | Opaque string 24 | Algorithm string 25 | HA1 string 26 | HA2 string 27 | Cnonce string 28 | Path string 29 | Nc int16 30 | Username string 31 | Password string 32 | } 33 | 34 | func basicAuth(auth *url.Userinfo) string { 35 | password, _ := auth.Password() 36 | header := auth.Username() + ":" + password 37 | return base64.StdEncoding.EncodeToString([]byte(header)) 38 | } 39 | 40 | func (d *DigestHeaders) digestChecksum() { 41 | switch d.Algorithm { 42 | case "MD5": 43 | // A1 44 | h := md5.New() 45 | A1 := fmt.Sprintf("%s:%s:%s", d.Username, d.Realm, d.Password) 46 | io.WriteString(h, A1) 47 | d.HA1 = fmt.Sprintf("%x", h.Sum(nil)) 48 | 49 | // A2 50 | h = md5.New() 51 | A2 := fmt.Sprintf("%s:%s", d.Method, d.Path) 52 | io.WriteString(h, A2) 53 | d.HA2 = fmt.Sprintf("%x", h.Sum(nil)) 54 | case "MD5-sess": 55 | // A1 56 | h := md5.New() 57 | A1 := fmt.Sprintf("%s:%s:%s", d.Username, d.Realm, d.Password) 58 | io.WriteString(h, A1) 59 | haPre := fmt.Sprintf("%x", h.Sum(nil)) 60 | h = md5.New() 61 | A1 = fmt.Sprintf("%s:%s:%s", haPre, d.Nonce, d.Cnonce) 62 | io.WriteString(h, A1) 63 | d.HA1 = fmt.Sprintf("%x", h.Sum(nil)) 64 | 65 | // A2 66 | h = md5.New() 67 | A2 := fmt.Sprintf("%s:%s", d.Method, d.Path) 68 | io.WriteString(h, A2) 69 | d.HA2 = fmt.Sprintf("%x", h.Sum(nil)) 70 | default: 71 | //token 72 | } 73 | } 74 | 75 | // ApplyAuth adds proper auth header to the passed request 76 | func (d *DigestHeaders) ApplyAuth(req *http.Request) { 77 | d.Nc += 0x1 78 | d.Cnonce = randomKey() 79 | d.Method = req.Method 80 | d.Path = req.URL.RequestURI() 81 | d.digestChecksum() 82 | response := h(strings.Join([]string{d.HA1, d.Nonce, fmt.Sprintf("%08x", d.Nc), 83 | d.Cnonce, d.Qop, d.HA2}, ":")) 84 | AuthHeader := fmt.Sprintf(`Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%08x, qop=%s, response="%s", algorithm=%s`, 85 | d.Username, d.Realm, d.Nonce, d.Path, d.Cnonce, d.Nc, d.Qop, response, d.Algorithm) 86 | if d.Opaque != "" { 87 | AuthHeader = fmt.Sprintf(`%s, opaque="%s"`, AuthHeader, d.Opaque) 88 | } 89 | req.Header.Set("Authorization", AuthHeader) 90 | } 91 | 92 | func EnsureAuth(resp *http.Response, auth *url.Userinfo, body io.Reader) (outResp *http.Response, err error) { 93 | if resp.StatusCode != 401 { 94 | return resp, nil 95 | } 96 | _ = resp.Body.Close() 97 | 98 | if auth == nil { 99 | return nil, fmt.Errorf("authentication required but credentials not provided") 100 | } 101 | if _, ok := auth.Password(); !ok { 102 | return nil, fmt.Errorf("authentication is required but password was not provided") 103 | } 104 | 105 | client := &http.Client{} 106 | wwwAuth := resp.Header.Get("Www-Authenticate") 107 | if strings.HasPrefix(strings.ToLower(wwwAuth), "basic") { 108 | req, err := http.NewRequest(resp.Request.Method, resp.Request.URL.String(), body) 109 | if err != nil { 110 | return nil, err 111 | } 112 | req.Header = resp.Request.Header.Clone() 113 | req.Header.Add("Authorization", "Basic "+basicAuth(auth)) 114 | outResp, err = client.Do(req) 115 | 116 | if outResp.StatusCode >= 400 { 117 | err = fmt.Errorf("unauthorized (HTTP %d)", outResp.StatusCode) 118 | } 119 | return outResp, err 120 | } 121 | 122 | authn := digestAuthParams(resp) 123 | if authn == nil { 124 | return nil, fmt.Errorf("unable to retrieve www-auth data from server") 125 | } 126 | 127 | algorithm := authn["algorithm"] 128 | d := &DigestHeaders{} 129 | d.Path = resp.Request.URL.RequestURI() 130 | d.Realm = authn["realm"] 131 | d.Qop = authn["qop"] 132 | d.Nonce = authn["nonce"] 133 | d.Opaque = authn["opaque"] 134 | if algorithm == "" { 135 | d.Algorithm = "MD5" 136 | } else { 137 | d.Algorithm = authn["algorithm"] 138 | } 139 | d.Nc = 0x0 140 | d.Username = auth.Username() 141 | pass, _ := auth.Password() 142 | d.Password = pass 143 | 144 | req, err := http.NewRequest(resp.Request.Method, resp.Request.URL.String(), body) 145 | if err != nil { 146 | return nil, err 147 | } 148 | req.Header = resp.Request.Header.Clone() 149 | d.ApplyAuth(req) 150 | outResp, err = client.Do(req) 151 | 152 | if outResp.StatusCode >= 400 { 153 | err = fmt.Errorf("unauthorized (HTTP %d)", outResp.StatusCode) 154 | } 155 | return 156 | } 157 | 158 | /* 159 | Parse Authorization header from the http.Request. Returns a map of 160 | auth parameters or nil if the header is not a valid parsable Digest 161 | auth header. 162 | */ 163 | func digestAuthParams(r *http.Response) map[string]string { 164 | s := strings.SplitN(r.Header.Get("Www-Authenticate"), " ", 2) 165 | if len(s) != 2 || s[0] != "Digest" { 166 | return nil 167 | } 168 | 169 | result := map[string]string{} 170 | for _, kv := range strings.Split(s[1], ",") { 171 | parts := strings.SplitN(kv, "=", 2) 172 | if len(parts) != 2 { 173 | continue 174 | } 175 | result[strings.Trim(parts[0], "\" ")] = strings.Trim(parts[1], "\" ") 176 | } 177 | return result 178 | } 179 | 180 | func randomKey() string { 181 | k := make([]byte, 12) 182 | for bytes := 0; bytes < len(k); { 183 | n, err := rand.Read(k[bytes:]) 184 | if err != nil { 185 | panic("rand.Read() failed") 186 | } 187 | bytes += n 188 | } 189 | return base64.StdEncoding.EncodeToString(k) 190 | } 191 | 192 | /* 193 | H function for MD5 algorithm (returns a lower-case hex MD5 digest) 194 | */ 195 | func h(data string) string { 196 | digest := md5.New() 197 | digest.Write([]byte(data)) 198 | return fmt.Sprintf("%x", digest.Sum(nil)) 199 | } 200 | -------------------------------------------------------------------------------- /ws/protocol.go: -------------------------------------------------------------------------------- 1 | package ws 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/Depau/ttyc" 8 | "io" 9 | "net/http" 10 | "net/url" 11 | "nhooyr.io/websocket" 12 | "strconv" 13 | "strings" 14 | "sync" 15 | "time" 16 | ) 17 | 18 | type AuthDTO struct { 19 | AuthToken string 20 | } 21 | 22 | type ResizeTerminalDTO struct { 23 | Columns int `json:"columns"` 24 | Rows int `json:"rows"` 25 | } 26 | 27 | const ( 28 | // Client messages 29 | MsgInput byte = '0' 30 | MsgResizeTerminal byte = '1' 31 | MsgPause byte = '2' 32 | MsgResume byte = '3' 33 | MsgJsonData byte = '{' 34 | MsgBreak byte = 'b' 35 | 36 | // Both 37 | MsgDetectBaudrate byte = 'B' 38 | 39 | // Server messages 40 | MsgOutput byte = '0' 41 | MsgSetWindowTitle byte = '1' 42 | MsgPreferences byte = '2' 43 | MsgServerPause byte = 'S' 44 | MsgServerResume byte = 'Q' 45 | ) 46 | 47 | type Client struct { 48 | BaseUrl *url.URL 49 | WsClient *websocket.Conn 50 | HttpResp *http.Response 51 | WinTitle <-chan []byte 52 | Output <-chan []byte 53 | Input chan<- []byte 54 | DetectedBaudrate <-chan [2]int64 55 | Error <-chan error 56 | CloseChan <-chan interface{} 57 | 58 | mainCtx context.Context 59 | mainCtxCancel context.CancelFunc 60 | wsHttpClient http.Client 61 | winTitle chan []byte 62 | detectedBaudrate chan [2]int64 63 | output chan []byte 64 | input chan []byte 65 | flowControl sync.Mutex 66 | flowControlEngaged bool 67 | error chan error 68 | 69 | watchdogInterval int 70 | toWs chan []byte 71 | fromWs chan []byte 72 | shutdown chan interface{} 73 | closeChan chan interface{} 74 | isShutdown bool 75 | closed bool 76 | } 77 | 78 | type TtyClientOps interface { 79 | io.Closer 80 | 81 | Redial(token *string, watchdog int) error 82 | Run() 83 | ResizeTerminal(cols int, rows int) 84 | RequestBaudrateDetect() 85 | Pause() 86 | Resume() 87 | SendBreak() 88 | SoftClose() error 89 | } 90 | 91 | func DialAndAuth(baseUrl *url.URL, token *string, watchdog int) (client *Client, err error) { 92 | client = &Client{ 93 | BaseUrl: baseUrl, 94 | winTitle: make(chan []byte), 95 | output: make(chan []byte), 96 | input: make(chan []byte), 97 | detectedBaudrate: make(chan [2]int64), 98 | flowControlEngaged: false, 99 | wsHttpClient: http.Client{}, 100 | error: make(chan error), 101 | toWs: make(chan []byte), 102 | fromWs: make(chan []byte), 103 | closeChan: make(chan interface{}), 104 | isShutdown: true, 105 | closed: false, 106 | watchdogInterval: watchdog, 107 | } 108 | client.mainCtx, client.mainCtxCancel = context.WithCancel(context.Background()) 109 | if err := client.Redial(token); err != nil { 110 | return nil, err 111 | } 112 | client.CloseChan = client.closeChan 113 | client.WinTitle = client.winTitle 114 | client.DetectedBaudrate = client.detectedBaudrate 115 | client.Output = client.output 116 | client.Input = client.input 117 | client.Error = client.error 118 | return 119 | } 120 | 121 | func (c *Client) getWriteContext() (context.Context, context.CancelFunc) { 122 | if c.watchdogInterval > 0 { 123 | return context.WithTimeout(c.mainCtx, time.Duration(c.watchdogInterval)*time.Second) 124 | } 125 | return c.getReadContext() 126 | } 127 | 128 | func (c *Client) getReadContext() (context.Context, context.CancelFunc) { 129 | return context.WithCancel(c.mainCtx) 130 | } 131 | 132 | func (c *Client) Redial(token *string) error { 133 | if c.closed { 134 | return fmt.Errorf("not allowed to redial on closed client") 135 | } 136 | 137 | dialOpts := websocket.DialOptions{ 138 | HTTPClient: &c.wsHttpClient, 139 | Subprotocols: []string{"tty"}, 140 | } 141 | wsUrl := ttyc.GetUrlFor(ttyc.UrlForWebSocket, c.BaseUrl) 142 | 143 | ctx, cancel := c.getWriteContext() 144 | wsClient, resp, err := websocket.Dial(ctx, wsUrl.String(), &dialOpts) 145 | cancel() 146 | if err != nil { 147 | ttyc.Trace() 148 | return err 149 | } 150 | authDTO := AuthDTO{ 151 | AuthToken: *token, 152 | } 153 | message, _ := json.Marshal(authDTO) 154 | 155 | ctx, cancel = c.getWriteContext() 156 | err = wsClient.Write(ctx, websocket.MessageBinary, message) 157 | cancel() 158 | if err != nil { 159 | ttyc.Trace() 160 | return err 161 | } 162 | 163 | c.WsClient = wsClient 164 | c.HttpResp = resp 165 | c.shutdown = make(chan interface{}) 166 | c.isShutdown = false 167 | return nil 168 | } 169 | 170 | func (c *Client) SoftClose() error { 171 | if !c.isShutdown { 172 | return fmt.Errorf("can only soft-close in order to redial if the client is already shut down") 173 | } 174 | err := c.WsClient.Close(websocket.StatusGoingAway, "") 175 | if err != nil { 176 | ttyc.Trace() 177 | return err 178 | } 179 | return nil 180 | } 181 | 182 | func (c *Client) Close() error { 183 | c.doShutdown(nil) 184 | if c.closed { 185 | return nil 186 | } 187 | c.closed = true 188 | 189 | close(c.closeChan) 190 | close(c.winTitle) 191 | close(c.output) 192 | close(c.input) 193 | close(c.error) 194 | close(c.toWs) 195 | close(c.fromWs) 196 | 197 | if err := c.SoftClose(); err != nil { 198 | ttyc.Trace() 199 | return err 200 | } 201 | 202 | c.mainCtxCancel() 203 | 204 | return nil 205 | } 206 | 207 | func (c *Client) doShutdown(err error) { 208 | if !c.isShutdown { 209 | close(c.shutdown) 210 | c.isShutdown = true 211 | 212 | if c.flowControlEngaged { 213 | c.flowControlEngaged = false 214 | c.flowControl.Unlock() 215 | } 216 | 217 | if err != nil { 218 | c.error <- err 219 | } 220 | } 221 | } 222 | 223 | func (c *Client) readLoop() { 224 | for !c.closed && !c.isShutdown { 225 | //println("BLOCKING readLoop") 226 | ctx, cancel := c.getReadContext() 227 | msgType, data, err := c.WsClient.Read(ctx) 228 | cancel() 229 | //println("Unblocked readLoop") 230 | if err != nil { 231 | ttyc.Trace() 232 | c.doShutdown(err) 233 | return 234 | } 235 | if msgType != websocket.MessageBinary && msgType != websocket.MessageText { 236 | continue 237 | } 238 | c.fromWs <- data 239 | } 240 | } 241 | 242 | func (c *Client) chanLoop() { 243 | for !c.closed && !c.isShutdown { 244 | //println("SELECT chanLoop") 245 | select { 246 | case data := <-c.fromWs: 247 | if len(data) <= 0 { 248 | continue 249 | } 250 | switch data[0] { 251 | case MsgOutput: 252 | c.output <- data[1:] 253 | case MsgServerPause: 254 | if !c.flowControlEngaged { 255 | c.flowControlEngaged = true 256 | c.flowControl.Lock() 257 | } 258 | case MsgServerResume: 259 | if c.flowControlEngaged { 260 | c.flowControlEngaged = false 261 | c.flowControl.Unlock() 262 | } 263 | case MsgSetWindowTitle: 264 | EmptyWinTitleChanLoop: 265 | // Empty channel so we don't block if the user is not reading 266 | for { 267 | select { 268 | case <-c.winTitle: 269 | default: 270 | break EmptyWinTitleChanLoop 271 | } 272 | } 273 | c.winTitle <- data[1:] 274 | case MsgDetectBaudrate: 275 | // Empty channel so we don't block if the user is not reading 276 | EmptyBaudChanLoop: 277 | for { 278 | select { 279 | case <-c.detectedBaudrate: 280 | default: 281 | break EmptyBaudChanLoop 282 | } 283 | } 284 | dataStr := string(data[1:]) 285 | var result [2]int64 286 | if strings.Contains(dataStr, ",") { 287 | split := strings.SplitN(dataStr, ",", 2) 288 | if len(split) != 2 { 289 | ttyc.TtycAngryPrintf("Received invalid detected baudrate: %s\n", dataStr) 290 | break 291 | } 292 | for index, item := range split { 293 | i, err := strconv.ParseInt(item, 10, 64) 294 | if err != nil { 295 | ttyc.TtycAngryPrintf("Unable to parse detected baudrate: %v\n", err) 296 | break 297 | } 298 | result[index] = i 299 | } 300 | } else { 301 | i, err := strconv.ParseInt(string(data[1:]), 10, 64) 302 | if err != nil { 303 | ttyc.TtycAngryPrintf("Unable to parse detected baudrate: %v\n", err) 304 | break 305 | } 306 | result[0] = i 307 | result[1] = 0 308 | } 309 | c.detectedBaudrate <- result 310 | } 311 | if data[0] == MsgOutput { 312 | } 313 | // Ignore WinTitle since it caused an issue and we're not using it anyway anywhere 314 | // Ignore MsgSetPreferences since we're not Xterm.js 315 | 316 | case data := <-c.toWs: 317 | if len(data) == 0 { 318 | continue 319 | } 320 | c.flowControl.Lock() 321 | ctx, cancel := c.getWriteContext() 322 | err := c.WsClient.Write(ctx, websocket.MessageBinary, data) 323 | cancel() 324 | c.flowControl.Unlock() 325 | if err != nil { 326 | ttyc.Trace() 327 | c.doShutdown(err) 328 | return 329 | } 330 | case data := <-c.input: 331 | if len(data) == 0 { 332 | continue 333 | } 334 | // I could avoid duplicating the code but I'd rather avoid the additional copy, since writing to the 335 | // WebSocket is this goroutine's job anyway. 336 | c.flowControl.Lock() 337 | ctx, cancel := c.getWriteContext() 338 | err := c.WsClient.Write(ctx, websocket.MessageBinary, append([]byte{MsgInput}, data...)) 339 | cancel() 340 | c.flowControl.Unlock() 341 | if err != nil { 342 | ttyc.Trace() 343 | c.doShutdown(err) 344 | return 345 | } 346 | case <-c.closeChan: 347 | case <-c.shutdown: 348 | } 349 | //println("SELECTED chanLoop") 350 | } 351 | } 352 | 353 | func (c *Client) watchdog(interval int) { 354 | pingDuration := time.Duration(interval) * time.Second 355 | nextPing := time.Now().Add(pingDuration) 356 | 357 | for !c.closed && !c.isShutdown { 358 | select { 359 | case <-time.After(nextPing.Sub(time.Now())): 360 | ctx, cancel := c.getWriteContext() 361 | err := c.WsClient.Ping(ctx) 362 | cancel() 363 | if err != nil { 364 | ttyc.Trace() 365 | c.doShutdown(err) 366 | return 367 | } 368 | nextPing = time.Now().Add(pingDuration) 369 | case <-c.closeChan: 370 | case <-c.shutdown: 371 | return 372 | } 373 | } 374 | } 375 | 376 | func (c *Client) Run(watchdog int) { 377 | go c.readLoop() 378 | if watchdog > 0 { 379 | go c.watchdog(watchdog) 380 | } 381 | c.chanLoop() 382 | } 383 | 384 | func (c *Client) ResizeTerminal(cols int, rows int) { 385 | dto := ResizeTerminalDTO{ 386 | Columns: cols, 387 | Rows: rows, 388 | } 389 | msg, _ := json.Marshal(&dto) 390 | c.toWs <- append([]byte{MsgResizeTerminal}, msg...) 391 | } 392 | 393 | func (c *Client) Pause() { 394 | c.toWs <- []byte{MsgPause} 395 | } 396 | 397 | func (c *Client) Resume() { 398 | c.toWs <- []byte{MsgResume} 399 | } 400 | 401 | func (c *Client) RequestBaudrateDetection() { 402 | c.toWs <- []byte{MsgDetectBaudrate} 403 | } 404 | 405 | func (c *Client) SendBreak() { 406 | c.toWs <- []byte{MsgBreak} 407 | } 408 | --------------------------------------------------------------------------------