diff --git a/blcu-programming/.gitattributes b/blcu-programming/.gitattributes
new file mode 100644
index 000000000..eba1110b5
--- /dev/null
+++ b/blcu-programming/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
\ No newline at end of file
diff --git a/blcu-programming/.gitignore b/blcu-programming/.gitignore
new file mode 100644
index 000000000..3d2760b96
--- /dev/null
+++ b/blcu-programming/.gitignore
@@ -0,0 +1,10 @@
+/.venv
+/.vscode
+*.pyc
+*__pycache__/
+*.pyo
+*.pyd
+.idea/
+containers/*/.venv
+.env
+*.log
\ No newline at end of file
diff --git a/blcu-programming/LICENSE b/blcu-programming/LICENSE
new file mode 100644
index 000000000..e62ec04cd
--- /dev/null
+++ b/blcu-programming/LICENSE
@@ -0,0 +1,674 @@
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ 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.
+
+
+ Copyright (C)
+
+ 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 .
+
+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:
+
+ Copyright (C)
+ 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
+.
+
+ 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
+.
diff --git a/blcu-programming/README.md b/blcu-programming/README.md
new file mode 100644
index 000000000..868e677d9
--- /dev/null
+++ b/blcu-programming/README.md
@@ -0,0 +1,76 @@
+# TFTP Server and Client
+
+**TFTP Server and Client** is a comprehensive Python-based application designed to facilitate Trivial File Transfer Protocol (TFTP) operations through a user-friendly graphical interface built with PyQt5. This tool allows users to efficiently manage file transfers to and from TFTP servers, making it an essential resource for network administrators.
+
+## Key Features
+
+### TFTP Server
+- **Start/Stop Server:** Easily control the TFTP server with start and stop functionalities.
+- **Select IP Address:** Choose the specific IP address for the server to listen on.
+- **Change Working Directory:** Modify the current working directory for file transfers with a straightforward interface.
+- **View Directory Contents:** Quickly access and view files in the current working directory.
+- **Logging:** Track server activity with real-time logging displayed in the application and stored in a log file.
+[tftp_server](../TFTP_GUI_Server_Client/screenshot/tftp_server.png)
+### TFTP Client
+- **Upload Files:** Seamlessly upload files to a TFTP server using a simple interface.
+- **Download Files:** Effortlessly download files from a TFTP server with progress monitoring.
+- **File Browsing:** Use an integrated file dialog for easy file selection.
+- **Status Updates:** Receive real-time status updates during upload and download processes.
+[tftp_client](../TFTP_GUI_Server_Client/screenshot/tftp_client.png)
+### Monitoring and Alerts
+- Monitor TFTP server activities and transfer statuses with immediate feedback on successes or failures.
+- Real-time updates ensure that users can track the progress of their operations.
+
+### Error Handling and Prompt Detection
+- Implement robust error handling specific to TFTP operations to ensure smooth functionality.
+- Dynamic prompt detection allows the application to handle varying device responses effectively.
+
+## Example Configurations
+
+### Setting Up the TFTP Server
+1. Launch the application and navigate to the TFTP Server tab.
+2. Select an available IP address from the dropdown menu.
+3. Specify the desired port number (default is 69).
+4. Click **Start Server** to begin listening for incoming TFTP requests.
+
+### Uploading Files
+1. Navigate to the TFTP Client tab.
+2. Enter the TFTP server IP address.
+3. Use the **Browse Upload...** button to select the file you wish to upload.
+4. Click **Upload File** and monitor the status for updates.
+
+### Downloading Files
+1. Enter the TFTP server IP address and specify the file name for download.
+2. Click **Download File** to initiate the download process.
+3. Progress and status will be displayed in real time.
+
+## System Requirements
+
+To run the TFTP Server and Client application, the following system requirements must be met:
+
+- **Python 3.x**
+- **PyQt5**
+- **TFTP Library**
+- **OS:** Windows 10 or Ubuntu >=20.04 (recommended) or any modern Linux distribution
+
+## Technologies Used
+
+- **Python:** The core language utilized for backend logic.
+- **PyQt5:** The framework used for developing the graphical user interface.
+- **TFTP Library:** Employed for implementing TFTP protocol functionalities.
+
+## License
+
+This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+
+## Contributing
+
+Contributions are welcome! Please fork the repository and create a pull request with your enhancements. Alternatively, you can open an issue to suggest improvements or report bugs.
+
+## Author
+
+**petrunetworking** (Network Engineer)
+
+## Acknowledgements
+
+Developed using Python and inspired by the need for efficient file transfer solutions, this application aims to simplify TFTP operations for network professionals, enabling them to manage their file transfers effectively and reliably.
diff --git a/blcu-programming/TFTP_GUI_Server.py b/blcu-programming/TFTP_GUI_Server.py
new file mode 100644
index 000000000..1fc4d3d9d
--- /dev/null
+++ b/blcu-programming/TFTP_GUI_Server.py
@@ -0,0 +1,232 @@
+import sys
+import os
+import threading
+import socket
+import logging
+from PyQt5 import QtWidgets, QtGui, QtCore
+from tftp.TFTPServer import TftpPacketDAT, TftpPacketERR, TftpServer
+from tftp.TftpClient import TftpClient
+# Logging Configuration
+logger = logging.getLogger('tftp_server')
+logger.setLevel(logging.INFO)
+file_handler = logging.FileHandler('tftp_server_activity.log')
+formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
+file_handler.setFormatter(formatter)
+logger.addHandler(file_handler)
+
+import socket
+
+import psutil
+
+def get_ip_addresses():
+ """Get the list of available IP addresses on the local machine across all interfaces."""
+ ip_addresses = []
+
+ for interface, addresses in psutil.net_if_addrs().items():
+ for address in addresses:
+ if address.family == socket.AF_INET: # IPv4 addresses only
+ ip_addresses.append(address.address)
+
+ # Remove duplicates and return the list of IP addresses
+ return list(set(ip_addresses))
+
+class TFTPClient(QtWidgets.QWidget):
+ log_signal = QtCore.pyqtSignal(str) # Signal to update log
+
+ def __init__(self):
+ super().__init__()
+ self.setWindowTitle("TFTP Client")
+ self.setGeometry(500, 100, 500, 400)
+
+ self.hardcoded_ip = "192.168.0.27"
+
+ self.ip_input = QtWidgets.QLineEdit(self)
+ self.ip_input.setPlaceholderText("Enter Server IP Address")
+ self.ip_input.setText(self.hardcoded_ip) # Set hardcoded IP
+ self.ip_input.setReadOnly(True)
+
+ # Separate inputs for upload and download
+ self.upload_file_input = QtWidgets.QLineEdit(self)
+ self.upload_file_input.setPlaceholderText("Select File to Upload")
+
+ self.download_file_input = QtWidgets.QLineEdit(self)
+ self.download_file_input.setPlaceholderText("Enter File Name to Download")
+
+ self.browse_button = QtWidgets.QPushButton("Browse Upload...", self)
+ self.browse_button.clicked.connect(self.browse_upload_file)
+
+ self.download_button = QtWidgets.QPushButton("Download File", self)
+ self.download_button.clicked.connect(self.download_file)
+
+ self.upload_button = QtWidgets.QPushButton("Upload File", self)
+ self.upload_button.clicked.connect(self.upload_file)
+
+ self.use_folder_checkbox = QtWidgets.QCheckBox("Use selected folder for download", self)
+ self.use_folder_checkbox.setChecked(False) # Default unchecked
+
+ self.default_directory_label = QtWidgets.QLabel(self)
+ self.default_directory_label.setText(f"Default Download Directory: {self.get_default_directory()}")
+
+ self.status_label = QtWidgets.QLabel("Status: Waiting", self)
+ self.status_label.setStyleSheet("font-weight: bold;")
+
+ self.log_output = QtWidgets.QTextEdit(self)
+ self.log_output.setReadOnly(True)
+
+ layout = QtWidgets.QVBoxLayout()
+ layout.addWidget(QtWidgets.QLabel("Enter Server IP Address:"))
+ layout.addWidget(self.ip_input)
+
+ # Upload file section
+ layout.addWidget(QtWidgets.QLabel("File to Upload:"))
+ layout.addWidget(self.upload_file_input)
+ layout.addWidget(self.browse_button)
+
+ # Download file section
+ layout.addWidget(QtWidgets.QLabel("File to Download:"))
+ layout.addWidget(self.download_file_input)
+ layout.addWidget(self.use_folder_checkbox) # Add the checkbox here
+
+ # Add the default directory label
+ layout.addWidget(self.default_directory_label)
+
+ button_layout = QtWidgets.QHBoxLayout()
+ button_layout.addWidget(self.download_button)
+ button_layout.addWidget(self.upload_button)
+ button_layout.addWidget(self.status_label)
+ layout.addLayout(button_layout)
+
+ layout.addWidget(QtWidgets.QLabel("Client Log:"))
+ layout.addWidget(self.log_output)
+
+ self.setLayout(layout)
+ self.setStyleSheet("background-color: #f0f0f0; font-family: Arial;")
+
+ self.total_size = 0
+ self.downloaded_size = 0
+
+ # Connect the log signal to the update_log method
+ self.log_signal.connect(self.update_log)
+
+ def get_default_directory(self):
+ """Return the default download directory."""
+ return os.path.expanduser("~") # User's home directory
+
+ def browse_upload_file(self):
+ options = QtWidgets.QFileDialog.Options()
+ file_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Select File to Upload", "", "All Files (*);;Text Files (*.txt)", options=options)
+ if file_name:
+ self.upload_file_input.setText(file_name) # Save the full path for the selected file
+
+ def download_file(self):
+ ip = self.ip_input.text() # Get the manually entered IP address
+ filename = self.download_file_input.text()
+
+ if self.use_folder_checkbox.isChecked():
+ # Open a dialog to select the folder for saving the downloaded file
+ folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Select Folder to Save Downloaded File")
+
+ if folder: # Proceed only if a folder was selected
+ self.status_label.setText("Status: Downloading...")
+ self.log_output.clear() # Clear previous logs
+
+ # Construct the full path for the downloaded file
+ full_path = os.path.join(folder, filename)
+
+ # Start a new thread for downloading to avoid blocking the UI
+ threading.Thread(target=self.perform_download, args=(ip, full_path), daemon=True).start()
+ else:
+ self.log_signal.emit("Download canceled: No folder selected.")
+ else:
+ # Default save path (you can modify this to your preferred default directory)
+ default_directory = self.get_default_directory()
+ full_path = os.path.join(default_directory, filename)
+
+ self.status_label.setText("Status: Downloading...")
+ self.log_output.clear() # Clear previous logs
+
+ # Start a new thread for downloading to avoid blocking the UI
+ threading.Thread(target=self.perform_download, args=(ip, full_path), daemon=True).start()
+
+ def perform_download(self, ip, full_path):
+ try:
+ client = TftpClient(ip, 69)
+
+ # Get total file size
+ self.total_size = client.get_file_size(os.path.basename(full_path))
+ if self.total_size <= 0:
+ self.status_label.setText("Error: Invalid file size.")
+ self.log_signal.emit("Error: Invalid file size.")
+ return
+
+ # Function to update progress
+ def update_progress(packet):
+ if isinstance(packet, TftpPacketERR):
+ self.log_signal.emit(f"Error: {packet.errmsg.decode()}")
+ return
+
+ # Check for DAT packets (data packets)
+ if isinstance(packet, TftpPacketDAT):
+ self.downloaded_size += len(packet.data)
+ self.log_signal.emit(f"Downloaded: {self.downloaded_size} bytes")
+
+ # Start downloading with the update_progress callback
+ client.download(os.path.basename(full_path), output=full_path, packethook=update_progress)
+
+ self.status_label.setText("Status: Download Complete")
+ self.log_signal.emit("Download complete.")
+ except Exception as e:
+ self.status_label.setText(f"Error: {str(e)}")
+ self.log_signal.emit(f"Error: {str(e)}")
+
+ def upload_file(self):
+ ip = self.ip_input.text() # Get the manually entered IP address
+ filename = self.upload_file_input.text()
+ self.status_label.setText("Status: Uploading...")
+ self.log_output.clear() # Clear previous logs
+
+ # Start a new thread for uploading to avoid blocking the UI
+ threading.Thread(target=self.perform_upload, args=(ip, filename), daemon=True).start()
+
+ def perform_upload(self, ip, filename):
+ try:
+ client = TftpClient(ip, 69)
+
+ # Get total file size
+ self.total_size = os.path.getsize(filename)
+ self.downloaded_size = 0 # Reset downloaded size
+
+ # Function to update progress
+ def update_progress(packet):
+ if isinstance(packet, TftpPacketERR):
+ self.log_signal.emit(f"Error: {packet.errmsg.decode()}")
+ return
+
+ # Check for DAT packets (data packets)
+ if isinstance(packet, TftpPacketDAT):
+ self.downloaded_size += len(packet.data)
+ self.log_signal.emit(f"Uploaded: {self.downloaded_size} bytes")
+
+ # Start uploading with the update_progress callback
+ with open(filename, 'rb') as f:
+ client.upload(os.path.basename(filename), input=f, packethook=update_progress)
+
+ self.status_label.setText("Status: Upload Complete")
+ self.log_signal.emit("Upload complete.")
+ except Exception as e:
+ self.status_label.setText(f"Error: {str(e)}")
+ self.log_signal.emit(f"Error: {str(e)}")
+
+ def update_log(self, message):
+ self.log_output.append(message)
+ self.log_output.moveCursor(QtGui.QTextCursor.End) # Scroll to the bottom
+
+
+if __name__ == "__main__":
+ app = QtWidgets.QApplication(sys.argv)
+ client = TFTPClient()
+ client.setWindowTitle("TFTP Client by petrunetworking")
+ client.setGeometry(100, 100, 500, 400)
+ client.setStyleSheet("background-color: #eaeaea; font-family: Arial;")
+ client.show()
+ sys.exit(app.exec_())
diff --git a/blcu-programming/api/main.py b/blcu-programming/api/main.py
new file mode 100644
index 000000000..15d9307ca
--- /dev/null
+++ b/blcu-programming/api/main.py
@@ -0,0 +1,92 @@
+from datetime import datetime, timezone
+from pathlib import Path
+
+from fastapi import FastAPI, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from tftp.TftpClient import TftpClient
+
+app = FastAPI(title="TFTP API", version="0.1.0")
+
+LOG_FILE = Path("tftp_server_activity.log")
+
+
+class TransferRequest(BaseModel):
+ host: str
+ port: int = Field(default=69, ge=1, le=65535)
+ remote_filename: str
+ local_path: str
+
+
+def _utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+@app.get("/health")
+def health() -> dict:
+ return {
+ "status": "ok",
+ "service": "tftp-api",
+ "timestamp": _utc_now(),
+ }
+
+
+@app.post("/upload")
+def upload_file(request: TransferRequest) -> dict:
+ local_path = Path(request.local_path).expanduser().resolve()
+ if not local_path.exists() or not local_path.is_file():
+ raise HTTPException(status_code=400, detail="local_path must be an existing file")
+
+ client = TftpClient(request.host, request.port)
+
+ try:
+ with local_path.open("rb") as file_handle:
+ client.upload(request.remote_filename, file_handle, timeout=3, retries=1)
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+ return {
+ "ok": True,
+ "message": "Upload complete",
+ "host": request.host,
+ "port": request.port,
+ "remote_filename": request.remote_filename,
+ "local_path": str(local_path),
+ }
+
+
+@app.post("/download")
+def download_file(request: TransferRequest) -> dict:
+ local_path = Path(request.local_path).expanduser().resolve()
+ local_path.parent.mkdir(parents=True, exist_ok=True)
+
+ client = TftpClient(request.host, request.port)
+
+ try:
+ client.download(request.remote_filename, output=str(local_path))
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+ return {
+ "ok": True,
+ "message": "Download complete",
+ "host": request.host,
+ "port": request.port,
+ "remote_filename": request.remote_filename,
+ "local_path": str(local_path),
+ }
+
+
+@app.get("/logs")
+def get_logs(tail: int = Query(default=200, ge=1, le=5000)) -> dict:
+ if not LOG_FILE.exists():
+ return {"path": str(LOG_FILE), "lines": [], "line_count": 0}
+
+ lines = LOG_FILE.read_text(encoding="utf-8", errors="replace").splitlines()
+ selected_lines = lines[-tail:]
+
+ return {
+ "path": str(LOG_FILE.resolve()),
+ "lines": selected_lines,
+ "line_count": len(selected_lines),
+ }
diff --git a/blcu-programming/screenshot/tftp_client.png b/blcu-programming/screenshot/tftp_client.png
new file mode 100644
index 000000000..2bd14f402
Binary files /dev/null and b/blcu-programming/screenshot/tftp_client.png differ
diff --git a/blcu-programming/screenshot/tftp_server.png b/blcu-programming/screenshot/tftp_server.png
new file mode 100644
index 000000000..27eb3b074
Binary files /dev/null and b/blcu-programming/screenshot/tftp_server.png differ
diff --git a/blcu-programming/tftp/TFTPServer.py b/blcu-programming/tftp/TFTPServer.py
new file mode 100644
index 000000000..ee28ddce4
--- /dev/null
+++ b/blcu-programming/tftp/TFTPServer.py
@@ -0,0 +1,164 @@
+import os
+import select
+import socket
+import threading
+import logging
+from errno import EINTR
+from .TftpShared import *
+from .TftpPacketTypes import *
+from .TftpPacketFactory import TftpPacketFactory
+from .TftpContexts import TftpContextServer
+
+log = logging.getLogger('tftpy.TftpServer')
+# Define the logger for TFTP server
+logger = logging.getLogger('tftp_server')
+logger.setLevel(logging.INFO)
+file_handler = logging.FileHandler('tftp_server_activity.log')
+formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
+file_handler.setFormatter(formatter)
+logger.addHandler(file_handler)
+
+class TftpServer(TftpSession):
+ def __init__(self, tftproot=None, dyn_file_func=None, upload_open=None):
+ super().__init__()
+ self.listenip = None
+ self.listenport = None
+ self.sock = None
+ self.root = os.path.abspath(tftproot)
+ self.dyn_file_func = dyn_file_func
+ self.upload_open = upload_open
+ self.sessions = {}
+ self.is_running = threading.Event()
+ self.shutdown_gracefully = False
+ self.shutdown_immediately = False
+
+ # Validate the TFTP root directory
+ if os.path.exists(self.root):
+ if not os.path.isdir(self.root):
+ raise TftpException("The tftproot must be a directory.")
+ if not os.access(self.root, os.R_OK):
+ raise TftpException("The tftproot must be readable.")
+ if not os.access(self.root, os.W_OK):
+ logger.warning("The tftproot is not writable.")
+ else:
+ raise TftpException("The tftproot does not exist.")
+
+ def handle_write_request(self, address, filename):
+ """
+ Handle write requests by saving the file to Django's MEDIA_ROOT.
+ """
+ filepath = os.path.join(self.root, filename)
+ try:
+ with open(filepath, 'wb') as file:
+ self.write_to_file(file)
+ logger.info(f"File written to {filepath}")
+ except Exception as e:
+ logger.error(f"Error writing file {filepath}: {e}")
+
+ def listen(self, listenip="", listenport=DEF_TFTP_PORT, timeout=SOCK_TIMEOUT, retries=DEF_TIMEOUT_RETRIES):
+ """
+ Start listening for incoming TFTP requests and handle them.
+ """
+ tftp_factory = TftpPacketFactory()
+
+ if not listenip:
+ listenip = '0.0.0.0'
+ logger.info("Server requested on IP %s, port %s" % (listenip, listenport))
+ try:
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.sock.bind((listenip, listenport))
+ _, self.listenport = self.sock.getsockname()
+ except socket.error as err:
+ logger.error(f"Socket error: {err}")
+ raise
+
+ self.is_running.set()
+
+ logger.info("Starting receive loop...")
+ while True:
+ if self.shutdown_immediately:
+ logger.warning("Shutting down immediately. Session count: %d" % len(self.sessions))
+ self.sock.close()
+ for key in self.sessions:
+ self.sessions[key].end()
+ self.sessions = {}
+ break
+
+ elif self.shutdown_gracefully:
+ if not self.sessions:
+ logger.warning("In graceful shutdown mode and all sessions complete.")
+ self.sock.close()
+ break
+
+ inputlist = [self.sock] + [session.sock for session in self.sessions.values()]
+ try:
+ readyinput, _, _ = select.select(inputlist, [], [], timeout)
+ except select.error as err:
+ if err[0] == EINTR:
+ logger.debug("Interrupted syscall, retrying")
+ continue
+ else:
+ logger.error(f"Select error: {err}")
+ raise
+
+ deletion_list = []
+
+ for readysock in readyinput:
+ if readysock == self.sock:
+ buffer, (raddress, rport) = self.sock.recvfrom(MAX_BLKSIZE)
+ if self.shutdown_gracefully:
+ logger.warning("Discarding data on main port, in graceful shutdown mode")
+ continue
+
+ key = "%s:%s" % (raddress, rport)
+ if key not in self.sessions:
+ self.sessions[key] = TftpContextServer(raddress, rport, timeout, self.root, self.dyn_file_func, self.upload_open, retries=retries)
+ try:
+ self.sessions[key].start(buffer)
+ except TftpException as err:
+ deletion_list.append(key)
+ logger.error("Fatal exception from session %s: %s" % (key, str(err)))
+ logger.info("Currently handling these sessions:")
+ for session_key, session in self.sessions.items():
+ logger.info(" %s" % session)
+
+ else:
+ for key in self.sessions:
+ if readysock == self.sessions[key].sock:
+ try:
+ self.sessions[key].cycle()
+ if self.sessions[key].state is None:
+ logger.info("Successful transfer.")
+ deletion_list.append(key)
+ except TftpException as err:
+ deletion_list.append(key)
+ logger.error("Fatal exception from session %s: %s" % (key, str(err)))
+ break
+ else:
+ logger.error("Can't find the owner for this packet. Discarding.")
+
+ for key in deletion_list:
+ if key in self.sessions:
+ self.sessions[key].end()
+ metrics = self.sessions[key].metrics
+ if metrics.duration == 0:
+ logger.info("Duration too short, rate undetermined")
+ else:
+ logger.info("Transferred %d bytes in %.2f seconds" % (metrics.bytes, metrics.duration))
+ logger.info("Average rate: %.2f kbps" % metrics.kbps)
+ logger.info("%.2f bytes in resent data" % metrics.resent_bytes)
+ logger.info("%d duplicate packets" % metrics.dupcount)
+ del self.sessions[key]
+
+ self.is_running.clear()
+ logger.debug("Server returning from while loop")
+ self.shutdown_gracefully = self.shutdown_immediately = False
+
+ def stop(self, now=False):
+ """
+ Stop the server gracefully. Do not take any new transfers, but complete the existing ones.
+ """
+ if now:
+ self.shutdown_immediately = True
+ else:
+ self.shutdown_gracefully = True
diff --git a/blcu-programming/tftp/TftpClient.py b/blcu-programming/tftp/TftpClient.py
new file mode 100644
index 000000000..b50b6953a
--- /dev/null
+++ b/blcu-programming/tftp/TftpClient.py
@@ -0,0 +1,131 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module implements the TFTP Client functionality. Instantiate an
+instance of the client, and then use its upload or download method. Logging is
+performed via a standard logging object set in TftpShared."""
+
+
+import io
+import types
+import logging
+from .TftpShared import *
+from .TftpPacketTypes import *
+from .TftpContexts import TftpContextClientDownload, TftpContextClientUpload
+
+log = logging.getLogger('tftpy.TftpClient')
+
+class TftpClient(TftpSession):
+ """This class is an implementation of a tftp client. Once instantiated, a
+ download can be initiated via the download() method, or an upload via the
+ upload() method."""
+
+ def __init__(self, host, port=69, options={}, localip = ""):
+ TftpSession.__init__(self)
+ self.context = None
+ self.host = host
+ self.iport = port
+ self.filename = None
+ self.options = options
+ self.localip = localip
+ if 'blksize' in self.options:
+ size = self.options['blksize']
+ tftpassert(int == type(size), "blksize must be an int")
+ if size < MIN_BLKSIZE or size > MAX_BLKSIZE:
+ raise TftpException("Invalid blksize: %d" % size)
+
+ def download(self, filename, output, packethook=None, timeout=SOCK_TIMEOUT, retries=DEF_TIMEOUT_RETRIES):
+ """This method initiates a tftp download from the configured remote
+ host, requesting the filename passed. It writes the file to output,
+ which can be a file-like object or a path to a local file. If a
+ packethook is provided, it must be a function that takes a single
+ parameter, which will be a copy of each DAT packet received in the
+ form of a TftpPacketDAT object. The timeout parameter may be used to
+ override the default SOCK_TIMEOUT setting, which is the amount of time
+ that the client will wait for a receive packet to arrive.
+ The retires paramater may be used to override the default DEF_TIMEOUT_RETRIES
+ settings, which is the amount of retransmission attemtpts the client will initiate
+ after encountering a timeout.
+
+ Note: If output is a hyphen, stdout is used."""
+ # We're downloading.
+ log.debug("Creating download context with the following params:")
+ log.debug("host = %s, port = %s, filename = %s" % (self.host, self.iport, filename))
+ log.debug("options = %s, packethook = %s, timeout = %s" % (self.options, packethook, timeout))
+ self.context = TftpContextClientDownload(self.host,
+ self.iport,
+ filename,
+ output,
+ self.options,
+ packethook,
+ timeout,
+ retries=retries,
+ localip=self.localip)
+ self.context.start()
+ # Download happens here
+ self.context.end()
+
+ metrics = self.context.metrics
+
+ log.info('')
+ log.info("Download complete.")
+ if metrics.duration == 0:
+ log.info("Duration too short, rate undetermined")
+ else:
+ log.info("Downloaded %.2f bytes in %.2f seconds" % (metrics.bytes, metrics.duration))
+ log.info("Average rate: %.2f kbps" % metrics.kbps)
+ log.info("%.2f bytes in resent data" % metrics.resent_bytes)
+ log.info("Received %d duplicate packets" % metrics.dupcount)
+ def get_file_size(self, filename):
+ """Simulate a request to get the file size from the server."""
+ # Create a request for the file
+ try:
+ # Here you would typically send a request to the server to check if the file exists
+ # Since TFTP doesn't support file size queries, we can simply perform a download in a way
+ # that we can track the size without saving the file, just for demonstration.
+ output = io.BytesIO() # Use a BytesIO object to avoid writing to disk
+ self.download(filename, output)
+
+ # Get the size of the downloaded data
+ return output.getbuffer().nbytes
+
+ except Exception as e:
+ log.error(f"Failed to get file size: {str(e)}")
+ return -1 # Return -1 or another sentinel value to indicate an error
+ def upload(self, filename, input, packethook=None, timeout=SOCK_TIMEOUT, retries=DEF_TIMEOUT_RETRIES):
+ """This method initiates a tftp upload to the configured remote host,
+ uploading the filename passed. It reads the file from input, which
+ can be a file-like object or a path to a local file. If a packethook
+ is provided, it must be a function that takes a single parameter,
+ which will be a copy of each DAT packet sent in the form of a
+ TftpPacketDAT object. The timeout parameter may be used to override
+ the default SOCK_TIMEOUT setting, which is the amount of time that
+ the client will wait for a DAT packet to be ACKd by the server.
+ The retires paramater may be used to override the default DEF_TIMEOUT_RETRIES
+ settings, which is the amount of retransmission attemtpts the client will initiate
+ after encountering a timeout.
+
+ Note: If input is a hyphen, stdin is used."""
+ self.context = TftpContextClientUpload(self.host,
+ self.iport,
+ filename,
+ input,
+ self.options,
+ packethook,
+ timeout,
+ retries=retries,
+ localip=self.localip)
+ self.context.start()
+ # Upload happens here
+ self.context.end()
+
+ metrics = self.context.metrics
+
+ log.info('')
+ log.info("Upload complete.")
+ if metrics.duration == 0:
+ log.info("Duration too short, rate undetermined")
+ else:
+ log.info("Uploaded %d bytes in %.2f seconds" % (metrics.bytes, metrics.duration))
+ log.info("Average rate: %.2f kbps" % metrics.kbps)
+ log.info("%.2f bytes in resent data" % metrics.resent_bytes)
+ log.info("Resent %d packets" % metrics.dupcount)
diff --git a/blcu-programming/tftp/TftpContexts.py b/blcu-programming/tftp/TftpContexts.py
new file mode 100644
index 000000000..f01509eee
--- /dev/null
+++ b/blcu-programming/tftp/TftpContexts.py
@@ -0,0 +1,437 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module implements all contexts for state handling during uploads and
+downloads, the main interface to which being the TftpContext base class.
+
+The concept is simple. Each context object represents a single upload or
+download, and the state object in the context object represents the current
+state of that transfer. The state object has a handle() method that expects
+the next packet in the transfer, and returns a state object until the transfer
+is complete, at which point it returns None. That is, unless there is a fatal
+error, in which case a TftpException is returned instead."""
+
+
+from .TftpShared import *
+from .TftpPacketTypes import *
+from .TftpPacketFactory import TftpPacketFactory
+from .TftpStates import *
+from . import compat
+import socket
+import time
+import sys
+import os
+import logging
+
+log = logging.getLogger('tftpy.TftpContext')
+
+###############################################################################
+# Utility classes
+###############################################################################
+
+class TftpMetrics(object):
+ """A class representing metrics of the transfer."""
+ def __init__(self):
+ # Bytes transferred
+ self.bytes = 0
+ # Bytes re-sent
+ self.resent_bytes = 0
+ # Duplicate packets received
+ self.dups = {}
+ self.dupcount = 0
+ # Times
+ self.start_time = 0
+ self.end_time = 0
+ self.duration = 0
+ # Rates
+ self.bps = 0
+ self.kbps = 0
+ # Generic errors
+ self.errors = 0
+
+ def compute(self):
+ # Compute transfer time
+ self.duration = self.end_time - self.start_time
+ if self.duration == 0:
+ self.duration = 1
+ log.debug("TftpMetrics.compute: duration is %s", self.duration)
+ self.bps = (self.bytes * 8.0) / self.duration
+ self.kbps = self.bps / 1024.0
+ log.debug("TftpMetrics.compute: kbps is %s", self.kbps)
+ for key in self.dups:
+ self.dupcount += self.dups[key]
+
+ def add_dup(self, pkt):
+ """This method adds a dup for a packet to the metrics."""
+ log.debug("Recording a dup of %s", pkt)
+ s = str(pkt)
+ if s in self.dups:
+ self.dups[s] += 1
+ else:
+ self.dups[s] = 1
+ tftpassert(self.dups[s] < MAX_DUPS, "Max duplicates reached")
+
+###############################################################################
+# Context classes
+###############################################################################
+
+class TftpContext(object):
+ """The base class of the contexts."""
+
+ def __init__(self, host, port, timeout, retries=DEF_TIMEOUT_RETRIES, localip = ""):
+ """Constructor for the base context, setting shared instance
+ variables."""
+ self.file_to_transfer = None
+ self.fileobj = None
+ self.options = None
+ self.packethook = None
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ if localip != "":
+ self.sock.bind((localip, 0))
+ self.sock.settimeout(timeout)
+ self.timeout = timeout
+ self.retries = retries
+ self.state = None
+ self.next_block = 0
+ self.factory = TftpPacketFactory()
+ # Note, setting the host will also set self.address, as it's a property.
+ self.host = host
+ self.port = port
+ # The port associated with the TID
+ self.tidport = None
+ # Metrics
+ self.metrics = TftpMetrics()
+ # Fluag when the transfer is pending completion.
+ self.pending_complete = False
+ # Time when this context last received any traffic.
+ # FIXME: does this belong in metrics?
+ self.last_update = 0
+ # The last packet we sent, if applicable, to make resending easy.
+ self.last_pkt = None
+ # Count the number of retry attempts.
+ self.retry_count = 0
+
+ def getBlocksize(self):
+ """Fetch the current blocksize for this session."""
+ return int(self.options.get('blksize', 512))
+
+ def __del__(self):
+ """Simple destructor to try to call housekeeping in the end method if
+ not called explicitely. Leaking file descriptors is not a good
+ thing."""
+ self.end()
+
+ def checkTimeout(self, now):
+ """Compare current time with last_update time, and raise an exception
+ if we're over the timeout time."""
+ log.debug("checking for timeout on session %s", self)
+ if now - self.last_update > self.timeout:
+ raise TftpTimeout("Timeout waiting for traffic")
+
+ def start(self):
+ raise NotImplementedError("Abstract method")
+
+ def end(self, close_fileobj=True):
+ """Perform session cleanup, since the end method should always be
+ called explicitely by the calling code, this works better than the
+ destructor.
+ Set close_fileobj to False so fileobj can be returned open."""
+ log.debug("in TftpContext.end - closing socket")
+ self.sock.close()
+ if close_fileobj and self.fileobj is not None and not self.fileobj.closed:
+ log.debug("self.fileobj is open - closing")
+ self.fileobj.close()
+
+ def gethost(self):
+ "Simple getter method for use in a property."
+ return self.__host
+
+ def sethost(self, host):
+ """Setter method that also sets the address property as a result
+ of the host that is set."""
+ self.__host = host
+ self.address = socket.gethostbyname(host)
+
+ host = property(gethost, sethost)
+
+ def setNextBlock(self, block):
+ if block >= 2 ** 16:
+ log.debug("Block number rollover to 0 again")
+ block = 0
+ self.__eblock = block
+
+ def getNextBlock(self):
+ return self.__eblock
+
+ next_block = property(getNextBlock, setNextBlock)
+
+ def cycle(self):
+ """Here we wait for a response from the server after sending it
+ something, and dispatch appropriate action to that response."""
+ try:
+ (buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE)
+ except socket.timeout:
+ log.warning("Timeout waiting for traffic, retrying...")
+ raise TftpTimeout("Timed-out waiting for traffic")
+
+ # Ok, we've received a packet. Log it.
+ log.debug("Received %d bytes from %s:%s",
+ len(buffer), raddress, rport)
+ # And update our last updated time.
+ self.last_update = time.time()
+
+ # Decode it.
+ recvpkt = self.factory.parse(buffer)
+
+ # Check for known "connection".
+ if raddress != self.address:
+ log.warning("Received traffic from %s, expected host %s. Discarding"
+ % (raddress, self.host))
+
+ if self.tidport and self.tidport != rport:
+ log.warning("Received traffic from %s:%s but we're "
+ "connected to %s:%s. Discarding."
+ % (raddress, rport,
+ self.host, self.tidport))
+
+ # If there is a packethook defined, call it. We unconditionally
+ # pass all packets, it's up to the client to screen out different
+ # kinds of packets. This way, the client is privy to things like
+ # negotiated options.
+ if self.packethook:
+ self.packethook(recvpkt)
+
+ # And handle it, possibly changing state.
+ self.state = self.state.handle(recvpkt, raddress, rport)
+ # If we didn't throw any exceptions here, reset the retry_count to
+ # zero.
+ self.retry_count = 0
+
+class TftpContextServer(TftpContext):
+ """The context for the server."""
+ def __init__(self,
+ host,
+ port,
+ timeout,
+ root,
+ dyn_file_func=None,
+ upload_open=None,
+ retries=DEF_TIMEOUT_RETRIES):
+ TftpContext.__init__(self,
+ host,
+ port,
+ timeout,
+ retries
+ )
+ # At this point we have no idea if this is a download or an upload. We
+ # need to let the start state determine that.
+ self.state = TftpStateServerStart(self)
+
+ self.root = root
+ self.dyn_file_func = dyn_file_func
+ self.upload_open = upload_open
+
+ def __str__(self):
+ return "%s:%s %s" % (self.host, self.port, self.state)
+
+ def start(self, buffer):
+ """Start the state cycle. Note that the server context receives an
+ initial packet in its start method. Also note that the server does not
+ loop on cycle(), as it expects the TftpServer object to manage
+ that."""
+ log.debug("In TftpContextServer.start")
+ self.metrics.start_time = time.time()
+ log.debug("Set metrics.start_time to %s", self.metrics.start_time)
+ # And update our last updated time.
+ self.last_update = time.time()
+
+ pkt = self.factory.parse(buffer)
+ log.debug("TftpContextServer.start() - factory returned a %s", pkt)
+
+ # Call handle once with the initial packet. This should put us into
+ # the download or the upload state.
+ self.state = self.state.handle(pkt,
+ self.host,
+ self.port)
+
+ def end(self):
+ """Finish up the context."""
+ TftpContext.end(self)
+ self.metrics.end_time = time.time()
+ log.debug("Set metrics.end_time to %s", self.metrics.end_time)
+ self.metrics.compute()
+
+class TftpContextClientUpload(TftpContext):
+ """The upload context for the client during an upload.
+ Note: If input is a hyphen, then we will use stdin."""
+ def __init__(self,
+ host,
+ port,
+ filename,
+ input,
+ options,
+ packethook,
+ timeout,
+ retries=DEF_TIMEOUT_RETRIES,
+ localip = ""):
+ TftpContext.__init__(self,
+ host,
+ port,
+ timeout,
+ retries,
+ localip)
+ self.file_to_transfer = filename
+ self.options = options
+ self.packethook = packethook
+ # If the input object has a read() function,
+ # assume it is file-like.
+ if hasattr(input, 'read'):
+ self.fileobj = input
+ elif input == '-':
+ self.fileobj = compat.binary_stdin()
+ else:
+ self.fileobj = open(input, "rb")
+
+ log.debug("TftpContextClientUpload.__init__()")
+ log.debug("file_to_transfer = %s, options = %s" %
+ (self.file_to_transfer, self.options))
+
+ def __str__(self):
+ return "%s:%s %s" % (self.host, self.port, self.state)
+
+ def start(self):
+ log.info("Sending tftp upload request to %s" % self.host)
+ log.info(" filename -> %s" % self.file_to_transfer)
+ log.info(" options -> %s" % self.options)
+
+ self.metrics.start_time = time.time()
+ log.debug("Set metrics.start_time to %s" % self.metrics.start_time)
+
+ # FIXME: put this in a sendWRQ method?
+ pkt = TftpPacketWRQ()
+ pkt.filename = self.file_to_transfer
+ pkt.mode = "octet" # FIXME - shouldn't hardcode this
+ pkt.options = self.options
+ self.sock.sendto(pkt.encode().buffer, (self.host, self.port))
+ self.next_block = 1
+ self.last_pkt = pkt
+ # FIXME: should we centralize sendto operations so we can refactor all
+ # saving of the packet to the last_pkt field?
+
+ self.state = TftpStateSentWRQ(self)
+
+ while self.state:
+ try:
+ log.debug("State is %s" % self.state)
+ self.cycle()
+ except TftpTimeout as err:
+ log.error(str(err))
+ self.retry_count += 1
+ if self.retry_count >= self.retries:
+ log.debug("hit max retries, giving up")
+ raise
+ else:
+ log.warning("resending last packet")
+ self.state.resendLast()
+
+ def end(self):
+ """Finish up the context."""
+ TftpContext.end(self)
+ self.metrics.end_time = time.time()
+ log.debug("Set metrics.end_time to %s" % self.metrics.end_time)
+ self.metrics.compute()
+
+
+class TftpContextClientDownload(TftpContext):
+ """The download context for the client during a download.
+ Note: If output is a hyphen, then the output will be sent to stdout."""
+ def __init__(self,
+ host,
+ port,
+ filename,
+ output,
+ options,
+ packethook,
+ timeout,
+ retries=DEF_TIMEOUT_RETRIES,
+ localip = ""):
+ TftpContext.__init__(self,
+ host,
+ port,
+ timeout,
+ retries,
+ localip)
+ # FIXME: should we refactor setting of these params?
+ self.file_to_transfer = filename
+ self.options = options
+ self.packethook = packethook
+ self.filelike_fileobj = False
+ # If the output object has a write() function,
+ # assume it is file-like.
+ if hasattr(output, 'write'):
+ self.fileobj = output
+ self.filelike_fileobj = True
+ # If the output filename is -, then use stdout
+ elif output == '-':
+ self.fileobj = sys.stdout
+ self.filelike_fileobj = True
+ else:
+ self.fileobj = open(output, "wb")
+
+ log.debug("TftpContextClientDownload.__init__()")
+ log.debug("file_to_transfer = %s, options = %s" %
+ (self.file_to_transfer, self.options))
+
+ def __str__(self):
+ return "%s:%s %s" % (self.host, self.port, self.state)
+
+ def start(self):
+ """Initiate the download."""
+ log.info("Sending tftp download request to %s" % self.host)
+ log.info(" filename -> %s" % self.file_to_transfer)
+ log.info(" options -> %s" % self.options)
+
+ self.metrics.start_time = time.time()
+ log.debug("Set metrics.start_time to %s" % self.metrics.start_time)
+
+ # FIXME: put this in a sendRRQ method?
+ pkt = TftpPacketRRQ()
+ pkt.filename = self.file_to_transfer
+ pkt.mode = "octet" # FIXME - shouldn't hardcode this
+ pkt.options = self.options
+ self.sock.sendto(pkt.encode().buffer, (self.host, self.port))
+ self.next_block = 1
+ self.last_pkt = pkt
+
+ self.state = TftpStateSentRRQ(self)
+
+ while self.state:
+ try:
+ log.debug("State is %s" % self.state)
+ self.cycle()
+ except TftpTimeout as err:
+ log.error(str(err))
+ self.retry_count += 1
+ if self.retry_count >= self.retries:
+ log.debug("hit max retries, giving up")
+ raise
+ else:
+ log.warning("resending last packet")
+ self.state.resendLast()
+ except TftpFileNotFoundError as err:
+ # If we received file not found, then we should not save the open
+ # output file or we'll be left with a size zero file. Delete it,
+ # if it exists.
+ log.error("Received File not found error")
+ if self.fileobj is not None and not self.filelike_fileobj:
+ if os.path.exists(self.fileobj.name):
+ log.debug("unlinking output file of %s", self.fileobj.name)
+ os.unlink(self.fileobj.name)
+
+ raise
+
+ def end(self):
+ """Finish up the context."""
+ TftpContext.end(self, not self.filelike_fileobj)
+ self.metrics.end_time = time.time()
+ log.debug("Set metrics.end_time to %s" % self.metrics.end_time)
+ self.metrics.compute()
diff --git a/blcu-programming/tftp/TftpPacketFactory.py b/blcu-programming/tftp/TftpPacketFactory.py
new file mode 100644
index 000000000..41f39a9e2
--- /dev/null
+++ b/blcu-programming/tftp/TftpPacketFactory.py
@@ -0,0 +1,47 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module implements the TftpPacketFactory class, which can take a binary
+buffer, and return the appropriate TftpPacket object to represent it, via the
+parse() method."""
+
+
+from .TftpShared import *
+from .TftpPacketTypes import *
+import logging
+
+log = logging.getLogger('tftpy.TftpPacketFactory')
+
+class TftpPacketFactory(object):
+ """This class generates TftpPacket objects. It is responsible for parsing
+ raw buffers off of the wire and returning objects representing them, via
+ the parse() method."""
+ def __init__(self):
+ self.classes = {
+ 1: TftpPacketRRQ,
+ 2: TftpPacketWRQ,
+ 3: TftpPacketDAT,
+ 4: TftpPacketACK,
+ 5: TftpPacketERR,
+ 6: TftpPacketOACK
+ }
+
+ def parse(self, buffer):
+ """This method is used to parse an existing datagram into its
+ corresponding TftpPacket object. The buffer is the raw bytes off of
+ the network."""
+ log.debug("parsing a %d byte packet" % len(buffer))
+ (opcode,) = struct.unpack(str("!H"), buffer[:2])
+ log.debug("opcode is %d" % opcode)
+ packet = self.__create(opcode)
+ packet.buffer = buffer
+ return packet.decode()
+
+ def __create(self, opcode):
+ """This method returns the appropriate class object corresponding to
+ the passed opcode."""
+ tftpassert(opcode in self.classes,
+ "Unsupported opcode: %d" % opcode)
+
+ packet = self.classes[opcode]()
+
+ return packet
diff --git a/blcu-programming/tftp/TftpPacketTypes.py b/blcu-programming/tftp/TftpPacketTypes.py
new file mode 100644
index 000000000..3d3bdf83c
--- /dev/null
+++ b/blcu-programming/tftp/TftpPacketTypes.py
@@ -0,0 +1,494 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module implements the packet types of TFTP itself, and the
+corresponding encode and decode methods for them."""
+
+
+import struct
+import sys
+import logging
+from .TftpShared import *
+
+log = logging.getLogger('tftpy.TftpPacketTypes')
+
+class TftpSession(object):
+ """This class is the base class for the tftp client and server. Any shared
+ code should be in this class."""
+ # FIXME: do we need this anymore?
+ pass
+
+class TftpPacketWithOptions(object):
+ """This class exists to permit some TftpPacket subclasses to share code
+ regarding options handling. It does not inherit from TftpPacket, as the
+ goal is just to share code here, and not cause diamond inheritance."""
+
+ def __init__(self):
+ self.options = {}
+
+ # Always use unicode strings, except at the encode/decode barrier.
+ # Simpler to keep things clear.
+ def setoptions(self, options):
+ log.debug("in TftpPacketWithOptions.setoptions")
+ log.debug("options: %s", options)
+ myoptions = {}
+ for key in options:
+ newkey = key
+ if isinstance(key, bytes):
+ newkey = newkey.decode('ascii')
+ newval = options[key]
+ if isinstance(newval, bytes):
+ newval = newval.decode('ascii')
+ myoptions[newkey] = newval
+ log.debug("populated myoptions with %s = %s", newkey, myoptions[newkey])
+
+ log.debug("setting options hash to: %s", myoptions)
+ self._options = myoptions
+
+ def getoptions(self):
+ log.debug("in TftpPacketWithOptions.getoptions")
+ return self._options
+
+ # Set up getter and setter on options to ensure that they are the proper
+ # type. They should always be strings, but we don't need to force the
+ # client to necessarily enter strings if we can avoid it.
+ options = property(getoptions, setoptions)
+
+ def decode_options(self, buffer):
+ """This method decodes the section of the buffer that contains an
+ unknown number of options. It returns a dictionary of option names and
+ values."""
+ fmt = b"!"
+ options = {}
+
+ log.debug("decode_options: buffer is: %s", repr(buffer))
+ log.debug("size of buffer is %d bytes", len(buffer))
+ if len(buffer) == 0:
+ log.debug("size of buffer is zero, returning empty hash")
+ return {}
+
+ # Count the nulls in the buffer. Each one terminates a string.
+ log.debug("about to iterate options buffer counting nulls")
+ length = 0
+ for i in range(len(buffer)):
+ if ord(buffer[i:i+1]) == 0:
+ log.debug("found a null at length %d", length)
+ if length > 0:
+ fmt += b"%dsx" % length
+ length = -1
+ else:
+ raise TftpException("Invalid options in buffer")
+ length += 1
+
+ log.debug("about to unpack, fmt is: %s", fmt)
+ mystruct = struct.unpack(fmt, buffer)
+
+ tftpassert(len(mystruct) % 2 == 0,
+ "packet with odd number of option/value pairs")
+
+ for i in range(0, len(mystruct), 2):
+ key = mystruct[i].decode('ascii')
+ val = mystruct[i+1].decode('ascii')
+ log.debug("setting option %s to %s", key, val)
+ log.debug("types are %s and %s", type(key), type(val))
+ options[key] = val
+
+ return options
+
+class TftpPacket(object):
+ """This class is the parent class of all tftp packet classes. It is an
+ abstract class, providing an interface, and should not be instantiated
+ directly."""
+ def __init__(self):
+ self.opcode = 0
+ self.buffer = None
+
+ def encode(self):
+ """The encode method of a TftpPacket takes keyword arguments specific
+ to the type of packet, and packs an appropriate buffer in network-byte
+ order suitable for sending over the wire.
+
+ This is an abstract method."""
+ raise NotImplementedError("Abstract method")
+
+ def decode(self):
+ """The decode method of a TftpPacket takes a buffer off of the wire in
+ network-byte order, and decodes it, populating internal properties as
+ appropriate. This can only be done once the first 2-byte opcode has
+ already been decoded, but the data section does include the entire
+ datagram.
+
+ This is an abstract method."""
+ raise NotImplementedError("Abstract method")
+
+class TftpPacketInitial(TftpPacket, TftpPacketWithOptions):
+ """This class is a common parent class for the RRQ and WRQ packets, as
+ they share quite a bit of code."""
+ def __init__(self):
+ TftpPacket.__init__(self)
+ TftpPacketWithOptions.__init__(self)
+ self.filename = None
+ self.mode = None
+
+ def encode(self):
+ """Encode the packet's buffer from the instance variables."""
+ tftpassert(self.filename, "filename required in initial packet")
+ tftpassert(self.mode, "mode required in initial packet")
+ # Make sure filename and mode are bytestrings.
+ filename = self.filename
+ mode = self.mode
+ if not isinstance(filename, bytes):
+ filename = filename.encode('ascii')
+ if not isinstance(self.mode, bytes):
+ mode = mode.encode('ascii')
+
+ ptype = None
+ if self.opcode == 1: ptype = "RRQ"
+ else: ptype = "WRQ"
+ log.debug("Encoding %s packet, filename = %s, mode = %s",
+ ptype, filename, mode)
+ for key in self.options:
+ log.debug(" Option %s = %s", key, self.options[key])
+
+ fmt = b"!H"
+ fmt += b"%dsx" % len(filename)
+ if mode == b"octet":
+ fmt += b"5sx"
+ else:
+ raise AssertionError("Unsupported mode: %s" % mode)
+ # Add options. Note that the options list must be bytes.
+ options_list = []
+ if len(list(self.options.keys())) > 0:
+ log.debug("there are options to encode")
+ for key in self.options:
+ # Populate the option name
+ name = key
+ if not isinstance(name, bytes):
+ name = name.encode('ascii')
+ options_list.append(name)
+ fmt += b"%dsx" % len(name)
+ # Populate the option value
+ value = self.options[key]
+ # Work with all strings.
+ if isinstance(value, int):
+ value = str(value)
+ if not isinstance(value, bytes):
+ value = value.encode('ascii')
+ options_list.append(value)
+ fmt += b"%dsx" % len(value)
+
+ log.debug("fmt is %s", fmt)
+ log.debug("options_list is %s", options_list)
+ log.debug("size of struct is %d", struct.calcsize(fmt))
+
+ self.buffer = struct.pack(fmt,
+ self.opcode,
+ filename,
+ mode,
+ *options_list)
+
+ log.debug("buffer is %s", repr(self.buffer))
+ return self
+
+ def decode(self):
+ tftpassert(self.buffer, "Can't decode, buffer is empty")
+
+ # FIXME - this shares a lot of code with decode_options
+ nulls = 0
+ fmt = b""
+ nulls = length = tlength = 0
+ log.debug("in decode: about to iterate buffer counting nulls")
+ subbuf = self.buffer[2:]
+ for i in range(len(subbuf)):
+ if ord(subbuf[i:i+1]) == 0:
+ nulls += 1
+ log.debug("found a null at length %d, now have %d", length, nulls)
+ fmt += b"%dsx" % length
+ length = -1
+ # At 2 nulls, we want to mark that position for decoding.
+ if nulls == 2:
+ break
+ length += 1
+ tlength += 1
+
+ log.debug("hopefully found end of mode at length %d", tlength)
+ # length should now be the end of the mode.
+ tftpassert(nulls == 2, "malformed packet")
+ shortbuf = subbuf[:tlength+1]
+ log.debug("about to unpack buffer with fmt: %s", fmt)
+ log.debug("unpacking buffer: %s", repr(shortbuf))
+ mystruct = struct.unpack(fmt, shortbuf)
+
+ tftpassert(len(mystruct) == 2, "malformed packet")
+ self.filename = mystruct[0].decode('ascii')
+ self.mode = mystruct[1].decode('ascii').lower() # force lc - bug 17
+ log.debug("set filename to %s", self.filename)
+ log.debug("set mode to %s", self.mode)
+
+ self.options = self.decode_options(subbuf[tlength+1:])
+ log.debug("options dict is now %s", self.options)
+ return self
+
+class TftpPacketRRQ(TftpPacketInitial):
+ """
+::
+
+ 2 bytes string 1 byte string 1 byte
+ -----------------------------------------------
+ RRQ/ | 01/02 | Filename | 0 | Mode | 0 |
+ WRQ -----------------------------------------------
+ """
+ def __init__(self):
+ TftpPacketInitial.__init__(self)
+ self.opcode = 1
+
+ def __str__(self):
+ s = 'RRQ packet: filename = %s' % self.filename
+ s += ' mode = %s' % self.mode
+ if self.options:
+ s += '\n options = %s' % self.options
+ return s
+
+class TftpPacketWRQ(TftpPacketInitial):
+ """
+::
+
+ 2 bytes string 1 byte string 1 byte
+ -----------------------------------------------
+ RRQ/ | 01/02 | Filename | 0 | Mode | 0 |
+ WRQ -----------------------------------------------
+ """
+ def __init__(self):
+ TftpPacketInitial.__init__(self)
+ self.opcode = 2
+
+ def __str__(self):
+ s = 'WRQ packet: filename = %s' % self.filename
+ s += ' mode = %s' % self.mode
+ if self.options:
+ s += '\n options = %s' % self.options
+ return s
+
+class TftpPacketDAT(TftpPacket):
+ """
+::
+
+ 2 bytes 2 bytes n bytes
+ ---------------------------------
+ DATA | 03 | Block # | Data |
+ ---------------------------------
+ """
+ def __init__(self):
+ TftpPacket.__init__(self)
+ self.opcode = 3
+ self.blocknumber = 0
+ self.data = None
+
+ def __str__(self):
+ s = 'DAT packet: block %s' % self.blocknumber
+ if self.data:
+ s += '\n data: %d bytes' % len(self.data)
+ return s
+
+ def encode(self):
+ """Encode the DAT packet. This method populates self.buffer, and
+ returns self for easy method chaining."""
+ if len(self.data) == 0:
+ log.debug("Encoding an empty DAT packet")
+ data = self.data
+ if not isinstance(self.data, bytes):
+ data = self.data.encode('ascii')
+ fmt = b"!HH%ds" % len(data)
+ self.buffer = struct.pack(fmt,
+ self.opcode,
+ self.blocknumber,
+ data)
+ return self
+
+ def decode(self):
+ """Decode self.buffer into instance variables. It returns self for
+ easy method chaining."""
+ # We know the first 2 bytes are the opcode. The second two are the
+ # block number.
+ (self.blocknumber,) = struct.unpack(str("!H"), self.buffer[2:4])
+ log.debug("decoding DAT packet, block number %d", self.blocknumber)
+ log.debug("should be %d bytes in the packet total", len(self.buffer))
+ # Everything else is data.
+ self.data = self.buffer[4:]
+ log.debug("found %d bytes of data", len(self.data))
+ return self
+
+class TftpPacketACK(TftpPacket):
+ """
+::
+
+ 2 bytes 2 bytes
+ -------------------
+ ACK | 04 | Block # |
+ --------------------
+ """
+ def __init__(self):
+ TftpPacket.__init__(self)
+ self.opcode = 4
+ self.blocknumber = 0
+
+ def __str__(self):
+ return 'ACK packet: block %d' % self.blocknumber
+
+ def encode(self):
+ log.debug("encoding ACK: opcode = %d, block = %d",
+ self.opcode, self.blocknumber)
+ self.buffer = struct.pack(str("!HH"), self.opcode, self.blocknumber)
+ return self
+
+ def decode(self):
+ if len(self.buffer) > 4:
+ log.debug("detected TFTP ACK but request is too large, will truncate")
+ log.debug("buffer was: %s", repr(self.buffer))
+ self.buffer = self.buffer[0:4]
+ self.opcode, self.blocknumber = struct.unpack(str("!HH"), self.buffer)
+ log.debug("decoded ACK packet: opcode = %d, block = %d",
+ self.opcode, self.blocknumber)
+ return self
+
+class TftpPacketERR(TftpPacket):
+ """
+::
+
+ 2 bytes 2 bytes string 1 byte
+ ----------------------------------------
+ ERROR | 05 | ErrorCode | ErrMsg | 0 |
+ ----------------------------------------
+
+ Error Codes
+
+ Value Meaning
+
+ 0 Not defined, see error message (if any).
+ 1 File not found.
+ 2 Access violation.
+ 3 Disk full or allocation exceeded.
+ 4 Illegal TFTP operation.
+ 5 Unknown transfer ID.
+ 6 File already exists.
+ 7 No such user.
+ 8 Failed to negotiate options
+ """
+ def __init__(self):
+ TftpPacket.__init__(self)
+ self.opcode = 5
+ self.errorcode = 0
+ # FIXME: We don't encode the errmsg...
+ self.errmsg = None
+ # FIXME - integrate in TftpErrors references?
+ self.errmsgs = {
+ 1: b"File not found",
+ 2: b"Access violation",
+ 3: b"Disk full or allocation exceeded",
+ 4: b"Illegal TFTP operation",
+ 5: b"Unknown transfer ID",
+ 6: b"File already exists",
+ 7: b"No such user",
+ 8: b"Failed to negotiate options"
+ }
+
+ def __str__(self):
+ s = 'ERR packet: errorcode = %d' % self.errorcode
+ s += '\n msg = %s' % self.errmsgs.get(self.errorcode, '')
+ return s
+
+ def encode(self):
+ """Encode the DAT packet based on instance variables, populating
+ self.buffer, returning self."""
+ fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode])
+ log.debug("encoding ERR packet with fmt %s", fmt)
+ self.buffer = struct.pack(fmt,
+ self.opcode,
+ self.errorcode,
+ self.errmsgs[self.errorcode])
+ return self
+
+ def decode(self):
+ "Decode self.buffer, populating instance variables and return self."
+ buflen = len(self.buffer)
+ tftpassert(buflen >= 4, "malformed ERR packet, too short")
+ log.debug("Decoding ERR packet, length %s bytes", buflen)
+ if buflen == 4:
+ log.debug("Allowing this affront to the RFC of a 4-byte packet")
+ fmt = b"!HH"
+ log.debug("Decoding ERR packet with fmt: %s", fmt)
+ self.opcode, self.errorcode = struct.unpack(fmt,
+ self.buffer)
+ else:
+ log.debug("Good ERR packet > 4 bytes")
+ fmt = b"!HH%dsx" % (len(self.buffer) - 5)
+ log.debug("Decoding ERR packet with fmt: %s", fmt)
+ self.opcode, self.errorcode, self.errmsg = struct.unpack(fmt,
+ self.buffer)
+ log.error("ERR packet - errorcode: %d, message: %s"
+ % (self.errorcode, self.errmsg))
+ return self
+
+class TftpPacketOACK(TftpPacket, TftpPacketWithOptions):
+ """
+::
+
+ +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
+ | opc | opt1 | 0 | value1 | 0 | optN | 0 | valueN | 0 |
+ +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+
+ """
+ def __init__(self):
+ TftpPacket.__init__(self)
+ TftpPacketWithOptions.__init__(self)
+ self.opcode = 6
+
+ def __str__(self):
+ return 'OACK packet:\n options = %s' % self.options
+
+ def encode(self):
+ fmt = b"!H" # opcode
+ options_list = []
+ log.debug("in TftpPacketOACK.encode")
+ for key in self.options:
+ value = self.options[key]
+ if isinstance(value, int):
+ value = str(value)
+ if not isinstance(key, bytes):
+ key = key.encode('ascii')
+ if not isinstance(value, bytes):
+ value = value.encode('ascii')
+ log.debug("looping on option key %s", key)
+ log.debug("value is %s", value)
+ fmt += b"%dsx" % len(key)
+ fmt += b"%dsx" % len(value)
+ options_list.append(key)
+ options_list.append(value)
+ self.buffer = struct.pack(fmt, self.opcode, *options_list)
+ return self
+
+ def decode(self):
+ self.options = self.decode_options(self.buffer[2:])
+ return self
+
+ def match_options(self, options):
+ """This method takes a set of options, and tries to match them with
+ its own. It can accept some changes in those options from the server as
+ part of a negotiation. Changed or unchanged, it will return a dict of
+ the options so that the session can update itself to the negotiated
+ options."""
+ for name in self.options:
+ if name in options:
+ if name == 'blksize':
+ # We can accept anything between the min and max values.
+ size = int(self.options[name])
+ if size >= MIN_BLKSIZE and size <= MAX_BLKSIZE:
+ log.debug("negotiated blksize of %d bytes", size)
+ options['blksize'] = size
+ else:
+ raise TftpException("blksize %s option outside allowed range" % size)
+ elif name == 'tsize':
+ size = int(self.options[name])
+ if size < 0:
+ raise TftpException("Negative file sizes not supported")
+ else:
+ raise TftpException("Unsupported option: %s" % name)
+ return True
diff --git a/blcu-programming/tftp/TftpShared.py b/blcu-programming/tftp/TftpShared.py
new file mode 100644
index 000000000..ab37bde0a
--- /dev/null
+++ b/blcu-programming/tftp/TftpShared.py
@@ -0,0 +1,52 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module holds all objects shared by all other modules in tftpy."""
+
+
+
+MIN_BLKSIZE = 8
+DEF_BLKSIZE = 512
+MAX_BLKSIZE = 65536
+SOCK_TIMEOUT = 50
+MAX_DUPS = 20
+DEF_TIMEOUT_RETRIES = 3
+DEF_TFTP_PORT = 69
+
+# A hook for deliberately introducing delay in testing.
+DELAY_BLOCK = 0
+
+def tftpassert(condition, msg):
+ """This function is a simple utility that will check the condition
+ passed for a false state. If it finds one, it throws a TftpException
+ with the message passed. This just makes the code throughout cleaner
+ by refactoring."""
+ if not condition:
+ raise TftpException(msg)
+
+class TftpErrors(object):
+ """This class is a convenience for defining the common tftp error codes,
+ and making them more readable in the code."""
+ NotDefined = 0
+ FileNotFound = 1
+ AccessViolation = 2
+ DiskFull = 3
+ IllegalTftpOp = 4
+ UnknownTID = 5
+ FileAlreadyExists = 6
+ NoSuchUser = 7
+ FailedNegotiation = 8
+
+class TftpException(Exception):
+ """This class is the parent class of all exceptions regarding the handling
+ of the TFTP protocol."""
+ pass
+
+class TftpTimeout(TftpException):
+ """This class represents a timeout error waiting for a response from the
+ other end."""
+ pass
+
+class TftpFileNotFoundError(TftpException):
+ """This class represents an error condition where we received a file
+ not found error."""
+ pass
diff --git a/blcu-programming/tftp/TftpStates.py b/blcu-programming/tftp/TftpStates.py
new file mode 100644
index 000000000..231b1ce6b
--- /dev/null
+++ b/blcu-programming/tftp/TftpStates.py
@@ -0,0 +1,611 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""This module implements all state handling during uploads and downloads, the
+main interface to which being the TftpState base class.
+
+The concept is simple. Each context object represents a single upload or
+download, and the state object in the context object represents the current
+state of that transfer. The state object has a handle() method that expects
+the next packet in the transfer, and returns a state object until the transfer
+is complete, at which point it returns None. That is, unless there is a fatal
+error, in which case a TftpException is returned instead."""
+
+
+from .TftpShared import *
+from .TftpPacketTypes import *
+import os
+import logging
+
+log = logging.getLogger('tftpy.TftpStates')
+
+###############################################################################
+# State classes
+###############################################################################
+
+class TftpState(object):
+ """The base class for the states."""
+
+ def __init__(self, context):
+ """Constructor for setting up common instance variables. The involved
+ file object is required, since in tftp there's always a file
+ involved."""
+ self.context = context
+
+ def handle(self, pkt, raddress, rport):
+ """An abstract method for handling a packet. It is expected to return
+ a TftpState object, either itself or a new state."""
+ raise NotImplementedError("Abstract method")
+
+ def handleOACK(self, pkt):
+ """This method handles an OACK from the server, syncing any accepted
+ options."""
+ if len(pkt.options.keys()) > 0:
+ if pkt.match_options(self.context.options):
+ log.info("Successful negotiation of options")
+ # Set options to OACK options
+ self.context.options = pkt.options
+ for key in self.context.options:
+ log.info(" %s = %s" % (key, self.context.options[key]))
+ else:
+ log.error("Failed to negotiate options")
+ raise TftpException("Failed to negotiate options")
+ else:
+ raise TftpException("No options found in OACK")
+
+ def returnSupportedOptions(self, options):
+ """This method takes a requested options list from a client, and
+ returns the ones that are supported."""
+ # We support the options blksize and tsize right now.
+ # FIXME - put this somewhere else?
+ accepted_options = {}
+ for option in options:
+ if option == 'blksize':
+ # Make sure it's valid.
+ if int(options[option]) > MAX_BLKSIZE:
+ log.info("Client requested blksize greater than %d "
+ "setting to maximum" % MAX_BLKSIZE)
+ accepted_options[option] = MAX_BLKSIZE
+ elif int(options[option]) < MIN_BLKSIZE:
+ log.info("Client requested blksize less than %d "
+ "setting to minimum" % MIN_BLKSIZE)
+ accepted_options[option] = MIN_BLKSIZE
+ else:
+ accepted_options[option] = options[option]
+ elif option == 'tsize':
+ log.debug("tsize option is set")
+ accepted_options['tsize'] = 0
+ else:
+ log.info("Dropping unsupported option '%s'" % option)
+ log.debug("Returning these accepted options: %s", accepted_options)
+ return accepted_options
+
+ def sendDAT(self):
+ """This method sends the next DAT packet based on the data in the
+ context. It returns a boolean indicating whether the transfer is
+ finished."""
+ finished = False
+ blocknumber = self.context.next_block
+ # Test hook
+ if DELAY_BLOCK and DELAY_BLOCK == blocknumber:
+ import time
+ log.debug("Deliberately delaying 10 seconds...")
+ time.sleep(10)
+ dat = None
+ blksize = self.context.getBlocksize()
+ buffer = self.context.fileobj.read(blksize)
+ log.debug("Read %d bytes into buffer", len(buffer))
+ if len(buffer) < blksize:
+ log.info("Reached EOF on file %s"
+ % self.context.file_to_transfer)
+ finished = True
+ dat = TftpPacketDAT()
+ dat.data = buffer
+ dat.blocknumber = blocknumber
+ self.context.metrics.bytes += len(dat.data)
+ log.debug("Sending DAT packet %d", dat.blocknumber)
+ self.context.sock.sendto(dat.encode().buffer,
+ (self.context.host, self.context.tidport))
+ if self.context.packethook:
+ self.context.packethook(dat)
+ self.context.last_pkt = dat
+ return finished
+
+ def sendACK(self, blocknumber=None):
+ """This method sends an ack packet to the block number specified. If
+ none is specified, it defaults to the next_block property in the
+ parent context."""
+ log.debug("In sendACK, passed blocknumber is %s", blocknumber)
+ if blocknumber is None:
+ blocknumber = self.context.next_block
+ log.info("Sending ack to block %d" % blocknumber)
+ ackpkt = TftpPacketACK()
+ ackpkt.blocknumber = blocknumber
+ self.context.sock.sendto(ackpkt.encode().buffer,
+ (self.context.host,
+ self.context.tidport))
+ self.context.last_pkt = ackpkt
+
+ def sendError(self, errorcode):
+ """This method uses the socket passed, and uses the errorcode to
+ compose and send an error packet."""
+ log.debug("In sendError, being asked to send error %d", errorcode)
+ errpkt = TftpPacketERR()
+ errpkt.errorcode = errorcode
+ if self.context.tidport == None:
+ log.debug("Error packet received outside session. Discarding")
+ else:
+ self.context.sock.sendto(errpkt.encode().buffer,
+ (self.context.host,
+ self.context.tidport))
+ self.context.last_pkt = errpkt
+
+ def sendOACK(self):
+ """This method sends an OACK packet with the options from the current
+ context."""
+ log.debug("In sendOACK with options %s", self.context.options)
+ pkt = TftpPacketOACK()
+ pkt.options = self.context.options
+ self.context.sock.sendto(pkt.encode().buffer,
+ (self.context.host,
+ self.context.tidport))
+ self.context.last_pkt = pkt
+
+ def resendLast(self):
+ "Resend the last sent packet due to a timeout."
+ log.warning("Resending packet %s on sessions %s"
+ % (self.context.last_pkt, self))
+ self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer)
+ self.context.metrics.add_dup(self.context.last_pkt)
+ sendto_port = self.context.tidport
+ if not sendto_port:
+ # If the tidport wasn't set, then the remote end hasn't even
+ # started talking to us yet. That's not good. Maybe it's not
+ # there.
+ sendto_port = self.context.port
+ self.context.sock.sendto(self.context.last_pkt.encode().buffer,
+ (self.context.host, sendto_port))
+ if self.context.packethook:
+ self.context.packethook(self.context.last_pkt)
+
+ def handleDat(self, pkt):
+ """This method handles a DAT packet during a client download, or a
+ server upload."""
+ log.info("Handling DAT packet - block %d" % pkt.blocknumber)
+ log.debug("Expecting block %s", self.context.next_block)
+ if pkt.blocknumber == self.context.next_block:
+ log.debug("Good, received block %d in sequence", pkt.blocknumber)
+
+ self.sendACK()
+ self.context.next_block += 1
+
+ log.debug("Writing %d bytes to output file", len(pkt.data))
+ self.context.fileobj.write(pkt.data)
+ self.context.metrics.bytes += len(pkt.data)
+ # Check for end-of-file, any less than full data packet.
+ if len(pkt.data) < self.context.getBlocksize():
+ log.info("End of file detected")
+ return None
+
+ elif pkt.blocknumber < self.context.next_block:
+ if pkt.blocknumber == 0:
+ log.warning("There is no block zero!")
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("There is no block zero!")
+ log.warning("Dropping duplicate block %d" % pkt.blocknumber)
+ self.context.metrics.add_dup(pkt)
+ log.debug("ACKing block %d again, just in case", pkt.blocknumber)
+ self.sendACK(pkt.blocknumber)
+
+ else:
+ # FIXME: should we be more tolerant and just discard instead?
+ msg = "Whoa! Received future block %d but expected %d" \
+ % (pkt.blocknumber, self.context.next_block)
+ log.error(msg)
+ raise TftpException(msg)
+
+ # Default is to ack
+ return TftpStateExpectDAT(self.context)
+
+class TftpServerState(TftpState):
+ """The base class for server states."""
+
+ def __init__(self, context):
+ TftpState.__init__(self, context)
+
+ # This variable is used to store the absolute path to the file being
+ # managed.
+ self.full_path = None
+
+ def serverInitial(self, pkt, raddress, rport):
+ """This method performs initial setup for a server context transfer,
+ put here to refactor code out of the TftpStateServerRecvRRQ and
+ TftpStateServerRecvWRQ classes, since their initial setup is
+ identical. The method returns a boolean, sendoack, to indicate whether
+ it is required to send an OACK to the client."""
+ options = pkt.options
+ sendoack = False
+ if not self.context.tidport:
+ self.context.tidport = rport
+ log.info("Setting tidport to %s" % rport)
+
+ log.debug("Setting default options, blksize")
+ self.context.options = { 'blksize': DEF_BLKSIZE }
+
+ if options:
+ log.debug("Options requested: %s", options)
+ supported_options = self.returnSupportedOptions(options)
+ self.context.options.update(supported_options)
+ sendoack = True
+
+ # FIXME - only octet mode is supported at this time.
+ if pkt.mode != 'octet':
+ #self.sendError(TftpErrors.IllegalTftpOp)
+ #raise TftpException("Only octet transfers are supported at this time.")
+ log.warning("Received non-octet mode request. I'll reply with binary data.")
+
+ # test host/port of client end
+ if self.context.host != raddress or self.context.port != rport:
+ self.sendError(TftpErrors.UnknownTID)
+ log.error("Expected traffic from %s:%s but received it "
+ "from %s:%s instead."
+ % (self.context.host,
+ self.context.port,
+ raddress,
+ rport))
+ # FIXME: increment an error count?
+ # Return same state, we're still waiting for valid traffic.
+ return self
+
+ log.debug("Requested filename is %s", pkt.filename)
+
+ # Build the filename on this server and ensure it is contained
+ # in the specified root directory.
+ #
+ # Filenames that begin with server root are accepted. It's
+ # assumed the client and server are tightly connected and this
+ # provides backwards compatibility.
+ #
+ # Filenames otherwise are relative to the server root. If they
+ # begin with a '/' strip it off as otherwise os.path.join will
+ # treat it as absolute (regardless of whether it is ntpath or
+ # posixpath module
+ if pkt.filename.startswith(self.context.root):
+ full_path = pkt.filename
+ else:
+ full_path = os.path.join(self.context.root, pkt.filename.lstrip('/'))
+
+ # Use abspath to eliminate any remaining relative elements
+ # (e.g. '..') and ensure that is still within the server's
+ # root directory
+ self.full_path = os.path.abspath(full_path)
+ log.debug("full_path is %s", full_path)
+ if self.full_path.startswith(os.path.normpath(self.context.root) + os.sep):
+ log.info("requested file is in the server root - good")
+ else:
+ log.warning("requested file is not within the server root - bad")
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("bad file path")
+
+ self.context.file_to_transfer = pkt.filename
+
+ return sendoack
+
+
+class TftpStateServerRecvRRQ(TftpServerState):
+ """This class represents the state of the TFTP server when it has just
+ received an RRQ packet."""
+ def handle(self, pkt, raddress, rport):
+ "Handle an initial RRQ packet as a server."
+ log.debug("In TftpStateServerRecvRRQ.handle")
+ sendoack = self.serverInitial(pkt, raddress, rport)
+ path = self.full_path
+ log.info("Opening file %s for reading" % path)
+ if os.path.exists(path):
+ # Note: Open in binary mode for win32 portability, since win32
+ # blows.
+ self.context.fileobj = open(path, "rb")
+ elif self.context.dyn_file_func:
+ log.debug("No such file %s but using dyn_file_func", path)
+ self.context.fileobj = \
+ self.context.dyn_file_func(self.context.file_to_transfer, raddress=raddress, rport=rport)
+
+ if self.context.fileobj is None:
+ log.debug("dyn_file_func returned 'None', treating as "
+ "FileNotFound")
+ self.sendError(TftpErrors.FileNotFound)
+ raise TftpException("File not found: %s" % path)
+ else:
+ log.warning("File not found: %s", path)
+ self.sendError(TftpErrors.FileNotFound)
+ raise TftpException("File not found: {}".format(path))
+
+ # Options negotiation.
+ if sendoack and 'tsize' in self.context.options:
+ # getting the file size for the tsize option. As we handle
+ # file-like objects and not only real files, we use this seeking
+ # method instead of asking the OS
+ self.context.fileobj.seek(0, os.SEEK_END)
+ tsize = str(self.context.fileobj.tell())
+ self.context.fileobj.seek(0, 0)
+ self.context.options['tsize'] = tsize
+
+ if sendoack:
+ # Note, next_block is 0 here since that's the proper
+ # acknowledgement to an OACK.
+ # FIXME: perhaps we do need a TftpStateExpectOACK class...
+ self.sendOACK()
+ # Note, self.context.next_block is already 0.
+ else:
+ self.context.next_block = 1
+ log.debug("No requested options, starting send...")
+ self.context.pending_complete = self.sendDAT()
+ # Note, we expect an ack regardless of whether we sent a DAT or an
+ # OACK.
+ return TftpStateExpectACK(self.context)
+
+ # Note, we don't have to check any other states in this method, that's
+ # up to the caller.
+
+class TftpStateServerRecvWRQ(TftpServerState):
+ """This class represents the state of the TFTP server when it has just
+ received a WRQ packet."""
+ def make_subdirs(self):
+ """The purpose of this method is to, if necessary, create all of the
+ subdirectories leading up to the file to the written."""
+ # Pull off everything below the root.
+ subpath = self.full_path[len(self.context.root):]
+ log.debug("make_subdirs: subpath is %s", subpath)
+ # Split on directory separators, but drop the last one, as it should
+ # be the filename.
+ dirs = subpath.split(os.sep)[:-1]
+ log.debug("dirs is %s", dirs)
+ current = self.context.root
+ for dir in dirs:
+ if dir:
+ current = os.path.join(current, dir)
+ if os.path.isdir(current):
+ log.debug("%s is already an existing directory", current)
+ else:
+ os.mkdir(current, 0o700)
+
+ def handle(self, pkt, raddress, rport):
+ "Handle an initial WRQ packet as a server."
+ log.debug("In TftpStateServerRecvWRQ.handle")
+ sendoack = self.serverInitial(pkt, raddress, rport)
+ path = self.full_path
+ if self.context.upload_open:
+ f = self.context.upload_open(path, self.context)
+ if f is None:
+ self.sendError(TftpErrors.AccessViolation)
+ raise TftpException("Dynamic path %s not permitted" % path)
+ else:
+ self.context.fileobj = f
+ else:
+ log.debug("Opening file %s for writing" % path)
+ if os.path.exists(path):
+ # FIXME: correct behavior?
+ log.debug("File %s exists already, overwriting..." % (
+ self.context.file_to_transfer))
+ # FIXME: I think we should upload to a temp file and not overwrite
+ # the existing file until the file is successfully uploaded.
+ self.make_subdirs()
+ self.context.fileobj = open(path, "wb")
+
+ # Options negotiation.
+ if sendoack:
+ log.debug("Sending OACK to client")
+ self.sendOACK()
+ else:
+ log.debug("No requested options, expecting transfer to begin...")
+ self.sendACK()
+ # Whether we're sending an oack or not, we're expecting a DAT for
+ # block 1
+ self.context.next_block = 1
+ # We may have sent an OACK, but we're expecting a DAT as the response
+ # to either the OACK or an ACK, so lets unconditionally use the
+ # TftpStateExpectDAT state.
+ return TftpStateExpectDAT(self.context)
+
+ # Note, we don't have to check any other states in this method, that's
+ # up to the caller.
+
+class TftpStateServerStart(TftpState):
+ """The start state for the server. This is a transitory state since at
+ this point we don't know if we're handling an upload or a download. We
+ will commit to one of them once we interpret the initial packet."""
+ def handle(self, pkt, raddress, rport):
+ """Handle a packet we just received."""
+ log.debug("In TftpStateServerStart.handle")
+ if isinstance(pkt, TftpPacketRRQ):
+ log.debug("Handling an RRQ packet")
+ return TftpStateServerRecvRRQ(self.context).handle(pkt,
+ raddress,
+ rport)
+ elif isinstance(pkt, TftpPacketWRQ):
+ log.debug("Handling a WRQ packet")
+ return TftpStateServerRecvWRQ(self.context).handle(pkt,
+ raddress,
+ rport)
+ else:
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Invalid packet to begin up/download: %s" % pkt)
+
+class TftpStateExpectACK(TftpState):
+ """This class represents the state of the transfer when a DAT was just
+ sent, and we are waiting for an ACK from the server. This class is the
+ same one used by the client during the upload, and the server during the
+ download."""
+ def handle(self, pkt, raddress, rport):
+ "Handle a packet, hopefully an ACK since we just sent a DAT."
+ if isinstance(pkt, TftpPacketACK):
+ log.debug("Received ACK for packet %d" % pkt.blocknumber)
+ # Is this an ack to the one we just sent?
+ if self.context.next_block == pkt.blocknumber:
+ if self.context.pending_complete:
+ log.info("Received ACK to final DAT, we're done.")
+ return None
+ else:
+ log.debug("Good ACK, sending next DAT")
+ self.context.next_block += 1
+ log.debug("Incremented next_block to %d",
+ self.context.next_block)
+ self.context.pending_complete = self.sendDAT()
+
+ elif pkt.blocknumber < self.context.next_block:
+ log.warning("Received duplicate ACK for block %d"
+ % pkt.blocknumber)
+ self.context.metrics.add_dup(pkt)
+
+ else:
+ log.warning("Oooh, time warp. Received ACK to packet we "
+ "didn't send yet. Discarding.")
+ self.context.metrics.errors += 1
+ return self
+ elif isinstance(pkt, TftpPacketERR):
+ log.error("Received ERR packet from peer: %s" % str(pkt))
+ raise TftpException("Received ERR packet from peer: %s" % str(pkt))
+ else:
+ log.warning("Discarding unsupported packet: %s" % str(pkt))
+ return self
+
+class TftpStateExpectDAT(TftpState):
+ """Just sent an ACK packet. Waiting for DAT."""
+ def handle(self, pkt, raddress, rport):
+ """Handle the packet in response to an ACK, which should be a DAT."""
+ if isinstance(pkt, TftpPacketDAT):
+ return self.handleDat(pkt)
+
+ # Every other packet type is a problem.
+ elif isinstance(pkt, TftpPacketACK):
+ # Umm, we ACK, you don't.
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received ACK from peer when expecting DAT")
+
+ elif isinstance(pkt, TftpPacketWRQ):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received WRQ from peer when expecting DAT")
+
+ elif isinstance(pkt, TftpPacketERR):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received ERR from peer: " + str(pkt))
+
+ else:
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received unknown packet type from peer: " + str(pkt))
+
+class TftpStateSentWRQ(TftpState):
+ """Just sent an WRQ packet for an upload."""
+ def handle(self, pkt, raddress, rport):
+ """Handle a packet we just received."""
+ if not self.context.tidport:
+ self.context.tidport = rport
+ log.debug("Set remote port for session to %s", rport)
+
+ # If we're going to successfully transfer the file, then we should see
+ # either an OACK for accepted options, or an ACK to ignore options.
+ if isinstance(pkt, TftpPacketOACK):
+ log.info("Received OACK from server")
+ try:
+ self.handleOACK(pkt)
+ except TftpException:
+ log.error("Failed to negotiate options")
+ self.sendError(TftpErrors.FailedNegotiation)
+ raise
+ else:
+ log.debug("Sending first DAT packet")
+ self.context.pending_complete = self.sendDAT()
+ log.debug("Changing state to TftpStateExpectACK")
+ return TftpStateExpectACK(self.context)
+
+ elif isinstance(pkt, TftpPacketACK):
+ log.info("Received ACK from server")
+ log.debug("Apparently the server ignored our options")
+ # The block number should be zero.
+ if pkt.blocknumber == 0:
+ log.debug("Ack blocknumber is zero as expected")
+ log.debug("Sending first DAT packet")
+ self.context.pending_complete = self.sendDAT()
+ log.debug("Changing state to TftpStateExpectACK")
+ return TftpStateExpectACK(self.context)
+ else:
+ log.warning("Discarding ACK to block %s" % pkt.blocknumber)
+ log.debug("Still waiting for valid response from server")
+ return self
+
+ elif isinstance(pkt, TftpPacketERR):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received ERR from server: %s" % pkt)
+
+ elif isinstance(pkt, TftpPacketRRQ):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received RRQ from server while in upload")
+
+ elif isinstance(pkt, TftpPacketDAT):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received DAT from server while in upload")
+
+ else:
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received unknown packet type from server: %s" % pkt)
+
+ # By default, no state change.
+ return self
+
+class TftpStateSentRRQ(TftpState):
+ """Just sent an RRQ packet."""
+ def handle(self, pkt, raddress, rport):
+ """Handle the packet in response to an RRQ to the server."""
+ if not self.context.tidport:
+ self.context.tidport = rport
+ log.info("Set remote port for session to %s" % rport)
+
+ # Now check the packet type and dispatch it properly.
+ if isinstance(pkt, TftpPacketOACK):
+ log.info("Received OACK from server")
+ try:
+ self.handleOACK(pkt)
+ except TftpException as err:
+ log.error("Failed to negotiate options: %s" % str(err))
+ self.sendError(TftpErrors.FailedNegotiation)
+ raise
+ else:
+ log.debug("Sending ACK to OACK")
+
+ self.sendACK(blocknumber=0)
+
+ log.debug("Changing state to TftpStateExpectDAT")
+ return TftpStateExpectDAT(self.context)
+
+ elif isinstance(pkt, TftpPacketDAT):
+ # If there are any options set, then the server didn't honour any
+ # of them.
+ log.info("Received DAT from server")
+ if self.context.options:
+ log.info("Server ignored options, falling back to defaults")
+ self.context.options = { 'blksize': DEF_BLKSIZE }
+ return self.handleDat(pkt)
+
+ # Every other packet type is a problem.
+ elif isinstance(pkt, TftpPacketACK):
+ # Umm, we ACK, the server doesn't.
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received ACK from server while in download")
+
+ elif isinstance(pkt, TftpPacketWRQ):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received WRQ from server while in download")
+
+ elif isinstance(pkt, TftpPacketERR):
+ self.sendError(TftpErrors.IllegalTftpOp)
+ log.debug("Received ERR packet: %s", pkt)
+ if pkt.errorcode == TftpErrors.FileNotFound:
+ raise TftpFileNotFoundError("File not found")
+ else:
+ raise TftpException("Received ERR from server: {}".format(pkt))
+
+ else:
+ self.sendError(TftpErrors.IllegalTftpOp)
+ raise TftpException("Received unknown packet type from server: %s" % pkt)
+
+ # By default, no state change.
+ return self
diff --git a/blcu-programming/tftp/__init__.py b/blcu-programming/tftp/__init__.py
new file mode 100644
index 000000000..88a7f5d83
--- /dev/null
+++ b/blcu-programming/tftp/__init__.py
@@ -0,0 +1,13 @@
+# vim: ts=4 sw=4 et ai:
+# -*- coding: utf8 -*-
+"""
+This library implements the tftp protocol, based on rfc 1350.
+http://www.faqs.org/rfcs/rfc1350.html
+At the moment it implements only a client class, but will include a server,
+with support for variable block sizes.
+
+As a client of tftpy, this is the only module that you should need to import
+directly. The TftpClient and TftpServer classes can be reached through it.
+"""
+
+
diff --git a/blcu-programming/tftp/compat.py b/blcu-programming/tftp/compat.py
new file mode 100644
index 000000000..00493963c
--- /dev/null
+++ b/blcu-programming/tftp/compat.py
@@ -0,0 +1,15 @@
+import sys
+
+def binary_stdin():
+ """
+ Get a file object for reading binary bytes from stdin instead of text.
+ Compatible with Py2/3, POSIX & win32.
+ Credits: https://stackoverflow.com/a/38939320/531179 (CC BY-SA 3.0)
+ """
+ if hasattr(sys.stdin, 'buffer'): # Py3+
+ return sys.stdin.buffer
+ else:
+ if sys.platform == 'win32':
+ import os, msvcrt
+ msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
+ return sys.stdin
diff --git a/electron-app/main.js b/electron-app/main.js
index 39ff4fb6f..224aea7dd 100644
--- a/electron-app/main.js
+++ b/electron-app/main.js
@@ -10,6 +10,7 @@ import { getConfigManager } from "./src/config/configInstance.js";
import { setupIpcHandlers } from "./src/ipc/handlers.js";
import { startBackend, stopBackend } from "./src/processes/backend.js";
import { stopPacketSender } from "./src/processes/packetSender.js";
+import { startBlcuProgramming, stopBlcuProgramming } from "./src/processes/blcuProgramming.js";
import { logger } from "./src/utils/logger.js";
import { createLogWindow } from "./src/windows/logWindow.js";
import { createWindow } from "./src/windows/mainWindow.js";
@@ -42,6 +43,13 @@ app.whenReady().then(async () => {
// Start backend already shows these errors
}
+ try {
+ await startBlcuProgramming(logWindow);
+ logger.electron.header("BLCU programming process spawned");
+ } catch (error) {
+ logger.electron.error("Failed to start BLCU programming:", error);
+ }
+
// Create main application window
const mainWindow = createWindow(screenWidth, screenHeight);
mainWindow.maximize();
@@ -100,7 +108,7 @@ app.on("window-all-closed", () => {
// Cleanup before app quits
app.on("before-quit", (e) => {
e.preventDefault();
- Promise.all([stopBackend(), stopPacketSender()])
+ Promise.all([stopBackend(), stopPacketSender(), stopBlcuProgramming()])
.catch((error) => logger.electron.error("Error during shutdown:", error))
.finally(() => app.exit());
});
diff --git a/electron-app/src/processes/blcuProgramming.js b/electron-app/src/processes/blcuProgramming.js
new file mode 100644
index 000000000..1721db77b
--- /dev/null
+++ b/electron-app/src/processes/blcuProgramming.js
@@ -0,0 +1,83 @@
+import { spawn } from "child_process";
+import fs from "fs";
+import path from "path";
+import { logger } from "../utils/logger.js";
+import { getAppPath } from "../utils/paths.js";
+
+let blcuProgrammingProcess = null;
+
+function getBlcuProgrammingRepoPath() {
+ return path.join(getAppPath(), "..", "blcu-programming");
+}
+
+function getPythonExecutable(repoPath) {
+ if (process.platform === "win32") {
+ return path.join(repoPath, ".venv", "Scripts", "python.exe");
+ }
+
+ return path.join(repoPath, ".venv", "bin", "python");
+}
+
+async function startBlcuProgramming() {
+ if (blcuProgrammingProcess && !blcuProgrammingProcess.killed) {
+ return blcuProgrammingProcess;
+ }
+
+ const repoPath = getBlcuProgrammingRepoPath();
+ const pythonBin = getPythonExecutable(repoPath);
+ const entrypointPath = path.join(repoPath, "api", "main.py");
+
+ if (!fs.existsSync(entrypointPath)) {
+ logger.process(
+ "BLCU Programming",
+ `Entrypoint not found at ${entrypointPath}`,
+ );
+ return null;
+ }
+
+ if (!fs.existsSync(pythonBin)) {
+ logger.process(
+ "BLCU Programming",
+ `Python executable not found at ${pythonBin}`,
+ );
+ return null;
+ }
+
+ blcuProgrammingProcess = spawn(
+ pythonBin,
+ ["-m", "uvicorn", "api.main:app"],
+ {
+ cwd: repoPath,
+ env: {
+ ...process.env,
+ PYTHONUNBUFFERED: "1",
+ },
+ },
+ );
+
+ blcuProgrammingProcess.stdout.on("data", (data) => {
+ logger.process("BLCU Programming", data.toString().trim());
+ });
+
+ blcuProgrammingProcess.stderr.on("data", (data) => {
+ logger.process("BLCU Programming", data.toString().trim());
+ });
+
+ blcuProgrammingProcess.on("close", (code) => {
+ logger.process("BLCU Programming", `Process exited with code ${code}`);
+ blcuProgrammingProcess = null;
+ });
+
+ return blcuProgrammingProcess;
+}
+
+async function stopBlcuProgramming() {
+ if (!blcuProgrammingProcess || blcuProgrammingProcess.killed) {
+ return;
+ }
+
+ blcuProgrammingProcess.kill("SIGTERM");
+ blcuProgrammingProcess = null;
+}
+
+export { startBlcuProgramming, stopBlcuProgramming };