reset the GitHub Repo
23
.gitignore
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
witty
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
*.log
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
504
LICENSE
Normal file
@ -0,0 +1,504 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
|
||||
USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random
|
||||
Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
121
README.md
Normal file
@ -0,0 +1,121 @@
|
||||
<mark>**WiTTY: Web-based interactive TTY**<mark>
|
||||
|
||||
# Introduction
|
||||
|
||||
This program allows you to use terminal in the browser. Simply run the program and give it the command to execute when users connect via the browser. The design goal of this tool is to help teaching courses that use Unix-like CLI environment. WiTTY has the following features that distinguish itself from other similar tools:
|
||||
|
||||
1. WiTTY allows users to **easily record, replay, and share console sessions** with just a few clicks. This make it a breeze to answer course-related questions. Instead of wall of text to describe their questions, students can just send a recorded session.
|
||||
|
||||
2. It allows others to **view ongoing interactive sessions**. This is useful for providing live remote help.
|
||||
|
||||
>A challenge of this use case is that our home networks are almost always behind NAT, making it difficult to run WiTTY as a publicly accessible server. Security is also potentially a concern.
|
||||
|
||||
3. Great attention has been paid to ensure the cleanses of the code. This, hopefully, provides a useful example of **Do as I say and as I do**.
|
||||
|
||||
# User Interface
|
||||
|
||||
You can use WiTTY to run any command line programs, such as ```bash```, ```htop```, ```vi```, ```ssh```. This screenshot shows the main page of WiTTY after login. There are two tabs that list live and recorded sessions, respectively. You can click ```New Session``` to create a new interactive session. Click the <img src="assets/img/view.svg" width="16px"> icon of an interactive session opens a read-only view of that session.
|
||||
|
||||
<img src="extra/main.png" width="800px">
|
||||
|
||||
|
||||
On the interactive terminal window, you can record an ongoing session.
|
||||
|
||||
<img src="extra/interactive.png" width="800px">
|
||||
|
||||
This screenshot shows three recorded sessions, you can replay <img src="assets/img/play.svg" width="16px">, download <img src="assets/img/download.svg" width="16px">, rename <img src="assets/img/edit.svg" width="16px">, and delete <img src="assets/img/delete.svg" width="16px"> recorded sessions.
|
||||
|
||||
<img src="extra/view.png" width="800px">
|
||||
|
||||
|
||||
Here is a recorded session, where we domonstrate how to use the command line replay utility (in ```cmd/replay```) to replay another recorded session that sshes into a Raspberry Pi running
|
||||
[pi-hole](https://pi-hole.net/). You can fully control the playback using the progress bar.
|
||||
|
||||
>The inception is strong with this one!
|
||||
|
||||
<img src="extra/replay.gif" width="800px">
|
||||
|
||||
|
||||
<!--
|
||||
commands to create high quality gif from mkv/mp4 files
|
||||
ffmpeg -i replay.mkv -vf palettegen palette.png
|
||||
ffmpeg -i replay.mkv -i palette.png -lavfi paletteuse output.gif
|
||||
gifsicle -O3 .\output.gif -o replay.gif
|
||||
-->
|
||||
|
||||
|
||||
This program is written in the [go programming language](https://go.dev/), using the
|
||||
[Gin web framework](https://github.com/gin-gonic/gin), [gorilla/websocket](https://github.com/gorilla/websocket), [pty](https://github.com/creack/pty), and the wonderful [xterm.js](https://xtermjs.org/)!
|
||||
The workflow is simple, the client will initiate a terminal
|
||||
window (xterm.js) and create a websocket with the server, which relays the data between pty and xterm. You can customize the look and feel of the HTML pages by editing files under the ```assets``` directory.
|
||||
|
||||
The program has been tested on Linux, WSL2, Raspberry Pi 3B (Debian), and MacOSX using Google Chrome, Firefox, and Safari.
|
||||
|
||||
Most icons were provided by [fontawesome](https://fontawesome.com/) under this [license](https://fontawesome.com/license).
|
||||
|
||||
# Installation
|
||||
|
||||
1. Install the [go](https://go.dev/) compiler. __Make sure you have go 1.17 or higher.__
|
||||
|
||||
2. Download the release and unzip it, or clone the repo
|
||||
|
||||
```git clone https://github.com/syssecfsu/witty.git```
|
||||
|
||||
3. Go to the root directory of the source code and build the program. WiTTY uses go:embed to embed assets in the binary. Remember to build WiTTY after changing templates.
|
||||
|
||||
```go build .```
|
||||
|
||||
4. WiTTY uses TLS to protect its traffic. You can request a free [Let's Encrypt](https://letsencrypt.org/) cert or use a self-signed cert. Here is how to create a self-signed cert in the ```tls``` sub-directory:
|
||||
|
||||
\# Generate a private key for a curve
|
||||
|
||||
```openssl ecparam -name prime256v1 -genkey -noout -out private-key.pem```
|
||||
|
||||
\# Create a self-signed certificate
|
||||
|
||||
```openssl req -new -x509 -key private-key.pem -out cert.pem -days 360```
|
||||
|
||||
5. Add a user to the user accounts, follow the instructions on screen to provide the password
|
||||
|
||||
```./witty adduser <username>```
|
||||
|
||||
6. Start the server and give it the command to run. By default, the server listens on 8080 (you can override it with the ```-p/-port``` option):
|
||||
|
||||
```./witty run htop``` or
|
||||
|
||||
```./witty run -p 9000 ssh <ssh_server_ip> -l <user_name>```
|
||||
|
||||
If so desired, you can disable user authenticate with ```-n/-naked```, (not recommended) for example:
|
||||
|
||||
```./witty run -naked htop```
|
||||
|
||||
7. Connect to the server with your browser at port 8080 or the one specified in step 6, for example
|
||||
|
||||
```https://<witty_server_ip>:8080```
|
||||
|
||||
# User Authentication
|
||||
|
||||
WiTTY uses username/password based authentication. The user database is stored in ```user.db```. The passwords are salted with 64 bytes of random characters and then hashed using SHA256. WiTTY has three sub-commands to manage ```user.db```.
|
||||
|
||||
- ```witty adduser <username>```
|
||||
- ```witty deluser <username>```
|
||||
- ```witty listusers```
|
||||
|
||||
They are pretty self-explanatory. Just follow the instructions on screen. Note that passwords must be 12 bytes or longer.
|
||||
|
||||
# Recorded Sessions
|
||||
|
||||
WiTTY provides two sub-commands to merge and replay recorded sessions.
|
||||
|
||||
- ```witty replay -w <wait_time> <recorded_session>```
|
||||
- ```witty merge -o <output_file> <record1> <record2> ...```
|
||||
|
||||
Recorded sessions often have long delay between outputs. You can set wait_time to limit the maximum wait time between outputs, to speed up the replay.
|
||||
|
||||
You can also use ```witty merge``` to merge two or more recorded sessions, as shown below.
|
||||
|
||||
<img src="extra/merge.png" width="640px">
|
||||
|
||||
The intended use case is to record a separate session for each individual task, rename and merge them into a final session for submission. The following screenshot shows how to rename a recorded session (you can also rename a recorded session using commands in a shell. All the recorded sessions are located under the ```records``` directory).
|
||||
|
||||
<img src="extra/rename.png" width="800px">
|
6
assets/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
This directory contains client side code, including xterm.js 4.16
|
||||
|
||||
To update the xterm library to a newer version of xterm.js, run
|
||||
`npm install xterm.js` in a different directory, and then copy
|
||||
xterm.js and xterm.js.map and xterm.css and the files for three
|
||||
of xterm.js's addons to the external directory.
|
7
assets/external/bootstrap.min.css
vendored
Normal file
1
assets/external/bootstrap.min.css.map
vendored
Normal file
7
assets/external/bootstrap.min.js
vendored
Normal file
1
assets/external/bootstrap.min.js.map
vendored
Normal file
2
assets/external/xterm-addon-attach.js
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.AttachAddon=e():t.AttachAddon=e()}(window,(function(){return function(t){var e={};function n(o){if(e[o])return e[o].exports;var r=e[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,o){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(o,r,function(e){return t[e]}.bind(null,r));return o},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=0)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AttachAddon=void 0;var o=function(){function t(t,e){this._disposables=[],this._socket=t,this._socket.binaryType="arraybuffer",this._bidirectional=!e||!1!==e.bidirectional}return t.prototype.activate=function(t){var e=this;this._disposables.push(r(this._socket,"message",(function(e){var n=e.data;t.write("string"==typeof n?n:new Uint8Array(n))}))),this._bidirectional&&(this._disposables.push(t.onData((function(t){return e._sendData(t)}))),this._disposables.push(t.onBinary((function(t){return e._sendBinary(t)})))),this._disposables.push(r(this._socket,"close",(function(){return e.dispose()}))),this._disposables.push(r(this._socket,"error",(function(){return e.dispose()})))},t.prototype.dispose=function(){this._disposables.forEach((function(t){return t.dispose()}))},t.prototype._sendData=function(t){1===this._socket.readyState&&this._socket.send(t)},t.prototype._sendBinary=function(t){if(1===this._socket.readyState){for(var e=new Uint8Array(t.length),n=0;n<t.length;++n)e[n]=255&t.charCodeAt(n);this._socket.send(e)}},t}();function r(t,e,n){return t.addEventListener(e,n),{dispose:function(){n&&t.removeEventListener(e,n)}}}e.AttachAddon=o}])}));
|
||||
//# sourceMappingURL=xterm-addon-attach.js.map
|
1
assets/external/xterm-addon-attach.js.map
vendored
Normal file
2
assets/external/xterm-addon-fit.js
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(self,(function(){return(()=>{"use strict";var e={775:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0;var r=function(){function e(){}return e.prototype.activate=function(e){this._terminal=e},e.prototype.dispose=function(){},e.prototype.fit=function(){var e=this.proposeDimensions();if(e&&this._terminal){var t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}},e.prototype.proposeDimensions=function(){if(this._terminal&&this._terminal.element&&this._terminal.element.parentElement){var e=this._terminal._core;if(0!==e._renderService.dimensions.actualCellWidth&&0!==e._renderService.dimensions.actualCellHeight){var t=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(t.getPropertyValue("height")),i=Math.max(0,parseInt(t.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),o=r-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=i-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-e.viewport.scrollBarWidth;return{cols:Math.max(2,Math.floor(a/e._renderService.dimensions.actualCellWidth)),rows:Math.max(1,Math.floor(o/e._renderService.dimensions.actualCellHeight))}}}},e}();t.FitAddon=r}},t={};return function r(i){if(t[i])return t[i].exports;var n=t[i]={exports:{}};return e[i](n,n.exports,r),n.exports}(775)})()}));
|
||||
//# sourceMappingURL=xterm-addon-fit.js.map
|
1
assets/external/xterm-addon-fit.js.map
vendored
Normal file
2
assets/external/xterm-addon-web-links.js
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.WebLinksAddon=t():e.WebLinksAddon=t()}(self,(function(){return(()=>{"use strict";var e={6:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0;var i=function(){function e(e,t,i,r){void 0===r&&(r={}),this._terminal=e,this._regex=t,this._handler=i,this._options=r}return e.prototype.provideLinks=function(e,t){var i=r.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(i))},e.prototype._addCallbacks=function(e){var t=this;return e.map((function(e){return e.leave=t._options.leave,e.hover=function(i,r){if(t._options.hover){var n=e.range;t._options.hover(i,r,n)}},e}))},e}();t.WebLinkProvider=i;var r=function(){function e(){}return e.computeLink=function(t,i,r,n){for(var o,a=new RegExp(i.source,(i.flags||"")+"g"),s=e._translateBufferLineToStringWithWrap(t-1,!1,r),d=s[0],l=s[1],u=-1,c=[];null!==(o=a.exec(d));){var h=o[1];if(!h){console.log("match found without corresponding matchIndex");break}if(u=d.indexOf(h,u+1),a.lastIndex=u+h.length,u<0)break;for(var v=u+h.length,p=l+1;v>r.cols;)v-=r.cols,p++;var f={start:{x:u+1,y:l+1},end:{x:v,y:p}};c.push({range:f,text:h,activate:n})}return c},e._translateBufferLineToStringWithWrap=function(e,t,i){var r,n,o="";do{if(!(s=i.buffer.active.getLine(e)))break;s.isWrapped&&e--,n=s.isWrapped}while(n);var a=e;do{var s,d=i.buffer.active.getLine(e+1);if(r=!!d&&d.isWrapped,!(s=i.buffer.active.getLine(e)))break;o+=s.translateToString(!r&&t).substring(0,i.cols),e++}while(r);return[o,a]},e}();t.LinkComputer=r}},t={};function i(r){var n=t[r];if(void 0!==n)return n.exports;var o=t[r]={exports:{}};return e[r](o,o.exports,i),o.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;var t=i(6),n=new RegExp("(?:^|[^\\da-z\\.-]+)((https?:\\/\\/)((([\\da-z\\.-]+)\\.([a-z\\.]{2,6}))|((\\d{1,3}\\.){3}\\d{1,3})|(localhost))(:\\d{1,5})?((\\/[\\/\\w\\.\\-%~:+@]*)*([^:\"'\\s]))?(\\?[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&'*+,:;~\\=\\.\\-]*)?(#[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&'*+,:;~\\=\\.\\-]*)?)($|[^\\/\\w\\.\\-%]+)");function o(e,t){var i=window.open();if(i){try{i.opener=null}catch(e){}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}var a=function(){function e(e,t,i){void 0===e&&(e=o),void 0===t&&(t={}),void 0===i&&(i=!1),this._handler=e,this._options=t,this._useLinkProvider=i}return e.prototype.activate=function(e){if(this._terminal=e,this._useLinkProvider&&"registerLinkProvider"in this._terminal){var i=(r=this._options).urlRegex||n;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,i,this._handler,r))}else{var r;(r=this._options).matchIndex=1,this._linkMatcherId=this._terminal.registerLinkMatcher(n,this._handler,r)}},e.prototype.dispose=function(){var e;void 0!==this._linkMatcherId&&void 0!==this._terminal&&this._terminal.deregisterLinkMatcher(this._linkMatcherId),null===(e=this._linkProvider)||void 0===e||e.dispose()},e}();e.WebLinksAddon=a})(),r})()}));
|
||||
//# sourceMappingURL=xterm-addon-web-links.js.map
|
1
assets/external/xterm-addon-web-links.js.map
vendored
Normal file
175
assets/external/xterm.css
vendored
Normal file
@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
|
||||
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
|
||||
* https://github.com/chjj/term.js
|
||||
* @license MIT
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*
|
||||
* Originally forked from (with the author's permission):
|
||||
* Fabrice Bellard's javascript vt100 for jslinux:
|
||||
* http://bellard.org/jslinux/
|
||||
* Copyright (c) 2011 Fabrice Bellard
|
||||
* The original design remains. The terminal itself
|
||||
* has been extended to include xterm CSI codes, among
|
||||
* other features.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Default styles for xterm.js
|
||||
*/
|
||||
|
||||
.xterm {
|
||||
position: relative;
|
||||
user-select: none;
|
||||
-ms-user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
|
||||
.xterm.focus,
|
||||
.xterm:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.xterm .xterm-helpers {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
/**
|
||||
* The z-index of the helpers must be higher than the canvases in order for
|
||||
* IMEs to appear on top.
|
||||
*/
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
.xterm .xterm-helper-textarea {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
margin: 0;
|
||||
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
left: -9999em;
|
||||
top: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
z-index: -5;
|
||||
/** Prevent wrapping so the IME appears against the textarea at the correct position */
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.xterm .composition-view {
|
||||
/* TODO: Composition position got messed up somewhere */
|
||||
background: #000;
|
||||
color: #FFF;
|
||||
display: none;
|
||||
position: absolute;
|
||||
white-space: nowrap;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.xterm .composition-view.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.xterm .xterm-viewport {
|
||||
/* On OS X this is required in order for the scroll bar to appear fully opaque */
|
||||
background-color: #000;
|
||||
overflow-y: scroll;
|
||||
cursor: default;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.xterm .xterm-screen {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.xterm .xterm-screen canvas {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.xterm .xterm-scroll-area {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.xterm-char-measure-element {
|
||||
display: inline-block;
|
||||
visibility: hidden;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -9999em;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.xterm {
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.xterm.enable-mouse-events {
|
||||
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.xterm.xterm-cursor-pointer,
|
||||
.xterm .xterm-cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.xterm.column-select.focus {
|
||||
/* Column selection mode */
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.xterm .xterm-accessibility,
|
||||
.xterm .xterm-message {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.xterm .live-region {
|
||||
position: absolute;
|
||||
left: -9999px;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.xterm-dim {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.xterm-underline {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.xterm-strikethrough {
|
||||
text-decoration: line-through;
|
||||
}
|
2
assets/external/xterm.js
vendored
Normal file
1
assets/external/xterm.js.map
vendored
Normal file
1
assets/img/delete.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="trash-alt" class="svg-inline--fa fa-trash-alt fa-w-14" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M32 464a48 48 0 0 0 48 48h288a48 48 0 0 0 48-48V128H32zm272-256a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zm-96 0a16 16 0 0 1 32 0v224a16 16 0 0 1-32 0zM432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16z"></path></svg>
|
After Width: | Height: | Size: 597 B |
1
assets/img/download.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="download" class="svg-inline--fa fa-download fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z"></path></svg>
|
After Width: | Height: | Size: 678 B |
1
assets/img/edit.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="edit" class="svg-inline--fa fa-edit fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M402.6 83.2l90.2 90.2c3.8 3.8 3.8 10 0 13.8L274.4 405.6l-92.8 10.3c-12.4 1.4-22.9-9.1-21.5-21.5l10.3-92.8L388.8 83.2c3.8-3.8 10-3.8 13.8 0zm162-22.9l-48.8-48.8c-15.2-15.2-39.9-15.2-55.2 0l-35.4 35.4c-3.8 3.8-3.8 10 0 13.8l90.2 90.2c3.8 3.8 10 3.8 13.8 0l35.4-35.4c15.2-15.3 15.2-40 0-55.2zM384 346.2V448H64V128h229.8c3.2 0 6.2-1.3 8.5-3.5l40-40c7.6-7.6 2.2-20.5-8.5-20.5H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V306.2c0-10.7-12.9-16-20.5-8.5l-40 40c-2.2 2.3-3.5 5.3-3.5 8.5z"></path></svg>
|
After Width: | Height: | Size: 735 B |
1
assets/img/keyboard.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="keyboard" class="svg-inline--fa fa-keyboard fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M528 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h480c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM128 180v-40c0-6.627-5.373-12-12-12H76c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm-336 96v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm-336 96v-40c0-6.627-5.373-12-12-12H76c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12zm288 0v-40c0-6.627-5.373-12-12-12H172c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h232c6.627 0 12-5.373 12-12zm96 0v-40c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12z"></path></svg>
|
After Width: | Height: | Size: 1.7 KiB |
1
assets/img/logo.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="terminal" class="svg-inline--fa fa-terminal fa-w-20" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path fill="currentColor" d="M257.981 272.971L63.638 467.314c-9.373 9.373-24.569 9.373-33.941 0L7.029 444.647c-9.357-9.357-9.375-24.522-.04-33.901L161.011 256 6.99 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L257.981 239.03c9.373 9.372 9.373 24.568 0 33.941zM640 456v-32c0-13.255-10.745-24-24-24H312c-13.255 0-24 10.745-24 24v32c0 13.255 10.745 24 24 24h304c13.255 0 24-10.745 24-24z"></path></svg>
|
After Width: | Height: | Size: 637 B |
1
assets/img/pause.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!-- Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) --><path d="M144 479H48c-26.5 0-48-21.5-48-48V79c0-26.5 21.5-48 48-48h96c26.5 0 48 21.5 48 48v352c0 26.5-21.5 48-48 48zm304-48V79c0-26.5-21.5-48-48-48h-96c-26.5 0-48 21.5-48 48v352c0 26.5 21.5 48 48 48h96c26.5 0 48-21.5 48-48z"/></svg>
|
After Width: | Height: | Size: 474 B |
1
assets/img/play.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!-- Font Awesome Free 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) --><path d="M424.4 214.7L72.4 6.6C43.8-10.3 0 6.1 0 47.9V464c0 37.5 40.7 60.1 72.4 41.3l352-208c31.4-18.5 31.5-64.1 0-82.6z"/></svg>
|
After Width: | Height: | Size: 371 B |
1
assets/img/record.svg
Executable file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="video" class="svg-inline--fa fa-video fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M336.2 64H47.8C21.4 64 0 85.4 0 111.8v288.4C0 426.6 21.4 448 47.8 448h288.4c26.4 0 47.8-21.4 47.8-47.8V111.8c0-26.4-21.4-47.8-47.8-47.8zm189.4 37.7L416 177.3v157.4l109.6 75.5c21.2 14.6 50.4-.3 50.4-25.8V127.5c0-25.4-29.1-40.4-50.4-25.8z"></path></svg>
|
After Width: | Height: | Size: 466 B |
1
assets/img/sign-in.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="sign-in-alt" class="svg-inline--fa fa-sign-in-alt fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M416 448h-84c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h84c17.7 0 32-14.3 32-32V160c0-17.7-14.3-32-32-32h-84c-6.6 0-12-5.4-12-12V76c0-6.6 5.4-12 12-12h84c53 0 96 43 96 96v192c0 53-43 96-96 96zm-47-201L201 79c-15-15-41-4.5-41 17v96H24c-13.3 0-24 10.7-24 24v96c0 13.3 10.7 24 24 24h136v96c0 21.5 26 32 41 17l168-168c9.3-9.4 9.3-24.6 0-34z"></path></svg>
|
After Width: | Height: | Size: 578 B |
1
assets/img/sign-out.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="sign-out-alt" class="svg-inline--fa fa-sign-out-alt fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M497 273L329 441c-15 15-41 4.5-41-17v-96H152c-13.3 0-24-10.7-24-24v-96c0-13.3 10.7-24 24-24h136V88c0-21.4 25.9-32 41-17l168 168c9.3 9.4 9.3 24.6 0 34zM192 436v-40c0-6.6-5.4-12-12-12H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h84c6.6 0 12-5.4 12-12V76c0-6.6-5.4-12-12-12H96c-53 0-96 43-96 96v192c0 53 43 96 96 96h84c6.6 0 12-5.4 12-12z"></path></svg>
|
After Width: | Height: | Size: 584 B |
1
assets/img/term.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="window-restore" class="svg-inline--fa fa-window-restore fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M512 48v288c0 26.5-21.5 48-48 48h-48V176c0-44.1-35.9-80-80-80H128V48c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zM384 176v288c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V176c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zm-68 28c0-6.6-5.4-12-12-12H76c-6.6 0-12 5.4-12 12v52h252v-52z"></path></svg>
|
After Width: | Height: | Size: 533 B |
1
assets/img/view.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="eye" class="svg-inline--fa fa-eye fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path fill="currentColor" d="M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z"></path></svg>
|
After Width: | Height: | Size: 556 B |
43
assets/main.css
Normal file
@ -0,0 +1,43 @@
|
||||
#terminal {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 10px 0 10px;
|
||||
}
|
||||
|
||||
#terminal #terminal_view {
|
||||
padding: 10px 20px;
|
||||
border-radius: 6px;
|
||||
background-color: #282a36;
|
||||
}
|
||||
|
||||
.xterm-viewport.xterm-viewport {
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.xterm-viewport::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
}
|
||||
|
||||
.xterm-viewport::-webkit-scrollbar-track {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.xterm-viewport::-webkit-scrollbar-thumb {
|
||||
min-height: 20px;
|
||||
background-color: #ffffff20;
|
||||
}
|
||||
|
||||
.navbar-xs .navbar-brand {
|
||||
padding: 0px 12px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.navbar-xs .navbar-nav>li>a {
|
||||
padding-top: 0px;
|
||||
padding-bottom: 0px;
|
||||
}
|
||||
|
||||
.btn:focus {
|
||||
outline: none;
|
||||
box-shadow: none;
|
||||
}
|
53
assets/main.js
Normal file
@ -0,0 +1,53 @@
|
||||
function createTerminal(path) {
|
||||
// vscode-snazzy https://github.com/Tyriar/vscode-snazzy
|
||||
// copied from xterm.js website
|
||||
var baseTheme = {
|
||||
foreground: '#eff0eb',
|
||||
background: '#282a36',
|
||||
selection: '#97979b33',
|
||||
black: '#282a36',
|
||||
brightBlack: '#686868',
|
||||
red: '#ff5c57',
|
||||
brightRed: '#ff5c57',
|
||||
green: '#5af78e',
|
||||
brightGreen: '#5af78e',
|
||||
yellow: '#f3f99d',
|
||||
brightYellow: '#f3f99d',
|
||||
blue: '#57c7ff',
|
||||
brightBlue: '#57c7ff',
|
||||
magenta: '#ff6ac1',
|
||||
brightMagenta: '#ff6ac1',
|
||||
cyan: '#9aedfe',
|
||||
brightCyan: '#9aedfe',
|
||||
white: '#f1f1f0',
|
||||
brightWhite: '#eff0eb'
|
||||
};
|
||||
|
||||
const term = new Terminal({
|
||||
fontFamily: `'Fira Code', ui-monospace,SFMono-Regular,'SF Mono',Menlo,Consolas,'Liberation Mono',monospace`,
|
||||
fontSize: 12,
|
||||
theme: baseTheme,
|
||||
convertEol: true,
|
||||
cursorBlink: true,
|
||||
});
|
||||
|
||||
term.open(document.getElementById('terminal_view'));
|
||||
term.resize(120, 36);
|
||||
|
||||
const weblinksAddon = new WebLinksAddon.WebLinksAddon();
|
||||
term.loadAddon(weblinksAddon);
|
||||
|
||||
// fit the xterm viewpoint to parent element
|
||||
const fitAddon = new FitAddon.FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
fitAddon.fit();
|
||||
|
||||
// create the websocket and connect to the server
|
||||
const ws_uri = "wss://" + window.location.host + path;
|
||||
const socket = new WebSocket(ws_uri);
|
||||
socket.binaryType = "arraybuffer";
|
||||
const attachAddon = new AttachAddon.AttachAddon(socket);
|
||||
term.loadAddon(attachAddon);
|
||||
|
||||
return term;
|
||||
}
|
177
assets/replay.js
Normal file
@ -0,0 +1,177 @@
|
||||
// create a xterm for replay
|
||||
function createReplayTerminal() {
|
||||
// vscode-snazzy https://github.com/Tyriar/vscode-snazzy
|
||||
// copied from xterm.js website
|
||||
var baseTheme = {
|
||||
foreground: '#eff0eb',
|
||||
background: '#282a36',
|
||||
selection: '#97979b33',
|
||||
black: '#282a36',
|
||||
brightBlack: '#686868',
|
||||
red: '#ff5c57',
|
||||
brightRed: '#ff5c57',
|
||||
green: '#5af78e',
|
||||
brightGreen: '#5af78e',
|
||||
yellow: '#f3f99d',
|
||||
brightYellow: '#f3f99d',
|
||||
blue: '#57c7ff',
|
||||
brightBlue: '#57c7ff',
|
||||
magenta: '#ff6ac1',
|
||||
brightMagenta: '#ff6ac1',
|
||||
cyan: '#9aedfe',
|
||||
brightCyan: '#9aedfe',
|
||||
white: '#f1f1f0',
|
||||
brightWhite: '#eff0eb'
|
||||
};
|
||||
|
||||
const term = new Terminal({
|
||||
fontFamily: `'Fira Code', ui-monospace,SFMono-Regular,'SF Mono',Menlo,Consolas,'Liberation Mono',monospace`,
|
||||
fontSize: 12,
|
||||
theme: baseTheme,
|
||||
convertEol: true,
|
||||
cursorBlink: true,
|
||||
});
|
||||
|
||||
term.open(document.getElementById('terminal_view'));
|
||||
term.resize(120, 36);
|
||||
|
||||
const weblinksAddon = new WebLinksAddon.WebLinksAddon();
|
||||
term.loadAddon(weblinksAddon);
|
||||
|
||||
// fit the xterm viewpoint to parent element
|
||||
const fitAddon = new FitAddon.FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
fitAddon.fit();
|
||||
|
||||
return term;
|
||||
}
|
||||
|
||||
// sleep for ms seconds
|
||||
function _sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// we could sleep for a long time
|
||||
// periodically check if we need to end replay.
|
||||
// This is pretty ugly but the callback mess otherwise
|
||||
async function sleep(ms, paused) {
|
||||
var loop_cnt = parseInt(ms / 20) + 1
|
||||
|
||||
for (i = 0; i < loop_cnt; i++) {
|
||||
if (paused()) {
|
||||
return paused()
|
||||
}
|
||||
|
||||
await _sleep(20)
|
||||
}
|
||||
|
||||
return paused()
|
||||
}
|
||||
// convert data to uint8array, we cannot convert it to string as
|
||||
// it will mess up special characters
|
||||
function base64ToUint8array(base64) {
|
||||
var raw = window.atob(base64);
|
||||
var rawLength = raw.length;
|
||||
var array = new Uint8Array(new ArrayBuffer(rawLength));
|
||||
|
||||
for (i = 0; i < rawLength; i++) {
|
||||
array[i] = raw.charCodeAt(i);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
// replay session
|
||||
// term: xterm, path: session file to replay,
|
||||
// start: start position to replay in percentile, range 0-100
|
||||
// paused: callback whether to stop play
|
||||
// prog: callback to update the progress bar
|
||||
// shift: callback whether we should change position
|
||||
// end: callback when playback is finished
|
||||
|
||||
async function replay_session(term, records, max_wait, total_dur, start, paused, prog, end) {
|
||||
var cur = 0
|
||||
|
||||
start = parseInt(total_dur * start / 100)
|
||||
term.reset()
|
||||
|
||||
for (const item of records) {
|
||||
// we will blast through the beginning of the session
|
||||
if (cur >= start) {
|
||||
// we are cheating a little bit here, we do not want to wait for too long
|
||||
exit = await sleep(Math.min(item.Duration, max_wait), paused)
|
||||
|
||||
if (exit) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
term.write(base64ToUint8array(item.Data))
|
||||
cur += item.Duration
|
||||
|
||||
if (cur > start) {
|
||||
prog(parseInt(cur * 100 / total_dur))
|
||||
}
|
||||
}
|
||||
|
||||
end()
|
||||
}
|
||||
|
||||
function forwardScreen(term, records, end) {
|
||||
var cur = 0
|
||||
end = parseInt(total_dur * end / 100)
|
||||
term.reset()
|
||||
|
||||
for (const item of records) {
|
||||
// we will blast through the beginning of the session
|
||||
if (cur >= end) {
|
||||
return
|
||||
}
|
||||
|
||||
term.write(base64ToUint8array(item.Data))
|
||||
cur += item.Duration
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function fetchAndParse(path, update) {
|
||||
var records
|
||||
var total_dur = 0
|
||||
|
||||
// read file from server, we need to await twice.
|
||||
var res = await fetch(path)
|
||||
|
||||
if (!res.ok) {
|
||||
return
|
||||
}
|
||||
|
||||
records = await res.json()
|
||||
|
||||
//calculate the total duration
|
||||
for (const item of records) {
|
||||
item.Duration = parseInt(item.Duration / 1000000)
|
||||
total_dur += item.Duration
|
||||
}
|
||||
|
||||
console.log("total_dur", total_dur)
|
||||
update(records, total_dur)
|
||||
}
|
||||
|
||||
|
||||
function Init() {
|
||||
let term = createReplayTerminal();
|
||||
var str = [
|
||||
' ┌────────────────────────────────────────────────────────────────────────────┐\n',
|
||||
' │ \u001b[32;1mhttps://github.com/syssecfsu/witty\x1b[0m <- click it! │\n',
|
||||
' └────────────────────────────────────────────────────────────────────────────┘\n',
|
||||
''
|
||||
].join('');
|
||||
|
||||
term.writeln(str);
|
||||
|
||||
// adjust the progress bar size to that of terminal
|
||||
var view = document.querySelector("#terminal")
|
||||
var pbar = document.querySelector("#replay-control")
|
||||
pbar.setAttribute("style", "width:" + (view.offsetWidth - 32) + "px");
|
||||
|
||||
return term
|
||||
}
|
39
assets/signin.css
Normal file
@ -0,0 +1,39 @@
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-top: 40px;
|
||||
padding-bottom: 40px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.form-signin {
|
||||
width: 100%;
|
||||
max-width: 330px;
|
||||
padding: 15px;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
.form-signin .checkbox {
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.form-signin .form-floating:focus-within {
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.form-signin input[type="text"] {
|
||||
margin-bottom: -1px;
|
||||
border-bottom-right-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
}
|
||||
|
||||
.form-signin input[type="password"] {
|
||||
margin-bottom: 10px;
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
}
|
166
assets/template/index.html
Normal file
@ -0,0 +1,166 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<link rel="icon" type="image/x-icon" href="/assets/img/logo.svg ">
|
||||
|
||||
<title>Web Terminal</title>
|
||||
|
||||
<!-- Bootstrap core CSS -->
|
||||
<script src="/assets/external/bootstrap.min.js"></script>
|
||||
<link href="/assets/external/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="/assets/main.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header>
|
||||
<nav class="navbar navbar-dark bg-dark shadow-sm navbar-xs">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand mx-auto" href="https://github.com/syssecfsu/witty" target="_blank">
|
||||
<h3>
|
||||
<!-- <img src="/assets/img/logo.svg" style="margin-right: 0.5rem;" height="32"> -->
|
||||
WiTTY: Web-based interactive TTY</h3>
|
||||
</a>
|
||||
<div class="btn-toolbar float-end" role="toolbar" aria-label="top buttons">
|
||||
<form action="/new" method="post" target="_blank" onsubmit="setTimeout(function(){refresh(true)}, 1000)">
|
||||
{{.csrfField}}
|
||||
<button class="btn btn-primary btn-sm m-1" type="submit">New Session</button>
|
||||
</form>
|
||||
|
||||
<a class="btn btn-primary btn-sm m-1 {{.disabled}}" href="/logout" role="button">
|
||||
Logout
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<!-- A modal to rename file -->
|
||||
<div class="modal" id="renameModal" tabindex="-1" aria-labelledby="renameModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-body bg-light">
|
||||
<div class="mb-3">
|
||||
<label for="new_name"><strong>Rename</strong></label>
|
||||
<label for="new_name" class="col-form-label"></label>
|
||||
<input type="text" class="form-control" id="new_name">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer bg-light">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="rename_btn()">Rename</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main>
|
||||
<div class="container-fluid" style="margin-top:1em;">
|
||||
<ul class="nav nav-tabs" id="js_sucks" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link bg-light active" id="interactive-tab" data-bs-toggle="tab"
|
||||
data-bs-target="#interactive-cnt" type="button" role="tab" aria-controls="interactive-cnt"
|
||||
aria-selected="true"><img src="/assets/img/keyboard.svg" style="margin-right: 0.5rem;" height="18px">Live
|
||||
Sessions</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link bg-light" id="saved-tab" data-bs-toggle="tab" data-bs-target="#saved-cnt"
|
||||
type="button" role="tab" aria-controls="saved-cnt" aria-selected="false"><img src="/assets/img/record.svg"
|
||||
style="margin-right: 0.5rem;" height="18px">Recorded Sessions</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content border border-info rounded-bottom" id="nav-tabContent">
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
var active_tab = 0
|
||||
|
||||
function del_btn(path) {
|
||||
let formData = new FormData()
|
||||
formData.append('gorilla.csrf.Token', {{.csrfToken}})
|
||||
|
||||
fetch("/delete/" + path, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
setTimeout(function () {
|
||||
refresh(true)
|
||||
}, 20);
|
||||
}
|
||||
|
||||
// fresh the page every 10 seconds, in case active sessions are closed.
|
||||
function refresh(once) {
|
||||
tabs = document.getElementById("nav-tabContent")
|
||||
fetch("/update/" + active_tab)
|
||||
.then((response) => {
|
||||
return response.text();
|
||||
})
|
||||
.then((result) => {
|
||||
tabs.innerHTML = result;
|
||||
});
|
||||
|
||||
if (once == false) {
|
||||
setTimeout(function () {
|
||||
refresh(false)
|
||||
}, 8000);
|
||||
}
|
||||
}
|
||||
|
||||
refresh(false)
|
||||
|
||||
var itab = document.querySelector('#interactive-tab')
|
||||
itab.addEventListener('shown.bs.tab', function (event) {
|
||||
active_tab = 0
|
||||
})
|
||||
|
||||
var stab = document.querySelector('#saved-tab')
|
||||
stab.addEventListener('shown.bs.tab', function (event) {
|
||||
active_tab = 1
|
||||
})
|
||||
|
||||
|
||||
var renameModal = document.getElementById('renameModal')
|
||||
|
||||
renameModal.addEventListener('show.bs.modal', function (event) {
|
||||
var button = event.relatedTarget // which button lunched this modal
|
||||
var file = button.getAttribute('data-bs-whatever')
|
||||
var modalTitle = renameModal.querySelector('.col-form-label')
|
||||
modalTitle.textContent = file
|
||||
})
|
||||
|
||||
function rename_btn() {
|
||||
var modalTitle = renameModal.querySelector('.col-form-label')
|
||||
var modalInput = renameModal.querySelector('.form-control')
|
||||
var newName = modalInput.value.trim()
|
||||
|
||||
if (newName == "") {
|
||||
console.log("New name is empty, ignore request")
|
||||
return
|
||||
}
|
||||
|
||||
path = "/rename/" + modalTitle.textContent + "/" + newName
|
||||
|
||||
let formData = new FormData()
|
||||
formData.append('gorilla.csrf.Token', {{.csrfToken}})
|
||||
|
||||
fetch(path, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
setTimeout(function () {
|
||||
refresh(true)
|
||||
}, 20);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
64
assets/template/login.html
Normal file
@ -0,0 +1,64 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<link rel="icon" type="image/x-icon" href="/assets/img/logo.svg">
|
||||
|
||||
<title>WiTTY Login</title>
|
||||
<script src="/assets/external/bootstrap.min.js"></script>
|
||||
<link href="/assets/external/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="/assets/signin.css" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body class="text-center">
|
||||
<div class="toast bg-primary text-white border-0" role="alert" aria-live="assertive" aria-atomic="true" id="authMsg"
|
||||
style="position: absolute;top: 0px; right: 10px; z-index:1;">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body">
|
||||
{{.msg}}
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
|
||||
aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main class="form-signin">
|
||||
<form action="/login" method="post">
|
||||
<img class="mb-4" src="/assets/img/keyboard.svg" alt="" width="64">
|
||||
|
||||
<div class="form-floating">
|
||||
<input type="text" class="form-control" id="username" name="username" placeholder="User Name" value="{{.username}}">
|
||||
<label for="username">User Name</label>
|
||||
</div>
|
||||
<div class="form-floating">
|
||||
<input type="password" class="form-control" id="passwd" name="passwd" placeholder="Password">
|
||||
<label for="passwd">Password</label>
|
||||
</div>
|
||||
|
||||
<div class="form-floating">
|
||||
{{.csrfField}}
|
||||
</div>
|
||||
<button class="w-100 btn btn-lg btn-primary mt-5" type="submit">Sign in</button>
|
||||
<p class="mt-5 mb-3 text-muted">WiTTY: Web-based Interactive TTY</p>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
var element = document.getElementById("authMsg");
|
||||
var toast = new bootstrap.Toast(element);
|
||||
|
||||
toast.show()
|
||||
setTimeout(() => {
|
||||
toast.hide()
|
||||
}, 1500)
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
114
assets/template/replay.html
Normal file
@ -0,0 +1,114 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/x-icon" href="/assets/img/logo.svg">
|
||||
|
||||
<script src="/assets/external/xterm.js"></script>
|
||||
<script src="/assets/external/xterm-addon-attach.js"></script>
|
||||
<script src="/assets/external/xterm-addon-fit.js"></script>
|
||||
<script src="/assets/external/xterm-addon-web-links.js"></script>
|
||||
|
||||
<script src="/assets/replay.js"></script>
|
||||
|
||||
<link rel="stylesheet" href="/assets/external/xterm.css" />
|
||||
<link href="/assets/external/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="/assets/main.css" />
|
||||
|
||||
<title>Replay</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header>
|
||||
<nav class="navbar navbar-light bg-light shadow-sm navbar-xs">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand mx-auto" href="https://github.com/syssecfsu/witty" target="_blank">
|
||||
<img src="/assets/img/record.svg" style="margin-right: 0.5rem;" height="32"
|
||||
class="d-inline-block align-text-top">
|
||||
replay terminal
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
|
||||
<div class="d-flex flex-column align-items-center" style="margin-top: 2rem;">
|
||||
<div id="terminal">
|
||||
<div id="terminal_view"></div>
|
||||
</div>
|
||||
<div class="d-flex align-items-center">
|
||||
<button type="button" class="btn btn-primary btn-sm" style="margin-right: 3px;" onclick="playbtn()">
|
||||
<img src="/assets/img/play.svg" id="play-btn" height="18px">
|
||||
</button>
|
||||
<input type="range" class="form-range" min="0" max="100" id="replay-control" step="1"
|
||||
oninput="seek(this.value)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
term = Init()
|
||||
|
||||
var rc = document.querySelector("#replay-control")
|
||||
rc.value = 0
|
||||
|
||||
var icon = document.getElementById("play-btn")
|
||||
var pause = false
|
||||
|
||||
var records
|
||||
var total_dur
|
||||
|
||||
// return values are not reliable with async functions
|
||||
fetchAndParse("/records/{{.fname}}",
|
||||
function (v1, v2) {
|
||||
records = v1
|
||||
total_dur = v2
|
||||
})
|
||||
|
||||
function playbtn() {
|
||||
if (icon.src.includes("play")) {
|
||||
icon.src = "/assets/img/pause.svg"
|
||||
pause = false
|
||||
replay_session(term, records, {{.max_wait}}, total_dur, rc.value,
|
||||
function () {
|
||||
return pause
|
||||
},
|
||||
function (percent) {
|
||||
rc.value = percent
|
||||
},
|
||||
function () {
|
||||
icon.src = "/assets/img/play.svg"
|
||||
rc.value = 0
|
||||
})
|
||||
} else {
|
||||
icon.src = "/assets/img/play.svg"
|
||||
pause = true
|
||||
}
|
||||
}
|
||||
|
||||
// limit the rate of refresh to twice per second. Otherwise
|
||||
// the screen flicks like crazy
|
||||
var lastFired = new Date().getTime()
|
||||
|
||||
function seek(end) {
|
||||
var now = new Date().getTime()
|
||||
var elapsed = now - lastFired
|
||||
|
||||
if (elapsed <= 500) {
|
||||
return
|
||||
}
|
||||
|
||||
lastFired = now
|
||||
|
||||
// pause the play if it is currently playing
|
||||
if (!icon.src.includes("play")) {
|
||||
playbtn()
|
||||
}
|
||||
|
||||
forwardScreen(term, records, end)
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
55
assets/template/tab.html
Normal file
@ -0,0 +1,55 @@
|
||||
<div class="tab-pane {{.active0}}" id="interactive-cnt" role="tabpanel" aria-labelledby="interactive-tab">
|
||||
<div class="card-deck row justify-content-center">
|
||||
|
||||
<!-- repeat this for each interactive session -->
|
||||
{{range .players}}
|
||||
<div class="card shadow-sm border-danger bg-white mb-3" style="width: 16rem; margin:1em;">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Interactive session</h5>
|
||||
<p class="card-text">From <em>{{.Ip}}</em>, running <strong>{{.Cmd}}</strong>, session ID:
|
||||
<u>{{.Id}}</u>
|
||||
</p>
|
||||
<a class="btn btn-outline-success btn-sm float-end" href="/view/{{.Id}}" target="_blank" role="button">
|
||||
<img src="/assets/img/view.svg" height="20px">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tab-pane {{.active1}}" id="saved-cnt" role="tabpanel" aria-labelledby="saved-tab">
|
||||
<div class="card-deck row justify-content-center">
|
||||
|
||||
<!-- repeat this for each recorded session -->
|
||||
{{range .records}}
|
||||
<div class="card shadow-sm border-info mb-3" style="width: 16rem; margin:1em;">
|
||||
<div class="card-body d-flex flex-column">
|
||||
<h5 class="card-title">Recorded session</h5>
|
||||
<p class="card-text">File name: <u>{{.Fname}}</u>, file size: <em>{{.Fsize}}KB</em>,
|
||||
recorded at <strong>{{.Time}}</strong>, duration: <mark>{{.Duration}}s</mark>,
|
||||
</p>
|
||||
<div class="btn-toolbar mt-auto" role="toolbar" aria-label="records buttons">
|
||||
<a class="btn btn-outline-success btn-sm m-1" href="/replay/{{.Fname}}" target="_blank"
|
||||
role="button">
|
||||
<img src="/assets/img/play.svg" height="20px">
|
||||
</a>
|
||||
<a class="btn btn-outline-success btn-sm m-1" href="/records/{{.Fname}}" role="button" download>
|
||||
<img src="/assets/img/download.svg" height="20px">
|
||||
</a>
|
||||
<!-- a button show the rename modal and pass data to it, do not change any data-bs- fields.
|
||||
that is the magic of bootstrap framework -->
|
||||
<button type="button" class="btn btn-outline-success btn-sm m-1" data-bs-toggle="modal" data-bs-target="#renameModal" data-bs-whatever="{{.Fname}}" >
|
||||
<img src="/assets/img/edit.svg" height="20px">
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-success btn-sm m-1" onclick="del_btn({{.Fname}})">
|
||||
<img src="/assets/img/delete.svg" height="20px">
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
</div>
|
||||
</div>
|
85
assets/template/term.html
Normal file
@ -0,0 +1,85 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/x-icon" href="/assets/img/logo.svg">
|
||||
|
||||
<script src="/assets/external/xterm.js"></script>
|
||||
<script src="/assets/external/xterm-addon-attach.js"></script>
|
||||
<script src="/assets/external/xterm-addon-fit.js"></script>
|
||||
<script src="/assets/external/xterm-addon-web-links.js"></script>
|
||||
|
||||
<script src="/assets/main.js"></script>
|
||||
|
||||
<link rel="stylesheet" href="/assets/external/xterm.css" />
|
||||
<link href="/assets/external/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="/assets/main.css" />
|
||||
|
||||
<title>{{.title}}</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header>
|
||||
<nav class="navbar navbar-light bg-light shadow-sm navbar-xs">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand mx-auto" href="https://github.com/syssecfsu/witty" target="_blank">
|
||||
<img src="/assets/img/{{.logo}}.svg" style="margin-right: 0.5rem;" height="32"
|
||||
class="d-inline-block align-text-top">
|
||||
{{.title}}
|
||||
</a>
|
||||
<button type="button" id="record_onoff" class="btn btn-primary btn-sm float-end" value="Record"
|
||||
onclick="recordOnOff()">Record</button>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
|
||||
<div style="margin-top: 2em;">
|
||||
<div id="terminal">
|
||||
<div id="terminal_view"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function recordOnOff(on) {
|
||||
let formData = new FormData()
|
||||
formData.append('gorilla.csrf.Token', {{.csrfToken}})
|
||||
|
||||
var btn = document.getElementById("record_onoff");
|
||||
if (btn.value == "Record") {
|
||||
btn.value = "Stop";
|
||||
btn.innerHTML = btn.value
|
||||
fetch("/record/{{.id}}", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
} else {
|
||||
btn.value = "Record";
|
||||
btn.innerHTML = btn.value
|
||||
fetch("/stop/{{.id}}", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function Init() {
|
||||
term = createTerminal("{{.path}}");
|
||||
// print something to test output and scroll
|
||||
var str = [
|
||||
' ┌────────────────────────────────────────────────────────────────────────────┐\n',
|
||||
' │ \u001b[32;1mhttps://github.com/syssecfsu/witty\x1b[0m <- click it! │\n',
|
||||
' └────────────────────────────────────────────────────────────────────────────┘\n',
|
||||
''
|
||||
].join('');
|
||||
|
||||
term.writeln(str)
|
||||
}
|
||||
|
||||
Init()
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
12
build.sh
Executable file
@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
go clean .
|
||||
go build .
|
||||
|
||||
DST="./release"
|
||||
rm -rf $DST
|
||||
mkdir $DST
|
||||
mkdir $DST/tls
|
||||
mkdir $DST/records
|
||||
cp tls/README.md $DST/tls/README.md
|
||||
cp witty LICENSE $DST
|
||||
echo "[]" > $DST/user.db
|
45
cmd/merge.go
Normal file
@ -0,0 +1,45 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/syssecfsu/witty/term_conn"
|
||||
)
|
||||
|
||||
func Merge(fnames []string, output string) {
|
||||
var all_recrods []term_conn.WriteRecord
|
||||
var records []term_conn.WriteRecord
|
||||
|
||||
for _, fname := range fnames {
|
||||
file, err := os.ReadFile(fname)
|
||||
if err != nil {
|
||||
log.Println("Failed to read users file", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(file, &records)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to parse json format", err, "for", fname)
|
||||
return
|
||||
}
|
||||
|
||||
all_recrods = append(all_recrods, records...)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(all_recrods)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to merge into JSON format", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(output, ".scr") {
|
||||
output += ".scr"
|
||||
}
|
||||
|
||||
os.WriteFile(output, data, 0664)
|
||||
}
|
68
cmd/replay.go
Normal file
@ -0,0 +1,68 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/syssecfsu/witty/term_conn"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func Replay(fname string, wait uint) {
|
||||
fp, err := os.Open(fname)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalln("Failed to open record file", err)
|
||||
}
|
||||
|
||||
screen := struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}{os.Stdin, os.Stdout}
|
||||
|
||||
t := term.NewTerminal(screen, "$")
|
||||
|
||||
if t == nil {
|
||||
log.Fatalln("Failed to create terminal")
|
||||
}
|
||||
|
||||
w, h, _ := term.GetSize(int(os.Stdout.Fd()))
|
||||
|
||||
if (w != 120) || (h != 36) {
|
||||
log.Println("Set terminal window to 120x36 before continue")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(fp)
|
||||
|
||||
if decoder == nil {
|
||||
log.Fatalln("Failed to create JSON decoder")
|
||||
}
|
||||
|
||||
// To work with javascript decoder, we organize the file as
|
||||
// an array of writeRecord. golang decode instead decode
|
||||
// as individual record. Call decoder.Token to skip opening [
|
||||
t.Write([]byte("\n\n---beginning of replay---\n\n"))
|
||||
|
||||
decoder.Token()
|
||||
for decoder.More() {
|
||||
var record term_conn.WriteRecord
|
||||
|
||||
if err := decoder.Decode(&record); err != nil {
|
||||
log.Println("Failed to decode record", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if record.Dur > time.Duration(wait)*time.Millisecond {
|
||||
record.Dur = time.Duration(wait) * time.Millisecond
|
||||
}
|
||||
|
||||
time.Sleep(record.Dur)
|
||||
t.Write(record.Data)
|
||||
}
|
||||
|
||||
t.Write([]byte("\n\n---end of replay---\n\n"))
|
||||
|
||||
}
|
189
cmd/user.go
Normal file
@ -0,0 +1,189 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/dchest/uniuri"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const (
|
||||
userFileName = "./user.db"
|
||||
)
|
||||
|
||||
type UserRecord struct {
|
||||
User []byte `json:"Username"`
|
||||
Seed []byte `json:"Seed"`
|
||||
Passwd [32]byte `json:"Password"`
|
||||
}
|
||||
|
||||
func hashPassword(seed []byte, passwd []byte) [32]byte {
|
||||
input := append(seed, passwd...)
|
||||
return sha256.Sum256(input)
|
||||
}
|
||||
|
||||
func addUser(username []byte, passwd []byte) {
|
||||
var users []UserRecord
|
||||
var err error
|
||||
|
||||
seed := []byte(uniuri.NewLen(64))
|
||||
hashed := hashPassword(seed, passwd)
|
||||
|
||||
exist := false
|
||||
file, err := os.ReadFile(userFileName)
|
||||
|
||||
if err != nil {
|
||||
goto nonexist
|
||||
}
|
||||
|
||||
if err = json.Unmarshal(file, &users); err != nil {
|
||||
log.Println("Failed to unmarsh file", err)
|
||||
goto nonexist
|
||||
}
|
||||
|
||||
// update the existing user if it exists
|
||||
for i, u := range users {
|
||||
if bytes.Equal(u.User, username) {
|
||||
users[i].Seed = seed
|
||||
users[i].Passwd = hashed
|
||||
exist = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
nonexist:
|
||||
if !exist {
|
||||
users = append(users, UserRecord{username, seed, hashed})
|
||||
}
|
||||
|
||||
output, err := json.Marshal(users)
|
||||
if err != nil {
|
||||
log.Println("Failed to marshal passwords", err)
|
||||
return
|
||||
}
|
||||
|
||||
os.WriteFile(userFileName, output, 0660)
|
||||
}
|
||||
|
||||
func AddUser(username string) {
|
||||
fmt.Println("Please type your password (it will not be echoed back):")
|
||||
passwd, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to read password", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(passwd) < 12 {
|
||||
fmt.Println("Password too short, at least 12 bytes")
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Please type your password again:")
|
||||
passwd2, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to read password", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !bytes.Equal(passwd, passwd2) {
|
||||
fmt.Println("Password mismatch, try again")
|
||||
return
|
||||
}
|
||||
|
||||
addUser([]byte(username), passwd)
|
||||
}
|
||||
|
||||
func DelUser(username string) {
|
||||
var users []UserRecord
|
||||
var err error
|
||||
|
||||
exist := false
|
||||
file, err := os.ReadFile(userFileName)
|
||||
if err != nil {
|
||||
log.Println("Failed to read users file", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(file, &users)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to parse json format", err)
|
||||
return
|
||||
}
|
||||
// update the existing user if it exists
|
||||
for i, u := range users {
|
||||
if bytes.Equal(u.User, []byte(username)) {
|
||||
users = append(users[:i], users[i+1:]...)
|
||||
exist = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if exist {
|
||||
output, err := json.Marshal(users)
|
||||
if err != nil {
|
||||
log.Println("Failed to marshal passwords", err)
|
||||
return
|
||||
}
|
||||
|
||||
os.WriteFile(userFileName, output, 0660)
|
||||
}
|
||||
}
|
||||
|
||||
func ListUsers() {
|
||||
var users []UserRecord
|
||||
var err error
|
||||
|
||||
file, err := os.ReadFile(userFileName)
|
||||
if err != nil {
|
||||
log.Println("Failed to read users file", err)
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(file, &users)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to parse json format", err)
|
||||
return
|
||||
}
|
||||
// update the existing user if it exists
|
||||
fmt.Println("Users of the system:")
|
||||
for _, u := range users {
|
||||
fmt.Println(" ", string(u.User))
|
||||
}
|
||||
}
|
||||
|
||||
func ValidateUser(username []byte, passwd []byte) bool {
|
||||
var users []UserRecord
|
||||
var err error
|
||||
|
||||
file, err := os.ReadFile(userFileName)
|
||||
if err != nil {
|
||||
log.Println("Failed to read users file", err)
|
||||
return false
|
||||
}
|
||||
|
||||
err = json.Unmarshal(file, &users)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to parse json format", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// update the existing user if it exists
|
||||
for _, u := range users {
|
||||
if bytes.Equal(u.User, []byte(username)) {
|
||||
hashed := hashPassword(u.Seed, passwd)
|
||||
return bytes.Equal(hashed[:], u.Passwd[:])
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
1
extra/M1NXZvHdvA8vSCKp_61e5d60f.scr
Normal file
BIN
extra/interactive.png
Normal file
After Width: | Height: | Size: 701 KiB |
BIN
extra/login.png
Normal file
After Width: | Height: | Size: 50 KiB |
BIN
extra/main.png
Normal file
After Width: | Height: | Size: 644 KiB |
BIN
extra/merge.png
Normal file
After Width: | Height: | Size: 53 KiB |
BIN
extra/rename.png
Normal file
After Width: | Height: | Size: 708 KiB |
BIN
extra/replay.gif
Executable file
After Width: | Height: | Size: 4.7 MiB |
BIN
extra/view.png
Normal file
After Width: | Height: | Size: 671 KiB |
40
go.mod
Normal file
@ -0,0 +1,40 @@
|
||||
module github.com/syssecfsu/witty
|
||||
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/creack/pty v1.1.17
|
||||
github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5
|
||||
github.com/gin-gonic/gin v1.7.7
|
||||
github.com/gorilla/websocket v1.4.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
|
||||
github.com/gomodule/redigo v2.0.0+incompatible // indirect
|
||||
github.com/gorilla/context v1.1.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.1 // indirect
|
||||
github.com/gorilla/sessions v1.2.1 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/gin-gonic/contrib v0.0.0-20201101042839-6a891bf89f19
|
||||
github.com/go-playground/locales v0.13.0 // indirect
|
||||
github.com/go-playground/universal-translator v0.17.0 // indirect
|
||||
github.com/go-playground/validator/v10 v10.4.1 // indirect
|
||||
github.com/golang/protobuf v1.3.3 // indirect
|
||||
github.com/gorilla/csrf v1.7.1
|
||||
github.com/gwatts/gin-adapter v0.0.0-20170508204228-c44433c485ad
|
||||
github.com/json-iterator/go v1.1.9 // indirect
|
||||
github.com/leodido/go-urn v1.2.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.12 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
|
||||
github.com/ugorji/go/codec v1.1.7 // indirect
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
|
||||
gopkg.in/yaml.v2 v2.2.8 // indirect
|
||||
)
|
82
go.sum
Normal file
@ -0,0 +1,82 @@
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff h1:RmdPFa+slIr4SCBg4st/l/vZWVe9QJKMXGO60Bxbe04=
|
||||
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw=
|
||||
github.com/creack/pty v1.1.17 h1:QeVUsEDNrLBW4tMgZHvxy18sKtr6VI492kBhUfhDJNI=
|
||||
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5 h1:RAV05c0xOkJ3dZGS0JFybxFKZ2WMLabgx3uXnd7rpGs=
|
||||
github.com/dchest/uniuri v0.0.0-20200228104902-7aecb25e1fe5/go.mod h1:GgB8SF9nRG+GqaDtLcwJZsQFhcogVCJ79j4EdT0c2V4=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/contrib v0.0.0-20201101042839-6a891bf89f19 h1:J2LPEOcQmWaooBnBtUDV9KHFEnP5LYTZY03GiQ0oQBw=
|
||||
github.com/gin-gonic/contrib v0.0.0-20201101042839-6a891bf89f19/go.mod h1:iqneQ2Df3omzIVTkIfn7c1acsVnMGiSLn4XF5Blh3Yg=
|
||||
github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs=
|
||||
github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U=
|
||||
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
|
||||
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
|
||||
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
|
||||
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||
github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0=
|
||||
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
github.com/gorilla/csrf v1.7.1 h1:Ir3o2c1/Uzj6FBxMlAUB6SivgVMy1ONXwYgXn+/aHPE=
|
||||
github.com/gorilla/csrf v1.7.1/go.mod h1:+a/4tCmqhG6/w4oafeAZ9pEa3/NZOWYVbD9fV0FwIQA=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w=
|
||||
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gwatts/gin-adapter v0.0.0-20170508204228-c44433c485ad h1:eGCbPkMnsg02jXBIxxXn1Fxep9dAuTUvEi6UdJsbOhg=
|
||||
github.com/gwatts/gin-adapter v0.0.0-20170508204228-c44433c485ad/go.mod h1:XywyZk8euPjg6CVt44eMyHjv0sZUiHbHtBnFKgmvj8I=
|
||||
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
|
||||
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
129
main.go
Normal file
@ -0,0 +1,129 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/syssecfsu/witty/cmd"
|
||||
"github.com/syssecfsu/witty/web"
|
||||
)
|
||||
|
||||
const (
|
||||
subcmds = "witty (adduser|deluser|listusers|replay|merge|run)"
|
||||
)
|
||||
|
||||
//go:embed assets/*
|
||||
var fullAssets embed.FS
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Println(subcmds)
|
||||
return
|
||||
}
|
||||
|
||||
switch os.Args[1] {
|
||||
case "adduser":
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Println("witty adduser <username>")
|
||||
return
|
||||
}
|
||||
cmd.AddUser(os.Args[2])
|
||||
|
||||
case "deluser":
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Println("witty deluser <username>")
|
||||
return
|
||||
}
|
||||
cmd.DelUser(os.Args[2])
|
||||
|
||||
case "listusers":
|
||||
cmd.ListUsers()
|
||||
|
||||
case "replay":
|
||||
var wait uint
|
||||
replayCmd := flag.NewFlagSet("replay", flag.ExitOnError)
|
||||
replayCmd.UintVar(&wait, "w", 1000, "Max wait time between outputs")
|
||||
replayCmd.UintVar(&wait, "wait", 1000, "Max wait time between outputs")
|
||||
|
||||
replayCmd.Parse(os.Args[2:])
|
||||
|
||||
if len(replayCmd.Args()) != 1 {
|
||||
fmt.Println("witty replay <recorded>")
|
||||
return
|
||||
}
|
||||
|
||||
cmd.Replay(replayCmd.Arg(0), wait)
|
||||
|
||||
case "merge":
|
||||
var output string
|
||||
|
||||
defName := "merged_" + strconv.FormatInt(time.Now().Unix(), 16) + ".scr"
|
||||
|
||||
mergeCmd := flag.NewFlagSet("merge", flag.ExitOnError)
|
||||
mergeCmd.StringVar(&output, "o", defName, "Set the name of merged files")
|
||||
mergeCmd.StringVar(&output, "output", defName, "Set the name of merged files")
|
||||
|
||||
mergeCmd.Parse(os.Args[2:])
|
||||
|
||||
if len(mergeCmd.Args()) < 2 {
|
||||
fmt.Println("witty merge -o output_file file1 file2 ... (at least two files)")
|
||||
return
|
||||
}
|
||||
|
||||
cmd.Merge(mergeCmd.Args(), output)
|
||||
|
||||
case "run":
|
||||
// setup the web options
|
||||
var options web.Options
|
||||
runCmd := flag.NewFlagSet("run", flag.ExitOnError)
|
||||
runCmd.BoolVar(&options.NoAuth, "n", false, "Run WiTTY without user authentication")
|
||||
runCmd.BoolVar(&options.NoAuth, "naked", false, "Run WiTTY without user authentication")
|
||||
runCmd.UintVar(&options.Port, "p", 8080, "Port number to listen on")
|
||||
runCmd.UintVar(&options.Port, "port", 8080, "Port number to listen on")
|
||||
runCmd.UintVar(&options.Wait, "w", 1000, "Max wait time between outputs")
|
||||
runCmd.UintVar(&options.Wait, "wait", 1000, "Max wait time between outputs")
|
||||
|
||||
fp, err := os.OpenFile("witty.log", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
|
||||
if err == nil {
|
||||
defer fp.Close()
|
||||
log.SetOutput(fp)
|
||||
}
|
||||
|
||||
options.LogFile = fp
|
||||
|
||||
runCmd.Parse(os.Args[2:])
|
||||
|
||||
var cmdToExec []string
|
||||
args := runCmd.Args()
|
||||
if len(args) > 0 {
|
||||
cmdToExec = args
|
||||
} else {
|
||||
cmdToExec = []string{"bash"}
|
||||
}
|
||||
|
||||
options.CmdToExec = cmdToExec
|
||||
|
||||
// we need to strip the top level directory for Gin to find the files
|
||||
assets, err := fs.Sub(fullAssets, "assets")
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Failed to load assets", err)
|
||||
}
|
||||
|
||||
options.Assets = assets
|
||||
|
||||
web.StartWeb(&options)
|
||||
|
||||
default:
|
||||
fmt.Println(subcmds)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
3
records/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Usage
|
||||
|
||||
This directory contains all the records of sessions.
|
81
term_conn/reg.go
Normal file
@ -0,0 +1,81 @@
|
||||
package term_conn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// a simple registry for actors and their channels. It is possible to
|
||||
// design this using channels, but it is simple enough with mutex
|
||||
type Registry struct {
|
||||
mtx sync.Mutex
|
||||
players map[string]*TermConn
|
||||
}
|
||||
|
||||
var registry Registry
|
||||
|
||||
func (reg *Registry) init() {
|
||||
reg.players = make(map[string]*TermConn)
|
||||
}
|
||||
|
||||
func (d *Registry) addPlayer(tc *TermConn) {
|
||||
d.mtx.Lock()
|
||||
if _, ok := d.players[tc.Name]; ok {
|
||||
log.Println(tc.Name, "Already exist in the dispatcher, skip registration")
|
||||
} else {
|
||||
d.players[tc.Name] = tc
|
||||
log.Println("Add interactive session to registry", tc.Name)
|
||||
}
|
||||
d.mtx.Unlock()
|
||||
}
|
||||
|
||||
func (d *Registry) removePlayer(name string) error {
|
||||
d.mtx.Lock()
|
||||
var err error = errors.New("not found")
|
||||
|
||||
if _, ok := d.players[name]; ok {
|
||||
delete(d.players, name)
|
||||
err = nil
|
||||
log.Println("Removed interactive session to registry", name)
|
||||
}
|
||||
|
||||
d.mtx.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// we do not want to return the channel to viewer so it won't be used out of the critical section
|
||||
func (d *Registry) sendToPlayer(name string, ws *websocket.Conn) bool {
|
||||
d.mtx.Lock()
|
||||
tc, ok := d.players[name]
|
||||
|
||||
if ok {
|
||||
tc.viewChan <- ws
|
||||
}
|
||||
|
||||
d.mtx.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
// Send a command to the session to start, stop recording
|
||||
func (d *Registry) recordSession(id string, cmd int) bool {
|
||||
d.mtx.Lock()
|
||||
tc, ok := d.players[id]
|
||||
|
||||
if ok {
|
||||
tc.recordChan <- cmd
|
||||
}
|
||||
|
||||
d.mtx.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func ForEachSession(fp func(tc *TermConn)) {
|
||||
registry.mtx.Lock()
|
||||
for _, v := range registry.players {
|
||||
fp(v)
|
||||
}
|
||||
registry.mtx.Unlock()
|
||||
}
|
443
term_conn/relay.go
Normal file
@ -0,0 +1,443 @@
|
||||
//This file contains code to relay traffic between websocket and pty
|
||||
package term_conn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/creack/pty"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
// Time allowed to write a message to the peer.
|
||||
readWait = 10 * time.Second
|
||||
writeWait = 10 * time.Second
|
||||
viewWait = 3 * time.Second
|
||||
|
||||
// Time allowed to read the next pong message from the peer.
|
||||
pongWait = 10 * time.Second
|
||||
|
||||
// Maximum message size allowed from peer.
|
||||
maxMessageSize = 4096
|
||||
readBufferSize = 1024
|
||||
WriteBufferSize = 1024
|
||||
|
||||
// Send pings to peer with this period. Must be less than pongWait.
|
||||
pingPeriod = (pongWait * 9) / 10
|
||||
|
||||
recordCmd = 1
|
||||
stopCmd = 0
|
||||
)
|
||||
|
||||
// simple function to check origin
|
||||
func checkOrigin(r *http.Request) bool {
|
||||
org := r.Header.Get("Origin")
|
||||
|
||||
if org != "https://"+r.Host {
|
||||
log.Println("Failed origin check of ", org, r.Host)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: readBufferSize,
|
||||
WriteBufferSize: WriteBufferSize,
|
||||
CheckOrigin: checkOrigin,
|
||||
}
|
||||
|
||||
// TermConn represents the connected websocket and pty.
|
||||
// if isViewer is true
|
||||
type TermConn struct {
|
||||
Name string
|
||||
Ip string
|
||||
|
||||
ws *websocket.Conn
|
||||
ptmx *os.File // the pty that runs the command
|
||||
record *os.File // record session
|
||||
lastRecTime time.Time // last time a record is written
|
||||
cmd *exec.Cmd // represents the process, we need it to terminate the process
|
||||
viewChan chan *websocket.Conn // channel to receive viewers
|
||||
recordChan chan int // channel to start/stop recording
|
||||
ws_done chan struct{} // ws is closed, only close this chan in ws reader
|
||||
pty_done chan struct{} // pty is closed, close this chan in pty reader
|
||||
}
|
||||
|
||||
type WriteRecord struct {
|
||||
Dur time.Duration `json:"Duration"`
|
||||
Data []byte `json:"Data"`
|
||||
}
|
||||
|
||||
func (tc *TermConn) createPty(cmdline []string) error {
|
||||
// Create a shell command.
|
||||
cmd := exec.Command(cmdline[0], cmdline[1:]...)
|
||||
|
||||
// Start the command with a pty.
|
||||
ptmx, err := pty.Start(cmd)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use fixed size, the xterm is initalized as 122x37,
|
||||
// But we set pty to 120x36. Using fullsize will lead
|
||||
// some program to misbehave.
|
||||
pty.Setsize(ptmx, &pty.Winsize{
|
||||
Cols: 120,
|
||||
Rows: 36,
|
||||
})
|
||||
|
||||
tc.ptmx = ptmx
|
||||
tc.cmd = cmd
|
||||
|
||||
log.Printf("Create shell process %v (%v)", cmdline, cmd.Process.Pid)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Periodically send ping message to detect the status of the ws
|
||||
func (tc *TermConn) ping(wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
ticker := time.NewTicker(pingPeriod)
|
||||
defer ticker.Stop()
|
||||
|
||||
out:
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
err := tc.ws.WriteControl(websocket.PingMessage,
|
||||
[]byte{}, time.Now().Add(writeWait))
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to write ping message:", err)
|
||||
break out
|
||||
}
|
||||
case <-tc.pty_done:
|
||||
log.Println("Exit ping routine as pty is going away")
|
||||
break out
|
||||
|
||||
case <-tc.ws_done:
|
||||
log.Println("Exit ping routine as ws is going away")
|
||||
break out
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Ping routine exited")
|
||||
}
|
||||
|
||||
// shovel data from websocket to pty stdin
|
||||
func (tc *TermConn) wsToPtyStdin(wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
tc.ws.SetReadLimit(maxMessageSize)
|
||||
|
||||
// set the readdeadline. The idea here is simple,
|
||||
// as long as we keep receiving pong message,
|
||||
// the readdeadline will keep updating. Otherwise
|
||||
// read will timeout.
|
||||
tc.ws.SetReadDeadline(time.Now().Add(pongWait))
|
||||
tc.ws.SetPongHandler(func(string) error {
|
||||
tc.ws.SetReadDeadline(time.Now().Add(pongWait))
|
||||
return nil
|
||||
})
|
||||
|
||||
bufChan := make(chan []byte)
|
||||
|
||||
go func() { //create a goroutine to read from ws
|
||||
for {
|
||||
_, buf, err := tc.ws.ReadMessage()
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to receive data from ws:", err)
|
||||
close(bufChan) // close chan by producer
|
||||
close(tc.ws_done)
|
||||
break
|
||||
}
|
||||
|
||||
bufChan <- buf
|
||||
}
|
||||
}()
|
||||
// we do not need to forward user input to viewers, only the stdout
|
||||
out:
|
||||
for {
|
||||
select {
|
||||
case buf, ok := <-bufChan:
|
||||
if !ok {
|
||||
log.Println("Exit wsToPtyStdin routine pty stdin error")
|
||||
break out
|
||||
}
|
||||
_, err := tc.ptmx.Write(buf)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to send data to pty stdin: ", err)
|
||||
break out
|
||||
}
|
||||
case <-tc.ws_done:
|
||||
log.Println("Exit wsToPtyStdin routine as ws is going away")
|
||||
break out
|
||||
case <-tc.pty_done:
|
||||
log.Println("Exit wsToPtyStdin routine as pty is going away")
|
||||
break out
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("wsToPtyStdin routine exited")
|
||||
}
|
||||
|
||||
// shovel data from pty Stdout to WS
|
||||
func (tc *TermConn) ptyStdoutToWs(wg *sync.WaitGroup) {
|
||||
var viewers []*websocket.Conn
|
||||
|
||||
defer wg.Done()
|
||||
bufChan := make(chan []byte)
|
||||
|
||||
go func() { //create a goroutine to read from pty
|
||||
for {
|
||||
readBuf := make([]byte, 1024) //pty reads in 1024 blocks
|
||||
n, err := tc.ptmx.Read(readBuf)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to read from pty stdout: ", err)
|
||||
close(bufChan)
|
||||
close(tc.pty_done)
|
||||
break
|
||||
}
|
||||
|
||||
readBuf = readBuf[0:n] // slice the buffer so that it is exact the size of data read.
|
||||
bufChan <- readBuf
|
||||
}
|
||||
}()
|
||||
|
||||
out:
|
||||
for {
|
||||
// handle viewers, we want to use non-blocking receive
|
||||
select {
|
||||
case buf, ok := <-bufChan:
|
||||
if !ok {
|
||||
tc.ws.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
tc.ws.WriteMessage(websocket.CloseMessage,
|
||||
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "Pty closed"))
|
||||
|
||||
break out
|
||||
}
|
||||
// We could add ws to viewers as well (then we can use io.MultiWriter),
|
||||
// but we want to handle errors differently
|
||||
tc.ws.SetWriteDeadline(time.Now().Add(writeWait))
|
||||
if err := tc.ws.WriteMessage(websocket.BinaryMessage, buf); err != nil {
|
||||
log.Println("Failed to write message: ", err)
|
||||
break out
|
||||
}
|
||||
|
||||
//write to the viewer
|
||||
for i, w := range viewers {
|
||||
if w == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// if the viewer exits, we will just ignore the error
|
||||
w.SetWriteDeadline(time.Now().Add(viewWait))
|
||||
if err := w.WriteMessage(websocket.BinaryMessage, buf); err != nil {
|
||||
log.Println("Failed to write message to viewer: ", err)
|
||||
|
||||
viewers[i] = nil
|
||||
w.Close() // we own the socket and need to close it
|
||||
}
|
||||
}
|
||||
|
||||
// Do we need to record the session?
|
||||
if tc.record != nil {
|
||||
jbuf, err := json.Marshal(WriteRecord{Dur: time.Since(tc.lastRecTime), Data: buf})
|
||||
if err != nil {
|
||||
log.Println("Failed to marshal record", err)
|
||||
} else {
|
||||
tc.record.Write([]byte(",")) // write a deliminator
|
||||
tc.record.Write(jbuf)
|
||||
}
|
||||
|
||||
tc.lastRecTime = time.Now()
|
||||
}
|
||||
|
||||
case cmd := <-tc.recordChan:
|
||||
var err error
|
||||
if cmd == recordCmd {
|
||||
// use the session ID and current as file name
|
||||
fname := "./records/" + tc.Name + "_" + strconv.FormatInt(time.Now().Unix(), 16) + ".scr"
|
||||
|
||||
tc.record, err = os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
log.Println("Failed to create record file", fname, err)
|
||||
tc.record = nil
|
||||
}
|
||||
|
||||
tc.record.Write([]byte("[")) // write a [ for an array of json objs
|
||||
|
||||
// write a dummy record
|
||||
tc.lastRecTime = time.Now()
|
||||
jbuf, _ := json.Marshal(WriteRecord{Dur: time.Since(tc.lastRecTime), Data: []byte("")})
|
||||
tc.record.Write(jbuf)
|
||||
|
||||
} else {
|
||||
tc.record.Write([]byte("]"))
|
||||
tc.record.Close()
|
||||
tc.record = nil
|
||||
}
|
||||
|
||||
case viewer := <-tc.viewChan:
|
||||
log.Println("Received viewer", viewer.RemoteAddr().String())
|
||||
viewers = append(viewers, viewer)
|
||||
|
||||
case <-tc.ws_done:
|
||||
log.Println("Exit ptyStdoutToWs routine as ws is going away")
|
||||
break out
|
||||
|
||||
case <-tc.pty_done:
|
||||
log.Println("Exit ptyStdoutToWs routine as pty is going away")
|
||||
break out // do not block on these two channels
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// close the watcher
|
||||
for _, w := range viewers {
|
||||
if w != nil {
|
||||
w.Close()
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("ptyStdoutToWs routine exited")
|
||||
}
|
||||
|
||||
// this function should be executed by the main goroutine for the connection
|
||||
func (tc *TermConn) release() {
|
||||
log.Println("Releasing terminal connection", tc.Name)
|
||||
|
||||
registry.removePlayer(tc.Name)
|
||||
|
||||
if tc.ptmx != nil {
|
||||
// cleanup the pty and its related process
|
||||
tc.ptmx.Close()
|
||||
|
||||
// terminate the command line process
|
||||
proc := tc.cmd.Process
|
||||
|
||||
// send an interrupt, this will cause the shell process to
|
||||
// return from syscalls if any is pending
|
||||
if err := proc.Signal(os.Interrupt); err != nil {
|
||||
log.Printf("Failed to send Interrupt to shell process(%v): %v ", proc.Pid, err)
|
||||
}
|
||||
|
||||
// Wait for a second for shell process to interrupt before kill it
|
||||
time.Sleep(time.Second)
|
||||
|
||||
log.Printf("Try to kill the shell process(%v)", proc.Pid)
|
||||
|
||||
if err := proc.Signal(os.Kill); err != nil {
|
||||
log.Printf("Failed to send KILL to shell process(%v): %v", proc.Pid, err)
|
||||
}
|
||||
|
||||
if _, err := proc.Wait(); err != nil {
|
||||
log.Printf("Failed to wait for shell process(%v): %v", proc.Pid, err)
|
||||
}
|
||||
|
||||
close(tc.viewChan)
|
||||
close(tc.recordChan)
|
||||
|
||||
if tc.record != nil {
|
||||
// write a ] and close the file
|
||||
tc.record.Write([]byte("]"))
|
||||
tc.record.Close()
|
||||
tc.record = nil
|
||||
}
|
||||
}
|
||||
|
||||
tc.ws.Close()
|
||||
}
|
||||
|
||||
// handle websockets
|
||||
func handlePlayer(w http.ResponseWriter, r *http.Request, name string, cmdline []string) {
|
||||
ws, err := upgrader.Upgrade(w, r, nil)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to create websocket: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
tc := TermConn{
|
||||
ws: ws,
|
||||
Name: name,
|
||||
Ip: ws.RemoteAddr().String(),
|
||||
}
|
||||
|
||||
defer tc.release()
|
||||
log.Println("Created the websocket to", ws.RemoteAddr().String())
|
||||
|
||||
tc.ws_done = make(chan struct{})
|
||||
tc.pty_done = make(chan struct{})
|
||||
tc.viewChan = make(chan *websocket.Conn)
|
||||
tc.recordChan = make(chan int)
|
||||
|
||||
if err := tc.createPty(cmdline); err != nil {
|
||||
log.Println("Failed to create PTY: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
registry.addPlayer(&tc)
|
||||
|
||||
// main event loop to shovel data between ws and pty
|
||||
// do not call ptyStdoutToWs in this goroutine, otherwise
|
||||
// the websocket will not close. This is because ptyStdoutToWs
|
||||
// is usually blocked in the pty.Read
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(3)
|
||||
|
||||
go tc.ping(&wg)
|
||||
go tc.ptyStdoutToWs(&wg)
|
||||
go tc.wsToPtyStdin(&wg)
|
||||
|
||||
wg.Wait()
|
||||
log.Println("Wait returned")
|
||||
}
|
||||
|
||||
// handle websockets
|
||||
func handleViewer(w http.ResponseWriter, r *http.Request, path string) {
|
||||
ws, err := upgrader.Upgrade(w, r, nil)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to create websocket: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Created the websocket to", ws.RemoteAddr().String())
|
||||
if !registry.sendToPlayer(path, ws) {
|
||||
log.Println("Failed to send websocket to player, close it")
|
||||
ws.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectTerm(w http.ResponseWriter, r *http.Request, isViewer bool, name string, cmdline []string) {
|
||||
if !isViewer {
|
||||
handlePlayer(w, r, name, cmdline)
|
||||
} else {
|
||||
handleViewer(w, r, name)
|
||||
}
|
||||
}
|
||||
|
||||
func Init() {
|
||||
registry.init()
|
||||
}
|
||||
|
||||
func StartRecord(id string) {
|
||||
registry.recordSession(id, recordCmd)
|
||||
}
|
||||
|
||||
func StopRecord(id string) {
|
||||
registry.recordSession(id, stopCmd)
|
||||
}
|
11
tls/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
Past lesson shows that a test cert hurts security (because
|
||||
people just use it). Follow the steps below to create a
|
||||
self-sigend ECC cert by yourself.
|
||||
|
||||
```
|
||||
# generate a private key for a curve
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out private-key.pem
|
||||
|
||||
# Create a self-signed certificate
|
||||
openssl req -new -x509 -key private-key.pem -out cert.pem -days 360
|
||||
```
|
106
web/auth.go
Normal file
@ -0,0 +1,106 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/syssecfsu/witty/cmd"
|
||||
)
|
||||
|
||||
const (
|
||||
userKey = "authorized_user"
|
||||
nameKey = "last_login"
|
||||
loginKey = "login_msg"
|
||||
)
|
||||
|
||||
func leftLoginMsg(c *gin.Context, msg string) {
|
||||
session := sessions.Default(c)
|
||||
session.Set(loginKey, msg)
|
||||
session.Save()
|
||||
}
|
||||
|
||||
func login(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
|
||||
username := c.PostForm("username")
|
||||
passwd := c.PostForm("passwd")
|
||||
|
||||
// Validate form input
|
||||
if strings.Trim(username, " ") == "" || strings.Trim(passwd, " ") == "" {
|
||||
leftLoginMsg(c, "User name or password cannot be empty")
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
|
||||
// Check for username and password match, usually from a database
|
||||
if !cmd.ValidateUser([]byte(username), []byte(passwd)) {
|
||||
leftLoginMsg(c, "Username/password does not match")
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
|
||||
// Save the username in the session
|
||||
session.Set(userKey, username)
|
||||
session.Set(nameKey, username)
|
||||
|
||||
if err := session.Save(); err != nil {
|
||||
leftLoginMsg(c, "Failed to save session data")
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
}
|
||||
|
||||
func logout(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
|
||||
user := session.Get(userKey)
|
||||
if user != nil {
|
||||
session.Delete(userKey)
|
||||
session.Save()
|
||||
}
|
||||
|
||||
leftLoginMsg(c, "Welcome to WiTTY")
|
||||
c.Redirect(http.StatusFound, "/login")
|
||||
}
|
||||
|
||||
// AuthRequired is a simple middleware to check the session
|
||||
func AuthRequired(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
user := session.Get(userKey)
|
||||
|
||||
if user == nil {
|
||||
leftLoginMsg(c, "Not authorized, login first")
|
||||
c.Redirect(http.StatusTemporaryRedirect, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func loginPage(c *gin.Context) {
|
||||
session := sessions.Default(c)
|
||||
msg := session.Get(loginKey)
|
||||
|
||||
if msg == nil {
|
||||
msg = "Login first"
|
||||
}
|
||||
|
||||
username := session.Get(nameKey)
|
||||
if username == nil {
|
||||
username = ""
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "login.html",
|
||||
gin.H{
|
||||
"msg": msg,
|
||||
"username": username,
|
||||
"csrfField": csrf.TemplateField(c.Request),
|
||||
},
|
||||
)
|
||||
}
|
101
web/interactive.go
Normal file
@ -0,0 +1,101 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/dchest/uniuri"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/syssecfsu/witty/term_conn"
|
||||
)
|
||||
|
||||
type InteractiveSession struct {
|
||||
Ip string
|
||||
Cmd string
|
||||
Id string
|
||||
}
|
||||
|
||||
func collectSessions(c *gin.Context, cmd string) (players []InteractiveSession) {
|
||||
term_conn.ForEachSession(func(tc *term_conn.TermConn) {
|
||||
players = append(players, InteractiveSession{
|
||||
Id: tc.Name,
|
||||
Ip: tc.Ip,
|
||||
Cmd: cmd,
|
||||
})
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func indexPage(c *gin.Context) {
|
||||
var disabled = ""
|
||||
|
||||
if options.NoAuth {
|
||||
disabled = "disabled"
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "index.html",
|
||||
gin.H{
|
||||
"disabled": disabled,
|
||||
"csrfField": csrf.TemplateField(c.Request),
|
||||
"csrfToken": csrf.Token(c.Request),
|
||||
})
|
||||
}
|
||||
|
||||
func updateIndex(c *gin.Context) {
|
||||
var active0, active1 string
|
||||
|
||||
// setup which tab is active, it is hard to do in javascript at
|
||||
// client side due to timing issues.
|
||||
which := c.Param("active")
|
||||
if which == "0" {
|
||||
active0 = "active"
|
||||
active1 = ""
|
||||
} else {
|
||||
active0 = ""
|
||||
active1 = "active"
|
||||
}
|
||||
|
||||
players := collectSessions(c, options.CmdToExec[0])
|
||||
records := collectRecords(c)
|
||||
|
||||
c.HTML(http.StatusOK, "tab.html", gin.H{
|
||||
"players": players,
|
||||
"records": records,
|
||||
"active0": active0,
|
||||
"active1": active1,
|
||||
})
|
||||
}
|
||||
|
||||
func newInteractive(c *gin.Context) {
|
||||
id := uniuri.New()
|
||||
|
||||
c.HTML(http.StatusOK, "term.html", gin.H{
|
||||
"title": "interactive terminal",
|
||||
"path": "/ws_new/" + id,
|
||||
"id": id,
|
||||
"logo": "keyboard",
|
||||
"csrfToken": csrf.Token(c.Request),
|
||||
})
|
||||
}
|
||||
|
||||
func newTermConn(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
term_conn.ConnectTerm(c.Writer, c.Request, false, id, options.CmdToExec)
|
||||
}
|
||||
|
||||
func viewPage(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
c.HTML(http.StatusOK, "term.html", gin.H{
|
||||
"title": "viewer terminal",
|
||||
"path": "/ws_view/" + id,
|
||||
"id": id,
|
||||
"logo": "view",
|
||||
"csrfToken": csrf.Token(c.Request),
|
||||
})
|
||||
}
|
||||
|
||||
func newViewWS(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
term_conn.ConnectTerm(c.Writer, c.Request, true, id, nil)
|
||||
}
|
127
web/record.go
Normal file
@ -0,0 +1,127 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/syssecfsu/witty/term_conn"
|
||||
)
|
||||
|
||||
type RecordedSession struct {
|
||||
Fname string
|
||||
Fsize string
|
||||
Duration string
|
||||
Time string
|
||||
}
|
||||
|
||||
// how many seconds of the session
|
||||
func getDuration(fname string) int64 {
|
||||
fp, err := os.Open("./records/" + fname)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to open record file", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(fp)
|
||||
|
||||
if decoder == nil {
|
||||
log.Println("Failed to create JSON decoder")
|
||||
return 0
|
||||
}
|
||||
|
||||
// To work with javascript decoder, we organize the file as
|
||||
// an array of writeRecord. golang decode instead decode
|
||||
// as individual record. Call decoder.Token to skip opening [
|
||||
decoder.Token()
|
||||
|
||||
var dur int64 = 0
|
||||
|
||||
for decoder.More() {
|
||||
var record term_conn.WriteRecord
|
||||
|
||||
if err := decoder.Decode(&record); err != nil {
|
||||
log.Println("Failed to decode record", err)
|
||||
continue
|
||||
}
|
||||
|
||||
dur += record.Dur.Milliseconds()
|
||||
}
|
||||
|
||||
return dur/1000 + 1
|
||||
}
|
||||
|
||||
func collectRecords(c *gin.Context) (records []RecordedSession) {
|
||||
files, err := ioutil.ReadDir("./records/")
|
||||
|
||||
if err == nil {
|
||||
for _, finfo := range files {
|
||||
fname := finfo.Name()
|
||||
if !strings.HasSuffix(fname, ".scr") {
|
||||
continue
|
||||
}
|
||||
fsize := finfo.Size() / 1024
|
||||
duration := getDuration(fname)
|
||||
|
||||
records = append(records,
|
||||
RecordedSession{
|
||||
Fname: fname,
|
||||
Fsize: strconv.FormatInt(fsize, 10),
|
||||
Duration: strconv.FormatInt(duration, 10),
|
||||
Time: finfo.ModTime().Format("Jan/2/2006, 15:04:05"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func startRecord(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
term_conn.StartRecord(id)
|
||||
}
|
||||
|
||||
func stopRecord(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
term_conn.StopRecord(id)
|
||||
}
|
||||
|
||||
func replayPage(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
log.Println("replay/ called with", id)
|
||||
c.HTML(http.StatusOK, "replay.html", gin.H{
|
||||
"fname": id,
|
||||
"max_wait": options.Wait,
|
||||
})
|
||||
}
|
||||
|
||||
func delRec(c *gin.Context) {
|
||||
fname := c.Param("fname")
|
||||
if err := os.Remove("./records/" + fname); err != nil {
|
||||
log.Println("Failed to delete file,", err)
|
||||
}
|
||||
}
|
||||
|
||||
func renameRec(c *gin.Context) {
|
||||
oldName := "./records/" + c.Param("oldname")
|
||||
newName := "./records/" + c.Param("newname")
|
||||
|
||||
if !strings.HasSuffix(newName, ".scr") {
|
||||
newName += ".scr"
|
||||
}
|
||||
|
||||
if _, err := os.Stat(newName); err == nil {
|
||||
log.Println(newName, "already exist, ignore the request")
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.Rename(oldName, newName); err != nil {
|
||||
log.Println("Failed to rename file,", err)
|
||||
}
|
||||
}
|
95
web/routing.go
Normal file
@ -0,0 +1,95 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/dchest/uniuri"
|
||||
"github.com/gin-gonic/contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/csrf"
|
||||
adapter "github.com/gwatts/gin-adapter"
|
||||
"github.com/syssecfsu/witty/term_conn"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Wait uint
|
||||
Port uint
|
||||
NoAuth bool
|
||||
CmdToExec []string
|
||||
Assets fs.FS
|
||||
LogFile *os.File
|
||||
}
|
||||
|
||||
var options Options
|
||||
|
||||
func StartWeb(opt *Options) {
|
||||
options = *opt
|
||||
|
||||
if options.LogFile != nil {
|
||||
gin.DefaultWriter = options.LogFile
|
||||
}
|
||||
|
||||
rt := gin.Default()
|
||||
|
||||
// We randomly generate a key for now, should use a fixed key
|
||||
// so login can survive server reboot
|
||||
store := sessions.NewCookieStore([]byte(uniuri.NewLen(32)))
|
||||
rt.Use(sessions.Sessions("witty-session", store))
|
||||
|
||||
csrfHttp := csrf.Protect([]byte(uniuri.NewLen(32)), csrf.Path("/"))
|
||||
csrfGin := adapter.Wrap(csrfHttp)
|
||||
rt.Use(csrfGin)
|
||||
|
||||
rt.SetTrustedProxies(nil)
|
||||
|
||||
templ := template.Must(template.New("assets").ParseFS(options.Assets, "template/*.html"))
|
||||
rt.SetHTMLTemplate(templ)
|
||||
|
||||
// handle static files
|
||||
rt.StaticFS("/assets", http.FS(options.Assets))
|
||||
rt.Static("/records", "./records")
|
||||
|
||||
rt.GET("/login", loginPage)
|
||||
rt.POST("/login", login)
|
||||
|
||||
g1 := rt.Group("/")
|
||||
|
||||
if !options.NoAuth {
|
||||
g1.Use(AuthRequired)
|
||||
}
|
||||
|
||||
// Fill in the index page
|
||||
g1.GET("/", indexPage)
|
||||
g1.GET("/logout", logout)
|
||||
|
||||
// to update the tabs of current interactive and saved sessions
|
||||
g1.GET("/update/:active", updateIndex)
|
||||
|
||||
// create a new interactive session
|
||||
g1.POST("/new", newInteractive)
|
||||
g1.GET("/ws_new/:id", newTermConn)
|
||||
|
||||
// create a viewer of an interactive session
|
||||
g1.GET("/view/:id", viewPage)
|
||||
g1.GET("/ws_view/:id", newViewWS)
|
||||
|
||||
// start/stop recording the session
|
||||
g1.POST("/record/:id", startRecord)
|
||||
g1.POST("/stop/:id", stopRecord)
|
||||
|
||||
// create a viewer of an interactive session
|
||||
g1.GET("/replay/:id", replayPage)
|
||||
|
||||
// delete a recording
|
||||
g1.POST("/delete/:fname", delRec)
|
||||
// Rename a recording
|
||||
g1.POST("/rename/:oldname/:newname", renameRec)
|
||||
|
||||
term_conn.Init()
|
||||
port := strconv.FormatUint(uint64(uint16(options.Port)), 10)
|
||||
rt.RunTLS(":"+port, "./tls/cert.pem", "./tls/private-key.pem")
|
||||
}
|