├── .gitignore ├── AUTHORS ├── COPYING ├── README.rst ├── bin ├── bootpd ├── dhcpd ├── ptftp ├── ptftpd └── pxed ├── debian ├── changelog ├── compat ├── control ├── copyright ├── docs ├── ptftp.install ├── pycompat ├── python-ptftplib.install ├── pyversions └── rules ├── doc ├── bootpd.1 ├── dhcpd.1 ├── ptftp.1 ├── ptftpd.1 └── pxed.1 ├── ptftplib ├── __init__.py ├── bootpserver.py ├── dhcpserver.py ├── notify.py ├── proto.py ├── pxeserver.py ├── state.py ├── tftpclient.py ├── tftpserver.py └── version.py ├── setup.cfg └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.egg-info 3 | /build/ 4 | /dist/ 5 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | AUTHORS 2 | ======= 3 | 4 | The pTFTPd tool suite is written and maintained by Maxime Petazzoni 5 | . Other contributors include: 6 | 7 | David Anderson 8 | DHCP and PXE servers. 9 | 10 | Maxime Ripard 11 | BOOTPd, based on David Anderson's work on DHCPd. 12 | 13 | Maxime Hadjinlian 14 | Packet number wraparound feature for pTFTP and pTFTPd. 15 | 16 | Thanks 17 | ^^^^^^ 18 | 19 | Thanks to David Anderson, Maxime Ripard, Thomas Petazzoni, Benjamin Collet and 20 | Maxime Hadjinlian for testing and using the pTFTPd utilities! 21 | 22 | Huge thanks to Marc Poulhiès for his help on the Debian packaging of pTFTPd. 23 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | pTFTPd - A pure-Python TFTP tool suite 2 | ====================================== 3 | 4 | pTFTPd is a collection of tools related to TFTP. It includes a TFTP 5 | server, a TFTP client, and a complete PXE solution based on this TFTP 6 | server and a micro-DHCP or BOOTP server. All these tools are written in 7 | Python and designed to be fast, RFC compliant and easy to use. 8 | 9 | Available tools include: 10 | 11 | - ``bootpd``: a BOOTP server (RFC951 and RFC1497 compliant) 12 | - ``dhcpd``: a simple, stripped-down DHCP server. 13 | - ``ptftpd``: the TFTP server (RFC1350, 2347, 2348, 2349 and 7440 compliant) 14 | - ``pxed``: a one-call PXE server using dhcpd and ptftpd. 15 | - ``ptftp``: a simple TFTP client (RFC1350, 2347, 2348, 2349 and 7440 16 | compliant and capable) 17 | 18 | They all support the ``--help`` option to present the usage summary to 19 | the user. 20 | 21 | All tools also understand the ``--rfc1350`` option, which forces them in 22 | basic TFTP RFC1350 compliance mode, disabling all TFTP extensions for 23 | increased compatibility would you encouter any problem with your target 24 | system. 25 | 26 | Installation 27 | ------------ 28 | 29 | pTFTPd is available on PyPI as the ``ptftpd`` distribution. 30 | 31 | .. code:: 32 | 33 | $ pip install ptftpd 34 | 35 | This will install the ``ptftplib`` Python package, as well as the scripts 36 | listed above. 37 | 38 | If you use the pTFTPd tool suite outside of a standard distribution 39 | installation, you may need to specify the Python module search path with 40 | ``PYTHONPATH`` before executing the binaries: 41 | 42 | .. code:: 43 | 44 | $ export PYTHONPATH=`pwd` 45 | $ bin/ptftp 46 | Connected to localhost:69. 47 | 48 | tftp> 49 | 50 | TFTP server and client 51 | ---------------------- 52 | 53 | The TFTP server, pTFTPd, fully supports the TFTP specification as 54 | defined in RFC1350. It also supports the TFTP Option Extension protocol 55 | (per RFC2347), the block size option as defined in RFC2348 and the 56 | transfer size option from RFC2349. 57 | 58 | For help on how to use pTFTPd, type: 59 | 60 | .. code:: 61 | 62 | $ ptftpd --help 63 | 64 | The port used can be changed using the ``-p`` option. The root path is 65 | given as a simple argument. For example, to serve ``/var/lib/tftp`` on 66 | port 6969 through the eth0 network interface: 67 | 68 | .. code:: 69 | 70 | $ ptftpd -p 6969 eth0 /var/lib/tftp 71 | 72 | The TFTP client is an interactive client, just launch it and type 73 | ``help`` to see the available commands: 74 | 75 | .. code:: 76 | 77 | $ ptftp 78 | tftp> help 79 | ... 80 | 81 | PXE solution 82 | ------------ 83 | 84 | The PXE system is also very easy to use. It takes three arguments: the 85 | network interface to listen on, the TFTP root path from which to serve 86 | files, and the PXE boot filename. It will automatically start a TFTP 87 | server and a DHCP server to serve hosts on the given interface. See 88 | ``--help`` for more details: 89 | 90 | .. code:: 91 | 92 | $ pxed --help 93 | 94 | Mechanics for using ``pxed.py`` with the BOOTP server are not yet in 95 | place, but such a solution can easily be constructed manually by 96 | starting the BOOTP server and the TFTP server manually: 97 | 98 | .. code:: 99 | 100 | $ bootpd & 101 | $ ptftpd 102 | -------------------------------------------------------------------------------- /bin/bootpd: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Authors: David Anderson 5 | # dave@natulte.net 6 | # Maxime Ripard 7 | # maxime.ripard@anandra.org 8 | # 9 | # This file is part of pTFTPd. 10 | # 11 | # pTFTPd is free software: you can redistribute it and/or modify it 12 | # under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # pTFTPd is distributed in the hope that it will be useful, but 17 | # WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 | # General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with pTFTPd. If not, see . 23 | 24 | import sys 25 | 26 | from ptftplib.bootpserver import main 27 | 28 | try: 29 | sys.exit(main()) 30 | except KeyboardInterrupt: 31 | pass 32 | 33 | -------------------------------------------------------------------------------- /bin/dhcpd: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: David Anderson 5 | # dave@natulte.net 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | import sys 23 | 24 | from ptftplib.dhcpserver import main 25 | 26 | try: 27 | sys.exit(main()) 28 | except KeyboardInterrupt: 29 | pass 30 | 31 | -------------------------------------------------------------------------------- /bin/ptftp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: Maxime Petazzoni 5 | # maxime.petazzoni@bulix.org 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | import sys 23 | 24 | from ptftplib.tftpclient import main 25 | 26 | try: 27 | sys.exit(main()) 28 | except KeyboardInterrupt: 29 | pass 30 | 31 | -------------------------------------------------------------------------------- /bin/ptftpd: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: Maxime Petazzoni 5 | # maxime.petazzoni@bulix.org 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | import sys 23 | 24 | from ptftplib.tftpserver import main 25 | 26 | try: 27 | sys.exit(main()) 28 | except KeyboardInterrupt: 29 | pass 30 | 31 | -------------------------------------------------------------------------------- /bin/pxed: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: Maxime Petazzoni 5 | # maxime.petazzoni@bulix.org 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | import sys 23 | 24 | from ptftplib.pxeserver import main 25 | 26 | try: 27 | sys.exit(main()) 28 | except KeyboardInterrupt: 29 | pass 30 | 31 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | ptftpd (1.2) unstable; urgency=low 2 | 3 | * New upstream version 1.2. 4 | * Protocol state machine fix for WRQ request handling in TFTP server. 5 | 6 | -- Maxime Petazzoni Tue, 11 Oct 2016 17:52:50 -0700 7 | 8 | ptftpd (1.0.2) unstable; urgency=low 9 | 10 | * New upstream version 1.0.2. 11 | * Have the TFTP server bind to a specific interface instead of all. 12 | 13 | -- Maxime Petazzoni Tue, 25 Dec 2012 22:26:12 +0100 14 | 15 | ptftpd (1.0.1) unstable; urgency=low 16 | 17 | * New upstream version 1.0.1. 18 | * Ignore duplicate N-1 ACK packets that can happen when 19 | network packets are duplicated/resent (fixes some U-Boot TFTP 20 | problems). 21 | 22 | -- Maxime Petazzoni Mon, 08 Feb 2010 14:33:23 +0100 23 | 24 | ptftpd (1.0) unstable; urgency=low 25 | 26 | * New major upstream version, 1.0. 27 | 28 | -- Maxime Petazzoni Fri, 22 Jul 2009 23:53:27 +0200 29 | 30 | ptftpd (0.2) unstable; urgency=low 31 | 32 | * Remove the .py extension from the Python executables. 33 | * New upstream version (0.2), including man pages. 34 | 35 | -- Maxime Petazzoni Fri, 16 Jul 2009 11:45:49 +0200 36 | 37 | ptftpd (0.1.3) unstable; urgency=low 38 | 39 | * Use two distinct packages, one for the python module and one for the CLI 40 | tools. 41 | 42 | -- Maxime Petazzoni Fri, 10 Jul 2009 23:38:52 +0200 43 | 44 | ptftpd (0.1.2) unstable; urgency=low 45 | 46 | * Upstream changes (code reorg) 47 | * Debian packaging fixes 48 | 49 | -- Maxime Petazzoni Fri, 10 Jul 2009 19:11:17 +0200 50 | 51 | ptftpd (0.1.1) unstable; urgency=low 52 | 53 | * Initial release 54 | 55 | -- Marc Poulhiès Thu, 09 Jul 2009 17:36:18 +0200 56 | -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 7 2 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: ptftpd 2 | Section: net 3 | Priority: extra 4 | Maintainer: Maxime Petazzoni 5 | Build-Depends: cdbs, debhelper (>= 7), python (>= 2.5), python-support 6 | Standards-Version: 3.8.2 7 | Homepage: https://github.com/mpetazzoni/github 8 | Vcs-Git: git://github.com/mpetazzoni/ptftpd.git 9 | 10 | Package: python-ptftplib 11 | Architecture: all 12 | Section: python 13 | Depends: ${python:Depends}, ${misc:Depends} 14 | Description: pTFTPd, the pure-Python TFTP tool suite (lib files) 15 | pTFTPd is a pure-Python TFTP tool suite. It features a TFTP server and client 16 | fully compliant to the TFTP specification defined in RFC1350. It also supports 17 | the TFTP Option Extension protocol (per RFC2347), the block size option as 18 | defined in RFC2348 and the transfer size option from RFC2349. 19 | . 20 | The pTFTPd tool suite also includes a mini-DHCP server, a BOOTP server, and a 21 | complexe PXE solution based on the DHCP and TFTP servers. 22 | 23 | Package: ptftp 24 | Architecture: all 25 | Depends: ${python:Depends}, ${misc:Depends}, python-ptftplib 26 | Conflicts: bootp 27 | Description: pTFTPd, a pure-Python TFTP tool suite that works (CLI clients) 28 | pTFTPd is a pure-Python TFTP tool suite. It features a TFTP server and client 29 | fully compliant to the TFTP specification defined in RFC1350. It also supports 30 | the TFTP Option Extension protocol (per RFC2347), the block size option as 31 | defined in RFC2348 and the transfer size option from RFC2349. 32 | . 33 | The pTFTPd tool suite also includes a mini-DHCP server, a BOOTP server, and a 34 | complexe PXE solution based on the DHCP and TFTP servers. 35 | -------------------------------------------------------------------------------- /debian/copyright: -------------------------------------------------------------------------------- 1 | This package was debianized by: 2 | 3 | Maxime Petazzoni on Thu, 10 Jul 2009 19:08:59 +0200 4 | 5 | It was downloaded from: 6 | 7 | https://github.com/mpetazzoni/ptftpd 8 | 9 | Upstream Author: 10 | 11 | Maxime Petazzoni 12 | 13 | Copyright: 14 | 15 | Copyright (C) 2008-2012 Maxime Petazzoni 16 | 17 | License: 18 | 19 | pTFTPd is free software: you can redistribute it and/or modify it 20 | under the terms of the GNU General Public License as published by 21 | the Free Software Foundation, either version 3 of the License, or 22 | (at your option) any later version. 23 | 24 | pTFTPd is distributed in the hope that it will be useful, but 25 | WITHOUT ANY WARRANTY; without even the implied warranty of 26 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 27 | General Public License for more details. 28 | 29 | You should have received a copy of the GNU General Public License 30 | along with pTFTPd. If not, see . 31 | 32 | On Debian systems, the complete text of the GNU General Public License 33 | version 2 can be found in `/usr/share/common-licenses/GPL-2'. the 34 | complete text of the GNU General Public License version 3 can be found 35 | in `/usr/share/common-licenses/GPL-3'. 36 | 37 | The Debian packaging is: 38 | 39 | Copyright (C) 2012 Maxime Petazzoni 40 | 41 | and is licensed under the GPL version 3, see above. 42 | 43 | -------------------------------------------------------------------------------- /debian/docs: -------------------------------------------------------------------------------- 1 | README.md 2 | -------------------------------------------------------------------------------- /debian/ptftp.install: -------------------------------------------------------------------------------- 1 | debian/tmp/usr/bin/* 2 | -------------------------------------------------------------------------------- /debian/pycompat: -------------------------------------------------------------------------------- 1 | 2 2 | -------------------------------------------------------------------------------- /debian/python-ptftplib.install: -------------------------------------------------------------------------------- 1 | debian/tmp/usr/lib/* 2 | -------------------------------------------------------------------------------- /debian/pyversions: -------------------------------------------------------------------------------- 1 | 2.5- -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | # -*- mode: makefile; coding: utf-8 -*- 3 | 4 | 5 | include /usr/share/cdbs/1/rules/debhelper.mk 6 | DEB_PYTHON_SYSTEM = pysupport 7 | include /usr/share/cdbs/1/class/python-distutils.mk 8 | 9 | DEB_COMPRESS_EXCLUDE := .py 10 | DEB_INSTALL_MANPAGES_ptftp := doc/bootpd.1 doc/dhcpd.1 doc/ptftp.1 doc/ptftpd.1 doc/pxed.1 11 | -------------------------------------------------------------------------------- /doc/bootpd.1: -------------------------------------------------------------------------------- 1 | .TH BOOTPD 1 "2009 Jul 21" 2 | .SH NAME 3 | bootpd \- A minimalistic, pure-Python BOOTP server. 4 | .SH SYNOPSIS 5 | .br 6 | .B bootpd 7 | [options] 8 | .SH DESCRIPTION 9 | .B bootpd 10 | is a minimalistic BOOTP server written in Python and designed to work in 11 | conjunction with 12 | .BR ptftpd "(1)" 13 | from the Python TFTP tool suite. It fully complies to the BOOTP specification 14 | as defined in RFC951, and also supports BOOTP options defined in RFC1497. 15 | .PP 16 | It is extremely similar to 17 | .BR dhcpd "(1):" 18 | it listens on the given network interface for BOOTP requests and serves IP 19 | addresses from the same subnet as the network segment it is listening to. 20 | .PP 21 | .B bootpd 22 | also indicates to the BOOTP clients which file they should use to boot (the PXE 23 | boot filename). This is very useful when running 24 | .B bootpd 25 | alongside a TFTP server capable of serving this file to the client. 26 | .SH OPTIONS 27 | .TP 15 28 | \-h, \-\-help 29 | Display 30 | .B bootpd 31 | help, options and usage. 32 | .TP 33 | .RB \-t " TFTP_SERVER", " " \-\-tftp-server= "TFTP_SERVER" 34 | Specify the IP address of the TFTP server, if not running on the same machine 35 | as this BOOTP server. 36 | .TP 37 | .RB \-g " ROUTER", " " \-\-gateway= "ROUTER" 38 | Specify the IP address of the default gateway for the BOOTP clients. 39 | .TP 40 | \-v, \-\-verbose 41 | Be verbose. 42 | Output information messages. 43 | .SH SEE ALSO 44 | dhcpd(1), ptftpd(1), pxed(1) 45 | .SH AUTHORS 46 | .B bootpd 47 | was contributed by Maxime Ripard , based on the work of David Anderson on 48 | .BR dhcpd "(1)." 49 | .PP 50 | It is maintained by Maxime Petazzoni . See the 51 | AUTHORS file for more information. 52 | -------------------------------------------------------------------------------- /doc/dhcpd.1: -------------------------------------------------------------------------------- 1 | .TH DHCPD 1 "2009 Jul 21" 2 | .SH NAME 3 | dhcpd \- A minimalistic, pure-Python DHCP server. 4 | .SH SYNOPSIS 5 | .br 6 | .B dhcpd 7 | [options] 8 | .SH DESCRIPTION 9 | .B dhcpd 10 | is a minimalistic DHCP server written in Python and designed to work in 11 | conjunction with 12 | .BR ptftpd "(1)" 13 | from the Python TFTP tool suite. It listens on the given network interface for DHCP requests and serves IP addresses from the same subnet as the network segment it is listening to. 14 | .PP 15 | .B dhcpd 16 | also indicates to the DHCP clients which file they should use to boot (the PXE 17 | boot filename). This is very useful when running 18 | .B dhcpd 19 | alongside a TFTP server capable of serving this file to the client. 20 | .PP 21 | If you plan to run both a DHCP server and a TFTP server 22 | .RB ( "dhcpd" (1) 23 | and 24 | .BR ptftpd "(1)" 25 | for example), it is simpler to use 26 | .BR pxed "(1)" 27 | which combines the two functions more elegantly. 28 | .SH OPTIONS 29 | .TP 15 30 | \-h, \-\-help 31 | Display 32 | .B dhcpd 33 | help, options and usage. 34 | .TP 35 | .RB \-t " TFTP_SERVER", " " \-\-tftp-server= "TFTP_SERVER" 36 | Specify the IP address of the TFTP server, if not running on the same machine 37 | as this DHCP server. 38 | .TP 39 | .RB \-g " ROUTER", " " \-\-gateway= "ROUTER" 40 | Specify the IP address of the default gateway for the DHCP clients. 41 | .TP 42 | \-v, \-\-verbose 43 | Be verbose. 44 | Output information messages. 45 | .SH SEE ALSO 46 | ptftpd(1), pxed(1) 47 | .SH AUTHORS 48 | .B dhcpd 49 | was contributed by David Anderson and is maintained by 50 | Maxime Petazzoni . See the AUTHORS file for more 51 | information. 52 | -------------------------------------------------------------------------------- /doc/ptftp.1: -------------------------------------------------------------------------------- 1 | .TH PTFTP 1 "2009 Jul 17" 2 | .SH NAME 3 | ptftp \- A simple, pure-Python TFTP client. 4 | .SH SYNOPSIS 5 | .br 6 | .B ptftp 7 | [options] 8 | .SH DESCRIPTION 9 | .B ptftp 10 | is a simple, command-line TFTP client. Like 11 | .BR ptftpd "(1)," 12 | it fully complies to the TFTP protocol defined in RFC1350, and supports TFTP 13 | extensions from RFC2347, RFC2348 and RFC2349 to the exception of the timeout 14 | option. 15 | .PP 16 | .B ptftp 17 | connects to the TFTP server via UDP on the specified port, defaulting to the 18 | normal TFTP port 69. The transfer mode and transfer block size can also be 19 | adjusted (see 20 | .B OPTIONS 21 | below for more details). 22 | .PP 23 | .B ptftp 24 | supports the packet number wraparound feature, allowing for the transfer of 25 | files of arbitrary size by resetting the packet number to 0 when it reaches the 26 | protocol maximum of 65535 = 2^16-1. This behavior can be disabled with the 27 | .B \-\-rfc1350 28 | option (strict RFC1350 compliance operation). 29 | .PP 30 | Once started, 31 | .B ptftp 32 | offers an interactive command line to the user where commands to get or push 33 | files can be issued. See the 34 | .B COMMANDS 35 | section below for a summary of the available commands and their usage. 36 | .SH OPTIONS 37 | The options may be given in any order on the command line. 38 | .br 39 | .TP 15 40 | \-?, \-\-help 41 | Display 42 | .B ptftp 43 | help, options and usage. 44 | .TP 45 | \-r, \-\-rfc1350 46 | Force 47 | .B ptftp 48 | to run in strict RFC1350 mode. 49 | Disables all TFTP extensions and options support from RFC2347, RFC2348 and 50 | RFC2349, as well as the packet number wraparound feature. 51 | .TP 52 | .RB \-h " HOST", " " \-\-host= "HOST" 53 | Specify the TFTP server to connect to. 54 | .TP 55 | .RB \-p " PORT", " " \-\-port= "PORT" 56 | Specify the port to use when connecting to the TFTP server. 57 | .TP 58 | .RB \-m " MODE", " " \-\-mode= "MODE" 59 | Set the TFTP transfer mode (defaults to 'octet'). It must be one of 'netascii' 60 | or 'octet'. 61 | .TP 62 | .RB \-b " BLKSIZE", " " \-\-blksize= "BLKSIZE" 63 | Set the transfer block size (defaults to 1400 bytes). Very low values have a 64 | dramatic effect on transfer performance as it forces TFTP packet fragmentation. 65 | .SH COMMANDS 66 | When started, 67 | .B ptftp 68 | will present a prompt to the user: 69 | .PP 70 | tftp> 71 | .PP 72 | A few commands to operate the TFTP client are available: 73 | .PP 74 | .TP 12 75 | ?, help 76 | Display the in-program help. 77 | .TP 78 | q, quit 79 | Quit the TFTP client. 80 | .TP 81 | .RB m, " " mode " [newmode]" 82 | Display or change the transfer mode to 83 | .BR newmode "." 84 | .TP 85 | .RB b, " " blksize " [newsize]" 86 | Display or change the transfer block size to 87 | .BR newsize "." 88 | .TP 89 | .RB g, " " get " " [-f] " filename" 90 | Get 91 | .B filename 92 | from the server. Use "-f" to overwrite a potentially existing local file. 93 | The received data is written into a temporary file that is only moved 94 | to a local file where ptftp is executed if the transfer completed 95 | successfully, thus avoiding loosing the content of a previous file of 96 | the same name if the transfer fails or is interrupted. 97 | .TP 98 | .RB p, " " put " filename" 99 | Push 100 | .B filename 101 | to the server. 102 | .SH SEE ALSO 103 | ptftp(1) 104 | .SH AUTHORS 105 | .B ptftpd 106 | is written and maintained by Maxime Petazzoni , 107 | with help from a few others. See the AUTHORS file for more information. 108 | -------------------------------------------------------------------------------- /doc/ptftpd.1: -------------------------------------------------------------------------------- 1 | .TH PTFTPD 1 "2009 Jul 17" 2 | .SH NAME 3 | ptftpd \- A full-featured, pure-Python TFTP server. 4 | .SH SYNOPSIS 5 | .br 6 | .B ptftpd 7 | [options] 8 | .SH DESCRIPTION 9 | .B ptftpd 10 | is a TFTP server entirely written in Python. It is fully compliant 11 | with the TFTP (Trivial File Transfer Protocol) as defined in RFC1350. It also 12 | supports TFTP extensions defined in RFC2347, RFC2348 and RFC2349, to the 13 | exception of the timeout option only. 14 | .PP 15 | .B ptftpd 16 | serves the given TFTP root directory to clients connecting to its listening 17 | port (defaults to the standard TFTP port UDP 69). It supports reads (RRQ) and 18 | writes (WRQ) in both netascii and octet mode and obviously complies to whatever 19 | directory and file permissions in the given TFTP root. 20 | .PP 21 | .B ptftpd 22 | is able to serve files of arbitrary size using the packet number wraparound 23 | feature (reset of the DATA packet number when it reaches the protocol maximum 24 | of 65535 = 2^16-1), but the client must support it. This behavior can be 25 | disabled by the 26 | .B \-\-rfc1350 27 | option (strict RFC1350 compliance operation). 28 | .PP 29 | .B ptftpd 30 | also treats the TFTP root as a jail, and will make sure no operation is 31 | attempted to access files outside the TFTP root directory. 32 | .SH OPTIONS 33 | The options may be given in any order, but the TFTP server's root directory 34 | must be specified last on the command line. 35 | .br 36 | .TP 15 37 | \-h, \-\-help 38 | Display 39 | .B ptftpd 40 | help, options and usage. 41 | .TP 42 | \-r, \-\-rfc1350 43 | Force 44 | .B ptftpd 45 | to run in strict RFC1350 mode. 46 | Disables all TFTP extensions and options support from RFC2347, RFC2348 and 47 | RFC2349, as well as the packet number wraparound feature (reset of the DATA 48 | packet number to 0 when it reaches the maximum packet number 65536). 49 | .TP 50 | .RB \-p " PORT", " " \-\-port= "PORT" 51 | Set the port 52 | .B ptftpd 53 | listens for TFTP requests on. 54 | .TP 55 | \-v, \-\-verbose 56 | Be verbose. Output information messages. 57 | .TP 58 | \-D, \-\-debug 59 | Be even more verbose. Output debugging information. 60 | .SH SEE ALSO 61 | ptftp(1) 62 | .SH AUTHORS 63 | .B ptftpd 64 | is written and maintained by Maxime Petazzoni , 65 | with help from a few others. See the AUTHORS file for more information. 66 | -------------------------------------------------------------------------------- /doc/pxed.1: -------------------------------------------------------------------------------- 1 | .TH PXED 1 "2009 Jul 21" 2 | .SH NAME 3 | pxed \- A complete PXE boot solution. 4 | .SH SYNOPSIS 5 | .br 6 | .B pxed 7 | [options] 8 | .SH DESCRIPTION 9 | .B pxed 10 | is a complete, pure-Python PXE solution to boot PXE clients with DHCP and TFTP. 11 | It is a simple wrapper around the 12 | .BR dhcpd "(1)" 13 | and 14 | .BR ptftpd "(1)" 15 | servers from the Python TFTP tool suite. 16 | .PP 17 | Options and arguments for 18 | .B pxed 19 | are very similar to 20 | .BR dhcpd "(1)" 21 | with the addition of the TFTP root which is passed to the TFTP server thread running 22 | .BR ptftpd "(1)." 23 | .SH OPTIONS 24 | .TP 15 25 | \-h, \-\-help 26 | Display 27 | .B pxed 28 | help, options and usage. 29 | .TP 30 | \-r, \-\-rfc1350 31 | Forces the TFTP server to run in strict RFC1350 mode. Disables all TFTP 32 | extensions from RFC2347, RFC2348 and RFC2349. 33 | .TP 34 | .RB \-g " ROUTER", " " \-\-gateway= "ROUTER" 35 | Specify the IP address of the default gateway for the BOOTP clients. 36 | .TP 37 | \-v, \-\-verbose 38 | Be verbose. Output information messages. 39 | .TP 40 | \-D, \-\-debug 41 | Be even more verbose. Output debugging information. 42 | .SH SEE ALSO 43 | dhcpd(1), ptftpd(1) 44 | .SH AUTHORS 45 | .B pxed 46 | was contributed David Anderson , and is maintained by Maxime 47 | Petazzoni . See the AUTHORS file for more 48 | information. 49 | -------------------------------------------------------------------------------- /ptftplib/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | -------------------------------------------------------------------------------- /ptftplib/bootpserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Authors: David Anderson 5 | # dave@natulte.net 6 | # Maxime Ripard 7 | # maxime.ripard@anandra.org 8 | # 9 | # This file is part of pTFTPd. 10 | # 11 | # pTFTPd is free software: you can redistribute it and/or modify it 12 | # under the terms of the GNU General Public License as published by 13 | # the Free Software Foundation, either version 3 of the License, or 14 | # (at your option) any later version. 15 | # 16 | # pTFTPd is distributed in the hope that it will be useful, but 17 | # WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 19 | # General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with pTFTPd. If not, see . 23 | 24 | """BOOTP Server. 25 | 26 | This is a minimal BOOTP Server. It fully complies with the RFC951 and supports 27 | the BOOTP options defined in RFC1497. 28 | 29 | If you are looking for something more advanced, use dhcpd.py, which is a more 30 | complete DHCP server, but just as efficient. 31 | """ 32 | 33 | import errno 34 | import logging 35 | import random 36 | import socket 37 | import struct 38 | import sys 39 | 40 | l = logging.getLogger('bootpd') 41 | 42 | # The IP protocol number in Ethernet frames. 43 | ETHERNET_IP_PROTO = 0x800 44 | 45 | # The UDP protocol number in IP datagrams. 46 | IP_UDP_PROTO = 0x11 47 | 48 | # The full size of a BOOTP packet 49 | BOOTP_PACKET_SIZE = 300 50 | 51 | # The BOOTP magic cookie value that precedes option fields. 52 | BOOTP_MAGIC_COOKIE = 0x63825363 53 | 54 | # BOOTP operation types. 55 | BOOTP_OP_BOOTPREQUEST = 1 56 | BOOTP_OP_BOOTPREPLY = 2 57 | 58 | # BOOTP vendor information extensions, as defined in RFC 1497 59 | BOOTP_OPTION_PAD = 0 60 | BOOTP_OPTION_SUBNET = 1 61 | BOOTP_OPTION_OFFSET = 2 62 | BOOTP_OPTION_GATEWAY = 3 63 | BOOTP_OPTION_TIMESERVER = 4 64 | BOOTP_OPTION_IEN_NAMESERVER = 5 65 | BOOTP_OPTION_DNS = 6 66 | BOOTP_OPTION_LOGSERVER = 7 67 | BOOTP_OPTION_QUOTESERVER = 8 68 | BOOTP_OPTION_LPRSERVER = 9 69 | BOOTP_OPTION_IMPRESSSERVER = 10 70 | BOOTP_OPTION_RLPSERVER = 11 71 | BOOTP_OPTION_HOSTNAME = 12 72 | BOOTP_OPTION_BOOTFILESIZE = 13 73 | BOOTP_OPTION_MERITDUMP = 14 74 | BOOTP_OPTION_DOMAINNAME = 15 75 | BOOTP_OPTION_SWAPSERVER = 16 76 | BOOTP_OPTION_ROOTPATH = 17 77 | BOOTP_OPTION_EXTENSION = 18 78 | BOOTP_OPTION_END = 255 79 | 80 | # Linux ioctl() commands to query the kernel. 81 | SIOCGIFADDR = 0x8915 # IP address for interface 82 | SIOCGIFNETMASK = 0x891B # Netmask for interface 83 | SIOCGIFHWADDR = 0x8927 # MAC address for interface 84 | 85 | 86 | def get_ip_config_for_iface(iface): 87 | """Retrieve and return the IP address/netmask and MAC address of the 88 | given interface.""" 89 | 90 | if 'linux' not in sys.platform: 91 | raise NotImplementedError("get_ip_address_for_iface is not " 92 | "implemented on your OS.") 93 | 94 | def ip_from_response(resp): 95 | return socket.inet_ntoa(resp[20:24]) 96 | 97 | def mac_from_response(resp): 98 | mac = struct.unpack('!6B', resp[18:24]) 99 | return ':'.join(['%02x' % x for x in mac]) 100 | 101 | import fcntl 102 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 103 | ifname = struct.pack('256s', iface[:15]) 104 | ip = fcntl.ioctl(s.fileno(), SIOCGIFADDR, ifname) 105 | mask = fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, ifname) 106 | mac = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR, ifname) 107 | return ip_from_response(ip), ip_from_response(mask), \ 108 | mac_from_response(mac) 109 | 110 | 111 | def compute_checksum(message): 112 | """Calculates the 16-bit one's complement of the one's complement sum 113 | of a given message.""" 114 | 115 | # If the message length isn't a multiple of 2 bytes, we pad with 116 | # zeros 117 | if len(message) % 2: 118 | message += struct.pack('x') 119 | 120 | # We build our blocks to sum 121 | to_sum = struct.unpack('!%dH' % (len(message)/2), message) 122 | 123 | # UDP checksum 124 | checksum = 0 125 | for v in to_sum: 126 | checksum += v 127 | if checksum > 2**16: 128 | checksum = (checksum & 0xFFFF) + 1 129 | return 0xFFFF - checksum 130 | 131 | 132 | def _pack_ip(ip_addr): 133 | """Pack a dotted quad IP string into a 4 byte string.""" 134 | return socket.inet_aton(ip_addr) 135 | 136 | 137 | def _unpack_ip(ip_addr): 138 | """Unpack a 4 byte IP address into a dotted quad string.""" 139 | return socket.inet_ntoa(ip_addr) 140 | 141 | 142 | def _pack_mac(mac_addr): 143 | """Pack a MAC address (00:00:00:00:00:00) into a 6 byte string.""" 144 | fields = [int(x, 16) for x in mac_addr.split(':')] 145 | return struct.pack('!6B', *fields) 146 | 147 | 148 | class NotBootpPacketError(Exception): 149 | """Packet being decoded is not a BOOTP packet.""" 150 | 151 | 152 | class UninterestingBootpPacket(Exception): 153 | """Packet is BOOTP, but we just don't care about it.""" 154 | 155 | 156 | class BootpPacket(object): 157 | def __init__(self, pkt): 158 | # Check the ethernet type. It needs to be IP (0x800). 159 | if struct.unpack('!H', pkt[12:14])[0] != ETHERNET_IP_PROTO: 160 | raise NotBootpPacketError() 161 | self.server_mac, self.client_mac = pkt[0:6], pkt[6:12] 162 | 163 | # Strip off the ethernet frame and check the IP packet type. It should 164 | # be UDP (0x11) 165 | pkt = pkt[14:] 166 | if ord(pkt[9]) != IP_UDP_PROTO: 167 | raise NotBootpPacketError() 168 | 169 | # Strip off the IP header and check the source/destination ports in the 170 | # UDP datagram. The packet should be from port 68 to port 67 to be 171 | # BOOTP. We don't care about checksum here 172 | header_len = (ord(pkt[0]) & 0xF) * 4 173 | pkt = pkt[header_len:] 174 | (src, dst) = struct.unpack('!2H4x', pkt[:8]) 175 | if not (src == 68 and dst == 67): 176 | raise NotBootpPacketError() 177 | 178 | # Looks like a BOOTP request. Strip off the UDP headers, parse out the 179 | # interesting data from the base BOOTP packet and check that the magic 180 | # cookie is right. 181 | pkt = pkt[8:] 182 | bootp_fmt = '!4xL20x6s10x64s128xL' 183 | bootp_size = struct.calcsize(bootp_fmt) 184 | (xid, mac, sname, cookie) = struct.unpack(bootp_fmt, pkt[:bootp_size]) 185 | 186 | # We strip off the padding bytes 187 | try: 188 | sname = sname[:sname.index('\x00')] 189 | except ValueError: 190 | pass 191 | 192 | self.sname = sname 193 | 194 | if cookie != BOOTP_MAGIC_COOKIE or self.client_mac != mac: 195 | raise NotBootpPacketError() 196 | 197 | self.xid = xid 198 | 199 | 200 | class BOOTPServer(object): 201 | def __init__(self, interface, bootfile, router=None, tftp_server=None): 202 | self.interface = interface 203 | self.ip, self.netmask, self.mac = get_ip_config_for_iface(interface) 204 | self.hostname = socket.gethostname() 205 | self.bootfile = bootfile 206 | self.router = router or self.ip 207 | self.tftp_server = tftp_server or self.ip 208 | self.ips_allocated = {} 209 | 210 | self.sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) 211 | self.sock.bind((self.interface, ETHERNET_IP_PROTO)) 212 | 213 | def serve_forever(self): 214 | l.info('Serving BOOTP requests on %s' % self.interface) 215 | while True: 216 | data = self.sock.recv(4096) 217 | try: 218 | pkt = BootpPacket(data) 219 | self.handle_bootp_request(pkt) 220 | except (NotBootpPacketError, UninterestingBootpPacket): 221 | continue 222 | 223 | def handle_bootp_request(self, pkt): 224 | # If the server is explicitly requested, and it's not ours, 225 | # we just ignore it 226 | if pkt.sname and pkt.sname != self.hostname: 227 | raise UninterestingBootpPacket() 228 | 229 | ip = self.generate_free_ip() 230 | l.info('Offering to boot client %s' % ip) 231 | l.info('Booting client %s with file %s' % (ip, self.bootfile)) 232 | 233 | self.sock.send(self.encode_bootp_reply(pkt, ip)) 234 | 235 | def encode_bootp_reply(self, request_pkt, client_ip): 236 | # Basic BOOTP reply 237 | reply = struct.pack('!B' # The op (0x2) 238 | 'B' # The htype (Ethernet -> 0x1) 239 | 'B' # The hlen (0x6) 240 | 'x' # The hops field, useless 241 | 'L' # XID 242 | '2x' # secs since boot, useless for the server 243 | 'H' # bootp flags (Broadcast -> 0x8000) 244 | '4x' # ciaddr, useless for the server 245 | '4s' # Client IP address 246 | '4s' # Next server IP address (TFTP server) 247 | '4x' # Gateway IP Adress, useless 248 | '6s' # Client MAC address 249 | '10x' # End of MAC Address 250 | '64s' # Server host name, often useless 251 | '128s' # PXE boot file 252 | 'L', # Magic cookie 253 | 0x2, 0x1, 0x6, request_pkt.xid, 0x8000, 254 | _pack_ip(client_ip), _pack_ip(self.tftp_server), 255 | request_pkt.client_mac, self.hostname, 256 | self.bootfile, BOOTP_MAGIC_COOKIE) 257 | 258 | bootp_options = ( 259 | (BOOTP_OPTION_SUBNET, _pack_ip(self.netmask)), 260 | (BOOTP_OPTION_GATEWAY, _pack_ip(self.router)), 261 | ) 262 | 263 | options = '' 264 | for option, data in bootp_options: 265 | options += struct.pack('!BB', option, len(data)) 266 | options += data 267 | reply += options + struct.pack('!B', 0xff) 268 | 269 | # We add the padding bytes to fit the full size of a BOOTP packet 270 | if len(reply) < BOOTP_PACKET_SIZE: 271 | reply += struct.pack(str(BOOTP_PACKET_SIZE - len(reply)) + 'x') 272 | 273 | # Construct the UDP datagram. 274 | # First, the checksum. Here we build our pseudo IP headers required 275 | # for the checksum, and then compute the checksum. 276 | udp_headers = struct.pack('!HHH', 67, 68, len(reply) + 8) 277 | pseudo_header = struct.pack('!4s4sxBH', _pack_ip(self.ip), 278 | _pack_ip('255.255.255.255'), IP_UDP_PROTO, 279 | len(udp_headers) + 2 + len(reply)) 280 | 281 | pseudo_packet = pseudo_header + udp_headers + reply 282 | checksum = compute_checksum(pseudo_packet) 283 | 284 | reply = udp_headers + struct.pack('!H', checksum) + reply 285 | 286 | # Now the IP datagram... 287 | ip_header1 = struct.pack('!BxH4xBB', 0x45, 20+len(reply), 0xFF, 288 | IP_UDP_PROTO) 289 | ip_header2 = struct.pack('4s4s', _pack_ip(self.ip), 290 | _pack_ip('255.255.255.255')) 291 | checksum = compute_checksum(ip_header1 + ip_header2) 292 | 293 | reply = ip_header1 + struct.pack('!H', checksum) + ip_header2 + reply 294 | 295 | # And finally the ethernet frame. 296 | reply = struct.pack('!6s6sH', _pack_mac('ff:ff:ff:ff:ff:ff'), 297 | _pack_mac(self.mac), 298 | ETHERNET_IP_PROTO) + reply 299 | 300 | # And here is our BOOTP packet 301 | return reply 302 | 303 | def generate_free_ip(self): 304 | server_ip = struct.unpack('!L', _pack_ip(self.ip))[0] 305 | netmask = struct.unpack('!L', _pack_ip(self.netmask))[0] 306 | anti_netmask = 0xFFFFFFFF - netmask 307 | 308 | while True: 309 | entropy = random.getrandbits(32) 310 | 311 | client_ip = (server_ip & netmask) | (entropy & anti_netmask) 312 | 313 | # Exclude using the server's address, the network's address, the 314 | # broadcast address, and any IP already in use. 315 | if (client_ip == server_ip or 316 | (client_ip & netmask) == 0 or 317 | (client_ip | netmask) == 0xFFFFFFFF): 318 | continue 319 | 320 | ip = _unpack_ip(struct.pack('!L', client_ip)) 321 | if ip in self.ips_allocated: 322 | continue 323 | 324 | return ip 325 | 326 | 327 | def main(): 328 | import optparse 329 | 330 | usage = "Usage: %prog " 331 | parser = optparse.OptionParser(usage=usage) 332 | parser.add_option("-t", "--tftp-server", dest="tftp_server", 333 | help="The IP address of the TFTP server, if not running " 334 | "on this machine", default=None) 335 | parser.add_option("-g", "--gateway", dest="router", 336 | help="The IP address of the default gateway, if not " 337 | "this machine", default=None) 338 | parser.add_option("-v", "--verbose", dest="loglevel", action="store_const", 339 | const=logging.INFO, help="Output information messages", 340 | default=logging.WARNING) 341 | 342 | (options, args) = parser.parse_args() 343 | 344 | if len(args) != 2: 345 | parser.print_help() 346 | return 1 347 | 348 | iface, bootfile = args 349 | 350 | logging.basicConfig(stream=sys.stdout, level=options.loglevel, 351 | format='%(levelname)s(%(name)s): %(message)s') 352 | 353 | try: 354 | server = BOOTPServer(iface, bootfile, router=options.router, 355 | tftp_server=options.tftp_server) 356 | server.serve_forever() 357 | except socket.error as e: 358 | sys.stderr.write('Socket error (%s): %s!\n' % 359 | (errno.errorcode[e.args[0]], e.args[1])) 360 | return 1 361 | 362 | return 0 363 | 364 | if __name__ == '__main__': 365 | try: 366 | sys.exit(main()) 367 | except KeyboardInterrupt: 368 | pass 369 | -------------------------------------------------------------------------------- /ptftplib/dhcpserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: David Anderson 5 | # dave@natulte.net 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | """PXE DHCP Server. 23 | 24 | This is a very simple, stripped down DHCP server, designed exclusively 25 | as a complement to pTFTPd. It cannot handle anything complicated, and 26 | only responds to DHCP requests that clearly originate from a system 27 | attempting to PXE boot. Use in conjunction with ptftpd.py to have a 28 | full, yet lightweight PXE boot setup. 29 | """ 30 | 31 | import errno 32 | import logging 33 | import random 34 | import socket 35 | import struct 36 | import sys 37 | import time 38 | 39 | from . import notify 40 | 41 | l = notify.getLogger('dhcpd') 42 | 43 | # The IP protocol number in Ethernet frames. 44 | ETHERNET_IP_PROTO = 0x800 45 | 46 | # The UDP protocol number in IP datagrams. 47 | IP_UDP_PROTO = 0x11 48 | 49 | # The DHCP magic cookie value that precedes option fields. 50 | DHCP_MAGIC_COOKIE = 0x63825363 51 | 52 | # DHCP operation types. There are others, but we don't care. 53 | DHCP_OP_DHCPDISCOVER = 1 54 | DHCP_OP_DHCPOFFER = 2 55 | DHCP_OP_DHCPREQUEST = 3 56 | DHCP_OP_DHCPACK = 5 57 | 58 | # DHCP options we care about. 59 | DHCP_OPTION_SUBNET = 1 # Subnet mask 60 | DHCP_OPTION_ROUTER = 3 # Router 61 | DHCP_OPTION_DNS = 6 # Domain Name Servers (DNS) 62 | DHCP_OPTION_REQUESTED_IP = 50 # Requested IP address 63 | DHCP_OPTION_LEASE_TIME = 51 # Lease time for the IP address 64 | DHCP_OPTION_OP = 53 # The DHCP operation (see above) 65 | DHCP_OPTION_SERVER_ID = 54 # Server Identifier (IP address) 66 | DHCP_OPTION_VENDOR_CLASS_ID = 60 # The vendor class identifier, used 67 | # to identify PXE clients 68 | DHCP_OPTION_CLIENT_UUID = 61 # The client machine UUID 69 | DHCP_OPTION_PXE_VENDOR = 43 # PXE vendor extensions 70 | DHCP_OPTION_CLIENT_UUID2 = 97 # The client machine UUID 71 | 72 | # Client UUID length. Some PXE clients use UUID2 to provide the client machine 73 | # MAC address, resulting in invalid UUID parsing. We ensure we're dealing with 74 | # client UUID by checking their length (16 bytes). 75 | DHCP_CLIENT_UUID_LENGTH = 16 76 | 77 | # DHCP lease timeout in seconds. Internally, we wait longer, to let 78 | # the client wrap up cleanly. 79 | DHCP_LEASE_TIMEOUT = 10*60 # 10 minutes 80 | DHCP_LEASE_TIMEOUT_INTERNAL = 15*60 # 15 minutes 81 | 82 | # Linux ioctl() commands to query the kernel. 83 | SIOCGIFADDR = 0x8915 # IP address for interface 84 | SIOCGIFNETMASK = 0x891B # Netmask for interface 85 | SIOCGIFHWADDR = 0x8927 # Mac address for interface 86 | 87 | 88 | def get_ip_config_for_iface(iface): 89 | """Retrieve and return the IP address/netmask of the given interface.""" 90 | if 'linux' not in sys.platform: 91 | raise NotImplementedError("get_ip_address_for_iface is not " 92 | "implemented on your OS.") 93 | 94 | def ip_from_response(resp): 95 | return socket.inet_ntoa(resp[20:24]) 96 | 97 | def mac_from_response(resp): 98 | mac = struct.unpack('!6B', resp[18:24]) 99 | return ':'.join(['%02x' % x for x in mac]) 100 | 101 | import fcntl 102 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 103 | ifname = struct.pack('256s', iface[:15].encode()) 104 | ip = fcntl.ioctl(s.fileno(), SIOCGIFADDR, ifname) 105 | mask = fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, ifname) 106 | mac = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR, ifname) 107 | return ip_from_response(ip), ip_from_response(mask), mac_from_response(mac) 108 | 109 | 110 | def _dhcp_options(options): 111 | """Generate a sequence of DHCP options from a raw byte stream.""" 112 | i = 0 113 | while i < len(options): 114 | code = ord(options[i]) 115 | 116 | # Handle pad and end options. 117 | if code == 0: 118 | i += 1 119 | continue 120 | if code == 255: 121 | return 122 | 123 | # Extract and yield the option number and option value. 124 | data_len = ord(options[i+1]) 125 | data = options[i + 2:i + 2 + data_len] 126 | i += 2 + data_len 127 | yield (code, data) 128 | 129 | 130 | def _pack_ip(ip_addr): 131 | """Pack a dotted quad IP string into a 4 byte string.""" 132 | return socket.inet_aton(ip_addr) 133 | 134 | 135 | def _unpack_ip(ip_addr): 136 | """Unpack a 4 byte IP address into a dotted quad string.""" 137 | return socket.inet_ntoa(ip_addr) 138 | 139 | 140 | def _pack_mac(mac_addr): 141 | """Pack a MAC address (00:00:00:00:00:00) into a 6 byte string.""" 142 | fields = [int(x, 16) for x in mac_addr.split(':')] 143 | return struct.pack('!6B', *fields) 144 | 145 | 146 | def _unpack_uuid(uuid): 147 | """Unpack a PXE UUID to its long form 148 | (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).""" 149 | fields = ['%02x' % x for x in struct.unpack('!16B', uuid)] 150 | return '%s-%s-%s-%s-%s' % (''.join(fields[:4]), 151 | ''.join(fields[4:6]), 152 | ''.join(fields[6:8]), 153 | ''.join(fields[8:10]), 154 | ''.join(fields[10:16])) 155 | 156 | 157 | class NotDhcpPacketError(Exception): 158 | """Packet being decoded is not a DHCP packet.""" 159 | 160 | 161 | class UninterestingDhcpPacket(Exception): 162 | """Packet is DHCP, but not of interest to us.""" 163 | 164 | 165 | class DhcpPacket(object): 166 | def __init__(self, pkt): 167 | # Check the ethernet type. It needs to be IP (0x800). 168 | if struct.unpack('!H', pkt[12:14])[0] != ETHERNET_IP_PROTO: 169 | raise NotDhcpPacketError() 170 | self.server_mac, self.client_mac = pkt[0:6], pkt[6:12] 171 | 172 | # Strip off the ethernet frame and check the IP packet type. It should 173 | # be UDP (0x11) 174 | pkt = pkt[14:] 175 | if ord(pkt[9]) != IP_UDP_PROTO: 176 | raise NotDhcpPacketError() 177 | 178 | # Strip off the IP header and check the source/destination ports in the 179 | # UDP datagram. The packet should be from port 68 to port 67 to 180 | # tentatively be DHCP. 181 | header_len = (ord(pkt[0]) & 0xF) * 4 182 | pkt = pkt[header_len:] 183 | (src, dst) = struct.unpack('!2H', pkt[:4]) 184 | if not (src == 68 and dst == 67): 185 | raise NotDhcpPacketError() 186 | 187 | # Looks like a DHCP request. Parse out the interesting data from the 188 | # base DHCP packet and check that the magic cookie is right. 189 | dhcp_fmt = '!12xL20x6s202xL' 190 | dhcp_size = struct.calcsize(dhcp_fmt) 191 | (xid, mac, cookie) = struct.unpack(dhcp_fmt, pkt[:dhcp_size]) 192 | 193 | if cookie != DHCP_MAGIC_COOKIE or self.client_mac != mac: 194 | raise NotDhcpPacketError() 195 | 196 | self.xid = xid 197 | 198 | self.uuid = 'not specified' 199 | 200 | self._parse_dhcp_options(pkt[dhcp_size:]) 201 | 202 | def _parse_dhcp_options(self, options): 203 | self.unknown_options = [] 204 | self.is_pxe_request = False 205 | self.requested_ip = None 206 | 207 | for option, value in _dhcp_options(options): 208 | if option == DHCP_OPTION_OP: 209 | self.op = ord(value) 210 | # We only care about interesting "incoming" DHCP ops. 211 | if self.op not in (DHCP_OP_DHCPDISCOVER, DHCP_OP_DHCPREQUEST): 212 | raise UninterestingDhcpPacket() 213 | elif (option in (DHCP_OPTION_CLIENT_UUID, 214 | DHCP_OPTION_CLIENT_UUID2) and 215 | len(value[1:]) == DHCP_CLIENT_UUID_LENGTH): 216 | # First byte of the UUID is \0 217 | self.uuid = _unpack_uuid(value[1:]) 218 | elif option == DHCP_OPTION_VENDOR_CLASS_ID and value.startswith('PXEClient'): 219 | self.is_pxe_request = True 220 | elif option == DHCP_OPTION_REQUESTED_IP: 221 | self.requested_ip = _unpack_ip(value) 222 | else: 223 | # Keep them around, in case other code feels like 224 | # being knowledgeable. 225 | self.unknown_options.append((option, value)) 226 | 227 | 228 | class DHCPServer(object): 229 | def __init__(self, interface, bootfile, router=None, tftp_server=None, 230 | answer_all_requests=False, name_servers=None): 231 | self.interface = interface 232 | self.ip, self.netmask, self.mac = get_ip_config_for_iface(interface) 233 | self.name_servers = name_servers 234 | self.bootfile = bootfile 235 | self.router = router or self.ip 236 | self.tftp_server = tftp_server or self.ip 237 | self.answer_all_requests = answer_all_requests 238 | self.ips_allocated = {} 239 | 240 | self.sock = socket.socket(socket.PF_PACKET, socket.SOCK_RAW) 241 | self.sock.bind((self.interface, ETHERNET_IP_PROTO)) 242 | 243 | def serve_forever(self): 244 | l.info('Serving PXE DHCP requests on %s' % self.interface) 245 | while True: 246 | data = self.sock.recv(4096) 247 | try: 248 | pkt = DhcpPacket(data) 249 | self.handle_dhcp_request(pkt) 250 | except (NotDhcpPacketError, UninterestingDhcpPacket): 251 | continue 252 | 253 | def handle_dhcp_request(self, pkt): 254 | if not pkt.is_pxe_request and not self.answer_all_requests: 255 | l.info('Ignoring non-PXE DHCP request') 256 | return 257 | 258 | # Clean up old leases before trying to get one for our new 259 | # client. 260 | self.gc_allocated_ips() 261 | 262 | if pkt.op == DHCP_OP_DHCPDISCOVER: 263 | ip = self.generate_free_ip() 264 | l.info('Offering to boot client %s (uuid : %s)' % (ip, pkt.uuid)) 265 | elif pkt.op == DHCP_OP_DHCPREQUEST: 266 | timeout = time.time() + DHCP_LEASE_TIMEOUT_INTERNAL 267 | if (pkt.requested_ip and 268 | pkt.requested_ip not in self.ips_allocated): 269 | self.ips_allocated[pkt.requested_ip] = timeout 270 | ip = pkt.requested_ip 271 | else: 272 | ip = self.generate_free_ip() 273 | self.ips_allocated[ip] = timeout 274 | l.info('PXE booting client %s (uuid : %s)' % (ip, pkt.uuid)) 275 | 276 | self.sock.send(self.encode_dhcp_reply(pkt, ip)) 277 | 278 | def gc_allocated_ips(self): 279 | current = time.time() 280 | old = [ip for ip, to in self.ips_allocated.items() 281 | if to <= current] 282 | for ip in old: 283 | l.info('Lease on %s expired' % ip) 284 | del self.ips_allocated[ip] 285 | 286 | def encode_dhcp_reply(self, request_pkt, client_ip): 287 | # Basic DHCP reply 288 | reply = struct.pack('!B' # The op (0x2) 289 | 'B' # The htype (Ethernet -> 0x1) 290 | 'B' # The hlen (0x6) 291 | 'x' # The hops field, useless 292 | 'L' # XID 293 | '8x' # Useless fields 294 | '4s' # Client IP address 295 | '4s' # Next server IP address (TFTP server) 296 | '4x' # Useless fields 297 | '6s' # Client MAC address 298 | '74x' # BOOTP legacy padding. 299 | '128s' # PXE boot file 300 | 'L', # Magic cookie 301 | 0x2, 0x1, 0x6, request_pkt.xid, 302 | _pack_ip(client_ip), _pack_ip(self.tftp_server), 303 | request_pkt.client_mac, self.bootfile, 304 | DHCP_MAGIC_COOKIE) 305 | 306 | # DHCP options relevant to PXE 307 | reply_kind = { 308 | DHCP_OP_DHCPDISCOVER: DHCP_OP_DHCPOFFER, 309 | DHCP_OP_DHCPREQUEST: DHCP_OP_DHCPACK 310 | }[request_pkt.op] 311 | dhcp_options = [ 312 | (DHCP_OPTION_OP, chr(reply_kind)), 313 | (DHCP_OPTION_LEASE_TIME, struct.pack('!L', DHCP_LEASE_TIMEOUT)), 314 | (DHCP_OPTION_SUBNET, _pack_ip(self.netmask)), 315 | (DHCP_OPTION_ROUTER, _pack_ip(self.router)), 316 | (DHCP_OPTION_SERVER_ID, _pack_ip(self.ip)), 317 | ] 318 | 319 | if self.name_servers: 320 | dns_servers = '' 321 | for name_server in self.name_servers: 322 | dns_servers += _pack_ip(name_server) 323 | dhcp_options.append((DHCP_OPTION_DNS, dns_servers)) 324 | 325 | buf = [] 326 | for code, data in dhcp_options: 327 | buf.append(struct.pack('!BB', code, len(data))) 328 | buf.append(data) 329 | reply += ''.join(buf) 330 | 331 | # Construct the UDP datagram. We don't checksum, for 332 | # simplicity. UDP conformant clients should not care anyway, we 333 | # set the field to the "checksum not computed" value. 334 | reply = struct.pack('!HHH2x', 67, 68, len(reply) + 8) + reply 335 | 336 | # Now the IP datagram... 337 | ip_header1 = struct.pack('!BxH4xBB', 0x45, 20+len(reply), 0xFF, 338 | IP_UDP_PROTO) 339 | ip_header2 = struct.pack('4s4s', _pack_ip(self.ip), 340 | _pack_ip('255.255.255.255')) 341 | # Header checksum computation 342 | checksum = 0 343 | for v in struct.unpack('!5H', ip_header1) + \ 344 | struct.unpack('!4H', ip_header2): 345 | checksum += v 346 | if checksum > 2**16: 347 | checksum = (checksum & 0xFFFF) + 1 348 | checksum = 0xFFFF - checksum 349 | reply = ip_header1 + struct.pack('!H', checksum) + ip_header2 + reply 350 | 351 | # And finally the ethernet frame. 352 | reply = struct.pack('!6s6sH', _pack_mac('ff:ff:ff:ff:ff:ff'), 353 | _pack_mac(self.mac), 354 | ETHERNET_IP_PROTO) + reply 355 | 356 | # Bingo, one DHCP reply russian doll^W^Wpacket! 357 | return reply 358 | 359 | def generate_free_ip(self): 360 | server_ip = struct.unpack('!L', _pack_ip(self.ip))[0] 361 | netmask = struct.unpack('!L', _pack_ip(self.netmask))[0] 362 | anti_netmask = 0xFFFFFFFF - netmask 363 | 364 | while True: 365 | entropy = random.getrandbits(32) 366 | 367 | client_ip = (server_ip & netmask) | (entropy & anti_netmask) 368 | 369 | # Exclude using the server's address, the network's 370 | # address, the broadcast address, and any IP already in 371 | # use. 372 | if (client_ip == server_ip or 373 | (client_ip & netmask) == 0 or 374 | (client_ip | netmask) == 0xFFFFFFFF): 375 | continue 376 | 377 | ip = _unpack_ip(struct.pack('!L', client_ip)) 378 | if ip in self.ips_allocated: 379 | continue 380 | 381 | return ip 382 | 383 | 384 | def main(): 385 | import optparse 386 | 387 | usage = "Usage: %prog [options] " 388 | parser = optparse.OptionParser(usage=usage) 389 | parser.add_option("-t", "--tftp-server", dest="tftp_server", 390 | help="The IP address of the TFTP server, if not running " 391 | "on this machine", default=None) 392 | parser.add_option("-g", "--gateway", dest="router", 393 | help="The IP address of the default gateway, if not " 394 | "this machine", default=None) 395 | parser.add_option("-a", "--answer-all-dhcp-requests", dest="answer_all_requests", 396 | help="Enables DHCP response to all clients, " 397 | "default is PXE clients only", action="store_true", default=False) 398 | parser.add_option("-n", "--name-servers", dest="name_servers", action='append', metavar='NAME_SERVER', 399 | help="Domain Name Servers (DNS) IPs to provide to DHCP client. " 400 | "Use multiple flags to specify up to 3 DNS servers", default=None) 401 | parser.add_option("-v", "--verbose", dest="loglevel", action="store_const", 402 | const=logging.INFO, help="Output information messages", 403 | default=logging.WARNING) 404 | 405 | (options, args) = parser.parse_args() 406 | 407 | if len(args) != 2: 408 | parser.print_help() 409 | return 1 410 | 411 | if options.name_servers and len(options.name_servers) > 3: 412 | print('Error: up to 3 DNS servers allowed\n') 413 | parser.print_help() 414 | return 1 415 | 416 | iface, bootfile = args 417 | 418 | # Setup notification logging 419 | notify.StreamEngine.install(l, stream=sys.stdout, 420 | loglevel=options.loglevel, 421 | fmt='%(levelname)s(%(name)s): %(message)s') 422 | 423 | try: 424 | server = DHCPServer(iface, bootfile, router=options.router, 425 | tftp_server=options.tftp_server, 426 | answer_all_requests=options.answer_all_requests) 427 | server.serve_forever() 428 | except socket.error as e: 429 | sys.stderr.write('Socket error (%s): %s!\n' % 430 | (errno.errorcode[e.args[0]], e.args[1])) 431 | return 1 432 | 433 | return 0 434 | 435 | if __name__ == '__main__': 436 | try: 437 | sys.exit(main()) 438 | except KeyboardInterrupt: 439 | pass 440 | -------------------------------------------------------------------------------- /ptftplib/notify.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Author: Maxime Petazzoni 3 | # maxime.petazzoni@bulix.org 4 | # 5 | # This file is part of pTFTPd. 6 | # 7 | # pTFTPd is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # pTFTPd is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | # General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with pTFTPd. If not, see . 19 | 20 | """Notification and logging system for the pTFTPd tool suite. 21 | 22 | This module implements a notification engine for the pTFTPd tools using 23 | Python's logging module. Its main feature include easily configurable 24 | notifications from various TFTP events such as start and end of a file 25 | transfer. 26 | 27 | These event notifications can be routed to several destinations by adding one 28 | or more engines to the notification chain. 29 | """ 30 | 31 | import logging 32 | import sys 33 | 34 | # Transfer states 35 | TRANSFER_STARTED = 1 36 | TRANSFER_COMPLETED = 2 37 | TRANSFER_FAILED = 3 38 | 39 | _STATE_NAMES = { 40 | TRANSFER_STARTED: 'STARTED', 41 | TRANSFER_COMPLETED: 'COMPLETED', 42 | TRANSFER_FAILED: 'FAILED', 43 | } 44 | 45 | 46 | class NullEngine(logging.Handler): 47 | """A no-op notification engine. Simply results in no logging messages being 48 | outputted anywhere.""" 49 | 50 | def emit(self, record): 51 | pass 52 | 53 | @staticmethod 54 | def install(logger): 55 | logger.addHandler(NullEngine()) 56 | 57 | 58 | class StreamEngine(logging.StreamHandler): 59 | """Simple stream log handler, similar to what you get using 60 | logging.basicConfig.""" 61 | 62 | def __init__(self, stream, loglevel, fmt): 63 | """Creates a new notification engine that simply logs to the given 64 | stream. 65 | 66 | Args: 67 | stream (stream): logging stream. 68 | loglevel (logging.loglevel): minimum level of messages to be 69 | outputted. 70 | fmt (string format): default format string to apply 71 | on log messages. 72 | """ 73 | 74 | logging.StreamHandler.__init__(self, stream) 75 | 76 | self.setFormatter(logging.Formatter(fmt)) 77 | self.setLevel(loglevel) 78 | 79 | @staticmethod 80 | def install(logger, stream=sys.stderr, loglevel=logging.WARNING, 81 | fmt='%(message)s'): 82 | handler = StreamEngine(stream, loglevel, fmt) 83 | logger.addHandler(handler) 84 | 85 | 86 | class DetailFilter(logging.Filter): 87 | """This log filter filters log records that don't possess the extra 88 | information we require for advanced notifications (host, port, file name 89 | and transfer state).""" 90 | 91 | def filter(self, record): 92 | r = record.__dict__ 93 | return all(['host' in r, 'port' in r, 'file' in r, 'state' in r]) 94 | 95 | 96 | class DetailledStreamEngine(StreamEngine): 97 | """The DetailledStreamEngine is a extension of the StreamEngine define 98 | above designed to log detailed notifications. Pertinent log records are 99 | filtered using the DetailFilter, as set up by the install() method.""" 100 | 101 | def emit(self, record): 102 | """Emits the given LogRecord object, first replacing the transfer state 103 | by its string representation. The original state numeric value is 104 | restored afterwards for other log handlers down the chain.""" 105 | 106 | state = record.state 107 | record.state = _STATE_NAMES[record.state] 108 | 109 | # Emit the log entry using the parent's method 110 | StreamEngine.emit(self, record) 111 | record.state = state 112 | 113 | @staticmethod 114 | def install(logger, stream=sys.stderr, loglevel=logging.INFO, 115 | fmt='%(message)s (%(host)s:%(port)d#%(file)s %(state)s)'): 116 | handler = DetailledStreamEngine(stream, loglevel, fmt) 117 | handler.addFilter(DetailFilter()) 118 | logger.addHandler(handler) 119 | 120 | 121 | class CallbackEngine(logging.Handler): 122 | """The CallbackEngine is another notification engine, using a callback 123 | mechanism. When a LogRecord is received by this handler and makes it 124 | through the DetailFilter, a callback function matchin the transfer state 125 | provided in the LogRecord object is called, passing the detail information 126 | along.""" 127 | 128 | def __init__(self, callbacks): 129 | """Creates a callback notification engine using the provided callback 130 | mapping. This handler has a default loglevel of logging.DEBUG, hence 131 | making sure all messages that pass the filter will be processed and 132 | result in a callback call.""" 133 | 134 | logging.Handler.__init__(self, logging.DEBUG) 135 | self.callbacks = callbacks 136 | 137 | def _nop(self, **kwargs): 138 | """Define a no-op callback to use as a default when no callback is 139 | provided for a transfer state.""" 140 | pass 141 | 142 | def emit(self, record): 143 | """Call the defined callback for the transfer state found in the log 144 | record.""" 145 | 146 | callback = self.callbacks.get(record.state, self._nop) 147 | callback(host=record.host, 148 | port=record.port, 149 | file=record.file, 150 | state=record.state) 151 | 152 | @staticmethod 153 | def install(logger, callbacks=None): 154 | if callbacks is None: 155 | callbacks = {} 156 | handler = CallbackEngine(callbacks) 157 | handler.addFilter(DetailFilter()) 158 | logger.addHandler(handler) 159 | 160 | 161 | def getLogger(name): 162 | """Return a named logger usable with the notification engines defined in 163 | this module. This logger is set with a loglevel of logging.DEBUG to make 164 | sure all log messages are processed by the logger and handed over to the 165 | attached handlers. It is then the responsibility of the handlers to define 166 | their desired logging level.""" 167 | 168 | l = logging.getLogger(name) 169 | l.setLevel(logging.DEBUG) 170 | return l 171 | -------------------------------------------------------------------------------- /ptftplib/proto.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Author: Maxime Petazzoni 3 | # maxime.petazzoni@bulix.org 4 | # 5 | # This file is part of pTFTPd. 6 | # 7 | # pTFTPd is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # pTFTPd is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | # General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with pTFTPd. If not, see . 19 | 20 | import re 21 | import struct 22 | 23 | from . import notify 24 | 25 | l = notify.getLogger('tftp-proto') 26 | notify.NullEngine.install(l) 27 | 28 | _LOG_PROTO = False 29 | 30 | # Uncomment these lines to enable full protocol dump. 31 | # import sys 32 | # import logging 33 | # 34 | # _LOG_PROTO = True 35 | # notify.StreamEngine.install(l, sys.stderr, logging.DEBUG) 36 | 37 | # The following values are defined in the following RFC documents: 38 | # - RFC1350 - The TFTP Protocol (revision 2) 39 | # - RFC2347 - TFTP Option Extension 40 | # - RFC2348 - TFTP Blocksize option 41 | # - RFC2349 - TFTP Timeout interval and Transfer size options 42 | # - RFC7440 - TFTP Windowsize Option 43 | 44 | # TFTP data packet size. A data packet with a length less than this 45 | # size is considered as being the last packet of the transmission. 46 | TFTP_DEFAULT_PACKET_SIZE = 512 47 | 48 | # Enhanced data packet size for LAN networks 49 | TFTP_LAN_PACKET_SIZE = 1400 50 | 51 | # TFTP default window size (equivalent to the option not being used). 52 | TFTP_DEFAULT_WINDOW_SIZE = 1 53 | 54 | # Enhanced window size for LAN networks 55 | TFTP_LAN_WINDOW_SIZE = 8 56 | 57 | # Maximum packet number (2^16). When reached, we may want to wraparound and 58 | # reset to TFTP_PACKETNUM_RESET to continue transfer (some clients may not 59 | # support it). 60 | # The wraparound can be disabled with --rfc1350. 61 | TFTP_PACKETNUM_MAX = 65536 62 | 63 | # Packet number value for reset (see above) 64 | TFTP_PACKETNUM_RESET = 0 65 | 66 | # TFTP opcodes 67 | TFTP_OPCODE_LEN = 2 68 | 69 | OP_RRQ = 1 70 | OP_WRQ = 2 71 | OP_DATA = 3 72 | OP_ACK = 4 73 | OP_ERROR = 5 74 | OP_OACK = 6 75 | 76 | TFTP_OPS = { 77 | OP_RRQ: 'RRQ', 78 | OP_WRQ: 'WRQ', 79 | OP_DATA: 'DATA', 80 | OP_ACK: 'ACK', 81 | OP_ERROR: 'ERROR', 82 | OP_OACK: 'OACK', 83 | } 84 | 85 | # TFTP error codes 86 | ERROR_UNDEF = 0 87 | ERROR_FILE_NOT_FOUND = 1 88 | ERROR_ACCESS_VIOLATION = 2 89 | ERROR_DISK_FULL = 3 90 | ERROR_ILLEGAL_OP = 4 91 | ERROR_UNKNOWN_ID = 5 92 | ERROR_FILE_ALREADY_EXISTS = 6 93 | ERROR_NO_SUCH_USER = 7 94 | ERROR_OPTION_NEGOCIATION = 8 95 | 96 | TFTP_ERRORS = { 97 | ERROR_UNDEF: 'Not defined, see error message (if any).', 98 | ERROR_FILE_NOT_FOUND: 'File not found.', 99 | ERROR_ACCESS_VIOLATION: 'Access violation.', 100 | ERROR_DISK_FULL: 'Disk full or allocation exceeded.', 101 | ERROR_ILLEGAL_OP: 'Illegal TFTP operation.', 102 | ERROR_UNKNOWN_ID: 'Unknown transfer ID.', 103 | ERROR_FILE_ALREADY_EXISTS: 'File already exists.', 104 | ERROR_NO_SUCH_USER: 'No such user.', 105 | ERROR_OPTION_NEGOCIATION: 'Option negociation failed', 106 | } 107 | 108 | # TFTP transfer modes (mail is deprecated as of RFC1350) 109 | TFTP_MODES = set(['netascii', 'octet']) 110 | NETASCII_TO_OCTET = re.compile('\r\n') 111 | OCTET_TO_NETASCII = re.compile('\r?\n') 112 | 113 | # TFTP option names, as defined in RFC2348, RFC2349 and RFC7440 114 | TFTP_OPTION_BLKSIZE = 'blksize' 115 | TFTP_OPTION_TIMEOUT = 'timeout' 116 | TFTP_OPTION_TSIZE = 'tsize' 117 | TFTP_OPTION_WINDOWSIZE = 'windowsize' 118 | 119 | TFTP_OPTIONS = set([ 120 | TFTP_OPTION_BLKSIZE, 121 | TFTP_OPTION_TIMEOUT, 122 | TFTP_OPTION_TSIZE, 123 | TFTP_OPTION_WINDOWSIZE 124 | ]) 125 | 126 | TFTP_BLKSIZE_MIN = 8 127 | TFTP_BLKSIZE_MAX = 65464 128 | 129 | TFTP_TIMEOUT_MIN = 1 130 | TFTP_TIMEOUT_MAX = 255 131 | 132 | TFTP_WINDOWSIZE_MIN = 1 133 | TFTP_WINDOWSIZE_MAX = 65535 134 | 135 | 136 | # noinspection PyPep8Naming 137 | class TFTPHelper(object): 138 | """ 139 | Static helper methods for the TFTP protocol. 140 | """ 141 | 142 | def createRRQ(filename, mode, opts): 143 | """ 144 | Creates a packed TFTP RRQ packet. 145 | 146 | Args: 147 | filename: the name of the requested file. 148 | mode: the transfer mode (must be one from TFTP_MODES). 149 | opts: a dictionnary of TFTP options. 150 | Returns: 151 | The request packet as a string. 152 | """ 153 | 154 | if _LOG_PROTO: 155 | l.debug(' > %s: %s (mode: %s, opts: %s)', 156 | TFTP_OPS[OP_RRQ], filename, mode, opts) 157 | 158 | packet = struct.pack('!H%dsc%dsc' % (len(filename), len(mode)), 159 | OP_RRQ, 160 | filename.encode('ascii'), b'\0', 161 | mode.encode('ascii'), b'\0') 162 | 163 | for opt, val in opts.items(): 164 | packet += struct.pack('!%dsc%dsc' % (len(opt), len(str(val))), 165 | opt.encode('ascii'), b'\0', 166 | str(val).encode('ascii'), b'\0') 167 | 168 | return packet 169 | 170 | def createWRQ(filename, mode, opts): 171 | """ 172 | Creates a packed TFTP WRQ packet. 173 | 174 | Args: 175 | filename: the name of the requested file. 176 | mode: the transfer mode (must be one from TFTP_MODES). 177 | opts: a dictionnary of TFTP options. 178 | Returns: 179 | The request packet as a string. 180 | """ 181 | 182 | if _LOG_PROTO: 183 | l.debug(' > %s: %s (mode: %s, opts: %s)', 184 | TFTP_OPS[OP_WRQ], filename, mode, opts) 185 | 186 | packet = struct.pack('!H%dsc%dsc' % (len(filename), len(mode)), 187 | OP_WRQ, 188 | filename.encode('ascii'), b'\0', 189 | mode.encode('ascii'), b'\0') 190 | 191 | for opt, val in opts.items(): 192 | packet += struct.pack('!%dsc%dsc' % (len(opt), len(str(val))), 193 | opt.encode('ascii'), b'\0', 194 | str(val).encode('ascii'), b'\0') 195 | 196 | return packet 197 | 198 | def createACK(num): 199 | """ 200 | Creates a packed TFTP ACK packet. 201 | 202 | Args: 203 | num (integer): the data packet number to ack. 204 | Returns: 205 | The ack packet as a string. 206 | """ 207 | 208 | if _LOG_PROTO: 209 | if num > 0: 210 | l.debug(' > %s: #%d', TFTP_OPS[OP_ACK], num) 211 | elif num == 0: 212 | l.debug(' > %s: Acknowledging transfer.', TFTP_OPS[OP_ACK]) 213 | 214 | return struct.pack('!HH', OP_ACK, num) 215 | 216 | def createERROR(errno, errmsg=None): 217 | """ 218 | Creates a packed TFTP error packet. 219 | 220 | Args: 221 | errno (integer): the TFTP error code. 222 | errmsg (string): when using error code ERROR_UNDEF, a specific 223 | error message can be attached to the error packet via this 224 | parameter. 225 | Returns: 226 | The error packet as a string. 227 | """ 228 | 229 | error = TFTP_ERRORS[errno] 230 | if errno == ERROR_UNDEF and errmsg: 231 | error = errmsg 232 | 233 | if _LOG_PROTO: 234 | l.debug(' > %s: %d %s', TFTP_OPS[OP_ERROR], errno, error) 235 | return struct.pack('!HH%dsc' % len(error), 236 | OP_ERROR, errno, 237 | error.encode('ascii'), b'\0') 238 | 239 | def createDATA(num, data): 240 | """ 241 | Creates a packed TFTP data packet. 242 | 243 | Args: 244 | num: the data packet number (int). 245 | data: the data to be sent (bytes). 246 | Returns: 247 | The data packet as a string. 248 | """ 249 | 250 | if _LOG_PROTO: 251 | l.debug(' > %s: #%d (%d bytes)', TFTP_OPS[OP_DATA], num, 252 | len(data)) 253 | return struct.pack('!HH%ds' % len(data), OP_DATA, num, data) 254 | 255 | def createOACK(opts): 256 | """ 257 | Creates an OACK TFTP packet for the given options. 258 | 259 | Args: 260 | opts (dict): a dictionnary of TFTP options. 261 | Returns: 262 | The OACK packet as a string. 263 | """ 264 | 265 | if _LOG_PROTO: 266 | l.debug(' > %s: %s', TFTP_OPS[OP_OACK], opts) 267 | 268 | opts_str = '' 269 | for opt, val in opts.items(): 270 | opts_str += '%s%c%s%c' % (opt, '\0', val, '\0') 271 | 272 | return struct.pack('!H%ds' % len(opts_str), 273 | OP_OACK, opts_str.encode('ascii')) 274 | 275 | def parseRRQ(request): 276 | """ 277 | Parses a RRQ packet to extract the requested mode and filename. 278 | 279 | Args: 280 | request: the RRQ packet without the TFTP opcode (string). 281 | Returns: 282 | The filename, mode and options of the request. 283 | Throws: 284 | If the parsing failed, a SyntaxError is raised. 285 | """ 286 | 287 | packet = request.split(b'\0')[:-1] 288 | 289 | # If the length of the parsed list is not even, the packet is 290 | # malformed and thus parsing should fail. 291 | if len(packet) % 2 != 0: 292 | raise SyntaxError('invalid request packet') 293 | 294 | filename = packet[0].decode('ascii') 295 | if not filename: 296 | raise SyntaxError('invalid filename') 297 | 298 | mode = packet[1].decode('ascii').lower() 299 | if mode not in TFTP_MODES: 300 | raise SyntaxError('unknown mode %s' % mode) 301 | 302 | opts = {} 303 | for i in range(2, len(packet)-1, 2): 304 | opt = packet[i].decode('ascii').lower() 305 | val = packet[i+1].decode('ascii') 306 | 307 | if opt in TFTP_OPTIONS: 308 | opts[opt] = val 309 | 310 | if _LOG_PROTO: 311 | l.debug(' < %s: %s (mode: %s, opts: %s)', 312 | TFTP_OPS[OP_RRQ], filename, mode, opts) 313 | return filename, mode, opts 314 | 315 | def parseWRQ(request): 316 | """ 317 | Parses a WRQ packet to extract the requested mode and filename. 318 | 319 | Args: 320 | request: the WRQ packet without the TFTP opcode (string). 321 | Returns: 322 | The filename, mode and options of the request. 323 | Throws: 324 | If the parsing failed, a SyntaxError is raised. 325 | """ 326 | 327 | packet = request.split(b'\0')[:-1] 328 | 329 | # If the length of the parsed list is not even, the packet is 330 | # malformed and thus parsing should fail. 331 | if len(packet) % 2 != 0: 332 | raise SyntaxError('invalid request packet') 333 | 334 | filename = packet[0].decode('ascii') 335 | if not filename: 336 | raise SyntaxError('invalid filename') 337 | 338 | mode = packet[1].decode('ascii').lower() 339 | if mode not in TFTP_MODES: 340 | raise SyntaxError('unknown mode %s' % mode) 341 | 342 | opts = {} 343 | for i in range(2, len(packet)-1, 2): 344 | opt = packet[i].decode('ascii').lower() 345 | val = packet[i+1].decode('ascii') 346 | 347 | if opt in TFTP_OPTIONS: 348 | opts[opt] = val 349 | 350 | if _LOG_PROTO: 351 | l.debug(' < %s: %s (mode: %s, opts: %s)', 352 | TFTP_OPS[OP_WRQ], filename, mode, opts) 353 | return filename, mode, opts 354 | 355 | def parseACK(request): 356 | """ 357 | Parses a ACK packet to extract the data packet number acked. 358 | 359 | Args: 360 | request: the ACK packet without the TFTP opcode (string). 361 | Returns: 362 | The number of the ACKed packet. 363 | Throws: 364 | If the parsing failed, a SyntaxError is raised. 365 | """ 366 | 367 | try: 368 | packet = struct.unpack('!H', request) 369 | except struct.error: 370 | raise SyntaxError('invalid acknowledgment packet') 371 | 372 | num = packet[0] 373 | 374 | if _LOG_PROTO: 375 | if num > 0: 376 | l.debug(' < %s: #%d', TFTP_OPS[OP_ACK], num) 377 | elif num == 0: 378 | l.debug(' < %s: Transfer acknowledged.', TFTP_OPS[OP_ACK]) 379 | 380 | return num 381 | 382 | def parseDATA(request): 383 | """ 384 | Parses a DATA packet to extract the data packet number acked. 385 | 386 | Args: 387 | request: the DATA packet without the TFTP opcode (string). 388 | Returns: 389 | A (num, data) tuple containing the number of the data packet 390 | and the data itself. 391 | Throws: 392 | If the parsing failed, a SyntaxError is raised. 393 | """ 394 | 395 | try: 396 | packet = struct.unpack('!H', request[:2]) 397 | except struct.error: 398 | raise SyntaxError('invalid data packet') 399 | 400 | num = packet[0] 401 | data = request[2:] 402 | 403 | if _LOG_PROTO: 404 | l.debug(' < %s: #%d (%d bytes)', 405 | TFTP_OPS[OP_DATA], num, len(data)) 406 | return num, data 407 | 408 | def parseERROR(request): 409 | """ 410 | Parses an ERROR packet to extract the data packet number acked. 411 | 412 | Args: 413 | request: the ERROR packet without the TFTP opcode (string). 414 | Returns: 415 | A (errno, errmsg) tuple containing the error number and the 416 | associated error message. 417 | Throws: 418 | If the parsing failed, a SyntaxError is raised. 419 | """ 420 | 421 | try: 422 | packet = struct.unpack('!H', request[:2]) 423 | errno = packet[0] 424 | errmsg = request[2:].split(b'\0')[0].decode('ascii') 425 | except (struct.error, IndexError): 426 | raise SyntaxError('invalid error packet') 427 | 428 | if _LOG_PROTO: 429 | l.debug(' < %s: %s', TFTP_OPS[OP_ERROR], errmsg) 430 | return errno, errmsg 431 | 432 | def parseOACK(request): 433 | """ 434 | Parses an OACK packet to extract the validated options. 435 | 436 | Args: 437 | request (string): the OACK packet without the TFTP opcode. 438 | Returns: 439 | A dictionnary of the acknowledged options. 440 | """ 441 | 442 | packet = request.split(b'\0')[:-1] 443 | 444 | # If the length of the parsed list is not even, the packet is 445 | # malformed and thus parsing should fail. 446 | if len(packet) % 2 != 0: 447 | raise SyntaxError('invalid request packet') 448 | 449 | opts = {} 450 | for i in range(0, len(packet)-1, 2): 451 | opt = packet[i].decode('ascii').lower() 452 | val = packet[i+1].decode('ascii') 453 | opts[opt] = val 454 | 455 | if _LOG_PROTO: 456 | l.debug(' < %s: %s', TFTP_OPS[OP_OACK], opts) 457 | 458 | return opts 459 | 460 | def get_opcode(data): 461 | if data: 462 | try: 463 | return struct.unpack('!H', data[:2])[0] 464 | except (struct.error, KeyError): 465 | raise SyntaxError('invalid packet') 466 | 467 | return None 468 | 469 | def parse_options(opts): 470 | """ 471 | Parse and validate the given options. 472 | 473 | Args: 474 | opts (dict): a dictionnary of validated TFTP options to use. 475 | Returns: 476 | The clean dictionnary of options. 477 | """ 478 | 479 | used = {} 480 | 481 | if TFTP_OPTION_BLKSIZE in opts: 482 | blksize = int(opts[TFTP_OPTION_BLKSIZE]) 483 | if TFTP_BLKSIZE_MIN <= blksize <= TFTP_BLKSIZE_MAX: 484 | used[TFTP_OPTION_BLKSIZE] = blksize 485 | else: 486 | return None 487 | else: 488 | used[TFTP_OPTION_BLKSIZE] = TFTP_DEFAULT_PACKET_SIZE 489 | 490 | if TFTP_OPTION_TIMEOUT in opts: 491 | timeout = int(opts[TFTP_OPTION_TIMEOUT]) 492 | if TFTP_TIMEOUT_MIN <= timeout <= TFTP_TIMEOUT_MAX: 493 | used[TFTP_OPTION_TIMEOUT] = timeout 494 | else: 495 | return None 496 | 497 | if TFTP_OPTION_TSIZE in opts: 498 | used[TFTP_OPTION_TSIZE] = int(opts[TFTP_OPTION_TSIZE]) 499 | 500 | if TFTP_OPTION_WINDOWSIZE in opts: 501 | windowsize = int(opts[TFTP_OPTION_WINDOWSIZE]) 502 | if TFTP_WINDOWSIZE_MIN <= windowsize <= TFTP_WINDOWSIZE_MAX: 503 | used[TFTP_OPTION_WINDOWSIZE] = windowsize 504 | else: 505 | return None 506 | else: 507 | used[TFTP_OPTION_WINDOWSIZE] = TFTP_DEFAULT_WINDOW_SIZE 508 | 509 | return used 510 | 511 | def get_data_size(blksize): 512 | """Return the expected size of a DATA packet, in bytes.""" 513 | return TFTP_OPCODE_LEN + 2 + blksize 514 | 515 | createRRQ = staticmethod(createRRQ) 516 | createWRQ = staticmethod(createWRQ) 517 | createACK = staticmethod(createACK) 518 | createDATA = staticmethod(createDATA) 519 | createERROR = staticmethod(createERROR) 520 | createOACK = staticmethod(createOACK) 521 | 522 | parseRRQ = staticmethod(parseRRQ) 523 | parseWRQ = staticmethod(parseWRQ) 524 | parseACK = staticmethod(parseACK) 525 | parseDATA = staticmethod(parseDATA) 526 | parseERROR = staticmethod(parseERROR) 527 | parseOACK = staticmethod(parseOACK) 528 | 529 | get_opcode = staticmethod(get_opcode) 530 | parse_options = staticmethod(parse_options) 531 | get_data_size = staticmethod(get_data_size) 532 | -------------------------------------------------------------------------------- /ptftplib/pxeserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: David Anderson 5 | # dave@natulte.net 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | """PXE Server. 23 | 24 | This program offers a streamlined combination of ptftpd.py and 25 | dhcpd.py in a single executable. With both daemons running side by 26 | side, the amount of configuration required to get a PXE boot system 27 | working is laughably small: specify the interface, the directory to 28 | serve over TFTP and the name of the PXE boot file, and you're all set. 29 | """ 30 | 31 | import errno 32 | import logging 33 | import socket 34 | import sys 35 | import threading 36 | 37 | from . import notify 38 | from . import tftpserver 39 | from . import dhcpserver 40 | 41 | l = notify.getLogger('pxed') 42 | 43 | 44 | class DHCPThread(threading.Thread): 45 | def __init__(self, iface, bootfile, router, answer_all_requests, name_servers): 46 | threading.Thread.__init__(self) 47 | self.setDaemon(True) 48 | self.server = dhcpserver.DHCPServer(iface, bootfile, router=router, 49 | answer_all_requests=answer_all_requests, 50 | name_servers=name_servers) 51 | 52 | def run(self): 53 | self.server.serve_forever() 54 | 55 | 56 | def main(): 57 | import optparse 58 | 59 | usage = "Usage: %prog [options] " 60 | parser = optparse.OptionParser(usage=usage) 61 | parser.add_option("-r", "--rfc1350", dest="strict_rfc1350", 62 | action="store_true", default=False, 63 | help="Run in strict RFC1350 compliance mode, " 64 | "with no extensions") 65 | parser.add_option("-g", "--gateway", dest="router", default=None, 66 | help="The IP address of the default gateway " 67 | "(by default, the IP of the PXE server)") 68 | parser.add_option("-a", "--answer-all-dhcp-requests", dest="answer_all_requests", 69 | help="Enables DHCP response to all clients, " 70 | "default is PXE clients only", action="store_true", default=False) 71 | parser.add_option("-n", "--name-servers", dest="name_servers", action='append', metavar='NAME_SERVER', 72 | help="Domain Name Servers (DNS) IPs to provide to DHCP client. " 73 | "Use multiple flags to specify up to 3 DNS servers", default=None) 74 | parser.add_option("-v", "--verbose", dest="loglevel", action="store_const", 75 | const=logging.INFO, help="Output information messages", 76 | default=logging.WARNING) 77 | parser.add_option("-D", "--debug", dest="loglevel", action="store_const", 78 | const=logging.DEBUG, help="Output debugging information") 79 | 80 | (options, args) = parser.parse_args() 81 | if len(args) != 3: 82 | parser.print_help() 83 | return 1 84 | 85 | if options.name_servers and len(options.name_servers) > 3: 86 | print('Error: up to 3 DNS servers allowed\n') 87 | parser.print_help() 88 | return 1 89 | 90 | iface, root, bootfile = args 91 | 92 | # Setup notification logging 93 | notify.StreamEngine.install(l, stream=sys.stdout, 94 | loglevel=options.loglevel, 95 | fmt='%(levelname)s(%(name)s): %(message)s') 96 | notify.StreamEngine.install(dhcpserver.l, stream=sys.stdout, 97 | loglevel=options.loglevel, 98 | fmt='%(levelname)s(%(name)s): %(message)s') 99 | notify.StreamEngine.install(tftpserver.l, stream=sys.stdout, 100 | loglevel=options.loglevel, 101 | fmt='%(levelname)s(%(name)s): %(message)s') 102 | 103 | try: 104 | dhcp = DHCPThread(iface, bootfile, options.router, options.answer_all_requests, 105 | options.name_servers) 106 | tftp = tftpserver.TFTPServer(iface, root, 107 | strict_rfc1350=options.strict_rfc1350) 108 | except tftpserver.TFTPServerConfigurationError as e: 109 | sys.stderr.write('TFTP server configuration error: %s!\n' % 110 | e.args) 111 | return 1 112 | except socket.error as e: 113 | sys.stderr.write('Socket error (%s): %s!\n' % 114 | (errno.errorcode[e.args[0]], e.args[1])) 115 | return 1 116 | 117 | dhcp.start() 118 | tftp.serve_forever() 119 | return 0 120 | 121 | if __name__ == '__main__': 122 | try: 123 | sys.exit(main()) 124 | except KeyboardInterrupt: 125 | pass 126 | -------------------------------------------------------------------------------- /ptftplib/state.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Author: Maxime Petazzoni 3 | # maxime.petazzoni@bulix.org 4 | # 5 | # This file is part of pTFTPd. 6 | # 7 | # pTFTPd is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # pTFTPd is distributed in the hope that it will be useful, but 13 | # WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | # General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with pTFTPd. If not, see . 19 | 20 | import errno 21 | import os 22 | import time 23 | 24 | from . import proto 25 | 26 | STATE_SEND = 1 27 | STATE_SEND_OACK = 2 28 | STATE_SEND_LAST = 4 29 | STATE_RECV = 8 30 | STATE_RECV_ACK = 16 31 | STATE_ERROR = 32 32 | 33 | STATE_TIMEOUT_SECS = 10 34 | 35 | 36 | class TFTPState(object): 37 | """ 38 | This class represents a peer's state. Because SocketServer is not 39 | stateful, we use a global state registry of TFTPState objects to 40 | keep track of each request's state through the life of a connexion 41 | with a client. 42 | """ 43 | 44 | def __init__(self, peer, op, path, filename, mode, loop_packet=True): 45 | """ 46 | Initializes a new TFTP state for the given peer. 47 | 48 | Args: 49 | peer (tuple): a tuple (ip, port) describing the peer. 50 | op (integer): the operation this state refers to. 51 | path (string): the server root path. 52 | filename (string): the relative path of the used file. 53 | mode (string): the transfer mode requested. 54 | loop_packet (boolean): activate packet number wraparound. 55 | Returns: 56 | A new, initialized TFTPState object with the options parsed. 57 | """ 58 | 59 | (self.peer, self.op, self.path, self.filename, self.mode) = \ 60 | (peer, op, path, filename, mode) 61 | self.filepath = os.path.abspath(os.path.join(self.path, self.filename)) 62 | 63 | self.tid = None # Transfer ID 64 | self.file = None # File object to read from or 65 | # write to 66 | self.filesize = 0 # File size in bytes 67 | self.state = None # Current transaction state 68 | # (send/recv/last/error) 69 | self.done = False # Transaction complete flag 70 | 71 | # Option defaults 72 | self.opts = { 73 | proto.TFTP_OPTION_BLKSIZE: proto.TFTP_DEFAULT_PACKET_SIZE, 74 | proto.TFTP_OPTION_WINDOWSIZE: proto.TFTP_DEFAULT_WINDOW_SIZE, 75 | } 76 | 77 | self.last_seen = time.time() 78 | 79 | self.packetnum = None # Current data packet number 80 | self.last_acked = 0 # Packet number of the last acked 81 | # DATA packet 82 | self.loop_packetnum = loop_packet # Packet number wraparound toggle 83 | self.total_packets = 0 # Total number of data packets sent 84 | # or received 85 | self.error = None # TFTP error code to send 86 | # (if state == error) 87 | self.data = None 88 | self.tosend = bytes() 89 | 90 | def extra(self, state): 91 | """Build an extra information dictionnary we can pass to logging 92 | functions when necessary. 93 | 94 | Args: 95 | state (notify state): a transfer state (see notify module). 96 | 97 | Returns a dictionnary containing the host, port, file and state 98 | mappings. 99 | """ 100 | return {'host': self.peer[0], 101 | 'port': self.peer[1], 102 | 'tid': self.tid, 103 | 'file': self.filename, 104 | 'state': state} 105 | 106 | def __del__(self): 107 | if not self.file: 108 | return 109 | 110 | try: 111 | self.file.close() 112 | except AttributeError: 113 | pass 114 | 115 | def __str__(self): 116 | s = "TFTPState/%s for %s<%s>\n" % (proto.TFTP_OPS[self.op], 117 | self.peer, 118 | self.tid) 119 | s += " filepath: %s\n" % self.filepath 120 | s += " mode : %s\n" % self.mode 121 | s += " state: %s\n" % self.state 122 | s += " opts : %s\n" % self.opts 123 | 124 | return s 125 | 126 | def __repr__(self): 127 | return self.__str__() 128 | 129 | def purge(self): 130 | """ 131 | Remove the used file on demand. 132 | """ 133 | 134 | if self.filepath and self.file: 135 | try: 136 | os.remove(self.filepath) 137 | return True 138 | except OSError: 139 | return False 140 | 141 | def ping(self): 142 | """ 143 | Update the last seen value to restart the watchdog. 144 | """ 145 | 146 | self.last_seen = time.time() 147 | 148 | def set_opts(self, opts): 149 | """ 150 | Set this state options. 151 | 152 | Args: 153 | opts (dict): a dictionnary of validated options. 154 | """ 155 | 156 | if not opts: 157 | return 158 | 159 | if opts.get(proto.TFTP_OPTION_TSIZE) == 0: 160 | opts[proto.TFTP_OPTION_TSIZE] = self.filesize 161 | 162 | self.opts = opts 163 | 164 | def next(self): 165 | """ 166 | Returns the next packet to be sent depending on this state. 167 | 168 | Args: 169 | None. 170 | Returns: 171 | The next packet to be sent, as a string (built through TFTPHelper) 172 | or None if no action is required. 173 | """ 174 | 175 | self.ping() 176 | 177 | if self.state == STATE_SEND: 178 | return self.__next_send() 179 | elif self.state == STATE_SEND_OACK: 180 | return self.__next_send_oack() 181 | elif self.state == STATE_RECV: 182 | return self.__next_recv() 183 | elif self.state == STATE_RECV_ACK: 184 | return self.__next_recv_ack() 185 | elif self.state == STATE_ERROR: 186 | return self.__next_error() 187 | 188 | return None 189 | 190 | def __next_send(self): 191 | blksize = self.opts[proto.TFTP_OPTION_BLKSIZE] 192 | fromfile = self.file.read(blksize - len(self.tosend)) 193 | 194 | # Convert LF to CRLF if needed 195 | if self.mode == 'netascii': 196 | fromfile = proto.OCTET_TO_NETASCII.sub(b'\r\n', fromfile) 197 | 198 | self.data = self.tosend + fromfile 199 | self.tosend = bytes() 200 | 201 | self.packetnum += 1 202 | self.total_packets += 1 203 | 204 | # Packet number wraparound 205 | if self.packetnum == proto.TFTP_PACKETNUM_MAX and self.loop_packetnum: 206 | self.packetnum = proto.TFTP_PACKETNUM_RESET 207 | 208 | data_len = len(self.data) 209 | if data_len > blksize: 210 | self.tosend = self.data[blksize:] 211 | self.data = self.data[:blksize] 212 | elif data_len < blksize: 213 | self.file.close() 214 | self.state = STATE_SEND_LAST 215 | 216 | packet = proto.TFTPHelper.createDATA(self.packetnum, self.data) 217 | 218 | # If the window hasn't been completed yet, send the DATA packet 219 | # and provide a continuation for the next DATA packet to send in the 220 | # window. 221 | next_window = self.last_acked + self.opts[proto.TFTP_OPTION_WINDOWSIZE] 222 | if self.state == STATE_SEND and self.packetnum < next_window: 223 | return packet, self.next 224 | 225 | # Otherwise just send this DATA packet and we'll wait for the client to 226 | # reply with a ACK. 227 | return packet 228 | 229 | def __next_send_oack(self): 230 | self.state = STATE_SEND if self.op == proto.OP_RRQ else STATE_RECV 231 | return proto.TFTPHelper.createOACK(self.opts) 232 | 233 | def __next_recv_ack(self): 234 | self.state = STATE_RECV 235 | return proto.TFTPHelper.createACK(0) 236 | 237 | def __next_recv(self): 238 | # Convert CRLF to LF if needed 239 | if self.mode == 'netascii': 240 | self.data = proto.NETASCII_TO_OCTET.sub('\n', self.data) 241 | 242 | data_len = len(self.data) 243 | if data_len < self.opts[proto.TFTP_OPTION_BLKSIZE]: 244 | self.done = True 245 | 246 | try: 247 | self.filesize += len(self.data) 248 | self.file.write(self.data) 249 | except IOError as e: 250 | self.file.close() 251 | if e.errno == errno.ENOSPC: 252 | return proto.TFTPHelper.createERROR(proto.ERROR_DISK_FULL) 253 | else: 254 | print('Undefined error occured: {}!' 255 | .format(errno.errorcode[e.errno])) 256 | return proto.TFTPHelper.createERROR(proto.ERROR_UNDEF) 257 | 258 | if self.done: 259 | self.file.close() 260 | 261 | packetnum = self.packetnum 262 | 263 | # Compute next packet number 264 | if not self.done: 265 | self.packetnum += 1 266 | self.total_packets += 1 267 | 268 | # Packet number wraparound 269 | if self.packetnum == proto.TFTP_PACKETNUM_MAX and self.loop_packetnum: 270 | self.packetnum = proto.TFTP_PACKETNUM_RESET 271 | 272 | # Only return a ACK if the window size has been reached, or when done 273 | next_window = self.last_acked + self.opts[proto.TFTP_OPTION_WINDOWSIZE] 274 | if self.done or packetnum >= next_window: 275 | self.last_acked = packetnum 276 | return proto.TFTPHelper.createACK(packetnum) 277 | 278 | def __next_error(self): 279 | return proto.TFTPHelper.createERROR(self.error) 280 | -------------------------------------------------------------------------------- /ptftplib/tftpclient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: Maxime Petazzoni 5 | # maxime.petazzoni@bulix.org 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | 23 | from __future__ import print_function 24 | 25 | try: 26 | # noinspection PyShadowingBuiltins 27 | input = raw_input # Py2 28 | except NameError: 29 | pass # Py3 30 | 31 | """Simple TFTP client. 32 | 33 | This is a very simple TFTP client that supports pull/push files from a 34 | TFTP server. It fully supports the TFTP specification as defined in 35 | RFC1350. It also supports the TFTP Option Extension protocol (per 36 | RFC2347), the block size option as defined in RFC2348 and the transfer 37 | size option from RFC2349. 38 | 39 | Note that this program currently does *not* support the timeout 40 | interval option from RFC2349. 41 | """ 42 | 43 | import os 44 | import shutil 45 | import socket 46 | import stat 47 | import sys 48 | import tempfile 49 | import time 50 | 51 | from . import notify 52 | from . import proto 53 | from . import state 54 | 55 | l = notify.getLogger('tftp') 56 | 57 | # UDP datagram size 58 | _UDP_TRANSFER_SIZE = 2**16 59 | 60 | _PTFTP_DEFAULT_PORT = 69 61 | _PTFTP_DEFAULT_HOST = 'localhost' 62 | _PTFTP_DEFAULT_MODE = 'octet' 63 | 64 | _PTFTP_DEFAULT_OPTS = { 65 | proto.TFTP_OPTION_BLKSIZE: proto.TFTP_LAN_PACKET_SIZE, 66 | proto.TFTP_OPTION_WINDOWSIZE: proto.TFTP_LAN_WINDOW_SIZE, 67 | } 68 | 69 | _PTFTP_RFC1350_OPTS = { 70 | proto.TFTP_OPTION_BLKSIZE: proto.TFTP_DEFAULT_PACKET_SIZE, 71 | } 72 | 73 | 74 | # noinspection PyPep8Naming 75 | class UDPMessageSocket(object): 76 | """A wrapper around a UDP datagram socket that provides per-message 77 | receival semantics. 78 | 79 | This wrapper is very specific to the TFTP client use case. Messages are 80 | expected to be received one at a time, expect for DATA messages which may 81 | come streaming when a window size greater than one is negotiated between 82 | the client and the server. When that's the case, reading from the socket 83 | returns more than one message but the client (and its state machine) still 84 | expects to process them one at a time. 85 | 86 | By utilizing the knowledge of the expected size of those DATA messages 87 | (based on the negotiated block size) this wrapper slices the received data 88 | accordingly to expose the desired one-at-a-time semantics. 89 | """ 90 | 91 | def __init__(self): 92 | self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 93 | self.reset() 94 | 95 | @property 96 | def rport(self): 97 | return self._rport 98 | 99 | def settimeout(self, timeout): 100 | self._sock.settimeout(timeout) 101 | 102 | def send(self, message, peer): 103 | self._sock.sendto(message, peer) 104 | 105 | def reset(self): 106 | self._buffer = None 107 | self._rport = None 108 | 109 | def close(self): 110 | self._sock.close() 111 | 112 | def recv(self, blksize): 113 | if not self._buffer: 114 | self._recv() 115 | if not self._buffer: 116 | return None 117 | 118 | opcode = proto.TFTPHelper.get_opcode(self._buffer) 119 | if opcode == proto.OP_DATA: 120 | size = proto.TFTPHelper.get_data_size(blksize) 121 | data, self._buffer = self._buffer[:size], self._buffer[size:] 122 | else: 123 | data, self._buffer = self._buffer, None 124 | 125 | return data 126 | 127 | def _recv(self): 128 | (data, (address, port)) = self._sock.recvfrom(_UDP_TRANSFER_SIZE) 129 | if not self._rport: 130 | self._rport = port 131 | elif port != self._rport: 132 | # Ignore packets from other peers 133 | return 134 | self._buffer = data 135 | 136 | 137 | # noinspection PyPep8Naming 138 | class TFTPClient(object): 139 | """ 140 | A small and simple TFTP client to pull/push files from a TFTP server. 141 | """ 142 | 143 | PTFTP_STATE = None 144 | 145 | def __init__(self, peer, opts=None, mode='octet', rfc1350=False, 146 | notification_callbacks=None): 147 | """ 148 | Initializes the TFTP client. 149 | 150 | Args: 151 | peer (tuple): a (host, port) tuple describing the server to connect 152 | to. 153 | opts (dict): a dictionnary of TFTP option values to use, 154 | or None to disable them (defaults to None). 155 | mode (string): the transfer mode to use by default, must be one of 156 | TFTP_MODES (defaults to octet). 157 | notification_callbacks (dict): a dictionary of notification 158 | callbacks to use for the callback notification engine. 159 | """ 160 | 161 | if notification_callbacks is None: 162 | notification_callbacks = {} 163 | 164 | self.peer = peer 165 | self.transfer_mode = mode 166 | self.error = False 167 | self.rfc1350 = rfc1350 168 | 169 | self.opts = opts 170 | 171 | if rfc1350: 172 | self.opts = _PTFTP_RFC1350_OPTS 173 | print('Running in RFC1350 compliance mode.') 174 | else: 175 | if not self.opts: 176 | self.opts = _PTFTP_DEFAULT_OPTS 177 | 178 | # This one is mandatory 179 | if proto.TFTP_OPTION_BLKSIZE not in self.opts: 180 | self.opts[proto.TFTP_OPTION_BLKSIZE] = \ 181 | _PTFTP_DEFAULT_OPTS[proto.TFTP_OPTION_BLKSIZE] 182 | 183 | # Finally, install the provided callbacks 184 | notify.CallbackEngine.install(l, notification_callbacks) 185 | 186 | def connect(self): 187 | """ 188 | Connects the sock to the remote host. Because TFTP is an UDP 189 | protocol, this has barely no effect. 190 | 191 | Args: 192 | None. 193 | """ 194 | 195 | self.sock = UDPMessageSocket() 196 | self.sock.settimeout(state.STATE_TIMEOUT_SECS) 197 | print('Connected to {}:{}.'.format(self.peer[0], self.peer[1])) 198 | 199 | def finish(self): 200 | """ 201 | Closes the connection with the server. 202 | 203 | Args: 204 | None. 205 | """ 206 | 207 | self.sock.close() 208 | 209 | def serve_forever(self): 210 | """ 211 | Serve the client prompt until the user exits the program. 212 | 213 | Args: 214 | None. 215 | """ 216 | 217 | self.connect() 218 | 219 | while True: 220 | print() 221 | try: 222 | command = input('tftp> ') 223 | except EOFError: 224 | print() 225 | break 226 | 227 | if not command: 228 | continue 229 | 230 | cmd_parts = command.split(' ') 231 | if cmd_parts[0] in ('?', 'help'): 232 | self.usage() 233 | elif cmd_parts[0] in ('g', 'get'): 234 | self.get(cmd_parts[1:]) 235 | elif cmd_parts[0] in ('p', 'put'): 236 | self.put(cmd_parts[1:]) 237 | elif cmd_parts[0] in ('q', 'quit'): 238 | break 239 | elif cmd_parts[0] in ('m', 'mode'): 240 | self.mode(cmd_parts[1:]) 241 | elif cmd_parts[0] in ('b', 'blksize'): 242 | self.blksize(cmd_parts[1:]) 243 | elif cmd_parts[0] in ('w', 'windowsize'): 244 | self.windowsize(cmd_parts[1:]) 245 | else: 246 | print('Unrecognized command. Try help.') 247 | 248 | self.finish() 249 | 250 | def usage(self): 251 | """ 252 | Display the client help to the user. 253 | 254 | Args: 255 | None. 256 | """ 257 | 258 | print('Available commands:') 259 | print() 260 | print('? help Display help') 261 | print('q quit Quit the TFTP client') 262 | print('m mode [newmode] Display or change transfer mode') 263 | print('b blksize [newsize] Display or change the transfer block size') 264 | print('w windowsize [newsize] Display or change the transfer window size') 265 | print() 266 | print('g get [-f] Get from server.') 267 | print(' (use -f to overwrite local file)') 268 | print('p put Push to the server') 269 | print() 270 | 271 | def handle(self): 272 | """ 273 | Handle an incoming TFTP packet and dispatch it to one of the 274 | serve methods below. 275 | 276 | Args: 277 | None. 278 | """ 279 | 280 | if not self.PTFTP_STATE: 281 | self.error = (True, 'Connection state error.') 282 | return 283 | 284 | # Reset the error flag 285 | self.error = False 286 | self.sock.reset() 287 | 288 | # Process incoming packet until the state is cleared by the 289 | # end of a succesfull transmission or an error 290 | while not self.PTFTP_STATE.done and not self.error: 291 | try: 292 | blksize = self.opts[proto.TFTP_OPTION_BLKSIZE] 293 | request = self.sock.recv(blksize) 294 | if not request: 295 | continue 296 | except socket.timeout: 297 | self.error = (True, 'Connection timed out.') 298 | return 299 | 300 | if not self.PTFTP_STATE.tid: 301 | self.PTFTP_STATE.tid = self.sock.rport 302 | print('Communicating with {}:{}.' 303 | .format(self.peer[0], self.PTFTP_STATE.tid)) 304 | 305 | # Reset the response packet 306 | response = None 307 | 308 | # Get the packet opcode and dispatch 309 | opcode = proto.TFTPHelper.get_opcode(request) 310 | if not opcode: 311 | self.error = (True, None) 312 | response = proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 313 | elif opcode not in proto.TFTP_OPS: 314 | self.error = (True, 315 | 'Unknown or unsupported operation %d!' % opcode) 316 | response = proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 317 | else: 318 | try: 319 | handler = getattr(self, 'serve' + proto.TFTP_OPS[opcode]) 320 | response = handler(opcode, request[2:]) 321 | except AttributeError: 322 | self.error = (True, 'Operation not supported.') 323 | response = proto.TFTPHelper.createERROR( 324 | proto.ERROR_UNDEF, 'Operation not supported.') 325 | 326 | # Finally, send the response if we have one 327 | if response: 328 | peer = (self.peer[0], self.PTFTP_STATE.tid) 329 | self.sock.send(response, peer) 330 | 331 | def serveOACK(self, op, request): 332 | """ 333 | Serves OACK packets. 334 | 335 | Args: 336 | op (integer): the TFTP opcode. 337 | request (string): the TFTP packet without its opcode. 338 | Returns: 339 | A response packet (as a string) or None if the request is 340 | ignored or completed. 341 | """ 342 | 343 | try: 344 | opts = proto.TFTPHelper.parseOACK(request) 345 | except SyntaxError: 346 | # Ignore malfored OACK packets 347 | return None 348 | 349 | if not self.PTFTP_STATE: 350 | return proto.TFTPHelper.createERROR(proto.ERROR_UNKNOWN_ID) 351 | 352 | # Analyze received options 353 | opts = proto.TFTPHelper.parse_options(opts) 354 | if opts: 355 | # HOOK: this is where we should check that we accept the 356 | # options provided by the server (tsize/timeout/...). 357 | 358 | self.PTFTP_STATE.set_opts(opts) 359 | else: 360 | self.error = (True, 'Transfer options parsing failed.') 361 | self.PTFTP_STATE.state = state.STATE_ERROR 362 | self.PTFTP_STATE.error = proto.ERROR_OPTION_NEGOCIATION 363 | 364 | if self.PTFTP_STATE.state == state.STATE_RECV: 365 | self.PTFTP_STATE.state = state.STATE_RECV_ACK 366 | 367 | return self.PTFTP_STATE.next() 368 | 369 | def serveACK(self, op, request): 370 | """ 371 | Serves ACK packets. 372 | 373 | Args: 374 | op (integer): the TFTP opcode. 375 | request (string): the TFTP packet without its opcode. 376 | Returns: 377 | A response packet (as a string) or None if the request is 378 | ignored or completed. 379 | """ 380 | 381 | try: 382 | num = proto.TFTPHelper.parseACK(request) 383 | except SyntaxError: 384 | # Ignore malfored ACK packets 385 | return None 386 | 387 | if not self.PTFTP_STATE: 388 | return proto.TFTPHelper.createERROR(proto.ERROR_UNKNOWN_ID) 389 | 390 | if self.PTFTP_STATE.state == state.STATE_SEND: 391 | if self.PTFTP_STATE.packetnum != num: 392 | self.error = (True, 393 | 'Got ACK with incoherent data packet number.') 394 | self.PTFTP_STATE.state = state.STATE_ERROR 395 | self.PTFTP_STATE.error = proto.ERROR_ILLEGAL_OP 396 | 397 | if not self.rfc1350 and num >= proto.TFTP_PACKETNUM_MAX-1: 398 | print('Packet number wraparound.') 399 | 400 | return self.PTFTP_STATE.next() 401 | 402 | elif self.PTFTP_STATE.state == state.STATE_SEND_LAST: 403 | self.PTFTP_STATE.done = True 404 | return None 405 | 406 | print('ERROR: Unexpected ACK!') 407 | self.error = (True, None) 408 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 409 | 410 | def serveDATA(self, op, request): 411 | """ 412 | Serves DATA packets. 413 | 414 | Args: 415 | op (integer): the TFTP opcode. 416 | request (string): the TFTP packet without its opcode. 417 | Returns: 418 | A response packet (as a string) or None if the request is 419 | ignored for some reason. 420 | """ 421 | 422 | try: 423 | num, data = proto.TFTPHelper.parseDATA(request) 424 | except SyntaxError: 425 | # Ignore malformed DATA packets 426 | return None 427 | 428 | if not self.PTFTP_STATE: 429 | return proto.TFTPHelper.createERROR(proto.ERROR_UNKNOWN_ID) 430 | 431 | if len(data) > self.PTFTP_STATE.opts[proto.TFTP_OPTION_BLKSIZE]: 432 | self.error = (True, None) 433 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 434 | 435 | if self.PTFTP_STATE.state == state.STATE_RECV: 436 | if num != self.PTFTP_STATE.packetnum: 437 | self.error = (True, 'Got DATA with incoherent packet number.') 438 | self.PTFTP_STATE.state = state.STATE_ERROR 439 | self.PTFTP_STATE.error = proto.ERROR_ILLEGAL_OP 440 | else: 441 | self.PTFTP_STATE.data = data 442 | 443 | if not self.PTFTP_STATE.done and not self.rfc1350 and \ 444 | num >= proto.TFTP_PACKETNUM_MAX - 1: 445 | print('Packet number wraparound.') 446 | 447 | return self.PTFTP_STATE.next() 448 | 449 | print('ERROR: Unexpected DATA!') 450 | self.error = (True, None) 451 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 452 | 453 | def serveERROR(self, op, request): 454 | """ 455 | Serves ERROR packets. 456 | 457 | Args: 458 | op (integer): the TFTP opcode. 459 | request (string): the TFTP packet without its opcode. 460 | Returns: 461 | A response packet (as a string) or None if the request is 462 | ignored for some reason. 463 | """ 464 | 465 | try: 466 | errno, errmsg = proto.TFTPHelper.parseERROR(request) 467 | except SyntaxError: 468 | # Ignore malformed ERROR packets 469 | return None 470 | 471 | # Clearing state 472 | if self.PTFTP_STATE.op == proto.OP_RRQ: 473 | self.PTFTP_STATE.purge() 474 | 475 | self.error = (True, errmsg) 476 | return None 477 | 478 | def get(self, args): 479 | """ 480 | Implements the GET command to retrieve a file from the server. 481 | 482 | Args: 483 | args (list): the list of arguments passed to the command. 484 | Returns: 485 | True or False depending on the success of the operation. 486 | """ 487 | 488 | if len(args) < 1 or len(args) > 2: 489 | print('Usage: get [-f] ') 490 | return False 491 | 492 | filepath = args[0] 493 | overwrite = False 494 | 495 | if len(args) == 2: 496 | filepath = args[1] 497 | if args[0] == '-f': 498 | overwrite = True 499 | 500 | (_, filename) = os.path.split(filepath) 501 | 502 | # First, check we're not going to overwrite an existing file 503 | if not overwrite: 504 | try: 505 | open(filename) 506 | print('Error: local file {} already exists!'.format(filename)) 507 | print('Use get -f to overwrite the local file.') 508 | return False 509 | except IOError: 510 | pass 511 | 512 | self.PTFTP_STATE = state.TFTPState(self.peer, proto.OP_RRQ, 513 | '', filepath, self.transfer_mode, 514 | not self.rfc1350) 515 | 516 | # Then, before sending anything to the server, open the file 517 | # for writing 518 | try: 519 | # We don't want tempfile to automatically delete the temporary 520 | # file on close() as we have to copy its content to the destination 521 | # file first. We'll handle it's deletion on our own. 522 | self.PTFTP_STATE.file = tempfile.NamedTemporaryFile(delete=False) 523 | self.PTFTP_STATE.packetnum = 1 524 | self.PTFTP_STATE.state = state.STATE_RECV 525 | except IOError as e: 526 | print('Error: {}'.format(os.strerror(e.errno))) 527 | print('Can\'t write to temporary file {}!' 528 | .format(self.PTFTP_STATE.file.name)) 529 | return False 530 | 531 | opts = dict(self.opts) 532 | 533 | # When not running in RFC1350 compliance mode, append tsize: 0 534 | # to the list of options in the request to get the requested 535 | # file size back in the OACK. 536 | if not self.rfc1350: 537 | opts[proto.TFTP_OPTION_TSIZE] = 0 538 | 539 | # Everything's OK, let's go 540 | print('Retrieving "%s" from the remote host...' % filename) 541 | 542 | packet = proto.TFTPHelper.createRRQ(filepath, self.transfer_mode, opts) 543 | 544 | transfer_start = time.time() 545 | self.sock.send(packet, self.peer) 546 | self.handle() 547 | transfer_time = time.time() - transfer_start 548 | 549 | if self.error: 550 | error, errmsg = self.error 551 | if error and errmsg: 552 | print('Error: {}'.format(errmsg)) 553 | # Remove the temporary file on error. The destionation file, 554 | # if it already existed, is left untouched. 555 | self.PTFTP_STATE.file.close() 556 | os.remove(self.PTFTP_STATE.file.name) 557 | return False 558 | 559 | # Copy the temporary file to its final destination 560 | try: 561 | shutil.copy(self.PTFTP_STATE.file.name, filename) 562 | except IOError as e: 563 | print('Error: {}'.format(os.strerror(e.errno))) 564 | print('Can\'t copy temporary file to local file {}!' 565 | .format(filename)) 566 | return False 567 | 568 | print('Transfer complete, {} bytes ({:.2f} kB/s)' 569 | .format(self.PTFTP_STATE.filesize, 570 | self.__get_speed(self.PTFTP_STATE.filesize, 571 | transfer_time))) 572 | self.PTFTP_STATE.file.close() 573 | os.remove(self.PTFTP_STATE.file.name) 574 | return True 575 | 576 | def put(self, args): 577 | """ 578 | Implements the PUT command to push a file to the server. 579 | 580 | Args: 581 | args (list): the list of arguments passed to the command. 582 | Returns: 583 | True or False depending on the success of the operation. 584 | """ 585 | 586 | if len(args) != 1: 587 | print('Usage: put ') 588 | return 589 | 590 | filepath = args[0] 591 | 592 | self.PTFTP_STATE = state.TFTPState(self.peer, proto.OP_WRQ, 593 | '', filepath, self.transfer_mode, 594 | not self.rfc1350) 595 | 596 | try: 597 | self.PTFTP_STATE.file = open(filepath, 'rb') 598 | self.PTFTP_STATE.filesize = os.stat(filepath)[stat.ST_SIZE] 599 | self.PTFTP_STATE.packetnum = 0 600 | self.PTFTP_STATE.state = state.STATE_SEND 601 | except IOError as e: 602 | print('Error: {}'.format(os.strerror(e.errno))) 603 | print('Can\'t read from local file {}!'.format(filepath)) 604 | return False 605 | 606 | opts = dict(self.opts) 607 | 608 | # When not running in RFC1350 compliance mode, append the 609 | # tsize option to the request options to specify the 610 | # transfered file size to the server. 611 | if not self.rfc1350: 612 | opts[proto.TFTP_OPTION_TSIZE] = self.PTFTP_STATE.filesize 613 | 614 | # Everything's OK, let's go 615 | print('Pushing "%s" to the remote host...' % filepath) 616 | 617 | packet = proto.TFTPHelper.createWRQ(filepath, self.transfer_mode, opts) 618 | 619 | transfer_start = time.time() 620 | self.sock.send(packet, self.peer) 621 | self.handle() 622 | transfer_time = time.time() - transfer_start 623 | 624 | if self.error: 625 | error, errmsg = self.error 626 | if error and errmsg: 627 | print('Error: {}'.format(errmsg)) 628 | return False 629 | 630 | print('Transfer complete, {} bytes ({:.2f} kB/s)' 631 | .format(self.PTFTP_STATE.filesize, 632 | self.__get_speed(self.PTFTP_STATE.filesize, 633 | transfer_time))) 634 | return True 635 | 636 | def mode(self, args): 637 | if len(args) > 1: 638 | print('Usage: mode [newmode]') 639 | return 640 | 641 | if not len(args): 642 | print('Current transfer mode: {}.'.format(self.transfer_mode)) 643 | print('Available transfer modes: {}' 644 | .format(', '.join(proto.TFTP_MODES))) 645 | return 646 | 647 | if args[0].lower() in proto.TFTP_MODES: 648 | self.transfer_mode = args[0].lower() 649 | print('Mode set to {}.'.format(self.transfer_mode)) 650 | else: 651 | print('Unknown transfer mode, use one of: {}' 652 | .format(', '.join(proto.TFTP_MODES))) 653 | 654 | def blksize(self, args): 655 | if len(args) > 1: 656 | print('Usage: blksize [newsize]') 657 | return 658 | 659 | if not len(args): 660 | print('Current block size: {} byte(s).' 661 | .format(self.opts[proto.TFTP_OPTION_BLKSIZE])) 662 | return 663 | 664 | try: 665 | self.opts[proto.TFTP_OPTION_BLKSIZE] = int(args[0]) 666 | print('Block size set to {} byte(s).' 667 | .format(self.opts[proto.TFTP_OPTION_BLKSIZE])) 668 | except ValueError: 669 | print('Block size must be a number!') 670 | 671 | def windowsize(self, args): 672 | if len(args) > 1: 673 | print('Usage: windowsize [newsize]') 674 | return 675 | 676 | if not len(args): 677 | print('Current window size: {} packet(s).' 678 | .format(self.opts[proto.TFTP_OPTION_WINDOWSIZE])) 679 | return 680 | 681 | try: 682 | self.opts[proto.TFTP_OPTION_WINDOWSIZE] = int(args[0]) 683 | print('Window size set to {} packet(s).' 684 | .format(self.opts[proto.TFTP_OPTION_WINDOWSIZE])) 685 | except ValueError: 686 | print('Window size must be a number!') 687 | 688 | def __get_speed(self, filesize, time): 689 | return filesize / 1024.0 / time 690 | 691 | 692 | def usage(): 693 | print('usage: %s [options]' % sys.argv[0]) 694 | print() 695 | print(' -? --help Get help') 696 | print(' -h --host Set TFTP server (default: %s)' % _PTFTP_DEFAULT_HOST) 697 | print(' -p --port Define the port to connect to (default: %d)' % _PTFTP_DEFAULT_PORT) 698 | print(' -m --mode Set transfer mode (default: %s)' % _PTFTP_DEFAULT_MODE) 699 | print(' Must be one of:', ', '.join(proto.TFTP_MODES)) 700 | print() 701 | print('Available extra options (using the TFTP option extension protocol):') 702 | print(' -b --blksize Set transfer block size (default: %d bytes)' % proto.TFTP_LAN_PACKET_SIZE) 703 | print(' Must be between %d and %d' % (proto.TFTP_BLKSIZE_MIN, proto.TFTP_BLKSIZE_MAX)) 704 | print(' -w --windowsize Set streaming window size (default: %d)' % proto.TFTP_LAN_WINDOW_SIZE) 705 | print(' Must be between %d and %d' % (proto.TFTP_WINDOWSIZE_MIN, proto.TFTP_WINDOWSIZE_MAX)) 706 | print() 707 | print('To disable the use of TFTP extensions:') 708 | print(' -r --rfc1350 Strictly comply to the RFC1350 only (no extensions)') 709 | print(' This will discard other TFTP option values.') 710 | print() 711 | 712 | 713 | def main(): 714 | # TODO: convert to optparse 715 | import getopt 716 | 717 | try: 718 | opts, args = getopt.getopt(sys.argv[1:], '?h:p:b:w:m:r', 719 | ['help', 'host=', 720 | 'port=', 'blksize=', 721 | 'windowsize=', 'mode=', 722 | 'rfc1350']) 723 | except getopt.GetoptError: 724 | usage() 725 | return 1 726 | 727 | host = _PTFTP_DEFAULT_HOST 728 | port = _PTFTP_DEFAULT_PORT 729 | mode = _PTFTP_DEFAULT_MODE 730 | exts = {} 731 | rfc1350 = False 732 | 733 | for opt, val in opts: 734 | if opt in ('-?', '--help'): 735 | usage() 736 | return 0 737 | if opt in ('-h', '--host'): 738 | host = val 739 | if opt in ('-p', '--port'): 740 | try: 741 | port = int(val) 742 | except ValueError: 743 | print('Port must be a number!') 744 | return 2 745 | if opt in ('-b', '--blksize'): 746 | try: 747 | exts[proto.TFTP_OPTION_BLKSIZE] = int(val) 748 | except ValueError: 749 | print('Block size must be a number!') 750 | return 2 751 | if opt in ('-w', '--windowsize'): 752 | try: 753 | exts[proto.TFTP_OPTION_WINDOWSIZE] = int(val) 754 | except ValueError: 755 | print('Window size must be a number!') 756 | return 2 757 | if opt in ('-m', '--mode'): 758 | if val in proto.TFTP_MODES: 759 | mode = val 760 | else: 761 | print('Transfer mode must be one of: {}' 762 | .format(', '.join(proto.TFTP_MODES))) 763 | return 2 764 | if opt in ('-r', '--rfc1350'): 765 | rfc1350 = True 766 | 767 | client = TFTPClient((host, port), exts, mode, rfc1350) 768 | client.serve_forever() 769 | print('Goodbye.') 770 | return 0 771 | 772 | if __name__ == '__main__': 773 | try: 774 | sys.exit(main()) 775 | except KeyboardInterrupt: 776 | pass 777 | -------------------------------------------------------------------------------- /ptftplib/tftpserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | 4 | # Author: Maxime Petazzoni 5 | # maxime.petazzoni@bulix.org 6 | # 7 | # This file is part of pTFTPd. 8 | # 9 | # pTFTPd is free software: you can redistribute it and/or modify it 10 | # under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # pTFTPd is distributed in the hope that it will be useful, but 15 | # WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | # General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with pTFTPd. If not, see . 21 | 22 | """TFTP Server. 23 | 24 | pTFTPd is a simple TFTP daemon written in Python. It fully supports 25 | the TFTP specification as defined in RFC1350. It also supports the 26 | TFTP Option Extension protocol (per RFC2347), the block size option as 27 | defined in RFC2348 and the transfer size option from RFC2349. 28 | 29 | Note that this program currently does *not* support the timeout 30 | interval option from RFC2349. 31 | """ 32 | 33 | import errno 34 | import fcntl 35 | import logging 36 | import os 37 | import socket 38 | import stat 39 | import struct 40 | import subprocess 41 | import sys 42 | import threading 43 | import time 44 | 45 | from . import notify 46 | from . import proto 47 | from . import state 48 | 49 | try: 50 | import SocketServer as socketserver # Py2 51 | except ImportError: 52 | import socketserver # Py3 53 | 54 | l = notify.getLogger('tftpd') 55 | 56 | _PTFTPD_SERVER_NAME = 'pFTPd' 57 | _PTFTPD_DEFAULT_PORT = 69 58 | _PTFTPD_DEFAULT_PATH = '/tftpboot' 59 | 60 | # When we can't figure out the UDP datagram size with sysctl, 61 | # this is a reasonable default we can use to keep things going. 62 | _DEFAULT_UDP_DATAGRAM_SIZE = 508 63 | 64 | 65 | def get_ip_config_for_iface(iface): 66 | """Retrieve and return the IP address/netmask of the given interface. 67 | 68 | Constants from https://github.com/torvalds/linux/blob/v6.8/include/uapi/linux/sockios.h#L62 69 | """ 70 | SIOCGIFADDR = 0x8915 71 | SIOCGIFNETMASK = 0x891B 72 | iface_b = struct.pack("256s", iface.encode()[:15]) 73 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 74 | try: 75 | ip = socket.inet_ntoa(fcntl.ioctl(s, SIOCGIFADDR, iface_b)[20:24]) 76 | nm = socket.inet_ntoa(fcntl.ioctl(s, SIOCGIFNETMASK, iface_b)[20:24]) 77 | except OSError as exc: 78 | if exc.errno != errno.ENODEV: 79 | raise 80 | raise TFTPServerConfigurationError( 81 | 'Unknown network interface {}'.format(iface)) from exc 82 | return ip, nm 83 | 84 | 85 | def get_max_udp_datagram_size(): 86 | """Retrieve the maximum UDP datagram size allowed by the system.""" 87 | try: 88 | val = subprocess.check_output(['sysctl', '-n', 'net.inet.udp.maxdgram']) 89 | return int(val) 90 | except subprocess.CalledProcessError: 91 | return _DEFAULT_UDP_DATAGRAM_SIZE 92 | 93 | class TFTPServerConfigurationError(Exception): 94 | """The configuration of the pTFTPd is incorrect.""" 95 | pass 96 | 97 | 98 | # noinspection PyPep8Naming 99 | class TFTPServerHandler(socketserver.DatagramRequestHandler): 100 | """ 101 | The SocketServer UDP datagram handler for the TFTP protocol. 102 | """ 103 | 104 | def handle(self): 105 | """ 106 | Handles an incoming request by unpacking the TFTP opcode and 107 | dispatching to one of the serve* method of this class. 108 | """ 109 | request = self.rfile.read() 110 | 111 | # Get the packet opcode and dispatch 112 | opcode = proto.TFTPHelper.get_opcode(request) 113 | 114 | if not opcode: 115 | l.error('Can\'t find packet opcode, packet ignored') 116 | return 117 | 118 | if opcode not in proto.TFTP_OPS: 119 | l.error('Unknown operation %d', opcode) 120 | response = proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 121 | self.send_response(response) 122 | return 123 | 124 | try: 125 | handler = getattr(self, 'serve' + proto.TFTP_OPS[opcode]) 126 | response = handler(opcode, request[2:]) 127 | except AttributeError: 128 | l.error('Unsupported operation %s', opcode) 129 | response = proto.TFTPHelper.createERROR( 130 | proto.ERROR_UNDEF, 131 | 'Operation not supported by server.') 132 | except: 133 | response = proto.TFTPHelper.createERROR( 134 | proto.ERROR_UNDEF, 135 | 'Server error.') 136 | finally: 137 | self.send_response(response) 138 | 139 | def send_response(self, response): 140 | """ 141 | Send a response to the client. 142 | 143 | Args: 144 | response (bytes or tuple): the response packet sequence. If the 145 | argument is a simple bytestring object, it is sent as-is. If it is 146 | a tuple, it is expected to be a 2-uple containing first a 147 | bytestring packet, and second a function that, when called, returns 148 | the next packet sequence to send through this method (recursively). 149 | """ 150 | while response: 151 | if type(response) == tuple: 152 | message, response = response[0], response[1]() 153 | else: 154 | message, response = response, None 155 | 156 | self.wfile.write(message) 157 | self.wfile.flush() 158 | 159 | def finish_state(self, peer_state): 160 | self.server.clients[self.client_address] = peer_state 161 | return peer_state.next() 162 | 163 | def serveRRQ(self, op, request): 164 | """ 165 | Serves RRQ packets (GET requests). 166 | 167 | Args: 168 | op (integer): the TFTP opcode. 169 | request (string): the TFTP packet without its opcode. 170 | Returns: 171 | A response packet (as a string) or None if the request is 172 | ignored for some reason. 173 | """ 174 | 175 | try: 176 | filename, mode, opts = proto.TFTPHelper.parseRRQ(request) 177 | except SyntaxError: 178 | # Ignore malformed RRQ requests 179 | return None 180 | 181 | peer_state = state.TFTPState(self.client_address, op, 182 | self.server.root, filename, mode, 183 | not self.server.strict_rfc1350) 184 | 185 | if not peer_state.filepath.startswith(self.server.root): 186 | peer_state.state = state.STATE_ERROR 187 | peer_state.error = proto.ERROR_ACCESS_VIOLATION 188 | 189 | l.warning('Out-of-jail path requested: %s!', filename, 190 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 191 | return self.finish_state(peer_state) 192 | 193 | try: 194 | peer_state.file = open(peer_state.filepath, 'rb') 195 | peer_state.filesize = os.stat(peer_state.filepath)[stat.ST_SIZE] 196 | peer_state.packetnum = 0 197 | peer_state.state = state.STATE_SEND 198 | 199 | l.info('Serving file %s to host %s...', 200 | filename, self.client_address[0], 201 | extra=peer_state.extra(notify.TRANSFER_STARTED)) 202 | 203 | # Only set options if not running in RFC1350 compliance mode 204 | # and when option were received. 205 | if not self.server.strict_rfc1350 and len(opts): 206 | opts = proto.TFTPHelper.parse_options(opts) 207 | if opts: 208 | blksize = opts[proto.TFTP_OPTION_BLKSIZE] 209 | windowsize = opts[proto.TFTP_OPTION_WINDOWSIZE] 210 | max_window_size = int( 211 | get_max_udp_datagram_size() / 212 | proto.TFTPHelper.get_data_size(blksize)) 213 | if windowsize > max_window_size: 214 | l.info('Restricting window size to %d to fit UDP.', 215 | max_window_size) 216 | opts[proto.TFTP_OPTION_WINDOWSIZE] = max_window_size 217 | 218 | # HOOK: this is where we should check that we accept 219 | # the options requested by the client. 220 | 221 | peer_state.state = state.STATE_SEND_OACK 222 | peer_state.set_opts(opts) 223 | else: 224 | peer_state.file.close() 225 | peer_state.state = state.STATE_ERROR 226 | peer_state.error = proto.ERROR_OPTION_NEGOCIATION 227 | 228 | except IOError as e: 229 | peer_state.state = state.STATE_ERROR 230 | 231 | if e.errno == errno.ENOENT: 232 | peer_state.error = proto.ERROR_FILE_NOT_FOUND 233 | l.warning('Client requested non-existent file %s', filename, 234 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 235 | elif e.errno == errno.EACCES or e.errno == errno.EPERM: 236 | peer_state.error = proto.ERROR_ACCESS_VIOLATION 237 | l.error('Client requested inaccessible file %s', filename, 238 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 239 | else: 240 | peer_state.error = proto.ERROR_UNDEF 241 | l.error('Unknown error while accessing file %s', filename, 242 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 243 | 244 | return self.finish_state(peer_state) 245 | 246 | def serveWRQ(self, op, request): 247 | """ 248 | Serves WRQ packets (PUT requests). 249 | 250 | Args: 251 | op (integer): the TFTP opcode. 252 | request (string): the TFTP packet without its opcode. 253 | Returns: 254 | A response packet (as a string) or None if the request is 255 | ignored for some reason. 256 | """ 257 | 258 | try: 259 | filename, mode, opts = proto.TFTPHelper.parseWRQ(request) 260 | except SyntaxError: 261 | # Ignore malfored WRQ requests 262 | return None 263 | 264 | peer_state = state.TFTPState(self.client_address, op, 265 | self.server.root, filename, mode, 266 | not self.server.strict_rfc1350) 267 | 268 | if not peer_state.filepath.startswith(self.server.root): 269 | peer_state.state = state.STATE_ERROR 270 | peer_state.error = proto.ERROR_ACCESS_VIOLATION 271 | 272 | l.warning('Out-of-jail path requested: %s!', filename, 273 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 274 | return self.finish_state(peer_state) 275 | 276 | try: 277 | # Try to open the file. If it succeeds, it means the file 278 | # already exists and report the error 279 | peer_state.file = open(peer_state.filepath) 280 | peer_state.state = state.STATE_ERROR 281 | peer_state.error = proto.ERROR_FILE_ALREADY_EXISTS 282 | 283 | l.warning('Client attempted to overwrite file %s!', filename, 284 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 285 | return self.finish_state(peer_state) 286 | 287 | except IOError as e: 288 | # Otherwise, if the open failed because the file did not 289 | # exist, create it and go on 290 | if e.errno == errno.ENOENT: 291 | try: 292 | peer_state.file = open(peer_state.filepath, 'wb') 293 | peer_state.packetnum = 1 294 | peer_state.state = state.STATE_RECV_ACK 295 | l.info('Upload of %s began.', filename, 296 | extra=peer_state.extra(notify.TRANSFER_STARTED)) 297 | except IOError: 298 | peer_state.state = state.STATE_ERROR 299 | peer_state.error = proto.ERROR_ACCESS_VIOLATION 300 | l.warning('Error creating file %s for upload!', filename, 301 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 302 | else: 303 | peer_state.state = state.STATE_ERROR 304 | peer_state.error = proto.ERROR_ACCESS_VIOLATION 305 | l.warning('Error creating file %s for upload!', filename, 306 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 307 | 308 | # Only set options if not running in RFC1350 compliance mode 309 | if not self.server.strict_rfc1350 and len(opts): 310 | opts = proto.TFTPHelper.parse_options(opts) 311 | if opts: 312 | # HOOK: this is where we should check that we accept 313 | # the options requested by the client. 314 | 315 | peer_state.state = state.STATE_SEND_OACK 316 | peer_state.set_opts(opts) 317 | else: 318 | peer_state.state = state.STATE_ERROR 319 | peer_state.error = proto.ERROR_OPTION_NEGOCIATION 320 | 321 | return self.finish_state(peer_state) 322 | 323 | def serveACK(self, op, request): 324 | """ 325 | Serves ACK packets. 326 | 327 | Args: 328 | op (integer): the TFTP opcode. 329 | request (string): the TFTP packet without its opcode. 330 | Returns: 331 | A response packet (as a string) or None if the request is 332 | ignored or completed. 333 | """ 334 | 335 | try: 336 | num = proto.TFTPHelper.parseACK(request) 337 | except SyntaxError: 338 | # Ignore malfored ACK packets 339 | return None 340 | 341 | try: 342 | peer_state = self.server.clients[self.client_address] 343 | except KeyError: 344 | return proto.TFTPHelper.createERROR(proto.ERROR_UNKNOWN_ID) 345 | 346 | if peer_state.state == state.STATE_SEND_OACK: 347 | if num != 0: 348 | peer_state.state = state.STATE_ERROR 349 | peer_state.error = proto.ERROR_ILLEGAL_OP 350 | l.error('Client did not reply correctly to the OACK packet. ' 351 | 'Aborting transmission.', 352 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 353 | else: 354 | peer_state.state = state.STATE_SEND 355 | 356 | return peer_state.next() 357 | 358 | elif peer_state.state == state.STATE_SEND: 359 | if peer_state.packetnum == num + 1: 360 | # Ignore duplicate N-1 ACK packets 361 | l.debug('Got duplicate ACK packet #%d. Ignoring.', num) 362 | pass 363 | elif peer_state.packetnum != num: 364 | # TODO: handle ACK recovery when operating in streaming mode. 365 | peer_state.state = state.STATE_ERROR 366 | peer_state.error = proto.ERROR_ILLEGAL_OP 367 | l.error('Got ACK with incoherent data packet number. ' 368 | 'Aborting transfer.', 369 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 370 | 371 | if not self.server.strict_rfc1350 and \ 372 | num == proto.TFTP_PACKETNUM_MAX - 1: 373 | l.debug('Packet number wraparound.') 374 | 375 | peer_state.last_acked = num 376 | return peer_state.next() 377 | 378 | elif peer_state.state == state.STATE_RECV and num == 0: 379 | return peer_state.next() 380 | 381 | elif peer_state.state == state.STATE_ERROR: 382 | l.debug('Error ACKed. Terminating transfer.', 383 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 384 | return None 385 | 386 | elif peer_state.state == state.STATE_SEND_LAST: 387 | l.debug(' > DATA: %d data packet(s) sent.', 388 | peer_state.total_packets) 389 | l.debug(' < ACK: Transfer complete, %d byte(s).', 390 | peer_state.filesize) 391 | l.info('Transfer of file %s completed.', peer_state.filename, 392 | extra=peer_state.extra(notify.TRANSFER_COMPLETED)) 393 | del self.server.clients[self.client_address] 394 | return None 395 | 396 | l.error('Unexpected ACK!', 397 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 398 | 399 | if peer_state.op == proto.OP_WRQ: 400 | peer_state.purge() 401 | del self.server.clients[self.client_address] 402 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 403 | 404 | def serveDATA(self, op, request): 405 | """ 406 | Serves DATA packets. 407 | 408 | Args: 409 | op (integer): the TFTP opcode. 410 | request (string): the TFTP packet without its opcode. 411 | Returns: 412 | A response packet (as a string) or None if the request is 413 | ignored for some reason. 414 | """ 415 | 416 | try: 417 | num, data = proto.TFTPHelper.parseDATA(request) 418 | except SyntaxError: 419 | # Ignore malformed DATA packets 420 | return None 421 | 422 | try: 423 | peer_state = self.server.clients[self.client_address] 424 | except KeyError: 425 | return proto.TFTPHelper.createERROR(proto.ERROR_UNKNOWN_ID) 426 | 427 | if len(data) > peer_state.opts[proto.TFTP_OPTION_BLKSIZE]: 428 | l.warning('Illegal TFTP option received.', 429 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 430 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 431 | 432 | if peer_state.state == state.STATE_RECV: 433 | if num != peer_state.packetnum: 434 | l.error('Unexpected packet number! Got #%d; wanted #%d', 435 | num, peer_state.packetnum) 436 | peer_state.state = state.STATE_ERROR 437 | peer_state.error = proto.ERROR_ILLEGAL_OP 438 | else: 439 | peer_state.data = data 440 | 441 | next_state = peer_state.next() 442 | 443 | if peer_state.done: 444 | l.debug(' < DATA: %d packet(s) received.', 445 | peer_state.total_packets) 446 | l.debug(' > ACK: Transfer complete, %d byte(s).', 447 | peer_state.filesize) 448 | l.info('Transfer of file %s completed.', peer_state.filename, 449 | extra=peer_state.extra(notify.TRANSFER_COMPLETED)) 450 | del self.server.clients[self.client_address] 451 | 452 | elif (not self.server.strict_rfc1350 and 453 | num == proto.TFTP_PACKETNUM_MAX-1): 454 | l.debug('Packet number wraparound.') 455 | 456 | return next_state 457 | 458 | l.error('Unexpected DATA!', 459 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 460 | 461 | if peer_state.op == proto.OP_WRQ: 462 | peer_state.purge() 463 | del self.server.clients[self.client_address] 464 | return proto.TFTPHelper.createERROR(proto.ERROR_ILLEGAL_OP) 465 | 466 | def serveERROR(self, op, request): 467 | """ 468 | Serves ERROR packets. 469 | 470 | Args: 471 | op (integer): the TFTP opcode. 472 | request (string): the TFTP packet without its opcode. 473 | Returns: 474 | A response packet (as a string) or None if the request is 475 | ignored for some reason. 476 | """ 477 | 478 | try: 479 | errno, errmsg = proto.TFTPHelper.parseERROR(request) 480 | except SyntaxError: 481 | # Ignore malformed ERROR packets 482 | return None 483 | 484 | if self.client_address not in self.server.clients: 485 | return None 486 | 487 | # An error packet immediately terminates a connection 488 | peer_state = self.server.clients[self.client_address] 489 | 490 | l.warning('Error packet received!', 491 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 492 | if peer_state.op == proto.OP_WRQ: 493 | peer_state.purge() 494 | del self.server.clients[self.client_address] 495 | 496 | 497 | class TFTPServerGarbageCollector(threading.Thread): 498 | """ 499 | A gc thread to clean up the server's state of timed out clients. 500 | """ 501 | 502 | def __init__(self, clients): 503 | threading.Thread.__init__(self) 504 | self.clients = clients 505 | self.setDaemon(True) 506 | 507 | def run(self): 508 | while True: 509 | # Sleep a little before doing a cycle. 510 | time.sleep(10) 511 | 512 | toremove = [] 513 | 514 | for peer, peer_state in self.clients.items(): 515 | delta = time.time() - peer_state.last_seen 516 | if delta > state.STATE_TIMEOUT_SECS: 517 | if peer_state.state != state.STATE_ERROR: 518 | l.debug('Peer %s:%d timed out.', *peer, 519 | extra=peer_state.extra(notify.TRANSFER_FAILED)) 520 | toremove.append(peer) 521 | 522 | for peer in toremove: 523 | if self.clients[peer].op == proto.OP_WRQ: 524 | self.clients[peer].purge() 525 | l.debug('Removed stale peer %s:%d.', *peer) 526 | del self.clients[peer] 527 | 528 | 529 | class TFTPServer(object): 530 | def __init__(self, iface, root, port=_PTFTPD_DEFAULT_PORT, 531 | strict_rfc1350=False, notification_callbacks=None): 532 | 533 | if notification_callbacks is None: 534 | notification_callbacks = {} 535 | 536 | self.iface, self.root, self.port, self.strict_rfc1350 = \ 537 | iface, root, port, strict_rfc1350 538 | self.client_registry = {} 539 | 540 | if not os.path.isdir(self.root): 541 | raise TFTPServerConfigurationError( 542 | 'The specified TFTP root does not exist') 543 | 544 | self.ip, self.netmask = get_ip_config_for_iface(self.iface) 545 | self.server = socketserver.UDPServer((self.ip, port), 546 | TFTPServerHandler) 547 | self.server.root = self.root 548 | self.server.strict_rfc1350 = self.strict_rfc1350 549 | self.server.clients = self.client_registry 550 | self.cleanup_thread = TFTPServerGarbageCollector(self.client_registry) 551 | 552 | # Add callback notifications 553 | notify.CallbackEngine.install(l, notification_callbacks) 554 | 555 | def serve_forever(self): 556 | l.info('Serving TFTP requests on %s/%s:%d in %s', 557 | self.iface, self.ip, self.port, self.root) 558 | self.cleanup_thread.start() 559 | self.server.serve_forever() 560 | 561 | 562 | def main(): 563 | import optparse 564 | 565 | usage = 'Usage: %prog [options] ' 566 | parser = optparse.OptionParser(usage=usage) 567 | parser.add_option('-r', '--rfc1350', dest='strict_rfc1350', 568 | action='store_true', default=False, 569 | help='Run in strict RFC1350 compliance mode, ' 570 | 'with no extensions') 571 | parser.add_option('-p', '--port', dest='port', action='store', type='int', 572 | default=_PTFTPD_DEFAULT_PORT, metavar='PORT', 573 | help='Listen for TFTP requests on PORT') 574 | parser.add_option('-v', '--verbose', dest='loglevel', action='store_const', 575 | const=logging.INFO, help='Output information messages', 576 | default=logging.WARNING) 577 | parser.add_option('-D', '--debug', dest='loglevel', action='store_const', 578 | const=logging.DEBUG, help='Output debugging information') 579 | 580 | (options, args) = parser.parse_args() 581 | if len(args) != 2: 582 | parser.print_help() 583 | return 1 584 | 585 | iface = args[0] 586 | root = os.path.abspath(args[1]) 587 | 588 | # Setup notification logging 589 | notify.StreamEngine.install(l, stream=sys.stdout, 590 | loglevel=options.loglevel, 591 | fmt='%(levelname)s(%(name)s): %(message)s') 592 | 593 | try: 594 | server = TFTPServer(iface, root, options.port, options.strict_rfc1350) 595 | server.serve_forever() 596 | except TFTPServerConfigurationError as e: 597 | sys.stderr.write('TFTP server configuration error: %s!' % e.args) 598 | return 1 599 | except socket.error as e: 600 | sys.stderr.write('Error creating a listening socket on port %d: ' 601 | '%s (%s).\n' % (options.port, e.args[1], 602 | errno.errorcode[e.args[0]])) 603 | return 1 604 | 605 | return 0 606 | 607 | if __name__ == '__main__': 608 | try: 609 | sys.exit(main()) 610 | except KeyboardInterrupt: 611 | pass 612 | -------------------------------------------------------------------------------- /ptftplib/version.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | name = 'ptftpd' 3 | version = '1.3' 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: Marc Poulhiès 5 | # dkm@kataplop.net 6 | # 7 | # This file is part of pTFTPd. 8 | # pTFTPd is free software: you can redistribute it and/or modify it 9 | # under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # pTFTPd is distributed in the hope that it will be useful, but 14 | # WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | # General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with pTFTPd. If not, see . 20 | 21 | from setuptools import setup, find_packages 22 | 23 | with open('ptftplib/version.py') as f: 24 | exec(f.read()) 25 | 26 | with open('README.rst') as readme: 27 | long_description = readme.read() 28 | 29 | setup( 30 | name=name, # noqa 31 | version=version, # noqa 32 | author='Maxime Petazzoni', 33 | author_email='maxime.petazzoni@bulix.org', 34 | description='pTFTPd, a pure-Python TFTP tool suite that works', 35 | license='GNU General Public License v2', 36 | long_description=long_description, 37 | zip_safe=True, 38 | install_requires=[], 39 | packages=find_packages(), 40 | entry_points={ 41 | 'console_scripts': 42 | ['bootpd=ptftplib.bootpserver:main', 43 | 'dhcpd=ptftplib.dhcpserver:main', 44 | 'ptftp=ptftplib.tftpclient:main', 45 | 'ptftpd=ptftplib.tftpserver:main', 46 | 'pxed=ptftplib.pxeserver:main'], 47 | }, 48 | classifiers=[ 49 | 'Operating System :: OS Independent', 50 | 'Programming Language :: Python', 51 | ], 52 | url='https://github.com/mpetazzoni/ptftpd', 53 | ) 54 | --------------------------------------------------------------------------------