initial commit

This commit is contained in:
April Ayres-Griffiths 2018-01-20 11:05:04 +11:00
commit 75d42c4597
33 changed files with 13064 additions and 0 deletions

14
.gitignore vendored Normal file
View File

@ -0,0 +1,14 @@
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state 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 program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

167
README.md Normal file
View File

@ -0,0 +1,167 @@
DSKalyzer is a cross-platform command-line tool for manipulating and managing Apple II DSK (and other) images.
Download from: https://github.com/paleotronic/dskalyzer/releases
Features include:
- Read from ProDOS, DOS 3.X, RDOS and Pascal disk images;
- ProDOS or DOS ordered; 2MG and NIB; 113-800K
- Write to Prodos and DOS 3.3 disk images;
- Extract and convert binary, text and detokenize BASIC files (Integer and Applesoft);
- Write binary, text and retokenized BASIC (Applesoft) files back to disk images;
- Copy and move files between disk images; delete files, create new folders (ProDOS), etc;
- Generate disk reports that provide track and sector information, text extraction and more;
- Compare multiple disks to determine duplication, or search disks for text or filenames.
- Use command-line flags (allows for automation) or an interactive shell;
- Builds for MacOS, Windows, Linux, FreeBSD and Raspberry Pi.
- Open source; GPLv3 licensed.
- Written in Go!
DSKalyzer is a command line tool for analyzing and managing Apple II DSK images and their archives. Its features include not only the standard set of disk manipulation tools -- extract (with text conversion), import to disk (including tokenisation of Applesoft BASIC), delete, and so forth -- but also the ability to identify duplicates — complete, active sector, and subset; find file, sector and other commonalities between disks (including as a percentage of similarity or difference); search de-tokenized BASIC, text and binary / sector data; generate reports identifying and / or collating disk type, DOS, geometry, size, and so forth; allowing for easier, semi-automated DSK archival management and research.
DSKalyzer works by first “ingesting” your disk(s), creating an index containing various pieces of information (disk / sector / file hashes, catalogs, text data, binary data etc.) about each disk that is then searchable using the same tool. This way you can easily find information stored on disks without tediously searching manually or through time-consuming multiple image scans. You can also identify duplicates, quasi-duplicates (disks with only minor differences or extraneous data), or iterations, reducing redundancies.
Once you've identified a search you can also extract selected files. DSKalyzer can report to standard output (terminal), to a text file, or to a CSV file.
```
Shell commands (executing DSKalyzer without flags enters shell):
Note: You must mount a disk before performing tasks on it.
analyze Process disk using dskalyzer analytics
cat Display file information
cd Change local path
copy Copy files from one volume to another
delete Remove file from disk
disks List mounted volumes
extract extract file from disk image
help Shows this help
info Information about the current disk
ingest Ingest directory containing disks (or single disk) into system
lock Lock file on the disk
ls List local files
mkdir Create a directory on disk
mount Mount a disk image
move Move files from one volume to another
put Copy local file to disk
quarantine Like report, but allow moving dupes to a backup folder
quit Leave this place
rename Rename a file on the disk
report Run a report
target Select mounted volume as default
unlock Unlock file on the disk
unmount unmount disk image
Command-line flags:
(Note: You must ingest your disk library before you can run comparison or search operations on it)
-active-sector-partial
Run partial sector match (active only) against all disks
-active-sector-subset
Run subset (active) sector match against all disks
-adorned
Extract files named similar to CP (default true)
-all-file-partial
Run partial file match against all disks
-all-file-subset
Run subset file match against all disks
-all-sector-partial
Run partial sector match (all) against all disks
-all-sector-subset
Run subset (non-zero) sector match against all disks
-as-dupes
Run active sectors only disk dupe report
-as-partial
Run partial active sector match against single disk (-disk required)
-c Cache data to memory for quicker processing (default true)
-cat-dupes
Run duplicate catalog report
-catalog
List disk contents (-with-disk)
-csv
Output data to CSV format
-datastore string
Database of disk fingerprints for checking (default "/Users/melody/DSKalyzer/fingerprints")
-dir
Directory specified disk (needs -disk)
-dir-create string
Directory to create (-with-disk)
-dir-format string
Format of dir (default "{filename} {type} {size:kb} Checksum: {sha256}")
-extract string
Extract files/disks matched in searches ('#'=extract disk, '@'=extract files)
-file string
Search for other disks containing file
-file-delete string
File to delete (-with-disk)
-file-dupes
Run file dupe report
-file-extract string
File to delete from disk (-with-disk)
-file-partial
Run partial file match against single disk (-disk required)
-file-put string
File to put on disk (-with-disk)
-force
Force re-ingest disks that already exist
-ingest string
Disk file or path to ingest
-ingest-mode int
Ingest mode:
0=Fingerprints only
1=Fingerprints + text
2=Fingerprints + sector data
3=All (default 1)
-max-diff int
Maximum different # files for -all-file-partial
-min-same int
Minimum same # files for -all-file-partial
-out string
Output file (empty for stdout)
-quarantine
Run -as-dupes and -whole-disk in quarantine mode
-query string
Disk file to query or analyze
-search-filename string
Search database for file with name
-search-sha string
Search database for file with checksum
-search-text string
Search database for file containing text
-select
Select files for analysis or search based on file/dir/mask
-shell
Start interactive mode
-shell-batch string
Execute shell command(s) from file and exit
-similarity float
Object match threshold for -*-partial reports (default 0.9)
-verbose
Log to stderr
-whole-dupes
Run whole disk dupe report
-with-disk string
Perform disk operation (-file-extract,-file-put,-file-delete)
```
Getting Started
Ingest your disk collection, so dskalyzer can report on them:
dskalyzer -ingest "C:\Users\myname\LotsOfDisks"
Simple Reports
Find Whole Disk duplicates:
dskalyzer -whole-dupes
Find Active Sectors duplicates (inactive sectors can be different):
dskalyzer -as-dupes
Find Duplicate files across disks:
dskalyzer -file-dupes
Limiting reports to subdirectories
Find Active Sector duplicates but only under a folder:
dskalyzer -as-dupes -select "C:\Users\myname\LotsOfDisks\Operating Systems"
```

32
USAGE.md Normal file
View File

@ -0,0 +1,32 @@
## Usage examples
Ingest your disk collection, so dskalyzer can report on them:
```
dskalyzer -ingest C:\Users\myname\LotsOfDisks
```
Find Whole Disk duplicates:
```
dskalyzer -whole-dupes
```
Find Active Sectors duplicates (inactive sectors can be different):
```
dskalyzer -as-dupes
```
Find Duplicate files across disks:
```
dskalyzer -file-dupes
```
Find Active Sector duplicates but only under a folder:
```
dskalyzer -as-dupes -select "C:\Users\myname\LotsOfDisks\Operating Systems"
```

17
banner.go Normal file
View File

@ -0,0 +1,17 @@
package main
import (
"encoding/base64"
"os"
)
var text = `ICBfXyAgICAgICAgICAgX18gICAgICAgICAgICAgICAgX19fICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF9fICAgICANCiAvXCBcICAgICAgICAgL1wgXCAgICAgICAgICAgICAgL1xfIFwgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC9cIFwgICAgDQogXF9cIFwgICAgX19fX1wgXCBcLydcICAgICAgX18gIFwvL1wgXCAgICBfXyAgX18gIF9fX18gICAgICBfXyAgIF8gX19cIFwgXCAgIA0KIC8nX2AgXCAgLycsX19cXCBcICwgPCAgICAvJ19fYFwgIFwgXCBcICAvXCBcL1wgXC9cXyAsYFwgIC8nX19gXC9cYCdfX1wgXCBcICANCi9cIFxMXCBcL1xfXywgYFxcIFwgXFxgXCAvXCBcTFwuXF8gXF9cIFxfXCBcIFxfXCBcL18vICAvXy9cICBfXy9cIFwgXC8gXCBcX1wgDQpcIFxfX18sX1wvXF9fX18vIFwgXF9cIFxfXCBcX18vLlxfXC9cX19fX1xcL2BfX19fIFwvXF9fX19cIFxfX19fXFwgXF9cICBcL1xfXA0KIFwvX18sXyAvXC9fX18vICAgXC9fL1wvXy9cL19fL1wvXy9cL19fX18vIGAvX19fLz4gXC9fX19fL1wvX19fXy8gXC9fLyAgIFwvXy8NCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvXF9fXy8gICAgICAgICAgICAgICAgICAgICAgICAgDQogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXC9fXy8gICAgICAgICAgICAgICAgICAgICAgICAgIA0K`
func banner() {
t, _ := base64.StdEncoding.DecodeString(text)
os.Stderr.WriteString(string(t) + "\r\n")
os.Stderr.WriteString("(c) 2015 - 2017 Paleotronic.com\n\n")
}

947
data.go Normal file
View File

@ -0,0 +1,947 @@
package main
import (
"errors"
"fmt"
"runtime"
"time"
"crypto/md5"
"encoding/hex"
"os"
"strings"
"encoding/gob"
"path/filepath"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
type Disk struct {
FullPath string
Filename string
SHA256 string // Sha of whole disk
SHA256Active string // Sha of active sectors/blocks only
Format string
FormatID disk.DiskFormat
Bitmap []bool
Tracks, Sectors, Blocks int
Files DiskCatalog
ActiveSectors DiskSectors
//ActiveBlocks DiskBlocks
InactiveSectors DiskSectors
//InactiveBlocks DiskBlocks
MatchFactor float64
MatchFiles map[*DiskFile]*DiskFile
MissingFiles, ExtraFiles []*DiskFile
IngestMode int
source string
}
type ByMatchFactor []*Disk
func (s ByMatchFactor) Len() int {
return len(s)
}
func (s ByMatchFactor) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByMatchFactor) Less(i, j int) bool {
return s[i].MatchFactor < s[j].MatchFactor
}
type TypeCode int
const (
TypeMask_AppleDOS TypeCode = 0x0000
TypeMask_ProDOS TypeCode = 0x0100
TypeMask_Pascal TypeCode = 0x0200
TypeMask_RDOS TypeCode = 0x0300
)
type DiskFile struct {
Filename string
Type string
Ext string
TypeCode TypeCode
SHA256 string
Size int
LoadAddress int
Text []byte
Data []byte
Locked bool
Created time.Time
Modified time.Time
}
func (d *DiskFile) GetNameAdorned() string {
var ext string
switch d.TypeCode & 0xff00 {
case TypeMask_AppleDOS:
ext = disk.FileType(d.TypeCode & 0xff).Ext()
case TypeMask_ProDOS:
ext = disk.ProDOSFileType(d.TypeCode & 0xff).Ext()
case TypeMask_RDOS:
ext = disk.RDOSFileType(d.TypeCode & 0xff).Ext()
case TypeMask_Pascal:
ext = disk.PascalFileType(d.TypeCode & 0xff).Ext()
}
return fmt.Sprintf("%s#0x%.4x.%s", d.Filename, d.LoadAddress, ext)
}
func (d *DiskFile) GetName() string {
var ext string
switch d.TypeCode & 0xff00 {
case TypeMask_AppleDOS:
ext = disk.FileType(d.TypeCode & 0xff).Ext()
case TypeMask_ProDOS:
ext = disk.ProDOSFileType(d.TypeCode & 0xff).Ext()
case TypeMask_RDOS:
ext = disk.RDOSFileType(d.TypeCode & 0xff).Ext()
case TypeMask_Pascal:
ext = disk.PascalFileType(d.TypeCode & 0xff).Ext()
}
return fmt.Sprintf("%s.%s", d.Filename, ext)
}
type DiskCatalog []*DiskFile
type DiskSectors []*DiskSector
type DiskBlocks []*DiskBlock
type DiskSector struct {
Track int
Sector int
SHA256 string
Data []byte
}
type DiskBlock struct {
Block int
SHA256 string
}
func (i Disk) LogBitmap(id int) {
l := loggy.Get(id)
if i.Tracks > 0 {
for t := 0; t < i.Tracks; t++ {
line := fmt.Sprintf("Track %.2d: ", t)
for s := 0; s < i.Sectors; s++ {
if i.Bitmap[t*i.Sectors+s] {
line += fmt.Sprintf("%.2x ", s)
} else {
line += ":: "
}
}
l.Logf("%s", line)
}
} else if i.Blocks > 0 {
tr := i.Blocks / 16
sc := 16
for t := 0; t < tr; t++ {
line := fmt.Sprintf("Block %.2d: ", t)
for s := 0; s < sc; s++ {
if i.Bitmap[t*i.Sectors+s] {
line += fmt.Sprintf("%.2x ", s)
} else {
line += ":: "
}
}
l.Logf("%s", line)
}
}
}
func (d Disk) GetFilename() string {
sum := md5.Sum([]byte(d.Filename))
// fmt.Printf("checksum: [%s] -> [%s]\n", d.Filename, hex.EncodeToString(sum[:]))
ff := fmt.Sprintf("%s/%d", strings.Trim(filepath.Dir(d.FullPath), "/"), d.FormatID.ID) + "_" + d.SHA256 + "_" + d.SHA256Active + "_" + hex.EncodeToString(sum[:]) + ".fgp"
if runtime.GOOS == "windows" {
ff = strings.Replace(ff, ":", "", -1)
ff = strings.Replace(ff, "\\", "/", -1)
}
return ff
}
func (d Disk) WriteToFile(filename string) error {
// b, err := yaml.Marshal(d)
// if err != nil {
// return err
// }
l := loggy.Get(0)
_ = os.MkdirAll(filepath.Dir(filename), 0755)
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
enc := gob.NewEncoder(f)
enc.Encode(d)
l.Logf("Created %s", filename)
return nil
}
func (d *Disk) ReadFromFile(filename string) error {
// b, err := ioutil.ReadFile(filename)
// if err != nil {
// return err
// }
// err = yaml.Unmarshal(b, d)
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
dec := gob.NewDecoder(f)
err = dec.Decode(d)
d.source = filename
return err
}
// GetExactBinaryMatches returns disks with the same Global SHA256
func (d *Disk) GetExactBinaryMatches(filter []string) []*Disk {
l := loggy.Get(0)
var out []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, fmt.Sprintf("%d", d.FormatID)+"_"+d.SHA256+"_*_*.fgp")
if !exists {
return out
}
for _, m := range matches {
l.Logf(":: Checking %s", m)
if item, err := cache.Get(m); err == nil {
if item.FullPath != d.FullPath {
out = append(out, item)
}
}
}
return out
}
// GetActiveSectorBinaryMatches returns disks with the same Active SHA256
func (d *Disk) GetActiveSectorBinaryMatches(filter []string) []*Disk {
l := loggy.Get(0)
var out []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, fmt.Sprintf("%d", d.FormatID)+"_*_"+d.SHA256Active+"_*.fgp")
if !exists {
return out
}
for _, m := range matches {
l.Logf(":: Checking %s", m)
if item, err := cache.Get(m); err == nil {
if item.FullPath != d.FullPath {
out = append(out, item)
}
}
}
return out
}
func (d *Disk) GetFileMap() map[string]*DiskFile {
out := make(map[string]*DiskFile)
for _, file := range d.Files {
f := file
out[file.SHA256] = f
}
return out
}
func (d *Disk) GetUtilizationMap() map[string]string {
out := make(map[string]string)
if len(d.ActiveSectors) > 0 {
for _, block := range d.ActiveSectors {
key := fmt.Sprintf("T%dS%d", block.Track, block.Sector)
out[key] = block.SHA256
}
}
return out
}
// CompareChunks returns a value 0-1
func (d *Disk) CompareChunks(b *Disk) (float64, float64, float64, float64) {
l := loggy.Get(0)
if d.FormatID != b.FormatID {
l.Logf("Trying to compare disks of different types")
return 0, 0, 0, 0
}
switch d.FormatID.ID {
case disk.DF_RDOS_3:
return d.compareSectorsPositional(b)
case disk.DF_RDOS_32:
return d.compareSectorsPositional(b)
case disk.DF_RDOS_33:
return d.compareSectorsPositional(b)
case disk.DF_PASCAL:
return d.compareBlocksPositional(b)
case disk.DF_DOS_SECTORS_13:
return d.compareSectorsPositional(b)
case disk.DF_DOS_SECTORS_16:
return d.compareSectorsPositional(b)
case disk.DF_PRODOS:
return d.compareBlocksPositional(b)
case disk.DF_PRODOS_800KB:
return d.compareBlocksPositional(b)
}
return 0, 0, 0, 0
}
func (d *Disk) compareSectorsPositional(b *Disk) (float64, float64, float64, float64) {
l := loggy.Get(0)
var sameSectors float64
var diffSectors float64
var dNotb float64
var bNotd float64
var emptySectors float64
var dTotal, bTotal float64
var dmap = d.GetUtilizationMap()
var bmap = b.GetUtilizationMap()
for t := 0; t < d.FormatID.TPD(); t++ {
for s := 0; s < d.FormatID.SPT(); s++ {
key := fmt.Sprintf("T%dS%d", t, s)
dCk, dEx := dmap[key]
bCk, bEx := bmap[key]
switch {
case dEx && bEx:
if dCk == bCk {
sameSectors += 1
} else {
diffSectors += 1
}
dTotal += 1
bTotal += 1
case dEx && !bEx:
dNotb += 1
dTotal += 1
case !dEx && bEx:
bNotd += 1
bTotal += 1
default:
emptySectors += 1
}
}
}
l.Debugf("Same Sectors : %f", sameSectors)
l.Debugf("Differing Sectors: %f", diffSectors)
l.Debugf("Not in other disk: %f", dNotb)
l.Debugf("Not in this disk : %f", bNotd)
// return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / btotal
return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / bTotal
}
func (d *Disk) compareBlocksPositional(b *Disk) (float64, float64, float64, float64) {
l := loggy.Get(0)
var sameSectors float64
var diffSectors float64
var dNotb float64
var bNotd float64
var emptySectors float64
var dTotal, bTotal float64
var dmap = d.GetUtilizationMap()
var bmap = b.GetUtilizationMap()
for t := 0; t < d.FormatID.BPD(); t++ {
key := fmt.Sprintf("B%d", t)
dCk, dEx := dmap[key]
bCk, bEx := bmap[key]
switch {
case dEx && bEx:
if dCk == bCk {
sameSectors += 1
} else {
diffSectors += 1
}
dTotal += 1
bTotal += 1
case dEx && !bEx:
dNotb += 1
dTotal += 1
case !dEx && bEx:
bNotd += 1
bTotal += 1
default:
emptySectors += 1
}
}
l.Debugf("Same Blocks : %f", sameSectors)
l.Debugf("Differing Blocks : %f", diffSectors)
l.Debugf("Not in other disk: %f", dNotb)
l.Debugf("Not in this disk : %f", bNotd)
// return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / btotal
return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / bTotal
}
// GetActiveSectorBinaryMatches returns disks with the same Active SHA256
func (d *Disk) GetPartialMatches(filter []string) ([]*Disk, []*Disk, []*Disk) {
l := loggy.Get(0)
var superset []*Disk = make([]*Disk, 0)
var subset []*Disk = make([]*Disk, 0)
var identical []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, fmt.Sprintf("%d", d.FormatID)+"_*_*_*.fgp")
if !exists {
return superset, subset, identical
}
for _, m := range matches {
//item := &Disk{}
if item, err := cache.Get(m); err == nil {
if item.FullPath != d.FullPath {
// only here if not looking at same disk
l.Logf(":: Checking overlapping data blocks %s", item.Filename)
l.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
dSame, iSame, dDiff, iDiff := d.CompareChunks(item)
l.Logf("== This disk shares %.2f percent of its allocated blocks with %s", dSame*100, item.Filename)
l.Logf("!= This disk differs %.2f percent of its allocate blocks with %s", dDiff*100, item.Filename)
l.Logf("== %s shares %.2f of its blocks with this disk", item.Filename, iSame*100)
l.Logf("!= %s differs %.2f of its blocks with this disk", item.Filename, iDiff*100)
if dSame == 1 && iSame < 1 {
superset = append(superset, item)
} else if iSame == 1 && dSame < 1 {
subset = append(subset, item)
} else if iSame == 1 && dSame == 1 {
identical = append(identical, item)
}
}
}
}
return superset, subset, identical
}
func (d *Disk) GetPartialMatchesWithThreshold(t float64, filter []string) []*Disk {
l := loggy.Get(0)
var matchlist []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, fmt.Sprintf("%d", d.FormatID)+"_*_*_*.fgp")
if !exists {
return matchlist
}
var lastPc int = -1
for i, m := range matches {
//item := &Disk{}
if item, err := cache.Get(m); err == nil {
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("Analyzing volumes... %d%% ", pc))
}
if item.FullPath != d.FullPath {
// only here if not looking at same disk
l.Logf(":: Checking overlapping data blocks %s", item.Filename)
// l.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
dSame, _, _, _ := d.CompareChunks(item)
// l.Logf("== This disk shares %.2f percent of its allocated blocks with %s", dSame*100, item.Filename)
// l.Logf("!= This disk differs %.2f percent of its allocate blocks with %s", dDiff*100, item.Filename)
// l.Logf("== %s shares %.2f of its blocks with this disk", item.Filename, iSame*100)
// l.Logf("!= %s differs %.2f of its blocks with this disk", item.Filename, iDiff*100)
item.MatchFactor = dSame
if dSame >= t {
matchlist = append(matchlist, item)
}
}
fmt.Print("\r")
lastPc = pc
}
}
return matchlist
}
func Aggregate(f func(d *Disk, collector interface{}), collector interface{}, pathfilter []string) {
l := loggy.Get(0)
exists, matches := existsPattern(*baseName, pathfilter, "*_*_*_*.fgp")
if !exists {
return
}
var lastPc int = -1
for i, m := range matches {
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("\rAggregating data... %d%% ", pc))
}
l.Logf(":: Checking %s", m)
//item := &Disk{}
if item, err := cache.Get(m); err == nil {
f(item, collector)
}
}
os.Stderr.WriteString("Done.\n")
return
}
func (d *Disk) CompareFiles(b *Disk) float64 {
var sameFiles float64
var missingFiles float64
var extraFiles float64
var dmap = d.GetFileMap()
var bmap = b.GetFileMap()
for fileCk, info := range dmap {
if info.Size == 0 {
continue
}
binfo, bEx := bmap[fileCk]
if bEx {
sameFiles += 1
// file match
if b.MatchFiles == nil {
b.MatchFiles = make(map[*DiskFile]*DiskFile)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
b.MatchFiles[binfo] = info
} else {
missingFiles += 1
// file match
if b.MissingFiles == nil {
b.MissingFiles = make([]*DiskFile, 0)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
b.MissingFiles = append(b.MissingFiles, info)
}
}
for fileCk, info := range bmap {
if info.Size == 0 {
continue
}
_, dEx := dmap[fileCk]
if !dEx {
extraFiles += 1
// file match
if b.ExtraFiles == nil {
b.ExtraFiles = make([]*DiskFile, 0)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
b.ExtraFiles = append(b.ExtraFiles, info)
}
}
// return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / btotal
return sameFiles / (sameFiles + extraFiles + missingFiles)
}
func (d *Disk) GetPartialFileMatchesWithThreshold(t float64, filter []string) []*Disk {
l := loggy.Get(0)
var matchlist []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, "*_*_*_*.fgp")
if !exists {
return matchlist
}
var lastPc int = -1
for i, m := range matches {
//item := &Disk{}
if item, err := cache.Get(m); err == nil {
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("Analyzing volumes... %d%% ", pc))
}
if item.FullPath != d.FullPath {
// only here if not looking at same disk
l.Logf(":: Checking overlapping files %s", item.Filename)
dSame := d.CompareFiles(item)
item.MatchFactor = dSame
if dSame >= t {
matchlist = append(matchlist, item)
}
}
fmt.Print("\r")
lastPc = pc
}
}
return matchlist
}
func (d *Disk) HasFileSHA256(sha string) (bool, *DiskFile) {
for _, file := range d.Files {
if sha == file.SHA256 {
return true, file
}
}
return false, nil
}
func (d *Disk) GetFileChecksum(filename string) (bool, string) {
for _, f := range d.Files {
if strings.ToLower(filename) == strings.ToLower(f.Filename) {
return true, f.SHA256
}
}
return false, ""
}
func (d *Disk) GetFileMatches(filename string, filter []string) []*Disk {
l := loggy.Get(0)
var matchlist []*Disk = make([]*Disk, 0)
exists, matches := existsPattern(*baseName, filter, "*_*_*_*.fgp")
if !exists {
return matchlist
}
fileexists, SHA256 := d.GetFileChecksum(filename)
if !fileexists {
os.Stderr.WriteString("File does not exist on this volume: " + filename + "\n")
return matchlist
}
_, srcFile := d.HasFileSHA256(SHA256)
var lastPc int = -1
for i, m := range matches {
//item := &Disk{}
if item, err := cache.Get(m); err == nil {
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("Analyzing volumes... %d%% ", pc))
}
if item.FullPath != d.FullPath {
// only here if not looking at same disk
l.Logf(":: Checking overlapping files %s", item.Filename)
if ex, file := item.HasFileSHA256(SHA256); ex {
if item.MatchFiles == nil {
item.MatchFiles = make(map[*DiskFile]*DiskFile)
}
item.MatchFiles[srcFile] = file
matchlist = append(matchlist, item)
}
}
fmt.Print("\r")
lastPc = pc
}
}
return matchlist
}
// Gets directory with custom format
func (d *Disk) GetDirectory(format string) string {
out := ""
for _, file := range d.Files {
tmp := format
// size
tmp = strings.Replace(tmp, "{size:blocks}", fmt.Sprintf("%3d Blocks", file.Size/256+1), -1)
tmp = strings.Replace(tmp, "{size:kb}", fmt.Sprintf("%4d Kb", file.Size/1024+1), -1)
tmp = strings.Replace(tmp, "{size:b}", fmt.Sprintf("%6d Bytes", file.Size), -1)
tmp = strings.Replace(tmp, "{size}", fmt.Sprintf("%6d", file.Size), -1)
// format
tmp = strings.Replace(tmp, "{filename}", fmt.Sprintf("%-20s", file.Filename), -1)
// type
tmp = strings.Replace(tmp, "{type}", fmt.Sprintf("%-20s", file.Type), -1)
// sha256
tmp = strings.Replace(tmp, "{sha256}", file.SHA256, -1)
// loadaddress
tmp = strings.Replace(tmp, "{loadaddr}", fmt.Sprintf("0x.%4X", file.LoadAddress), -1)
out += tmp + "\n"
}
return out
}
type CacheContext int
const (
CC_All CacheContext = iota
CC_ActiveSectors
CC_AllSectors
CC_Files
)
type DiskMetaDataCache struct {
ctx CacheContext
Disks map[string]*Disk
}
var cache = NewCache(CC_All, "")
func (c *DiskMetaDataCache) Get(filename string) (*Disk, error) {
cached, ok := c.Disks[filename]
if ok {
return cached, nil
}
item := &Disk{}
if err := item.ReadFromFile(filename); err == nil {
c.Disks[filename] = item
return item, nil
}
return nil, errors.New("Not found")
}
func (c *DiskMetaDataCache) Put(filename string, item *Disk) {
c.Disks[filename] = item
}
func NewCache(ctx CacheContext, pattern string) *DiskMetaDataCache {
cache := &DiskMetaDataCache{
ctx: ctx,
Disks: make(map[string]*Disk),
}
return cache
}
func CreateCache(ctx CacheContext, pattern string, filter []string) *DiskMetaDataCache {
cache := &DiskMetaDataCache{
ctx: ctx,
Disks: make(map[string]*Disk),
}
exists, matches := existsPattern(*baseName, filter, pattern)
if !exists {
return cache
}
var lastPc int = -1
for i, m := range matches {
item := &Disk{}
if err := item.ReadFromFile(m); err == nil {
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("Caching data... %d%% ", pc))
}
// Load cache
cache.Put(m, item)
fmt.Print("\r")
lastPc = pc
}
}
return cache
}
func SearchPartialFileMatchesWithThreshold(t float64, filter []string) map[string][2]*Disk {
l := loggy.Get(0)
matchlist := make(map[string][2]*Disk)
exists, matches := existsPattern(*baseName, filter, "*_*_*_*.fgp")
if !exists {
return matchlist
}
done := make(map[string]bool)
var lastPc int = -1
for i, m := range matches {
//item := &Disk{}
if disk, err := cache.Get(m); err == nil {
d := *disk
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
os.Stderr.WriteString(fmt.Sprintf("Analyzing volumes... %d%% ", pc))
}
for _, n := range matches {
if jj, err := cache.Get(n); err == nil {
item := *jj
key := d.SHA256 + ":" + item.SHA256
if item.SHA256 < d.SHA256 {
key = item.SHA256 + ":" + d.SHA256
}
if _, ok := done[key]; ok {
continue
}
if item.FullPath != d.FullPath {
// only here if not looking at same disk
l.Logf(":: Checking overlapping files %s", item.Filename)
dSame := d.CompareFiles(&item)
item.MatchFactor = dSame
if dSame >= t {
matchlist[key] = [2]*Disk{&d, &item}
}
}
done[key] = true
}
}
fmt.Print("\r")
lastPc = pc
}
}
return matchlist
}
const ingestWorkers = 4
const processWorkers = 6
func exists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
}
return true
}

757
disk/atokens.go Normal file
View File

@ -0,0 +1,757 @@
package disk
import (
"fmt"
"strconv"
"strings"
"regexp"
)
//import "strings"
var ApplesoftTokens = map[int]string{
0x80: "END",
0x81: "FOR",
0x82: "NEXT",
0x83: "DATA",
0x84: "INPUT",
0x85: "DEL",
0x86: "DIM",
0x87: "READ",
0x88: "GR",
0x89: "TEXT",
0x8A: "PR#",
0x8B: "IN#",
0x8C: "CALL",
0x8D: "PLOT",
0x8E: "HLIN",
0x8F: "VLIN",
0x90: "HGR2",
0x91: "HGR",
0x92: "HCOLOR=",
0x93: "HPLOT",
0x94: "DRAW",
0x95: "XDRAW",
0x96: "HTAB",
0x97: "HOME",
0x98: "ROT=",
0x99: "SCALE=",
0x9A: "SHLOAD",
0x9B: "TRACE",
0x9C: "NOTRACE",
0x9D: "NORMAL",
0x9E: "INVERSE",
0x9F: "FLASH",
0xA0: "COLOR=",
0xA1: "POP",
0xA2: "VTAB",
0xA3: "HIMEM:",
0xA4: "LOMEM:",
0xA5: "ONERR",
0xA6: "RESUME",
0xA7: "RECALL",
0xA8: "STORE",
0xA9: "SPEED=",
0xAA: "LET",
0xAB: "GOTO",
0xAC: "RUN",
0xAD: "IF",
0xAE: "RESTORE",
0xAF: "&",
0xB0: "GOSUB",
0xB1: "RETURN",
0xB2: "REM",
0xB3: "STOP",
0xB4: "ON",
0xB5: "WAIT",
0xB6: "LOAD",
0xB7: "SAVE",
0xB8: "DEF",
0xB9: "POKE",
0xBA: "PRINT",
0xBB: "CONT",
0xBC: "LIST",
0xBD: "CLEAR",
0xBE: "GET",
0xBF: "NEW",
0xC0: "TAB(",
0xC1: "TO",
0xC2: "FN",
0xC3: "SPC(",
0xC4: "THEN",
0xC5: "AT",
0xC6: "NOT",
0xC7: "STEP",
0xC8: "+",
0xC9: "-",
0xCA: "*",
0xCB: "/",
0xCC: "^",
0xCD: "AND",
0xCE: "OR",
0xCF: ">",
0xD0: "=",
0xD1: "<",
0xD2: "SGN",
0xD3: "INT",
0xD4: "ABS",
0xD5: "USR",
0xD6: "FRE",
0xD7: "SCRN(",
0xD8: "PDL",
0xD9: "POS",
0xDA: "SQR",
0xDB: "RND",
0xDC: "LOG",
0xDD: "EXP",
0xDE: "COS",
0xDF: "SIN",
0xE0: "TAN",
0xE1: "ATN",
0xE2: "PEEK",
0xE3: "LEN",
0xE4: "STR$",
0xE5: "VAL",
0xE6: "ASC",
0xE7: "CHR$",
0xE8: "LEFT$",
0xE9: "RIGHT$",
0xEA: "MID$",
}
var ApplesoftReverse map[string]int
var IntegerReverse map[string]int
func init() {
ApplesoftReverse = make(map[string]int)
IntegerReverse = make(map[string]int)
for k, v := range ApplesoftTokens {
ApplesoftReverse[v] = k
}
for k, v := range IntegerTokens {
IntegerReverse[v] = k
}
tst()
}
var IntegerTokens = map[int]string{
0x00: "HIMEM:",
0x02: "_",
0x03: ":",
0x04: "LOAD",
0x05: "SAVE",
0x06: "CON",
0x07: "RUN",
0x08: "RUN",
0x09: "DEL",
0x0A: ",",
0x0B: "NEW",
0x0C: "CLR",
0x0D: "AUTO",
0x0E: ",",
0x0F: "MAN",
0x10: "HIMEM:",
0x11: "LOMEM:",
0x12: "+",
0x13: "-",
0x14: "*",
0x15: "/",
0x16: "=",
0x17: "#",
0x18: ">=",
0x19: ">",
0x1A: "<=",
0x1B: "<>",
0x1C: "<",
0x1D: "AND",
0x1E: "OR",
0x1F: "MOD",
0x20: "^",
0x21: "+",
0x22: "(",
0x23: ",",
0x24: "THEN",
0x25: "THEN",
0x26: ",",
0x27: ",",
0x28: "\"",
0x29: "\"",
0x2A: "(",
0x2B: "!",
0x2C: "!",
0x2D: "(",
0x2E: "PEEK",
0x2F: "RND",
0x30: "SGN",
0x31: "ABS",
0x32: "PDL",
0x33: "RNDX",
0x34: "(",
0x35: "+",
0x36: "-",
0x37: "NOT",
0x38: "(",
0x39: "=",
0x3A: "#",
0x3B: "LEN(",
0x3C: "ASC(",
0x3D: "SCRN(",
0x3E: ",",
0x3F: "(",
0x40: "$",
0x41: "$",
0x42: "(",
0x43: ",",
0x44: ",",
0x45: ";",
0x46: ";",
0x47: ";",
0x48: ",",
0x49: ",",
0x4A: ",",
0x4B: "TEXT",
0x4C: "GR",
0x4D: "CALL",
0x4E: "DIM",
0x4F: "DIM",
0x50: "TAB",
0x51: "END",
0x52: "INPUT",
0x53: "INPUT",
0x54: "INPUT",
0x55: "FOR",
0x56: "=",
0x57: "TO",
0x58: "STEP",
0x59: "NEXT",
0x5A: ",",
0x5B: "RETURN",
0x5C: "GOSUB",
0x5D: "REM",
0x5E: "LET",
0x5F: "GOTO",
0x60: "IF",
0x61: "PRINT",
0x62: "PRINT",
0x63: "PRINT",
0x64: "POKE",
0x65: ",",
0x66: "COLOR=",
0x67: "PLOT",
0x68: ",",
0x69: "HLIN",
0x6A: ",",
0x6B: "AT",
0x6C: "VLIN",
0x6D: ",",
0x6E: "AT",
0x6F: "VTAB",
0x70: "=",
0x71: "=",
0x72: ")",
0x73: ")",
0x74: "LIST",
0x75: ",",
0x76: "LIST",
0x77: "POP",
0x78: "NODSP",
0x79: "DSP",
0x7A: "NOTRACE",
0x7B: "DSP",
0x7C: "DSP",
0x7D: "TRACE",
0x7E: "PR#",
0x7F: "IN#",
}
func Read16(srcptr, length *int, buffer []byte) int {
// if *length < 2 {
// *srcptr += *length
// *length = 0
// return 0
// }
//fmt.Printf("-- srcptr=%d, length=%d, len(buffer)=%d\n", *srcptr, *length, len(buffer))
v := int(buffer[*srcptr]) + 256*int(buffer[*srcptr+1])
*srcptr += 2
*length -= 2
return v
}
func Read8(srcptr, length *int, buffer []byte) byte {
// if *length < 1 {
// *srcptr += *length
// *length = 0
// return 0
// }
//fmt.Printf("-- srcptr=%d, length=%d, len(buffer)=%d\n", *srcptr, *length, len(buffer))
v := buffer[*srcptr]
*srcptr += 1
*length -= 1
return v
}
func StripText(b []byte) []byte {
c := make([]byte, len(b))
for i, v := range b {
c[i] = v & 127
}
return c
}
func ApplesoftDetoks(data []byte) []byte {
//var baseaddr int = 0x801
var srcptr int = 0x00
var length int = len(data)
var out []byte = make([]byte, 0)
if length < 2 {
// not enough here
return []byte("\r\n")
}
for length > 0 {
var nextAddr int
var lineNum int
var inQuote bool = false
var inRem bool = false
if length < 2 {
break
}
nextAddr = Read16(&srcptr, &length, data)
if nextAddr == 0 {
break
}
/* output line number */
if length < 2 {
break
}
lineNum = Read16(&srcptr, &length, data)
ln := fmt.Sprintf("%d", lineNum)
out = append(out, []byte(" "+ln+" ")...)
if length == 0 {
break
}
var t byte = Read8(&srcptr, &length, data)
for t != 0 && length > 0 {
// process token
if t&0x80 != 0 {
/* token */
tokstr, ok := ApplesoftTokens[int(t)]
if ok {
out = append(out, []byte(" "+tokstr+" ")...)
} else {
out = append(out, []byte(" ERROR ")...)
}
if t == 0xb2 {
inRem = true
}
} else {
/* simple character */
r := rune(t)
if r == '"' && !inRem {
if !inQuote {
out = append(out, t)
} else {
out = append(out, t)
}
inQuote = !inQuote
} else if r == ':' && !inRem && !inQuote {
out = append(out, t)
} else if inRem && (r == '\r' || r == '\n') {
out = append(out, []byte("*")...)
} else {
out = append(out, t)
}
}
// Advance
t = Read8(&srcptr, &length, data)
}
out = append(out, []byte("\r\n")...)
inQuote, inRem = false, false
if length == 0 {
break
}
}
//fmt.Println(string(out))
return out
}
func IntegerDetoks(data []byte) []byte {
var srcptr int = 0x00
var length int = len(data)
var out []byte = make([]byte, 0)
if length < 2 {
// not enough here
return []byte("\r\n")
}
for length > 0 {
// starting state for line
var lineLen byte
var lineNum int
var trailingSpace bool
var newTrailingSpace bool = false
// read the line length
lineLen = Read8(&srcptr, &length, data)
if lineLen == 0 {
break // zero length line found
}
// read line number
lineNum = Read16(&srcptr, &length, data)
out = append(out, []byte(fmt.Sprintf("%d ", lineNum))...)
// now process line
var t byte
t = Read8(&srcptr, &length, data)
for t != 0x01 && length > 0 {
if t == 0x03 {
out = append(out, []byte(" :")...)
t = Read8(&srcptr, &length, data)
} else if t == 0x28 {
/* start of quoted text */
out = append(out, 34)
t = Read8(&srcptr, &length, data)
for t != 0x29 && length > 0 {
out = append(out, t&0x7f)
t = Read8(&srcptr, &length, data)
}
if t != 0x29 {
break
}
out = append(out, 34)
t = Read8(&srcptr, &length, data)
} else if t == 0x5d {
/* start of REM statement, run to EOL */
if trailingSpace {
out = append(out, 32)
}
out = append(out, []byte("REM ")...)
t = Read8(&srcptr, &length, data)
for t != 0x01 && length > 0 {
out = append(out, t&0x7f)
t = Read8(&srcptr, &length, data)
}
if t != 0x01 {
break
}
} else if t >= 0xb0 && t <= 0xb9 {
/* start of integer constant */
if length < 2 {
break
}
val := Read16(&srcptr, &length, data)
out = append(out, []byte(fmt.Sprintf("%d", val))...)
t = Read8(&srcptr, &length, data)
} else if t >= 0xc1 && t <= 0xda {
/* start of variable name */
for (t >= 0xc1 && t <= 0xda) || (t >= 0xb0 && t <= 0xb9) {
/* note no RTF-escaped chars in this range */
out = append(out, t&0x7f)
t = Read8(&srcptr, &length, data)
}
} else if t < 0x80 {
/* found a token; try to get the whitespace right */
/* (maybe should've left whitespace on the ends of tokens
that are always followed by whitespace...?) */
token, _ := IntegerTokens[int(t)]
if token[0] >= 0x21 && token[0] <= 0x3f || t < 0x12 {
/* does not need leading space */
out = append(out, []byte(token)...)
} else {
/* needs leading space; combine with prev if it exists */
if trailingSpace {
out = append(out, []byte(token)...)
} else {
out = append(out, []byte(" "+token)...)
}
out = append(out, 32)
}
if token[len(token)-1] == 32 {
newTrailingSpace = true
}
t = Read8(&srcptr, &length, data)
} else {
/* should not happen */
t = Read8(&srcptr, &length, data)
}
trailingSpace = newTrailingSpace
newTrailingSpace = false
}
if t != 0x01 && length > 0 {
break // must have failed
}
// ok, new line
out = append(out, []byte("\r\n")...)
}
return out
}
func breakingChar(ch rune) bool {
return ch == '(' || ch == ')' || ch == '.' || ch == ',' || ch == ';' || ch == ':' || ch == ' '
}
func ApplesoftTokenize(lines []string) []byte {
start := 0x801
currAddr := start
buffer := make([]byte, 0)
for _, l := range lines {
l = strings.Trim(l, "\r")
if l == "" {
continue
}
chunk := ""
inqq := false
tmp := strings.SplitN(l, " ", 2)
ln, _ := strconv.Atoi(tmp[0])
rest := strings.Trim(tmp[1], " ")
linebuffer := make([]byte, 4)
// LINE NUMBER
linebuffer[0x02] = byte(ln & 0xff)
linebuffer[0x03] = byte(ln / 0x100)
// PROCESS LINE
for _, ch := range rest {
switch {
case inqq && ch != '"':
linebuffer = append(linebuffer, byte(ch))
continue
case ch == '"':
linebuffer = append(linebuffer, byte(ch))
inqq = !inqq
continue
case !inqq && breakingChar(ch):
linebuffer = append(linebuffer, []byte(chunk)...)
chunk = ""
linebuffer = append(linebuffer, byte(ch))
continue
}
chunk += string(ch)
code, ok := ApplesoftReverse[strings.ToUpper(chunk)]
if ok {
linebuffer = append(linebuffer, byte(code))
chunk = ""
}
}
if chunk != "" {
linebuffer = append(linebuffer, []byte(chunk)...)
}
// ENDING ZERO BYTE
linebuffer = append(linebuffer, 0x00)
nextAddr := currAddr + len(linebuffer)
linebuffer[0x00] = byte(nextAddr & 0xff)
linebuffer[0x01] = byte(nextAddr / 0x100)
currAddr = nextAddr
buffer = append(buffer, linebuffer...)
}
buffer = append(buffer, 0x00, 0x00)
return buffer
}
var reInt = regexp.MustCompile("^(-?[0-9]+)$")
func isInt(s string) (bool, [3]byte) {
if reInt.MatchString(s) {
m := reInt.FindAllStringSubmatch(s, -1)
i, _ := strconv.ParseInt(m[0][1], 10, 32)
return true, [3]byte{0xb9, byte(i % 256), byte(i / 256)}
} else {
return false, [3]byte{0x00, 0x00, 0x00}
}
}
func IntegerTokenize(lines []string) []byte {
start := 0x801
currAddr := start
buffer := make([]byte, 0)
var linebuffer []byte
add := func(chunk string) {
if chunk != "" {
if ok, ival := isInt(chunk); ok {
linebuffer = append(linebuffer, ival[:]...)
//fmt.Printf("TOK Integer(%d)\n", int(ival[1])+256*int(ival[2]))
} else {
// Encode strings with high bit (0x80) set
//fmt.Printf("TOK String(%s)\n", strings.ToUpper(chunk))
data := []byte(strings.ToUpper(chunk))
for i, v := range data {
data[i] = v | 0x80
}
linebuffer = append(linebuffer, data...)
}
}
}
for _, l := range lines {
l = strings.Trim(l, "\r")
if l == "" {
continue
}
chunk := ""
inqq := false
tmp := strings.SplitN(l, " ", 2)
ln, _ := strconv.Atoi(tmp[0])
rest := strings.Trim(tmp[1], " ")
linebuffer = make([]byte, 3)
// LINE NUMBER
linebuffer[0x01] = byte(ln & 0xff)
linebuffer[0x02] = byte(ln / 0x100)
// PROCESS LINE
for _, ch := range rest {
switch {
case inqq && ch != '"':
linebuffer = append(linebuffer, byte(ch|0x80))
continue
case ch == ':' && !inqq:
linebuffer = append(linebuffer, 0x03)
continue
case ch == ',' && !inqq:
linebuffer = append(linebuffer, 0x0A)
continue
case ch == ';' && !inqq:
linebuffer = append(linebuffer, 0x45)
continue
case ch == '(' && !inqq:
linebuffer = append(linebuffer, 0x22)
continue
case ch == ')' && !inqq:
linebuffer = append(linebuffer, 0x72)
continue
case ch == '+' && !inqq:
linebuffer = append(linebuffer, 0x12)
continue
case ch == '"':
inqq = !inqq
if inqq {
ch = 0x28
} else {
ch = 0x29
}
linebuffer = append(linebuffer, byte(ch))
continue
case !inqq && breakingChar(ch):
add(chunk)
chunk = ""
//linebuffer = append(linebuffer, byte(ch|0x80))
continue
}
chunk += string(ch)
code, ok := IntegerReverse[strings.ToUpper(chunk)]
if ok {
//fmt.Printf("TOK Token(%s)\n", chunk)
linebuffer = append(linebuffer, byte(code))
chunk = ""
}
}
if chunk != "" {
add(chunk)
}
linebuffer = append(linebuffer, 0x01) // EOL token
nextAddr := currAddr + len(linebuffer)
linebuffer[0x00] = byte(len(linebuffer))
currAddr = nextAddr
buffer = append(buffer, linebuffer...)
}
// Encode file length
// buffer[0] = byte((len(buffer) - 2) % 256)
// buffer[1] = byte((len(buffer) - 2) / 256)
return buffer
}
func tst() {
// lines := []string{
// "10 PRINT \"HELLO WORLD!\"",
// "20 GOTO 10",
// }
// b := IntegerTokenize(lines)
// Dump(b)
// os.Exit(1)
}

31
disk/di_test.go Normal file
View File

@ -0,0 +1,31 @@
package disk
import (
//"strings"
"testing"
)
import "fmt"
//import "os"
func TestDisk(t *testing.T) {
if STD_DISK_BYTES != 143360 {
t.Error(fmt.Sprintf("Wrong size got %d", STD_DISK_BYTES))
}
dsk, e := NewDSKWrapper("g19.dsk")
if e != nil {
t.Error(e)
}
fmt.Printf("Disk format is %d\n", dsk.Format)
_, fdlist, e := dsk.GetCatalogProDOSPathed(2, "GAMES", "")
for _, fd := range fdlist {
fmt.Printf("[%s]\n", fd.Name())
}
t.Fail()
}

1090
disk/diskimage.go Normal file

File diff suppressed because it is too large Load Diff

106
disk/diskimage2mg.go Normal file
View File

@ -0,0 +1,106 @@
package disk
import "fmt"
/*
2MG format loader...
*/
const PREAMBLE_2MG_SIZE = 0x40
var MAGIC_2MG = []byte{byte('2'), byte('I'), byte('M'), byte('G')}
type Header2MG struct {
Data [64]byte
}
func (h *Header2MG) SetData(data []byte) {
for i, v := range data {
if i < 64 {
h.Data[i] = v
}
}
}
func (h *Header2MG) GetID() string {
return string(h.Data[0x00:0x04])
}
func (h *Header2MG) GetCreatorID() string {
return string(h.Data[0x04:0x08])
}
func (h *Header2MG) GetHeaderSize() int {
return int(h.Data[0x08]) + 256*int(h.Data[0x09])
}
func (h *Header2MG) GetVersion() int {
return int(h.Data[0x0A]) + 256*int(h.Data[0x0B])
}
func (h *Header2MG) GetImageFormat() int {
return int(h.Data[0x0C]) + 256*int(h.Data[0x0D]) + 65336*int(h.Data[0x0E]) + 16777216*int(h.Data[0x0F])
}
func (h *Header2MG) GetDOSFlags() int {
return int(h.Data[0x10]) + 256*int(h.Data[0x11]) + 65336*int(h.Data[0x12]) + 16777216*int(h.Data[0x13])
}
func (h *Header2MG) GetProDOSBlocks() int {
return int(h.Data[0x14]) + 256*int(h.Data[0x15]) + 65336*int(h.Data[0x16]) + 16777216*int(h.Data[0x17])
}
func (h *Header2MG) GetDiskDataStart() int {
return int(h.Data[0x18]) + 256*int(h.Data[0x19]) + 65336*int(h.Data[0x1A]) + 16777216*int(h.Data[0x1B])
}
func (h *Header2MG) GetDiskDataLength() int {
return int(h.Data[0x1C]) + 256*int(h.Data[0x1D]) + 65336*int(h.Data[0x1E]) + 16777216*int(h.Data[0x1F])
}
func (dsk *DSKWrapper) Is2MG() (bool, DiskFormat, SectorOrder, *DSKWrapper) {
h := &Header2MG{}
h.SetData(dsk.Data[:0x40])
if h.GetID() != "2IMG" {
return false, GetDiskFormat(DF_NONE), SectorOrderDOS33, nil
}
fmt.Println("Disk has 2MG Magic")
fmt.Printf("Block count %d\n", h.GetProDOSBlocks())
start := h.GetDiskDataStart()
size := h.GetDiskDataLength()
if size < len(dsk.Data)-start {
size = len(dsk.Data) - start
}
if size != STD_DISK_BYTES && size != PRODOS_800KB_DISK_BYTES && size != PRODOS_400KB_DISK_BYTES {
fmt.Printf("Bad size %d bytes @ start %d\n", size, start)
return false, GetDiskFormat(DF_NONE), SectorOrderDOS33, nil
}
data := dsk.Data[start : start+size]
format := h.GetImageFormat()
switch format {
case 0x00: /* DOS sector order */
zdsk, _ := NewDSKWrapperBin(dsk.Nibbles, data, dsk.Filename)
return true, GetDiskFormat(DF_DOS_SECTORS_16), SectorOrderDOS33, zdsk
case 0x01: /* ProDOS sector order */
zdsk, _ := NewDSKWrapperBin(dsk.Nibbles, data, dsk.Filename)
if h.GetProDOSBlocks() == 1600 {
return true, GetDiskFormat(DF_PRODOS_800KB), SectorOrderProDOSLinear, zdsk
} else if h.GetProDOSBlocks() == 800 {
return true, GetDiskFormat(DF_PRODOS_400KB), SectorOrderProDOSLinear, zdsk
} else {
return true, GetPDDiskFormat(DF_PRODOS_CUSTOM, h.GetProDOSBlocks()), SectorOrderProDOSLinear, zdsk
}
}
return false, GetDiskFormat(DF_NONE), SectorOrderDOS33, nil
}

1136
disk/diskimageappledos.go Normal file

File diff suppressed because it is too large Load Diff

314
disk/diskimagepas.go Normal file
View File

@ -0,0 +1,314 @@
package disk
import (
"errors"
"regexp"
"strings"
)
const PASCAL_BLOCK_SIZE = 512
const PASCAL_VOLUME_BLOCK = 2
const PASCAL_MAX_VOLUME_NAME = 7
const PASCAL_DIRECTORY_ENTRY_LENGTH = 26
const PASCAL_OVERSIZE_DIR = 32
func (dsk *DSKWrapper) IsPascal() (bool, string) {
dsk.Format = GetDiskFormat(DF_PRODOS)
data, err := dsk.PRODOSGetBlock(PASCAL_VOLUME_BLOCK)
if err != nil {
return false, ""
}
if !(data[0x00] == 0 && data[0x01] == 0) ||
!(data[0x04] == 0 && data[0x05] == 0) ||
!(data[0x06] > 0 && data[0x06] <= PASCAL_MAX_VOLUME_NAME) {
return false, ""
}
l := int(data[0x06])
name := data[0x07 : 0x07+l]
str := ""
for _, ch := range name {
if ch == 0x00 {
break
}
if ch < 0x20 || ch >= 0x7f {
return false, ""
}
if strings.Contains("$=?,[#:", string(ch)) {
return false, ""
}
str += string(ch)
}
return true, str
}
type PascalVolumeHeader struct {
data [PASCAL_DIRECTORY_ENTRY_LENGTH]byte
}
func (pvh *PascalVolumeHeader) SetData(data []byte) {
for i, v := range data {
if i < len(pvh.data) {
pvh.data[i] = v
}
}
}
func (pvh *PascalVolumeHeader) GetStartBlock() int {
return int(pvh.data[0x00]) + 256*int(pvh.data[0x01])
}
func (pvh *PascalVolumeHeader) GetNextBlock() int {
return int(pvh.data[0x02]) + 256*int(pvh.data[0x03])
}
type PascalFileType int
const (
FileType_PAS_NONE PascalFileType = 0
FileType_PAS_BADD PascalFileType = 1
FileType_PAS_CODE PascalFileType = 2
FileType_PAS_TEXT PascalFileType = 3
FileType_PAS_INFO PascalFileType = 4
FileType_PAS_DATA PascalFileType = 5
FileType_PAS_GRAF PascalFileType = 6
FileType_PAS_FOTO PascalFileType = 7
FileType_PAS_SECD PascalFileType = 8
)
var PascalTypeMap = map[PascalFileType][2]string{
0x00: [2]string{"UNK", "ASCII Text"},
0x01: [2]string{"BAD", "Bad Block"},
0x02: [2]string{"PCD", "Pascal Code"},
0x03: [2]string{"PTX", "Pascal Text"},
0x04: [2]string{"PIF", "Pascal Info"},
0x05: [2]string{"PDA", "Pascal Data"},
0x06: [2]string{"GRF", "Pascal Graphics"},
0x07: [2]string{"FOT", "HiRes Graphics"},
0x08: [2]string{"SEC", "Secure Directory"},
}
func (ft PascalFileType) String() string {
info, ok := PascalTypeMap[ft]
if ok {
return info[1]
}
return "Unknown"
}
func (ft PascalFileType) Ext() string {
info, ok := PascalTypeMap[ft]
if ok {
return info[0]
}
return "UNK"
}
func PascalFileTypeFromExt(ext string) PascalFileType {
for ft, info := range PascalTypeMap {
if strings.ToUpper(ext) == info[0] {
return ft
}
}
return 0x00
}
func (pvh *PascalVolumeHeader) GetType() int {
return int(int(pvh.data[0x04]) + 256*int(pvh.data[0x05]))
}
func (pvh *PascalVolumeHeader) GetNameLength() int {
return int(pvh.data[0x06]) & 0x07
}
func (pvh *PascalVolumeHeader) GetName() string {
l := pvh.GetNameLength()
return string(pvh.data[0x07 : 0x07+l])
}
func (pvh *PascalVolumeHeader) GetTotalBlocks() int {
return int(pvh.data[0x0e]) + 256*int(pvh.data[0x0f])
}
func (pvh *PascalVolumeHeader) GetNumFiles() int {
return int(pvh.data[0x10]) + 256*int(pvh.data[0x11])
}
type PascalFileEntry struct {
data [PASCAL_DIRECTORY_ENTRY_LENGTH]byte
}
func (pfe *PascalFileEntry) SetData(data []byte) {
for i, v := range data {
if i < len(pfe.data) {
pfe.data[i] = v
}
}
}
func (pvh *PascalFileEntry) IsLocked() bool {
return true
}
func (pvh *PascalFileEntry) GetStartBlock() int {
return int(pvh.data[0x00]) + 256*int(pvh.data[0x01])
}
func (pvh *PascalFileEntry) GetNextBlock() int {
return int(pvh.data[0x02]) + 256*int(pvh.data[0x03])
}
func (pvh *PascalFileEntry) GetType() PascalFileType {
return PascalFileType(int(pvh.data[0x04]) + 256*int(pvh.data[0x05]))
}
func (pvh *PascalFileEntry) GetNameLength() int {
return int(pvh.data[0x06]) & 0x0f
}
func (pvh *PascalFileEntry) GetName() string {
l := pvh.GetNameLength()
return string(pvh.data[0x07 : 0x07+l])
}
func (pvh *PascalFileEntry) GetBytesRemaining() int {
return int(pvh.data[0x16]) + 256*int(pvh.data[0x17])
}
func (pvh *PascalFileEntry) GetFileSize() int {
return pvh.GetBytesRemaining() + (pvh.GetNextBlock()-pvh.GetStartBlock()-1)*PASCAL_BLOCK_SIZE
}
func (dsk *DSKWrapper) PascalGetCatalog(pattern string) ([]*PascalFileEntry, error) {
pattern = strings.Replace(pattern, ".", "[.]", -1)
pattern = strings.Replace(pattern, "*", ".*", -1)
pattern = strings.Replace(pattern, "?", ".", -1)
rx := regexp.MustCompile("(?i)" + pattern)
files := make([]*PascalFileEntry, 0)
//
d, err := dsk.PRODOSGetBlock(PASCAL_VOLUME_BLOCK)
if err != nil {
return nil, err
}
pvh := &PascalVolumeHeader{}
pvh.SetData(d)
numBlocks := pvh.GetNextBlock() - PASCAL_VOLUME_BLOCK
if numBlocks < 0 || numBlocks > PASCAL_OVERSIZE_DIR {
return files, errors.New("Directory appears corrupt")
}
// disk catalog is okay
catdata := make([]byte, 0)
for block := PASCAL_VOLUME_BLOCK; block < PASCAL_VOLUME_BLOCK+numBlocks; block++ {
data, err := dsk.PRODOSGetBlock(block)
if err != nil {
return files, err
}
catdata = append(catdata, data...)
}
dirPtr := PASCAL_DIRECTORY_ENTRY_LENGTH
for i := 0; i < pvh.GetNumFiles(); i++ {
b := catdata[dirPtr : dirPtr+PASCAL_DIRECTORY_ENTRY_LENGTH]
fd := &PascalFileEntry{}
fd.SetData(b)
// add file
if rx.MatchString(fd.GetName()) {
files = append(files, fd)
}
// move
dirPtr += PASCAL_DIRECTORY_ENTRY_LENGTH
}
return files, nil
}
func (dsk *DSKWrapper) PascalUsedBitmap() ([]bool, error) {
activeBlocks := dsk.Format.BPD()
used := make([]bool, activeBlocks)
files, err := dsk.PascalGetCatalog("*")
if err != nil {
return used, err
}
for _, file := range files {
length := file.GetNextBlock() - file.GetStartBlock()
start := file.GetStartBlock()
if start+length > activeBlocks {
continue // file is bad
}
for block := start; block < start+length; block++ {
used[block] = true
}
}
return used, nil
}
func (dsk *DSKWrapper) PascalReadFile(file *PascalFileEntry) ([]byte, error) {
activeSectors := dsk.Format.BPD()
length := file.GetNextBlock() - file.GetStartBlock()
start := file.GetStartBlock()
// If file is damaged return nothing
if start+length > activeSectors {
return []byte(nil), nil
}
block := start
data := make([]byte, 0)
for block < start+length && len(data) < file.GetFileSize() {
chunk, err := dsk.PRODOSGetBlock(block)
if err != nil {
return data, err
}
needed := file.GetFileSize() - len(data)
if needed >= PASCAL_BLOCK_SIZE {
data = append(data, chunk...)
} else {
data = append(data, chunk[:needed]...)
}
block++
}
return data, nil
}

1852
disk/diskimagepd.go Normal file

File diff suppressed because it is too large Load Diff

382
disk/diskimagerdos.go Normal file
View File

@ -0,0 +1,382 @@
package disk
import (
"bytes"
"regexp"
"strings"
)
const RDOS_CATALOG_TRACK = 0x01
const RDOS_CATALOG_LENGTH = 0xB
const RDOS_ENTRY_LENGTH = 0x20
const RDOS_NAME_LENGTH = 0x18
var RDOS_SIGNATURE = []byte{
byte('R' + 0x80),
byte('D' + 0x80),
byte('O' + 0x80),
byte('S' + 0x80),
byte(' ' + 0x80),
}
var RDOS_SIGNATURE_32 = []byte{
byte('R' + 0x80),
byte('D' + 0x80),
byte('O' + 0x80),
byte('S' + 0x80),
byte(' ' + 0x80),
byte('2' + 0x80),
}
var RDOS_SIGNATURE_33 = []byte{
byte('R' + 0x80),
byte('D' + 0x80),
byte('O' + 0x80),
byte('S' + 0x80),
byte(' ' + 0x80),
byte('3' + 0x80),
}
type RDOSFormatSpec struct {
SectorStride int
SectorMax int
CatalogTrack int
CatalogSector int
Ordering SectorOrder
}
type RDOSFormat int
const (
RDOS_Unknown RDOSFormat = iota
RDOS_3
RDOS_32
RDOS_33
)
func (f RDOSFormat) String() string {
switch f {
case RDOS_3:
return "RDOS3"
case RDOS_32:
return "RDOS32"
case RDOS_33:
return "RDOS33"
}
return "Unknown"
}
func (f RDOSFormat) Spec() *RDOSFormatSpec {
switch f {
case RDOS_32:
return &RDOSFormatSpec{
SectorStride: 13,
SectorMax: 13,
CatalogTrack: 1,
CatalogSector: 0,
Ordering: SectorOrderDOS33,
}
case RDOS_3:
return &RDOSFormatSpec{
SectorStride: 16,
SectorMax: 13,
CatalogTrack: 0,
CatalogSector: 1,
Ordering: SectorOrderDOS33,
}
case RDOS_33:
return &RDOSFormatSpec{
SectorStride: 16,
SectorMax: 16,
CatalogTrack: 1,
CatalogSector: 12,
Ordering: SectorOrderProDOS,
}
}
return nil
}
func (dsk *DSKWrapper) IsRDOS() (bool, RDOSFormat) {
// It needs to be either 140K or 113K
if len(dsk.Data) != STD_DISK_BYTES && len(dsk.Data) != STD_DISK_BYTES_OLD {
return false, RDOS_Unknown
}
sectorStride := (len(dsk.Data) / STD_TRACKS_PER_DISK) / 256
idbytes := dsk.Data[sectorStride*256 : sectorStride*256+6]
if bytes.Compare(idbytes, RDOS_SIGNATURE_32) == 0 && sectorStride == 13 {
return true, RDOS_32
}
if bytes.Compare(idbytes, RDOS_SIGNATURE_32) == 0 && sectorStride == 16 {
return true, RDOS_3
}
if bytes.Compare(idbytes, RDOS_SIGNATURE_33) == 0 && sectorStride == 16 {
return true, RDOS_33
}
return false, RDOS_Unknown
}
type RDOSFileDescriptor struct {
data [RDOS_ENTRY_LENGTH]byte
}
func (fd *RDOSFileDescriptor) SetData(in []byte) {
for i, b := range in {
if i < RDOS_ENTRY_LENGTH {
fd.data[i] = b
}
}
}
func (fd *RDOSFileDescriptor) IsDeleted() bool {
return fd.data[24] == 0xa0 || fd.data[0] == 0x80
}
func (fd *RDOSFileDescriptor) IsUnused() bool {
return fd.data[24] == 0x00
}
func (fd *RDOSFileDescriptor) IsLocked() bool {
return true
}
type RDOSFileType int
const (
FileType_RDOS_Unknown RDOSFileType = iota
FileType_RDOS_AppleSoft
FileType_RDOS_Binary
FileType_RDOS_Text
)
var RDOSTypeMap = map[RDOSFileType][2]string{
FileType_RDOS_Unknown: [2]string{"UNK", "Unknown"},
FileType_RDOS_AppleSoft: [2]string{"APP", "Applesoft Basic Program"},
FileType_RDOS_Binary: [2]string{"BIN", "Binary File"},
FileType_RDOS_Text: [2]string{"TXT", "ASCII Text"},
}
func (ft RDOSFileType) String() string {
info, ok := RDOSTypeMap[ft]
if ok {
return info[1]
}
return "Unknown"
}
func (ft RDOSFileType) Ext() string {
info, ok := RDOSTypeMap[ft]
if ok {
return info[0]
}
return "UNK"
}
func RDOSFileTypeFromExt(ext string) RDOSFileType {
for ft, info := range RDOSTypeMap {
if strings.ToUpper(ext) == info[0] {
return ft
}
}
return 0x00
}
func (fd *RDOSFileDescriptor) Type() RDOSFileType {
switch rune(fd.data[24]) {
case 'A' + 0x80:
return FileType_RDOS_AppleSoft
case 'B' + 0x80:
return FileType_RDOS_Binary
case 'T' + 0x80:
return FileType_RDOS_Text
}
return FileType_RDOS_Unknown
}
func (fd *RDOSFileDescriptor) Name() string {
str := ""
for i := 0; i < RDOS_NAME_LENGTH; i++ {
ch := rune(fd.data[i] & 127)
if ch == 0 {
break
}
str += string(ch)
}
str = strings.TrimRight(str, " ")
switch fd.Type() {
case FileType_RDOS_AppleSoft:
str += ".a"
case FileType_RDOS_Binary:
str += ".s"
case FileType_RDOS_Text:
str += ".t"
}
return str
}
func (fd *RDOSFileDescriptor) NameUnadorned() string {
str := ""
for i := 0; i < RDOS_NAME_LENGTH; i++ {
ch := rune(fd.data[i] & 127)
if ch == 0 {
break
}
str += string(ch)
}
return str
}
func (fd RDOSFileDescriptor) NumSectors() int {
return int(fd.data[25])
}
func (fd RDOSFileDescriptor) LoadAddress() int {
return int(fd.data[26]) + 256*int(fd.data[27])
}
func (fd RDOSFileDescriptor) StartSector() int {
return int(fd.data[30]) + 256*int(fd.data[31])
}
func (fd RDOSFileDescriptor) Length() int {
return int(fd.data[28]) + 256*int(fd.data[29])
}
func (dsk *DSKWrapper) RDOSGetCatalog(pattern string) ([]*RDOSFileDescriptor, error) {
pattern = strings.Replace(pattern, ".", "[.]", -1)
pattern = strings.Replace(pattern, "*", ".*", -1)
pattern = strings.Replace(pattern, "?", ".", -1)
rx := regexp.MustCompile("(?i)" + pattern)
var files = make([]*RDOSFileDescriptor, 0)
d := make([]byte, 0)
for s := 0; s < RDOS_CATALOG_LENGTH; s++ {
dsk.SetTrack(1)
dsk.SetSector(s)
chunk := dsk.Read()
d = append(d, chunk...)
}
var dirPtr int
for i := 0; i < RDOS_CATALOG_LENGTH*RDOS_ENTRY_LENGTH; i++ {
entry := &RDOSFileDescriptor{}
entry.SetData(d[dirPtr : dirPtr+RDOS_ENTRY_LENGTH])
dirPtr += RDOS_ENTRY_LENGTH
if entry.IsUnused() {
break
}
if !entry.IsDeleted() && rx.MatchString(entry.NameUnadorned()) {
files = append(files, entry)
}
}
return files, nil
}
func (dsk *DSKWrapper) RDOSUsedBitmap() ([]bool, error) {
spt := dsk.RDOSFormat.Spec().SectorMax
activeSectors := spt * 35
used := make([]bool, activeSectors)
files, err := dsk.RDOSGetCatalog("*")
if err != nil {
return used, err
}
for _, file := range files {
length := file.NumSectors()
start := file.StartSector()
if start+length > activeSectors {
continue // file is bad
}
for block := start; block < start+length; block++ {
used[block] = true
}
}
return used, nil
}
func (dsk *DSKWrapper) RDOSReadFile(file *RDOSFileDescriptor) ([]byte, error) {
spt := dsk.RDOSFormat.Spec().SectorMax
activeSectors := spt * 35
length := file.NumSectors()
start := file.StartSector()
// If file is damaged return nothing
if start+length > activeSectors {
return []byte(nil), nil
}
block := start
data := make([]byte, 0)
for block < start+length && len(data) < file.Length() {
track := block / spt
sector := block % spt
dsk.SetTrack(track)
dsk.SetSector(sector)
chunk := dsk.Read()
needed := file.Length() - len(data)
if needed >= 256 {
data = append(data, chunk...)
} else {
data = append(data, chunk[:needed]...)
}
block++
}
return data, nil
}

33
disk/int.go Normal file
View File

@ -0,0 +1,33 @@
package disk
import "time"
type CatalogEntryType int
const (
CETUnknown CatalogEntryType = iota
CETBinary
CETBasicApplesoft
CETBasicInteger
CETPascal
CETText
CETData
CETGraphics
)
type CatalogEntry interface {
Size() int // file size in bytes
Name() string
NameUnadorned() string
Date() time.Time
Type() CatalogEntryType
}
type DiskImage interface {
IsValid() (bool, DiskFormat, SectorOrder)
GetCatalog(path string, pattern string) ([]CatalogEntry, error)
ReadFile(fd CatalogEntry) (int, []byte, error)
StoreFile(fd CatalogEntry) error
GetUsedBitmap() ([]bool, error)
Nibblize() ([]byte, error)
}

151
drvappledos13.go Normal file
View File

@ -0,0 +1,151 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"time"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzeDOS13(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
l.Logf("Reading Disk VTOC...")
vtoc, err := dsk.AppleDOSGetVTOC()
if err != nil {
l.Errorf("Error reading VTOC: %s", err.Error())
return
}
info.Tracks, info.Sectors = vtoc.GetTracks(), vtoc.GetSectors()
l.Logf("Tracks: %d, Sectors: %d", info.Tracks, info.Sectors)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Tracks*info.Sectors)
info.ActiveSectors = make(DiskSectors, 0)
info.InactiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
for t := 0; t < info.Tracks; t++ {
for s := 0; s < info.Sectors; s++ {
info.Bitmap[t*info.Sectors+s] = !vtoc.IsTSFree(t, s)
// checksum sector
//info.SectorFingerprints[dsk.ChecksumSector(t, s)] = &DiskBlock{Track: t, Sector: s}
if info.Bitmap[t*info.Sectors+s] {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
activeData = append(activeData, data...)
if *ingestMode&2 == 2 {
sector.Data = data
}
info.ActiveSectors = append(info.ActiveSectors, sector)
} else {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
if *ingestMode&2 == 2 {
sector.Data = data
}
//activeData = append(activeData, data...)
info.InactiveSectors = append(info.InactiveSectors, sector)
}
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// Analyzing files
l.Log("Starting Analysis of files")
vtoc, files, err := dsk.AppleDOSGetCatalog("*")
if err != nil {
l.Errorf("Problem reading directory: %s", err.Error())
return
}
info.Files = make([]*DiskFile, 0)
for _, fd := range files {
l.Logf("- Name=%s, Type=%s", fd.NameUnadorned(), fd.Type())
file := DiskFile{
Filename: fd.NameUnadorned(),
Type: fd.Type().String(),
Locked: fd.IsLocked(),
Ext: fd.Type().Ext(),
Created: time.Now(),
Modified: time.Now(),
}
_, _, data, err := dsk.AppleDOSReadFileRaw(fd)
if err == nil {
sum := sha256.Sum256(data)
file.SHA256 = hex.EncodeToString(sum[:])
file.Size = len(data)
if *ingestMode&1 == 1 {
if fd.Type() == disk.FileTypeAPP {
file.Text = disk.ApplesoftDetoks(data)
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.Data = data
file.LoadAddress = 0x801
} else if fd.Type() == disk.FileTypeINT {
file.Text = disk.IntegerDetoks(data)
file.Data = data
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.LoadAddress = 0x1000
} else if fd.Type() == disk.FileTypeTXT {
file.Text = disk.StripText(data)
file.Data = data
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.LoadAddress = 0x0000
} else if fd.Type() == disk.FileTypeBIN && len(data) >= 2 {
file.LoadAddress = int(data[0]) + 256*int(data[1])
file.Data = data[2:]
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
} else {
file.LoadAddress = 0x0000
file.Data = data
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
}
}
}
info.Files = append(info.Files, &file)
}
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

186
drvappledos16.go Normal file
View File

@ -0,0 +1,186 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"time"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzeDOS16(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
l.Logf("Reading Disk VTOC...")
vtoc, err := dsk.AppleDOSGetVTOC()
if err != nil {
l.Errorf("Error reading VTOC: %s", err.Error())
return
}
info.Tracks, info.Sectors = vtoc.GetTracks(), vtoc.GetSectors()
if vtoc.BytesPerSector() != 256 {
l.Errorf("Disk does not seem to be AppleDOS - treat as generic")
dsk.Format = disk.GetDiskFormat(disk.DF_NONE)
analyzeNONE(id, dsk, info)
return
}
l.Logf("Tracks: %d, Sectors: %d", info.Tracks, info.Sectors)
l.Logf("Sector order: %d", vtoc.GetTrackOrder())
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Tracks*info.Sectors)
var useAlt bool
if vtoc.IsTSFree(17, 0) {
info.Bitmap, _ = dsk.AppleDOSUsedBitmap()
useAlt = true
}
info.ActiveSectors = make(DiskSectors, 0)
info.InactiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
for t := 0; t < info.Tracks; t++ {
for s := 0; s < info.Sectors; s++ {
if !useAlt {
info.Bitmap[t*info.Sectors+s] = !vtoc.IsTSFree(t, s)
}
// checksum sector
//info.SectorFingerprints[dsk.ChecksumSector(t, s)] = &DiskBlock{Track: t, Sector: s}
if info.Bitmap[t*info.Sectors+s] {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
activeData = append(activeData, data...)
if *ingestMode&2 == 2 {
sector.Data = data
}
info.ActiveSectors = append(info.ActiveSectors, sector)
} else {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
if *ingestMode&2 == 2 {
sector.Data = data
}
//activeData = append(activeData, data...)
info.InactiveSectors = append(info.InactiveSectors, sector)
}
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// Analyzing files
l.Log("Starting Analysis of files")
// lines := []string{
// "10 PRINT \"HELLO WORLDS\"",
// "20 GOTO 10",
// }
// e := dsk.AppleDOSWriteFile("CHEESE", disk.FileTypeAPP, disk.ApplesoftTokenize(lines), 0x801)
// if e != nil {
// l.Errorf("Error writing file: %s", e.Error())
// panic(e)
// }
// f, _ := os.Create("out.dsk")
// f.Write(dsk.Data)
// f.Close()
vtoc, files, err := dsk.AppleDOSGetCatalog("*")
if err != nil {
l.Errorf("Problem reading directory: %s", err.Error())
return
}
info.Files = make([]*DiskFile, 0)
for _, fd := range files {
l.Logf("- Name=%s, Type=%s", fd.NameUnadorned(), fd.Type())
file := DiskFile{
Filename: fd.NameUnadorned(),
Type: fd.Type().String(),
Locked: fd.IsLocked(),
Ext: fd.Type().Ext(),
Created: time.Now(),
Modified: time.Now(),
}
//l.Log("start read")
_, _, data, err := dsk.AppleDOSReadFileRaw(fd)
if err == nil {
sum := sha256.Sum256(data)
file.SHA256 = hex.EncodeToString(sum[:])
file.Size = len(data)
if *ingestMode&1 == 1 {
if fd.Type() == disk.FileTypeAPP {
file.Text = disk.ApplesoftDetoks(data)
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.Data = data
file.LoadAddress = 0x801
} else if fd.Type() == disk.FileTypeINT {
file.Text = disk.IntegerDetoks(data)
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.LoadAddress = 0x1000
file.Data = data
} else if fd.Type() == disk.FileTypeTXT {
file.Text = disk.StripText(data)
file.Data = data
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
file.LoadAddress = 0x0000
} else if fd.Type() == disk.FileTypeBIN && len(data) >= 2 {
file.LoadAddress = int(data[0]) + 256*int(data[1])
file.Data = data[2:]
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
} else {
file.LoadAddress = 0x0000
file.Data = data
file.TypeCode = TypeMask_AppleDOS | TypeCode(fd.Type())
}
}
}
//l.Log("end read")
info.Files = append(info.Files, &file)
}
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

86
drvgeneric.go Normal file
View File

@ -0,0 +1,86 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzeNONE(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
switch len(dsk.Data) {
case disk.STD_DISK_BYTES:
info.Tracks = 35
info.Sectors = 16
case disk.STD_DISK_BYTES_OLD:
info.Tracks = 35
info.Sectors = 13
case disk.PRODOS_800KB_DISK_BYTES:
info.Tracks = disk.GetDiskFormat(disk.DF_PRODOS_800KB).TPD()
info.Sectors = disk.GetDiskFormat(disk.DF_PRODOS_800KB).SPT()
default:
l.Errorf("Unknown size %d bytes", len(dsk.Data))
}
l.Logf("Tracks: %d, Sectors: %d", info.Tracks, info.Sectors)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
l.Logf("Assuming all sectors might be used")
info.Bitmap = make([]bool, info.Tracks*info.Sectors)
for i := range info.Bitmap {
info.Bitmap[i] = true
}
info.ActiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
for t := 0; t < info.Tracks; t++ {
for s := 0; s < info.Sectors; s++ {
if info.Bitmap[t*info.Sectors+s] {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
activeData = append(activeData, data...)
if *ingestMode&2 == 2 {
sector.Data = data
}
info.ActiveSectors = append(info.ActiveSectors, sector)
}
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// Analyzing files
l.Log("Skipping Analysis of files")
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

176
drvpascal.go Normal file
View File

@ -0,0 +1,176 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func dump(in []byte) string {
out := ""
for i, v := range in {
if i%16 == 0 {
if out != "" {
out += "\n"
}
out += fmt.Sprintf("%.4x: ", i)
}
out += fmt.Sprintf("%.2x ", v)
}
out += "\n"
return out
}
func analyzePASCAL(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
l.Logf("Reading Disk Structure...")
info.Blocks = dsk.Format.BPD()
l.Logf("Blocks: %d", info.Blocks)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Tracks*info.Sectors)
info.ActiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
var err error
info.Bitmap, err = dsk.PascalUsedBitmap()
if err != nil {
l.Errorf("Error reading bitmap: %s", err.Error())
return
}
for b := 0; b < info.Blocks; b++ {
if info.Bitmap[b] {
data, _ := dsk.PRODOSGetBlock(b)
t, s1, s2 := dsk.PRODOSGetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.ActiveSectors = append(info.ActiveSectors, sec1, sec2)
activeData = append(activeData, data...)
} else {
data, _ := dsk.PRODOSGetBlock(b)
t, s1, s2 := dsk.PRODOSGetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.InactiveSectors = append(info.InactiveSectors, sec1, sec2)
//activeData = append(activeData, data...)
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// Analyzing files
l.Log("Starting Analysis of files")
files, err := dsk.PascalGetCatalog("*")
if err != nil {
l.Errorf("Problem reading directory: %s", err.Error())
return
}
info.Files = make([]*DiskFile, 0)
for _, fd := range files {
l.Logf("- Name=%s, Type=%d, Len=%d", fd.GetName(), fd.GetType(), fd.GetFileSize())
file := DiskFile{
Filename: fd.GetName(),
Type: fd.GetType().String(),
Locked: fd.IsLocked(),
Ext: fd.GetType().Ext(),
Created: time.Now(),
Modified: time.Now(),
}
//l.Log("start read")
data, err := dsk.PascalReadFile(fd)
if err == nil {
sum := sha256.Sum256(data)
file.SHA256 = hex.EncodeToString(sum[:])
file.Size = len(data)
if *ingestMode&1 == 1 {
// text ingestion
if fd.GetType() == disk.FileType_PAS_TEXT {
file.Text = disk.StripText(data)
file.Data = data
file.TypeCode = TypeMask_Pascal | TypeCode(fd.GetType())
} else {
file.Data = data
file.TypeCode = TypeMask_Pascal | TypeCode(fd.GetType())
}
}
}
//l.Log("end read")
info.Files = append(info.Files, &file)
}
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

224
drvprodos16.go Normal file
View File

@ -0,0 +1,224 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzePRODOS16(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
isPD, Format, Layout := dsk.IsProDOS()
l.Logf("IsProDOS=%v, Format=%s, Layout=%d", isPD, Format, Layout)
if isPD {
dsk.Layout = Layout
}
// Sector bitmap
l.Logf("Reading Disk VTOC...")
vtoc, err := dsk.PRODOSGetVDH(2)
if err != nil {
l.Errorf("Error reading VTOC: %s", err.Error())
return
}
info.Blocks = vtoc.GetTotalBlocks()
l.Logf("Filecount: %d", vtoc.GetFileCount())
l.Logf("Blocks: %d", info.Blocks)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Blocks)
info.ActiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
vbitmap, err := dsk.PRODOSGetVolumeBitmap()
if err != nil {
l.Errorf("Error reading volume bitmap: %s", err.Error())
return
}
l.Debug(vbitmap)
for b := 0; b < info.Blocks; b++ {
info.Bitmap[b] = !vbitmap.IsBlockFree(b)
if info.Bitmap[b] {
data, _ := dsk.PRODOSGetBlock(b)
t, s1, s2 := dsk.PRODOSGetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.ActiveSectors = append(info.ActiveSectors, sec1, sec2)
activeData = append(activeData, data...)
} else {
data, _ := dsk.PRODOSGetBlock(b)
t, s1, s2 := dsk.PRODOSGetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.InactiveSectors = append(info.InactiveSectors, sec1, sec2)
//activeData = append(activeData, data...)
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// // Analyzing files
l.Log("Starting Analysis of files")
prodosDir(id, 2, "", dsk, info)
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
e := info.WriteToFile(*baseName + "/" + info.GetFilename())
if e != nil {
l.Errorf("Error writing fingerprint: %v", e)
panic(e)
}
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}
func prodosDir(id int, start int, path string, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
_, files, err := dsk.PRODOSGetCatalog(start, "*")
if err != nil {
l.Errorf("Problem reading directory: %s", err.Error())
return
}
if info.Files == nil {
info.Files = make([]*DiskFile, 0)
}
for _, fd := range files {
l.Logf("- Path=%s, Name=%s, Type=%s", path, fd.NameUnadorned(), fd.Type())
var file DiskFile
if path == "" {
file = DiskFile{
Filename: fd.NameUnadorned(),
Type: fd.Type().String(),
Locked: fd.IsLocked(),
Ext: fd.Type().Ext(),
Created: fd.CreateTime(),
Modified: fd.ModTime(),
}
} else {
file = DiskFile{
Filename: path + "/" + fd.NameUnadorned(),
Type: fd.Type().String(),
Locked: fd.IsLocked(),
Ext: fd.Type().Ext(),
Created: fd.CreateTime(),
Modified: fd.ModTime(),
}
}
if fd.Type() != disk.FileType_PD_Directory {
_, _, data, err := dsk.PRODOSReadFileRaw(fd)
if err == nil {
sum := sha256.Sum256(data)
file.SHA256 = hex.EncodeToString(sum[:])
file.Size = len(data)
if *ingestMode&1 == 1 {
if fd.Type() == disk.FileType_PD_APP {
file.Text = disk.ApplesoftDetoks(data)
file.TypeCode = TypeMask_ProDOS | TypeCode(fd.Type())
file.Data = data
file.LoadAddress = fd.AuxType()
} else if fd.Type() == disk.FileType_PD_INT {
file.Text = disk.IntegerDetoks(data)
file.TypeCode = TypeMask_ProDOS | TypeCode(fd.Type())
file.Data = data
file.LoadAddress = fd.AuxType()
} else if fd.Type() == disk.FileType_PD_TXT {
file.Text = disk.StripText(data)
file.Data = data
file.TypeCode = TypeMask_ProDOS | TypeCode(fd.Type())
file.LoadAddress = fd.AuxType()
} else {
file.LoadAddress = fd.AuxType()
file.Data = data
file.TypeCode = TypeMask_ProDOS | TypeCode(fd.Type())
}
}
}
}
info.Files = append(info.Files, &file)
if fd.Type() == disk.FileType_PD_Directory {
newpath := path
if path != "" {
newpath += "/" + fd.NameUnadorned()
} else {
newpath = fd.NameUnadorned()
}
prodosDir(id, fd.IndexBlock(), newpath, dsk, info)
}
}
}

124
drvprodos800.go Normal file
View File

@ -0,0 +1,124 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzePRODOS800(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
l.Logf("Reading Disk VTOC...")
vtoc, err := dsk.PRODOS800GetVDH(2)
if err != nil {
l.Errorf("Error reading VTOC: %s", err.Error())
return
}
info.Blocks = vtoc.GetTotalBlocks()
l.Logf("Blocks: %d", info.Blocks)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Blocks)
info.ActiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
vbitmap, err := dsk.PRODOS800GetVolumeBitmap()
if err != nil {
l.Errorf("Error reading volume bitmap: %s", err.Error())
return
}
l.Debug(vbitmap)
for b := 0; b < info.Blocks; b++ {
info.Bitmap[b] = !vbitmap.IsBlockFree(b)
if info.Bitmap[b] {
data, _ := dsk.PRODOS800GetBlock(b)
t, s1, s2 := dsk.PRODOS800GetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.ActiveSectors = append(info.ActiveSectors, sec1, sec2)
activeData = append(activeData, data...)
} else {
data, _ := dsk.PRODOS800GetBlock(b)
t, s1, s2 := dsk.PRODOS800GetBlockSectors(b)
sec1 := &DiskSector{
Track: t,
Sector: s1,
SHA256: dsk.ChecksumSector(t, s1),
}
sec2 := &DiskSector{
Track: t,
Sector: s2,
SHA256: dsk.ChecksumSector(t, s2),
}
if *ingestMode&2 == 2 {
sec1.Data = data[:256]
sec2.Data = data[256:]
}
info.InactiveSectors = append(info.InactiveSectors, sec1, sec2)
//activeData = append(activeData, data...)
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// // Analyzing files
l.Log("Starting Analysis of files")
info.Files = make([]*DiskFile, 0)
prodosDir(id, 2, "", dsk, info)
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

142
drvrdos.go Normal file
View File

@ -0,0 +1,142 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
)
func analyzeRDOS(id int, dsk *disk.DSKWrapper, info *Disk) {
l := loggy.Get(id)
// Sector bitmap
l.Logf("Reading Disk Structure...")
info.Tracks, info.Sectors = 35, dsk.RDOSFormat.Spec().SectorMax
l.Logf("Tracks: %d, Sectors: %d", info.Tracks, info.Sectors)
l.Logf("Reading sector bitmap and SHA256'ing sectors")
info.Bitmap = make([]bool, info.Tracks*info.Sectors)
info.ActiveSectors = make(DiskSectors, 0)
info.InactiveSectors = make(DiskSectors, 0)
activeData := make([]byte, 0)
var err error
info.Bitmap, err = dsk.RDOSUsedBitmap()
if err != nil {
l.Errorf("Error reading bitmap: %s", err.Error())
return
}
for t := 0; t < info.Tracks; t++ {
for s := 0; s < info.Sectors; s++ {
if info.Bitmap[t*info.Sectors+s] {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
activeData = append(activeData, data...)
if *ingestMode&2 == 2 {
sector.Data = data
}
info.ActiveSectors = append(info.ActiveSectors, sector)
} else {
sector := &DiskSector{
Track: t,
Sector: s,
SHA256: dsk.ChecksumSector(t, s),
}
data := dsk.Read()
if *ingestMode&2 == 2 {
sector.Data = data
}
//activeData = append(activeData, data...)
info.InactiveSectors = append(info.InactiveSectors, sector)
}
}
}
sum := sha256.Sum256(activeData)
info.SHA256Active = hex.EncodeToString(sum[:])
info.LogBitmap(id)
// Analyzing files
l.Log("Starting Analysis of files")
files, err := dsk.RDOSGetCatalog("*")
if err != nil {
l.Errorf("Problem reading directory: %s", err.Error())
return
}
info.Files = make([]*DiskFile, 0)
for _, fd := range files {
l.Logf("- Name=%s, Type=%s", fd.NameUnadorned(), fd.Type())
file := DiskFile{
Filename: fd.NameUnadorned(),
Type: fd.Type().String(),
Ext: fd.Type().Ext(),
}
//l.Log("start read")
data, err := dsk.RDOSReadFile(fd)
if err == nil {
sum := sha256.Sum256(data)
file.SHA256 = hex.EncodeToString(sum[:])
file.Size = len(data)
if *ingestMode&1 == 1 {
if fd.Type() == disk.FileType_RDOS_AppleSoft {
file.Text = disk.ApplesoftDetoks(data)
file.TypeCode = TypeMask_RDOS | TypeCode(fd.Type())
file.Data = data
} else if fd.Type() == disk.FileType_RDOS_Text {
file.Text = disk.StripText(data)
file.TypeCode = TypeMask_RDOS | TypeCode(fd.Type())
file.Data = data
} else {
file.Data = data
file.LoadAddress = fd.LoadAddress()
file.TypeCode = TypeMask_RDOS | TypeCode(fd.Type())
}
}
}
//l.Log("end read")
l.Logf("FILETEXT=\n%s", dump(data))
info.Files = append(info.Files, &file)
}
exists := exists(*baseName + "/" + info.GetFilename())
if !exists || *forceIngest {
info.WriteToFile(*baseName + "/" + info.GetFilename())
} else {
l.Log("Not writing as it already exists")
}
out(dsk.Format)
}

410
fuzzyblocks.go Normal file
View File

@ -0,0 +1,410 @@
package main
import (
"fmt"
"os"
"os/signal"
"sync"
)
const EMPTYSECTOR = "5341e6b2646979a70e57653007a1f310169421ec9bdd9f1a5648f75ade005af1"
func GetAllDiskSectors(pattern string, pathfilter []string) map[string]DiskSectors {
cache := make(map[string]DiskSectors)
exists, matches := existsPattern(*baseName, pathfilter, pattern)
if !exists {
return cache
}
workchan := make(chan string, 100)
var s sync.Mutex
var wg sync.WaitGroup
for i := 0; i < ingestWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
item := &Disk{}
if err := item.ReadFromFile(m); err == nil {
//
chunk := append(item.ActiveSectors, item.InactiveSectors...)
tmp := make(DiskSectors, 0)
for _, v := range chunk {
if v.SHA256 != EMPTYSECTOR {
tmp = append(tmp, v)
} else {
fmt.Printf("%s: throw away zero sector T%d,S%d\n", item.Filename, v.Track, v.Sector)
}
}
// Load cache
s.Lock()
cache[item.FullPath] = tmp
s.Unlock()
}
}
wg.Done()
}()
}
var lastPc int = -1
for i, m := range matches {
workchan <- m
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Caching disk sector data... %d%% ", pc))
}
lastPc = pc
}
close(workchan)
wg.Wait()
return cache
}
func GetActiveDiskSectors(pattern string, pathfilter []string) map[string]DiskSectors {
cache := make(map[string]DiskSectors)
exists, matches := existsPattern(*baseName, pathfilter, pattern)
if !exists {
return cache
}
workchan := make(chan string, 100)
var s sync.Mutex
var wg sync.WaitGroup
for i := 0; i < ingestWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
item := &Disk{}
if err := item.ReadFromFile(m); err == nil {
// Load cache
s.Lock()
cache[item.FullPath] = item.ActiveSectors
s.Unlock()
}
}
wg.Done()
}()
}
var lastPc int = -1
for i, m := range matches {
workchan <- m
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Caching disk sector data... %d%% ", pc))
}
lastPc = pc
}
close(workchan)
wg.Wait()
return cache
}
func GetSectorMap(d DiskSectors) map[string]*DiskSector {
out := make(map[string]*DiskSector)
for _, v := range d {
out[fmt.Sprintf("T%d,S%d", v.Track, v.Sector)] = v
}
return out
}
type SectorOverlapRecord struct {
same map[string]map[*DiskSector]*DiskSector
percent map[string]float64
missing map[string][]*DiskSector
extras map[string][]*DiskSector
}
func (f *SectorOverlapRecord) Remove(key string) {
delete(f.same, key)
delete(f.percent, key)
delete(f.missing, key)
delete(f.extras, key)
}
func (f *SectorOverlapRecord) IsSubsetOf(filename string) bool {
// f is a subset if:
// missing == 0
// extra > 0
if _, ok := f.same[filename]; !ok {
return false
}
return len(f.extras[filename]) > 0 && len(f.missing[filename]) == 0
}
func (f *SectorOverlapRecord) IsSupersetOf(filename string) bool {
// f is a superset if:
// missing > 0
// extra == 0
if _, ok := f.same[filename]; !ok {
return false
}
return len(f.extras[filename]) == 0 && len(f.missing[filename]) > 0
}
func CompareSectors(d, b DiskSectors, r *SectorOverlapRecord, key string) float64 {
var sameSectors float64
var missingSectors float64
var extraSectors float64
var dmap = GetSectorMap(d)
var bmap = GetSectorMap(b)
for fileCk, info := range dmap {
binfo, bEx := bmap[fileCk]
if bEx && info.SHA256 == binfo.SHA256 {
sameSectors += 1
if r.same[key] == nil {
r.same[key] = make(map[*DiskSector]*DiskSector)
}
r.same[key][binfo] = info
} else {
missingSectors += 1
if r.missing[key] == nil {
r.missing[key] = make([]*DiskSector, 0)
}
r.missing[key] = append(r.missing[key], info)
}
}
for fileCk, info := range bmap {
_, dEx := dmap[fileCk]
if !dEx {
extraSectors += 1
// file match
if r.extras[key] == nil {
r.extras[key] = make([]*DiskSector, 0)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
r.extras[key] = append(r.extras[key], info)
}
}
if (sameSectors + extraSectors + missingSectors) == 0 {
return 0
}
// return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / btotal
return sameSectors / (sameSectors + extraSectors + missingSectors)
}
// Actual fuzzy file match report
func CollectSectorOverlapsAboveThreshold(t float64, pathfilter []string, ff func(pattern string, pathfilter []string) map[string]DiskSectors) map[string]*SectorOverlapRecord {
filerecords := ff("*_*_*_*.fgp", pathfilter)
results := make(map[string]*SectorOverlapRecord)
workchan := make(chan string, 100)
var wg sync.WaitGroup
var s sync.Mutex
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for i := 0; i < processWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
v := &SectorOverlapRecord{
same: make(map[string]map[*DiskSector]*DiskSector),
percent: make(map[string]float64),
missing: make(map[string][]*DiskSector),
extras: make(map[string][]*DiskSector),
}
d := filerecords[m]
for k, b := range filerecords {
if k == m {
continue // dont compare ourselves
}
// ok good to compare -- only keep if we need our threshold
if closeness := CompareSectors(d, b, v, k); closeness < t {
v.Remove(k)
} else {
v.percent[k] = closeness
}
}
// since we delete < threshold, only add if we have any result
if len(v.percent) > 0 {
//os.Stderr.WriteString("\r\nAdded file: " + m + "\r\n\r\n")
s.Lock()
results[m] = v
s.Unlock()
}
}
wg.Done()
}()
}
// feed data in
var lastPc int = -1
var i int
for k, _ := range filerecords {
if len(c) > 0 {
sig := <-c
if sig == os.Interrupt {
close(c)
os.Stderr.WriteString("\r\nInterrupted. Waiting for workers to stop.\r\n\r\n")
break
}
}
workchan <- k
pc := int(100 * float64(i) / float64(len(filerecords)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Processing sectors data... %d%% ", pc))
}
lastPc = pc
i++
}
close(workchan)
wg.Wait()
return results
}
// Actual fuzzy file match report
func CollectSectorSubsets(pathfilter []string, ff func(pattern string, pathfilter []string) map[string]DiskSectors) map[string]*SectorOverlapRecord {
filerecords := ff("*_*_*_*.fgp", pathfilter)
results := make(map[string]*SectorOverlapRecord)
workchan := make(chan string, 100)
var wg sync.WaitGroup
var s sync.Mutex
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for i := 0; i < processWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
v := &SectorOverlapRecord{
same: make(map[string]map[*DiskSector]*DiskSector),
percent: make(map[string]float64),
missing: make(map[string][]*DiskSector),
extras: make(map[string][]*DiskSector),
}
d := filerecords[m]
for k, b := range filerecords {
if k == m {
continue // dont compare ourselves
}
// ok good to compare -- only keep if we need our threshold
closeness := CompareSectors(d, b, v, k)
if !v.IsSubsetOf(k) {
v.Remove(k)
} else {
v.percent[k] = closeness
}
}
// since we delete < threshold, only add if we have any result
if len(v.percent) > 0 {
//os.Stderr.WriteString("\r\nAdded file: " + m + "\r\n\r\n")
s.Lock()
results[m] = v
s.Unlock()
}
}
wg.Done()
}()
}
// feed data in
var lastPc int = -1
var i int
for k, _ := range filerecords {
if len(c) > 0 {
sig := <-c
if sig == os.Interrupt {
close(c)
os.Stderr.WriteString("\r\nInterrupted. Waiting for workers to stop.\r\n\r\n")
break
}
}
workchan <- k
pc := int(100 * float64(i) / float64(len(filerecords)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Processing sectors data... %d%% ", pc))
}
lastPc = pc
i++
}
close(workchan)
wg.Wait()
return results
}

467
fuzzyfiles.go Normal file
View File

@ -0,0 +1,467 @@
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"sync"
)
func inList(item string, list []string) bool {
for _, v := range list {
if strings.ToLower(v) == strings.ToLower(item) {
return true
}
}
return false
}
const EXCLUDEZEROBYTE = true
const EXCLUDEHELLO = true
func GetAllFiles(pattern string, pathfilter []string) map[string]DiskCatalog {
cache := make(map[string]DiskCatalog)
exists, matches := existsPattern(*baseName, pathfilter, pattern)
if !exists {
return cache
}
workchan := make(chan string, 100)
var s sync.Mutex
var wg sync.WaitGroup
for i := 0; i < ingestWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
item := &Disk{}
if err := item.ReadFromFile(m); err == nil {
if len(item.Files) == 0 {
continue
}
// Load cache
s.Lock()
cache[item.FullPath] = item.Files
s.Unlock()
} else {
fmt.Println("FAIL")
}
}
wg.Done()
}()
}
var lastPc int = -1
for i, m := range matches {
//fmt.Printf("Queue: %s\n", m)
workchan <- m
pc := int(100 * float64(i) / float64(len(matches)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Caching data... %d%% ", pc))
}
lastPc = pc
}
close(workchan)
wg.Wait()
return cache
}
type FileOverlapRecord struct {
files map[string]map[*DiskFile]*DiskFile
percent map[string]float64
missing map[string][]*DiskFile
extras map[string][]*DiskFile
}
func (f *FileOverlapRecord) Remove(key string) {
delete(f.files, key)
delete(f.percent, key)
delete(f.missing, key)
delete(f.extras, key)
}
func (f *FileOverlapRecord) IsSubsetOf(filename string) bool {
// f is a subset if:
// missing == 0
// extra > 0
if _, ok := f.files[filename]; !ok {
return false
}
return len(f.extras[filename]) > 0 && len(f.missing[filename]) == 0
}
func (f *FileOverlapRecord) IsSupersetOf(filename string) bool {
// f is a superset if:
// missing > 0
// extra == 0
if _, ok := f.files[filename]; !ok {
return false
}
return len(f.extras[filename]) == 0 && len(f.missing[filename]) > 0
}
// Actual fuzzy file match report
func CollectFilesOverlapsAboveThreshold(t float64, pathfilter []string) map[string]*FileOverlapRecord {
filerecords := GetAllFiles("*_*_*_*.fgp", pathfilter)
results := make(map[string]*FileOverlapRecord)
workchan := make(chan string, 100)
var wg sync.WaitGroup
var s sync.Mutex
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for i := 0; i < processWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
v := &FileOverlapRecord{
files: make(map[string]map[*DiskFile]*DiskFile),
percent: make(map[string]float64),
missing: make(map[string][]*DiskFile),
extras: make(map[string][]*DiskFile),
}
d := filerecords[m]
for k, b := range filerecords {
if k == m {
continue // dont compare ourselves
}
// ok good to compare -- only keep if we need our threshold
if closeness := CompareCatalogs(d, b, v, k); closeness < t {
v.Remove(k)
} else {
v.percent[k] = closeness
}
}
// since we delete < threshold, only add if we have any result
if len(v.percent) > 0 {
//os.Stderr.WriteString("\r\nAdded file: " + m + "\r\n\r\n")
s.Lock()
results[m] = v
s.Unlock()
}
}
wg.Done()
}()
}
// feed data in
var lastPc int = -1
var i int
for k, _ := range filerecords {
if len(c) > 0 {
sig := <-c
if sig == os.Interrupt {
close(c)
os.Stderr.WriteString("\r\nInterrupted. Waiting for workers to stop.\r\n\r\n")
break
}
}
workchan <- k
pc := int(100 * float64(i) / float64(len(filerecords)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Processing files data... %d%% ", pc))
}
lastPc = pc
i++
}
close(workchan)
wg.Wait()
return results
}
func GetCatalogMap(d DiskCatalog) map[string]*DiskFile {
out := make(map[string]*DiskFile)
for _, v := range d {
out[v.SHA256] = v
}
return out
}
func CompareCatalogs(d, b DiskCatalog, r *FileOverlapRecord, key string) float64 {
var sameFiles float64
var missingFiles float64
var extraFiles float64
var dmap = GetCatalogMap(d)
var bmap = GetCatalogMap(b)
for fileCk, info := range dmap {
if info.Size == 0 && EXCLUDEZEROBYTE {
continue
}
if info.Filename == "hello" && EXCLUDEHELLO {
continue
}
binfo, bEx := bmap[fileCk]
if bEx {
sameFiles += 1
// file match
if r.files[key] == nil {
r.files[key] = make(map[*DiskFile]*DiskFile)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
r.files[key][binfo] = info
} else {
missingFiles += 1
// file match
if r.missing[key] == nil {
r.missing[key] = make([]*DiskFile, 0)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
r.missing[key] = append(r.missing[key], info)
}
}
for fileCk, info := range bmap {
if info.Size == 0 {
continue
}
_, dEx := dmap[fileCk]
if !dEx {
extraFiles += 1
// file match
if r.extras[key] == nil {
r.extras[key] = make([]*DiskFile, 0)
}
//fmt.Printf("*** %s: %s -> %s\n", b.Filename, binfo.Filename, info.Filename)
r.extras[key] = append(r.extras[key], info)
}
}
if (sameFiles + extraFiles + missingFiles) == 0 {
return 0
}
// return sameSectors / dTotal, sameSectors / bTotal, diffSectors / dTotal, diffSectors / btotal
return sameFiles / (sameFiles + extraFiles + missingFiles)
}
func CollectFileSubsets(pathfilter []string) map[string]*FileOverlapRecord {
filerecords := GetAllFiles("*_*_*_*.fgp", pathfilter)
results := make(map[string]*FileOverlapRecord)
workchan := make(chan string, 100)
var wg sync.WaitGroup
var s sync.Mutex
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for i := 0; i < processWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
v := &FileOverlapRecord{
files: make(map[string]map[*DiskFile]*DiskFile),
percent: make(map[string]float64),
missing: make(map[string][]*DiskFile),
extras: make(map[string][]*DiskFile),
}
d := filerecords[m]
for k, b := range filerecords {
if k == m {
continue // dont compare ourselves
}
// ok good to compare -- only keep if we need our threshold
closeness := CompareCatalogs(d, b, v, k)
if !v.IsSubsetOf(k) {
v.Remove(k)
} else {
v.percent[k] = closeness
}
}
// since we delete < threshold, only add if we have any result
if len(v.percent) > 0 {
//os.Stderr.WriteString("\r\nAdded file: " + m + "\r\n\r\n")
s.Lock()
results[m] = v
s.Unlock()
}
}
wg.Done()
}()
}
// feed data in
var lastPc int = -1
var i int
for k, _ := range filerecords {
if len(c) > 0 {
sig := <-c
if sig == os.Interrupt {
close(c)
os.Stderr.WriteString("\r\nInterrupted. Waiting for workers to stop.\r\n\r\n")
break
}
}
workchan <- k
pc := int(100 * float64(i) / float64(len(filerecords)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Processing files data... %d%% ", pc))
}
lastPc = pc
i++
}
close(workchan)
wg.Wait()
return results
}
func CollectFilesOverlapsCustom(keep func(d1, d2 string, v *FileOverlapRecord) bool, pathfilter []string) map[string]*FileOverlapRecord {
filerecords := GetAllFiles("*_*_*_*.fgp", pathfilter)
results := make(map[string]*FileOverlapRecord)
workchan := make(chan string, 100)
var wg sync.WaitGroup
var s sync.Mutex
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for i := 0; i < processWorkers; i++ {
wg.Add(1)
go func() {
for m := range workchan {
v := &FileOverlapRecord{
files: make(map[string]map[*DiskFile]*DiskFile),
percent: make(map[string]float64),
missing: make(map[string][]*DiskFile),
extras: make(map[string][]*DiskFile),
}
d := filerecords[m]
for k, b := range filerecords {
if k == m {
continue // dont compare ourselves
}
// ok good to compare -- only keep if we need our threshold
closeness := CompareCatalogs(d, b, v, k)
if !keep(m, k, v) {
v.Remove(k)
} else {
v.percent[k] = closeness
}
}
// since we delete < threshold, only add if we have any result
if len(v.files) > 0 {
//os.Stderr.WriteString("\r\nAdded file: " + m + "\r\n\r\n")
s.Lock()
results[m] = v
s.Unlock()
}
}
wg.Done()
}()
}
// feed data in
var lastPc int = -1
var i int
for k, _ := range filerecords {
if len(c) > 0 {
sig := <-c
if sig == os.Interrupt {
close(c)
os.Stderr.WriteString("\r\nInterrupted. Waiting for workers to stop.\r\n\r\n")
break
}
}
workchan <- k
pc := int(100 * float64(i) / float64(len(filerecords)))
if pc != lastPc {
fmt.Print("\r")
os.Stderr.WriteString(fmt.Sprintf("Processing files data... %d%% ", pc))
}
lastPc = pc
i++
}
close(workchan)
wg.Wait()
return results
}

358
ingestor.go Normal file
View File

@ -0,0 +1,358 @@
package main
import (
"encoding/hex"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"sync"
"time"
"strings"
"crypto/md5"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
"github.com/paleotronic/diskm8/panic"
)
var diskRegex = regexp.MustCompile("(?i)[.](po|do|dsk)$")
func processFile(path string, info os.FileInfo, err error) error {
if err != nil {
loggy.Get(0).Errorf(err.Error())
return err
}
if diskRegex.MatchString(path) {
incoming <- path
fmt.Printf("\rIngested: %d volumes ...", processed)
}
return nil
}
const loaderWorkers = 8
var incoming chan string
var processed int
var errorcount int
var indisk map[disk.DiskFormat]int
var outdisk map[disk.DiskFormat]int
var cm sync.Mutex
func init() {
indisk = make(map[disk.DiskFormat]int)
outdisk = make(map[disk.DiskFormat]int)
}
func in(f disk.DiskFormat) {
cm.Lock()
indisk[f] = indisk[f] + 1
cm.Unlock()
}
func out(f disk.DiskFormat) {
cm.Lock()
outdisk[f] = outdisk[f] + 1
cm.Unlock()
}
func walk(dir string) {
start := time.Now()
incoming = make(chan string, 16)
indisk = make(map[disk.DiskFormat]int)
outdisk = make(map[disk.DiskFormat]int)
var wg sync.WaitGroup
var s sync.Mutex
for i := 0; i < loaderWorkers; i++ {
wg.Add(1)
go func(i int) {
id := 1 + i
l := loggy.Get(id)
for filename := range incoming {
panic.Do(
func() {
analyze(id, filename)
s.Lock()
processed++
s.Unlock()
},
func(r interface{}) {
l.Errorf("Error processing volume: %s", filename)
l.Errorf(string(debug.Stack()))
s.Lock()
errorcount++
s.Unlock()
},
)
}
wg.Done()
}(i)
}
filepath.Walk(dir, processFile)
close(incoming)
wg.Wait()
fmt.Printf("\rIngested: %d volumes ...", processed)
fmt.Println()
duration := time.Since(start)
fmt.Println("=============================================================")
fmt.Printf(" DSKalyzer process report (%d Workers, %v)\n", loaderWorkers, duration)
fmt.Println("=============================================================")
tin, tout := 0, 0
for f, count := range indisk {
outcount := outdisk[f]
fmt.Printf("%-30s %6d in %6d out\n", f.String(), count, outcount)
tin += count
tout += outcount
}
fmt.Println()
fmt.Printf("%-30s %6d in %6d out\n", "Total", tin, tout)
fmt.Println()
average := duration / time.Duration(processed+errorcount)
fmt.Printf("%v average time spent per disk.\n", average)
}
func existsPatternOld(base string, pattern string) (bool, []string) {
l := loggy.Get(0)
p := base + "/" + pattern
l.Logf("glob: %s", p)
matches, _ := filepath.Glob(p)
return (len(matches) > 0), matches
}
func resolvePathfilters(base string, pathfilter []string, pattern string) []*regexp.Regexp {
tmp := strings.Replace(pattern, ".", "[.]", -1)
tmp = strings.Replace(tmp, "?", ".", -1)
tmp = strings.Replace(tmp, "*", ".+", -1)
tmp += "$"
// pathfilter either contains filenames or a pattern (eg. if it was quoted)
var out []*regexp.Regexp
for _, p := range pathfilter {
if runtime.GOOS == "windows" {
//p = strings.Replace(p, ":", "", -1)
p = strings.Replace(p, "\\", "/", -1)
}
//fmt.Printf("Stat [%s]\n", p)
p, e := filepath.Abs(p)
if e != nil {
continue
}
//fmt.Printf("OK\n")
// path is okay and now absolute
info, e := os.Stat(p)
if e != nil {
continue
}
if runtime.GOOS == "windows" {
p = strings.Replace(p, ":", "", -1)
p = strings.Replace(p, "\\", "/", -1)
}
var realpath string
if info.IsDir() {
realpath = strings.Replace(base, "\\", "/", -1) + "/" + strings.Trim(p, "/") + "/" + tmp
} else {
// file
b := strings.Trim(filepath.Base(p), " /")
s := md5.Sum([]byte(b))
realpath = strings.Replace(base, "\\", "/", -1) + "/" + strings.Trim(filepath.Dir(p), "/") + "/.+_.+_.+_" + hex.EncodeToString(s[:]) + "[.]fgp$"
}
//fmt.Printf("Regexp [%s]\n", realpath)
out = append(out, regexp.MustCompile(realpath))
}
return out
}
func existsPattern(base string, filters []string, pattern string) (bool, []string) {
tmp := strings.Replace(pattern, ".", "[.]", -1)
tmp = strings.Replace(tmp, "?", ".", -1)
tmp = strings.Replace(tmp, "*", ".+", -1)
tmp = "(?i)" + tmp + "$"
//os.Stderr.WriteString("Globby is: " + tmp + "\r\n")
fileRxp := regexp.MustCompile(tmp)
var out []string
var found bool
processPatternPath := func(path string, info os.FileInfo, err error) error {
l := loggy.Get(0)
if err != nil {
l.Errorf(err.Error())
return err
}
if fileRxp.MatchString(filepath.Base(path)) {
found = true
out = append(out, path)
}
return nil
}
filepath.Walk(base, processPatternPath)
fexp := resolvePathfilters(base, filters, pattern)
if len(fexp) > 0 {
out2 := make([]string, 0)
for _, p := range out {
if runtime.GOOS == "windows" {
p = strings.Replace(p, "\\", "/", -1)
}
for _, rxp := range fexp {
//fmt.Printf("Match [%s]\n", p)
if rxp.MatchString(p) {
out2 = append(out2, p)
//fmt.Printf("Match regexp: %s\n", p)
break
}
}
}
//fmt.Printf("%d returns\n", len(out2))
return (len(out2) > 0), out2
}
//fmt.Printf("%d returns\n", len(out))
return found, out
}
func analyze(id int, filename string) (*Disk, error) {
l := loggy.Get(id)
var err error
var dsk *disk.DSKWrapper
var dskInfo Disk = Disk{}
dskInfo.Filename = path.Base(filename)
if abspath, e := filepath.Abs(filename); e == nil {
filename = abspath
}
dskInfo.FullPath = path.Clean(filename)
l.Logf("Reading disk image from file source %s", filename)
//fmt.Printf("Processing %s\n", filename)
//fmt.Print(".")
dsk, err = disk.NewDSKWrapper(defNibbler, filename)
if err != nil {
l.Errorf("Disk read failed: %s", err)
return &dskInfo, err
}
if dsk.Format.ID == disk.DF_DOS_SECTORS_13 || dsk.Format.ID == disk.DF_DOS_SECTORS_16 {
isADOS, _, _ := dsk.IsAppleDOS()
if !isADOS {
dsk.Format.ID = disk.DF_NONE
dsk.Layout = disk.SectorOrderDOS33
}
}
// fmt.Printf("%s: IsAppleDOS=%v, Format=%s, Layout=%d\n", path.Base(filename), isADOS, Format, Layout)
l.Log("Load is OK.")
dskInfo.SHA256 = dsk.ChecksumDisk()
l.Logf("SHA256 is %s", dskInfo.SHA256)
dskInfo.Format = dsk.Format.String()
dskInfo.FormatID = dsk.Format
l.Logf("Format is %s", dskInfo.Format)
l.Debugf("TOSO MAGIC: %v", hex.EncodeToString(dsk.Data[:32]))
t, s := dsk.HuntVTOC(35, 13)
l.Logf("Hunt VTOC says: %d, %d", t, s)
// Check if it exists
in(dsk.Format)
dskInfo.IngestMode = *ingestMode
switch dsk.Format.ID {
case disk.DF_DOS_SECTORS_16:
analyzeDOS16(id, dsk, &dskInfo)
case disk.DF_DOS_SECTORS_13:
analyzeDOS13(id, dsk, &dskInfo)
case disk.DF_PRODOS_400KB:
analyzePRODOS800(id, dsk, &dskInfo)
case disk.DF_PRODOS_800KB:
analyzePRODOS800(id, dsk, &dskInfo)
case disk.DF_PRODOS:
analyzePRODOS16(id, dsk, &dskInfo)
case disk.DF_RDOS_3:
analyzeRDOS(id, dsk, &dskInfo)
case disk.DF_RDOS_32:
analyzeRDOS(id, dsk, &dskInfo)
case disk.DF_RDOS_33:
analyzeRDOS(id, dsk, &dskInfo)
case disk.DF_PASCAL:
analyzePASCAL(id, dsk, &dskInfo)
default:
analyzeNONE(id, dsk, &dskInfo)
}
return &dskInfo, nil
}

138
loggy/logger.go Normal file
View File

@ -0,0 +1,138 @@
package loggy
import (
"fmt"
"os"
"strings"
"time"
)
var logFile *os.File
var ECHO bool = false
var SILENT bool = false
var LogFolder string = "./logs/"
type Logger struct {
logFile *os.File
id int
app string
}
var loggers map[int]*Logger
var app string
func Get(id int) *Logger {
if loggers == nil {
loggers = make(map[int]*Logger)
}
l, ok := loggers[id]
if !ok {
l = NewLogger(id, app)
loggers[id] = l
}
return l
}
func NewLogger(id int, app string) *Logger {
if app == "" {
app = "dskalyzer"
}
filename := fmt.Sprintf("%s_%d_%s.log", app, id, fts())
os.MkdirAll(LogFolder, 0755)
logFile, _ = os.Create(LogFolder + filename)
l := &Logger{
id: id,
logFile: logFile,
app: app,
}
return l
}
func ts() string {
t := time.Now()
return fmt.Sprintf(
"%.4d/%.2d/%.2d %.2d:%.2d:%.2d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second(),
)
}
func fts() string {
t := time.Now()
return fmt.Sprintf(
"%.4d%.2d%.2d%.2d%.2d%.2d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second(),
)
}
func (l *Logger) llogf(format string, designator string, v ...interface{}) {
format = ts() + " " + designator + " :: " + format
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
l.logFile.WriteString(fmt.Sprintf(format, v...))
l.logFile.Sync()
if ECHO {
os.Stderr.WriteString(fmt.Sprintf(format, v...))
}
}
func (l *Logger) llog(designator string, v ...interface{}) {
format := ts() + " " + designator + " :: "
for _, vv := range v {
format += fmt.Sprintf("%v ", vv)
}
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
l.logFile.WriteString(format)
l.logFile.Sync()
if ECHO {
os.Stderr.WriteString(format)
}
}
func (l *Logger) Logf(format string, v ...interface{}) {
l.llogf(format, "INFO ", v...)
}
func (l *Logger) Log(v ...interface{}) {
l.llog("INFO ", v...)
}
func (l *Logger) Errorf(format string, v ...interface{}) {
l.llogf(format, "ERROR", v...)
}
func (l *Logger) Error(v ...interface{}) {
l.llog("ERROR", v...)
}
func (l *Logger) Debugf(format string, v ...interface{}) {
l.llogf(format, "DEBUG", v...)
}
func (l *Logger) Debug(v ...interface{}) {
l.llog("DEBUG", v...)
}
func (l *Logger) Fatalf(format string, v ...interface{}) {
l.llogf(format, "FATAL", v...)
}
func (l *Logger) Fatal(v ...interface{}) {
l.llog("FATAL", v...)
}

352
main.go Normal file
View File

@ -0,0 +1,352 @@
package main
/*
DiskM8 is an open source offshoot of the file handling code from the Octalyzer
project.
It provides some command line tools for manipulating Apple // disk images, and
some work in progress reporting tools to ingest large quantities of files,
catalog them and detect duplicates.
The code currently needs a lot of refactoring and cleanup, which we will be working
through as time goes by.
*/
import (
"fmt"
"io/ioutil"
"path"
"path/filepath"
"runtime/debug"
"flag"
"os"
"github.com/paleotronic/diskm8/disk"
"github.com/paleotronic/diskm8/loggy"
"runtime"
"strings"
"time"
"github.com/paleotronic/diskm8/panic"
)
func usage() {
fmt.Printf(`%s <options>
Tool checks for duplicate or similar apple ][ disks, specifically those
with %d bytes size.
`, path.Base(os.Args[0]), disk.STD_DISK_BYTES)
flag.PrintDefaults()
}
func binpath() string {
if runtime.GOOS == "windows" {
return os.Getenv("USERPROFILE") + "/DiskM8"
}
return os.Getenv("HOME") + "/DiskM8"
}
func init() {
loggy.LogFolder = binpath() + "/logs/"
}
var dskName = flag.String("ingest", "", "Disk file or path to ingest")
var dskInfo = flag.String("query", "", "Disk file to query or analyze")
var baseName = flag.String("datastore", binpath()+"/fingerprints", "Database of disk fingerprints for checking")
var verbose = flag.Bool("verbose", false, "Log to stderr")
var fileDupes = flag.Bool("file-dupes", false, "Run file dupe report")
var wholeDupes = flag.Bool("whole-dupes", false, "Run whole disk dupe report")
var activeDupes = flag.Bool("as-dupes", false, "Run active sectors only disk dupe report")
var asPartial = flag.Bool("as-partial", false, "Run partial active sector match against single disk (-disk required)")
var similarity = flag.Float64("similarity", 0.90, "Object match threshold for -*-partial reports")
var minSame = flag.Int("min-same", 0, "Minimum same # files for -all-file-partial")
var maxDiff = flag.Int("max-diff", 0, "Maximum different # files for -all-file-partial")
var filePartial = flag.Bool("file-partial", false, "Run partial file match against single disk (-disk required)")
var fileMatch = flag.String("file", "", "Search for other disks containing file")
var dir = flag.Bool("dir", false, "Directory specified disk (needs -disk)")
var dirFormat = flag.String("dir-format", "{filename} {type} {size:kb} Checksum: {sha256}", "Format of dir")
var preCache = flag.Bool("c", true, "Cache data to memory for quicker processing")
var allFilePartial = flag.Bool("all-file-partial", false, "Run partial file match against all disks")
var allSectorPartial = flag.Bool("all-sector-partial", false, "Run partial sector match (all) against all disks")
var activeSectorPartial = flag.Bool("active-sector-partial", false, "Run partial sector match (active only) against all disks")
var allFileSubset = flag.Bool("all-file-subset", false, "Run subset file match against all disks")
var activeSectorSubset = flag.Bool("active-sector-subset", false, "Run subset (active) sector match against all disks")
var allSectorSubset = flag.Bool("all-sector-subset", false, "Run subset (non-zero) sector match against all disks")
var filterPath = flag.Bool("select", false, "Select files for analysis or search based on file/dir/mask")
var csvOut = flag.Bool("csv", false, "Output data to CSV format")
var reportFile = flag.String("out", "", "Output file (empty for stdout)")
var catDupes = flag.Bool("cat-dupes", false, "Run duplicate catalog report")
var searchFilename = flag.String("search-filename", "", "Search database for file with name")
var searchSHA = flag.String("search-sha", "", "Search database for file with checksum")
var searchTEXT = flag.String("search-text", "", "Search database for file containing text")
var forceIngest = flag.Bool("force", false, "Force re-ingest disks that already exist")
var ingestMode = flag.Int("ingest-mode", 1, "Ingest mode:\n\t0=Fingerprints only\n\t1=Fingerprints + text\n\t2=Fingerprints + sector data\n\t3=All")
var extract = flag.String("extract", "", "Extract files/disks matched in searches ('#'=extract disk, '@'=extract files)")
var adornedCP = flag.Bool("adorned", true, "Extract files named similar to CP")
var shell = flag.Bool("shell", false, "Start interactive mode")
var shellBatch = flag.String("shell-batch", "", "Execute shell command(s) from file and exit")
var withDisk = flag.String("with-disk", "", "Perform disk operation (-file-extract,-file-put,-file-delete)")
var fileExtract = flag.String("file-extract", "", "File to delete from disk (-with-disk)")
var filePut = flag.String("file-put", "", "File to put on disk (-with-disk)")
var fileDelete = flag.String("file-delete", "", "File to delete (-with-disk)")
var fileMkdir = flag.String("dir-create", "", "Directory to create (-with-disk)")
var fileCatalog = flag.Bool("catalog", false, "List disk contents (-with-disk)")
var quarantine = flag.Bool("quarantine", false, "Run -as-dupes and -whole-disk in quarantine mode")
func main() {
runtime.GOMAXPROCS(8)
banner()
//l.Default.Level = l.LevelCrit
flag.Parse()
var filterpath []string
if *filterPath || *shell {
for _, v := range flag.Args() {
filterpath = append(filterpath, filepath.Clean(v))
}
}
//l.SILENT = !*logToFile
loggy.ECHO = *verbose
if *withDisk != "" {
dsk, err := disk.NewDSKWrapper(defNibbler, *withDisk)
if err != nil {
os.Stderr.WriteString(err.Error())
os.Exit(2)
}
commandVolumes[0] = dsk
commandTarget = 0
switch {
case *fileExtract != "":
shellProcess("extract " + *fileExtract)
case *filePut != "":
shellProcess("put " + *filePut)
case *fileMkdir != "":
shellProcess("mkdir " + *fileMkdir)
case *fileDelete != "":
shellProcess("delete " + *fileDelete)
case *fileCatalog:
shellProcess("cat ")
default:
os.Stderr.WriteString("Additional flag required")
os.Exit(3)
}
time.Sleep(5 * time.Second)
os.Exit(0)
}
// if *preCache {
// x := GetAllFiles("*_*_*_*.fgp")
// fmt.Println(len(x))
// }
if *shellBatch != "" {
var data []byte
var err error
if *shellBatch == "stdin" {
data, err = ioutil.ReadAll(os.Stdin)
if err != nil {
os.Stderr.WriteString("Failed to read commands from stdin. Aborting")
os.Exit(1)
}
} else {
data, err = ioutil.ReadFile(*shellBatch)
if err != nil {
os.Stderr.WriteString("Failed to read commands from file. Aborting")
os.Exit(1)
}
}
lines := strings.Split(string(data), "\n")
for i, l := range lines {
r := shellProcess(l)
if r == -1 {
os.Stderr.WriteString(fmt.Sprintf("Script failed at line %d: %s\n", i+1, l))
os.Exit(2)
}
if r == 999 {
os.Stderr.WriteString("Script terminated")
return
}
}
return
}
if *shell {
var dsk *disk.DSKWrapper
var err error
if len(filterpath) > 0 {
fmt.Printf("Trying to load %s\n", filterpath[0])
dsk, err = disk.NewDSKWrapper(defNibbler, filterpath[0])
if err != nil {
fmt.Println("Error: " + err.Error())
os.Exit(1)
}
}
shellDo(dsk)
os.Exit(0)
}
defer func() {
if fileExtractCounter > 0 {
os.Stderr.WriteString(fmt.Sprintf("%d files were extracted\n", fileExtractCounter))
}
}()
if *searchFilename != "" {
searchForFilename(*searchFilename, filterpath)
return
}
if *searchSHA != "" {
searchForSHA256(*searchSHA, filterpath)
return
}
if *searchTEXT != "" {
searchForTEXT(*searchTEXT, filterpath)
return
}
if *dir {
directory(filterpath, *dirFormat)
return
}
if *allFileSubset {
allFilesSubsetReport(filterpath)
os.Exit(0)
}
if *activeSectorSubset {
activeSectorsSubsetReport(filterpath)
os.Exit(0)
}
if *allSectorSubset {
allSectorsSubsetReport(filterpath)
os.Exit(0)
}
if *catDupes {
allFilesPartialReport(1.0, filterpath, "DUPLICATE CATALOG REPORT")
os.Exit(0)
}
if *allFilePartial {
if *minSame == 0 && *maxDiff == 0 {
allFilesPartialReport(*similarity, filterpath, "")
} else if *minSame > 0 {
allFilesCustomReport(keeperAtLeastNSame, filterpath, fmt.Sprintf("AT LEAST %d FILES MATCH", *minSame))
} else if *maxDiff > 0 {
allFilesCustomReport(keeperMaximumNDiff, filterpath, fmt.Sprintf("NO MORE THAN %d FILES DIFFER", *maxDiff))
}
os.Exit(0)
}
if *allSectorPartial {
allSectorsPartialReport(*similarity, filterpath)
os.Exit(0)
}
if *activeSectorPartial {
activeSectorsPartialReport(*similarity, filterpath)
os.Exit(0)
}
if *fileDupes {
fileDupeReport(filterpath)
os.Exit(0)
}
if *wholeDupes {
if *quarantine {
quarantineWholeDisks(filterpath)
} else {
wholeDupeReport(filterpath)
}
os.Exit(0)
}
if *activeDupes {
if *quarantine {
quarantineActiveDisks(filterpath)
} else {
activeDupeReport(filterpath)
}
os.Exit(0)
}
_, e := os.Stat(*baseName)
if e != nil {
loggy.Get(0).Logf("Creating path %s", *baseName)
os.MkdirAll(*baseName, 0755)
}
if *dskName == "" && *dskInfo == "" {
var dsk *disk.DSKWrapper
var err error
if len(filterpath) > 0 {
fmt.Printf("Trying to load %s\n", filterpath[0])
dsk, err = disk.NewDSKWrapper(defNibbler, filterpath[0])
if err != nil {
fmt.Println("Error: " + err.Error())
os.Exit(1)
}
}
shellDo(dsk)
os.Exit(0)
}
info, err := os.Stat(*dskName)
if err != nil {
loggy.Get(0).Errorf("Error stating file: %s", err.Error())
os.Exit(2)
}
if info.IsDir() {
walk(*dskName)
} else {
indisk = make(map[disk.DiskFormat]int)
outdisk = make(map[disk.DiskFormat]int)
panic.Do(
func() {
dsk, e := analyze(0, *dskName)
// handle any disk specific
if e == nil && *asPartial {
asPartialReport(dsk, *similarity, *reportFile, filterpath)
} else if e == nil && *filePartial {
filePartialReport(dsk, *similarity, *reportFile, filterpath)
} else if e == nil && *fileMatch != "" {
fileMatchReport(dsk, *fileMatch, filterpath)
} else if e == nil && *dir {
info := dsk.GetDirectory(*dirFormat)
fmt.Printf("Directory of %s:\n\n", dsk.Filename)
fmt.Println(info)
}
},
func(r interface{}) {
loggy.Get(0).Errorf("Error processing volume: %s", *dskName)
loggy.Get(0).Errorf(string(debug.Stack()))
},
)
}
}

27
make.sh Executable file
View File

@ -0,0 +1,27 @@
#!/bin/bash
ARCHES="darwin-amd64 windows-386 windows-amd64 linux-386 linux-amd64 linux-arm freebsd-arm freebsd-amd64 freebsd-386"
PUBLISH="publish"
mkdir -p "$PUBLISH"
go get github.com/chzyer/readline
exitState=0
for arch in `echo $ARCHES`; do
export GOOS=`echo $arch | awk -F"-" '{print $1}'`
export GOARCH=`echo $arch | awk -F"-" '{print $2}'`
EXENAME="diskm8"
ZIPNAME="$PUBLISH/diskm8-$GOOS-$GOARCH.zip"
if [ "$GOOS" == "windows" ]; then
EXENAME="$EXENAME.exe"
fi
echo "Building $EXENAME..."
go build -o "$EXENAME" .
if [ "$?" == "0" ]; then
echo "Zipping -> $ZIPNAME"
zip "$ZIPNAME" "$EXENAME" "LICENSE" "README.md" "USAGE.md"
else
exit 2
fi
done

13
nibbler.go Normal file
View File

@ -0,0 +1,13 @@
package main
type defaultNibbler struct{}
var defNibbler = &defaultNibbler{}
func (d *defaultNibbler) SetNibble(index int, value byte) {
}
func (d *defaultNibbler) GetNibble(index int) byte {
return 0
}

17
panic/panicwrap.go Normal file
View File

@ -0,0 +1,17 @@
package panic
func Do( f func(), h func(r interface{}) ) {
defer func() {
if r := recover(); r != nil {
h(r)
}
}()
f()
}

703
report.go Normal file
View File

@ -0,0 +1,703 @@
package main
import (
"fmt"
"os"
"sort"
)
type DuplicateSource struct {
Fullpath string
Filename string
GSHA string
fingerprint string
}
type DuplicateFileCollection struct {
data map[string][]DuplicateSource
}
type DuplicateWholeDiskCollection struct {
data map[string][]DuplicateSource
}
type DuplicateActiveSectorDiskCollection struct {
data map[string][]DuplicateSource
data_as map[string][]DuplicateSource
}
func (dfc *DuplicateFileCollection) Add(checksum string, fullpath string, filename string, fgp string) {
if dfc.data == nil {
dfc.data = make(map[string][]DuplicateSource)
}
list, ok := dfc.data[checksum]
if !ok {
list = make([]DuplicateSource, 0)
}
list = append(list, DuplicateSource{Fullpath: fullpath, Filename: filename, fingerprint: fgp})
dfc.data[checksum] = list
}
func (dfc *DuplicateWholeDiskCollection) Add(checksum string, fullpath string, fgp string) {
if dfc.data == nil {
dfc.data = make(map[string][]DuplicateSource)
}
list, ok := dfc.data[checksum]
if !ok {
list = make([]DuplicateSource, 0)
}
list = append(list, DuplicateSource{Fullpath: fullpath, fingerprint: fgp})
dfc.data[checksum] = list
}
func (dfc *DuplicateActiveSectorDiskCollection) Add(checksum string, achecksum string, fullpath string, fgp string) {
if dfc.data == nil {
dfc.data = make(map[string][]DuplicateSource)
}
list, ok := dfc.data[achecksum]
if !ok {
list = make([]DuplicateSource, 0)
}
list = append(list, DuplicateSource{Fullpath: fullpath, GSHA: checksum, fingerprint: fgp})
dfc.data[achecksum] = list
}
func (dfc *DuplicateFileCollection) Report(filename string) {
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
for sha256, list := range dfc.data {
if len(list) > 1 {
w.WriteString(fmt.Sprintf("\nChecksum %s duplicated %d times:\n", sha256, len(list)))
for i, v := range list {
w.WriteString(fmt.Sprintf(" %d) %s >> %s\n", i, v.Fullpath, v.Filename))
}
}
}
}
func AggregateDuplicateFiles(d *Disk, collection interface{}) {
for _, f := range d.Files {
collection.(*DuplicateFileCollection).Add(f.SHA256, d.FullPath, f.Filename, d.source)
}
}
func AggregateDuplicateWholeDisks(d *Disk, collection interface{}) {
collection.(*DuplicateWholeDiskCollection).Add(d.SHA256, d.FullPath, d.source)
}
func AggregateDuplicateActiveSectorDisks(d *Disk, collection interface{}) {
collection.(*DuplicateActiveSectorDiskCollection).Add(d.SHA256, d.SHA256Active, d.FullPath, d.source)
}
func (dfc *DuplicateWholeDiskCollection) Report(filename string) {
var disksWithDupes int
var extras int
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
for sha256, list := range dfc.data {
if len(list) > 1 {
disksWithDupes++
original := list[0]
dupes := list[1:]
w.WriteString("\n")
w.WriteString(fmt.Sprintf("Volume %s has %d duplicate(s):\n", original.Fullpath, len(dupes)))
for _, v := range dupes {
w.WriteString(fmt.Sprintf(" %s (sha256: %s)\n", v.Fullpath, sha256))
extras++
}
}
}
w.WriteString("\n")
w.WriteString("SUMMARY\n")
w.WriteString("=======\n")
w.WriteString(fmt.Sprintf("Total disks which have duplicates: %d\n", disksWithDupes))
w.WriteString(fmt.Sprintf("Total redundant copies found : %d\n", extras))
}
func (dfc *DuplicateActiveSectorDiskCollection) Report(filename string) {
var disksWithDupes int
var extras int
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
for sha256, list := range dfc.data {
if len(list) > 1 {
m := make(map[string]int)
for _, v := range list {
m[v.GSHA] = 1
}
if len(m) == 1 {
continue
}
disksWithDupes++
original := list[0]
dupes := list[1:]
w.WriteString("\n")
w.WriteString("--------------------------------------\n")
w.WriteString(fmt.Sprintf("Volume : %s\n", original.Fullpath))
w.WriteString(fmt.Sprintf("Active SHA256: %s\n", sha256))
w.WriteString(fmt.Sprintf("Global SHA256: %s\n", original.GSHA))
w.WriteString(fmt.Sprintf("# Duplicates : %d\n", len(dupes)))
for i, v := range dupes {
w.WriteString("\n")
w.WriteString(fmt.Sprintf(" Duplicate #%d\n", i+1))
w.WriteString(fmt.Sprintf(" = Volume : %s\n", v.Fullpath))
w.WriteString(fmt.Sprintf(" = Active SHA256: %s\n", sha256))
w.WriteString(fmt.Sprintf(" = Global SHA256: %s\n", v.GSHA))
extras++
}
w.WriteString("\n")
}
}
w.WriteString("\n")
w.WriteString("SUMMARY\n")
w.WriteString("=======\n")
w.WriteString(fmt.Sprintf("Total disks which have duplicates: %d\n", disksWithDupes))
w.WriteString(fmt.Sprintf("Total redundant copies found : %d\n", extras))
}
func asPartialReport(d *Disk, t float64, filename string, pathfilter []string) {
matches := d.GetPartialMatchesWithThreshold(t, pathfilter)
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
w.WriteString(fmt.Sprintf("PARTIAL ACTIVE SECTOR MATCH REPORT FOR %s (Above %.2f%%)\n\n", d.Filename, 100*t))
//sort.Sort(ByMatchFactor(matches))
sort.Sort(ByMatchFactor(matches))
w.WriteString(fmt.Sprintf("%d matches found\n\n", len(matches)))
for i := len(matches) - 1; i >= 0; i-- {
v := matches[i]
w.WriteString(fmt.Sprintf("%.2f%%\t%s\n", v.MatchFactor*100, v.FullPath))
}
w.WriteString("")
}
func filePartialReport(d *Disk, t float64, filename string, pathfilter []string) {
matches := d.GetPartialFileMatchesWithThreshold(t, pathfilter)
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
w.WriteString(fmt.Sprintf("PARTIAL FILE MATCH REPORT FOR %s (Above %.2f%%)\n\n", d.Filename, 100*t))
//sort.Sort(ByMatchFactor(matches))
sort.Sort(ByMatchFactor(matches))
w.WriteString(fmt.Sprintf("%d matches found\n\n", len(matches)))
for i := len(matches) - 1; i >= 0; i-- {
v := matches[i]
w.WriteString(fmt.Sprintf("%.2f%%\t%s (%d missing, %d extras)\n", v.MatchFactor*100, v.FullPath, len(v.MissingFiles), len(v.ExtraFiles)))
for f1, f2 := range v.MatchFiles {
w.WriteString(fmt.Sprintf("\t == %s -> %s\n", f1.Filename, f2.Filename))
}
for _, f := range v.MissingFiles {
w.WriteString(fmt.Sprintf("\t -- %s\n", f.Filename))
}
for _, f := range v.ExtraFiles {
w.WriteString(fmt.Sprintf("\t ++ %s\n", f.Filename))
}
w.WriteString("")
}
w.WriteString("")
}
func fileMatchReport(d *Disk, filename string, pathfilter []string) {
matches := d.GetFileMatches(filename, pathfilter)
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stdout
}
w.WriteString(fmt.Sprintf("PARTIAL FILE MATCH REPORT FOR %s (File: %s)\n\n", d.Filename, filename))
w.WriteString(fmt.Sprintf("%d matches found\n\n", len(matches)))
for i, v := range matches {
w.WriteString(fmt.Sprintf("%d)\t%s\n", i, v.FullPath))
for f1, f2 := range v.MatchFiles {
w.WriteString(fmt.Sprintf("\t == %s -> %s\n", f1.Filename, f2.Filename))
}
w.WriteString("")
}
w.WriteString("")
}
func fileDupeReport(filter []string) {
dfc := &DuplicateFileCollection{}
Aggregate(AggregateDuplicateFiles, dfc, filter)
fmt.Println("DUPLICATE FILE REPORT")
fmt.Println()
dfc.Report(*reportFile)
}
func wholeDupeReport(filter []string) {
dfc := &DuplicateWholeDiskCollection{}
Aggregate(AggregateDuplicateWholeDisks, dfc, filter)
fmt.Println("DUPLICATE WHOLE DISK REPORT")
fmt.Println()
dfc.Report(*reportFile)
}
func activeDupeReport(filter []string) {
dfc := &DuplicateActiveSectorDiskCollection{}
Aggregate(AggregateDuplicateActiveSectorDisks, dfc, filter)
fmt.Println("DUPLICATE ACTIVE SECTORS DISK REPORT")
fmt.Println()
dfc.Report(*reportFile)
}
func allFilesPartialReport(t float64, filter []string, oheading string) {
matches := CollectFilesOverlapsAboveThreshold(t, filter)
if *csvOut {
dumpFileOverlapCSV(matches, *reportFile)
return
}
if oheading != "" {
fmt.Println(oheading + "\n")
} else {
fmt.Printf("PARTIAL ALL FILE MATCH REPORT (Above %.2f%%)\n\n", 100*t)
}
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, ratio := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: %.2f%% Match to %s\n", 100*ratio, k)
for f1, f2 := range matchdata.files[k] {
fmt.Printf(" == %s -> %s\n", f1.Filename, f2.Filename)
}
for _, f := range matchdata.missing[k] {
fmt.Printf(" -- %s\n", f.Filename)
}
for _, f := range matchdata.extras[k] {
fmt.Printf(" ++ %s\n", f.Filename)
}
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func allSectorsPartialReport(t float64, filter []string) {
matches := CollectSectorOverlapsAboveThreshold(t, filter, GetAllDiskSectors)
if *csvOut {
dumpSectorOverlapCSV(matches, *reportFile)
return
}
fmt.Printf("NON-ZERO SECTOR MATCH REPORT (Above %.2f%%)\n\n", 100*t)
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, ratio := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: %.2f%% Match to %s\n", 100*ratio, k)
fmt.Printf(" == %d Sectors matched\n", len(matchdata.same[k]))
fmt.Printf(" -- %d Sectors missing\n", len(matchdata.missing[k]))
fmt.Printf(" ++ %d Sectors extra\n", len(matchdata.extras[k]))
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func activeSectorsPartialReport(t float64, filter []string) {
matches := CollectSectorOverlapsAboveThreshold(t, filter, GetActiveDiskSectors)
if *csvOut {
dumpSectorOverlapCSV(matches, *reportFile)
return
}
fmt.Printf("PARTIAL ACTIVE SECTOR MATCH REPORT (Above %.2f%%)\n\n", 100*t)
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, ratio := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: %.2f%% Match to %s\n", 100*ratio, k)
fmt.Printf(" == %d Sectors matched\n", len(matchdata.same[k]))
fmt.Printf(" -- %d Sectors missing\n", len(matchdata.missing[k]))
fmt.Printf(" ++ %d Sectors extra\n", len(matchdata.extras[k]))
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func allFilesSubsetReport(filter []string) {
matches := CollectFileSubsets(filter)
if *csvOut {
dumpFileOverlapCSV(matches, *reportFile)
return
}
fmt.Printf("SUBSET DISK FILE MATCH REPORT\n\n")
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, _ := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: Is a file subset of %s\n", k)
for f1, f2 := range matchdata.files[k] {
fmt.Printf(" == %s -> %s\n", f1.Filename, f2.Filename)
}
for _, f := range matchdata.missing[k] {
fmt.Printf(" -- %s\n", f.Filename)
}
for _, f := range matchdata.extras[k] {
fmt.Printf(" ++ %s\n", f.Filename)
}
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func activeSectorsSubsetReport(filter []string) {
matches := CollectSectorSubsets(filter, GetActiveDiskSectors)
if *csvOut {
dumpSectorOverlapCSV(matches, *reportFile)
return
}
fmt.Printf("ACTIVE SECTOR SUBSET MATCH REPORT\n\n")
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, _ := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: Is a subset (based on active sectors) of %s\n", k)
fmt.Printf(" == %d Sectors matched\n", len(matchdata.same[k]))
fmt.Printf(" ++ %d Sectors extra\n", len(matchdata.extras[k]))
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func allSectorsSubsetReport(filter []string) {
matches := CollectSectorSubsets(filter, GetAllDiskSectors)
if *csvOut {
dumpSectorOverlapCSV(matches, *reportFile)
return
}
fmt.Printf("NON-ZERO SECTOR SUBSET MATCH REPORT\n\n")
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, _ := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: Is a subset (based on active sectors) of %s\n", k)
fmt.Printf(" == %d Sectors matched\n", len(matchdata.same[k]))
fmt.Printf(" ++ %d Sectors extra\n", len(matchdata.extras[k]))
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}
func dumpFileOverlapCSV(matches map[string]*FileOverlapRecord, filename string) {
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stderr
}
w.WriteString("MATCH,DISK1,FILENAME1,DISK2,FILENAME2,EXISTS\n")
for disk1, matchdata := range matches {
for disk2, match := range matchdata.percent {
for f1, f2 := range matchdata.files[disk2] {
w.WriteString(fmt.Sprintf(`%.2f,"%s","%s","%s","%s",%s`, match, disk1, f1.Filename, disk2, f2.Filename, "Y") + "\n")
}
for _, f1 := range matchdata.missing[disk2] {
w.WriteString(fmt.Sprintf(`%.2f,"%s","%s","%s","%s",%s`, match, disk1, f1.Filename, disk2, "", "N") + "\n")
}
for _, f2 := range matchdata.extras[disk2] {
w.WriteString(fmt.Sprintf(`%.2f,"%s","%s","%s","%s",%s`, match, disk1, "", disk2, f2.Filename, "N") + "\n")
}
}
}
if filename != "" {
fmt.Println("\nWrote " + filename + "\n")
}
}
func dumpSectorOverlapCSV(matches map[string]*SectorOverlapRecord, filename string) {
var w *os.File
var err error
if filename != "" {
w, err = os.Create(filename)
if err != nil {
return
}
defer w.Close()
} else {
w = os.Stderr
}
w.WriteString("MATCH,DISK1,DISK2,SAME,MISSING,EXTRA\n")
for disk1, matchdata := range matches {
for disk2, match := range matchdata.percent {
w.WriteString(fmt.Sprintf(`%.2f,"%s","%s",%d,%d,%d`, match, disk1, disk2, len(matchdata.same[disk2]), len(matchdata.missing[disk2]), len(matchdata.extras[disk2])) + "\n")
}
}
if filename != "" {
fmt.Println("\nWrote " + filename + "\n")
}
}
func keeperAtLeastNSame(d1, d2 string, v *FileOverlapRecord) bool {
return len(v.files[d2]) >= *minSame
}
func keeperMaximumNDiff(d1, d2 string, v *FileOverlapRecord) bool {
return len(v.files[d2]) > 0 && (len(v.missing[d2])+len(v.extras[d2])) <= *maxDiff
}
func allFilesCustomReport(keep func(d1, d2 string, v *FileOverlapRecord) bool, filter []string, oheading string) {
matches := CollectFilesOverlapsCustom(keep, filter)
if *csvOut {
dumpFileOverlapCSV(matches, *reportFile)
return
}
fmt.Println(oheading + "\n")
fmt.Printf("%d matches found\n\n", len(matches))
for volumename, matchdata := range matches {
fmt.Printf("Disk: %s\n", volumename)
for k, ratio := range matchdata.percent {
fmt.Println()
fmt.Printf(" :: %.2f%% Match to %s\n", 100*ratio, k)
for f1, f2 := range matchdata.files[k] {
fmt.Printf(" == %s -> %s\n", f1.Filename, f2.Filename)
}
for _, f := range matchdata.missing[k] {
fmt.Printf(" -- %s\n", f.Filename)
}
for _, f := range matchdata.extras[k] {
fmt.Printf(" ++ %s\n", f.Filename)
}
fmt.Println()
}
fmt.Println()
}
fmt.Println()
}

206
search.go Normal file
View File

@ -0,0 +1,206 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
type SearchResultContext int
const (
SRC_UNKNOWN SearchResultContext = iota
SRC_FILE
SRC_DISK
)
type SearchResultItem struct {
DiskPath string
File *DiskFile
}
func searchForFilename(filename string, filter []string) {
fd := GetAllFiles("*_*_*_*.fgp", filter)
fmt.Printf("Filter: %s\n", filter)
fmt.Println()
fmt.Println()
fmt.Printf("SEARCH RESULTS FOR '%s'\n", filename)
fmt.Println()
for diskname, list := range fd {
//fmt.Printf("Checking: %s\n", diskname)
for _, f := range list {
if strings.Contains(strings.ToLower(f.Filename), strings.ToLower(filename)) {
fmt.Printf("%32s:\n %s (%s, %d bytes, sha: %s)\n\n", diskname, f.Filename, f.Type, f.Size, f.SHA256)
if *extract == "@" {
ExtractFile(diskname, f, *adornedCP, false)
} else if *extract == "#" {
ExtractDisk(diskname)
}
}
}
}
}
func searchForSHA256(sha string, filter []string) {
fd := GetAllFiles("*_*_*_*.fgp", filter)
fmt.Println()
fmt.Println()
fmt.Printf("SEARCH RESULTS FOR SHA256 '%s'\n", sha)
fmt.Println()
for diskname, list := range fd {
for _, f := range list {
if f.SHA256 == sha {
fmt.Printf("%32s:\n %s (%s, %d bytes, sha: %s)\n\n", diskname, f.Filename, f.Type, f.Size, f.SHA256)
if *extract == "@" {
ExtractFile(diskname, f, *adornedCP, false)
} else if *extract == "#" {
ExtractDisk(diskname)
}
}
}
}
}
func searchForTEXT(text string, filter []string) {
fd := GetAllFiles("*_*_*_*.fgp", filter)
fmt.Println()
fmt.Println()
fmt.Printf("SEARCH RESULTS FOR TEXT CONTENT '%s'\n", text)
fmt.Println()
for diskname, list := range fd {
for _, f := range list {
if strings.Contains(strings.ToLower(string(f.Text)), strings.ToLower(text)) {
fmt.Printf("%32s:\n %s (%s, %d bytes, sha: %s)\n\n", diskname, f.Filename, f.Type, f.Size, f.SHA256)
if *extract == "@" {
ExtractFile(diskname, f, *adornedCP, false)
} else if *extract == "#" {
ExtractDisk(diskname)
}
}
}
}
}
func directory(filter []string, format string) {
fd := GetAllFiles("*_*_*_*.fgp", filter)
fmt.Println()
fmt.Println()
fmt.Println()
for diskname, list := range fd {
fmt.Printf("CATALOG RESULTS FOR '%s'\n", diskname)
//fmt.Printf("Checking: %s\n", diskname)
out := ""
for _, file := range list {
tmp := format
// size
tmp = strings.Replace(tmp, "{size:blocks}", fmt.Sprintf("%3d Blocks", file.Size/256+1), -1)
tmp = strings.Replace(tmp, "{size:kb}", fmt.Sprintf("%4d Kb", file.Size/1024+1), -1)
tmp = strings.Replace(tmp, "{size:b}", fmt.Sprintf("%6d Bytes", file.Size), -1)
tmp = strings.Replace(tmp, "{size}", fmt.Sprintf("%6d", file.Size), -1)
// format
tmp = strings.Replace(tmp, "{filename}", fmt.Sprintf("%-36s", file.Filename), -1)
// type
tmp = strings.Replace(tmp, "{type}", fmt.Sprintf("%-20s", file.Type), -1)
// sha256
tmp = strings.Replace(tmp, "{sha256}", file.SHA256, -1)
out += tmp + "\n"
if *extract == "@" {
ExtractFile(diskname, file, *adornedCP, false)
} else if *extract == "#" {
ExtractDisk(diskname)
}
}
fmt.Println(out + "\n\n")
}
}
var fileExtractCounter int
func ExtractFile(diskname string, fd *DiskFile, adorned bool, local bool) error {
var name string
if adorned {
name = fd.GetNameAdorned()
} else {
name = fd.GetName()
}
path := binpath() + "/extract" + diskname
if local {
ext := filepath.Ext(diskname)
base := strings.Replace(filepath.Base(diskname), ext, "", -1)
path = "./" + base
}
if path != "." {
os.MkdirAll(path, 0755)
}
//fmt.Printf("FD.EXT=%s\n", fd.Ext)
f, err := os.Create(path + "/" + name)
if err != nil {
return err
}
defer f.Close()
f.Write(fd.Data)
os.Stderr.WriteString("Extracted file to " + path + "/" + name + "\n")
if strings.ToLower(fd.Ext) == "int" || strings.ToLower(fd.Ext) == "bas" || strings.ToLower(fd.Ext) == "txt" {
f, err := os.Create(path + "/" + name + ".ASC")
if err != nil {
return err
}
defer f.Close()
f.Write(fd.Text)
os.Stderr.WriteString("Extracted file to " + path + "/" + name + ".ASC\n")
}
//os.Stderr.WriteString("Extracted file to " + path + "/" + name)
fileExtractCounter++
return nil
}
func ExtractDisk(diskname string) error {
path := binpath() + "/extract" + diskname
os.MkdirAll(path, 0755)
data, err := ioutil.ReadFile(diskname)
if err != nil {
return err
}
target := path + "/" + filepath.Base(diskname)
return ioutil.WriteFile(target, data, 0755)
}

1732
shell.go Normal file

File diff suppressed because it is too large Load Diff