net-tftp_latest_version 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. data/GPL.txt +340 -0
  2. data/LICENSE.txt +58 -0
  3. data/README.txt +31 -0
  4. data/lib/net/tftp.rb +631 -0
  5. metadata +49 -0
data/GPL.txt ADDED
@@ -0,0 +1,340 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Library General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License
307
+ along with this program; if not, write to the Free Software
308
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
309
+
310
+
311
+ Also add information on how to contact you by electronic and paper mail.
312
+
313
+ If the program is interactive, make it output a short notice like this
314
+ when it starts in an interactive mode:
315
+
316
+ Gnomovision version 69, Copyright (C) year name of author
317
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
318
+ This is free software, and you are welcome to redistribute it
319
+ under certain conditions; type `show c' for details.
320
+
321
+ The hypothetical commands `show w' and `show c' should show the appropriate
322
+ parts of the General Public License. Of course, the commands you use may
323
+ be called something other than `show w' and `show c'; they could even be
324
+ mouse-clicks or menu items--whatever suits your program.
325
+
326
+ You should also get your employer (if you work as a programmer) or your
327
+ school, if any, to sign a "copyright disclaimer" for the program, if
328
+ necessary. Here is a sample; alter the names:
329
+
330
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
331
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
332
+
333
+ <signature of Ty Coon>, 1 April 1989
334
+ Ty Coon, President of Vice
335
+
336
+ This General Public License does not permit incorporating your program into
337
+ proprietary programs. If your program is a subroutine library, you may
338
+ consider it more useful to permit linking proprietary applications with the
339
+ library. If this is what you want to do, use the GNU Library General
340
+ Public License instead of this License.
@@ -0,0 +1,58 @@
1
+ Net::TFTP is copyrighted free software by Guillaume Marcais <guillaume.marcais@free.fr>.
2
+ You can redistribute it and/or modify it under either the terms of the GPL
3
+ (see GPL.txt file), or the conditions below:
4
+
5
+ 1. You may make and give away verbatim copies of the source form of the
6
+ software without restriction, provided that you duplicate all of the
7
+ original copyright notices and associated disclaimers.
8
+
9
+ 2. You may modify your copy of the software in any way, provided that
10
+ you do at least ONE of the following:
11
+
12
+ a) place your modifications in the Public Domain or otherwise
13
+ make them Freely Available, such as by posting said
14
+ modifications to Usenet or an equivalent medium, or by allowing
15
+ the author to include your modifications in the software.
16
+
17
+ b) use the modified software only within your corporation or
18
+ organization.
19
+
20
+ c) rename any non-standard executables so the names do not conflict
21
+ with standard executables, which must also be provided.
22
+
23
+ d) make other distribution arrangements with the author.
24
+
25
+ 3. You may distribute the software in object code or executable
26
+ form, provided that you do at least ONE of the following:
27
+
28
+ a) distribute the executables and library files of the software,
29
+ together with instructions (in the manual page or equivalent)
30
+ on where to get the original distribution.
31
+
32
+ b) accompany the distribution with the machine-readable source of
33
+ the software.
34
+
35
+ c) give non-standard executables non-standard names, with
36
+ instructions on where to get the original software distribution.
37
+
38
+ d) make other distribution arrangements with the author.
39
+
40
+ 4. You may modify and include the part of the software into any other
41
+ software (possibly commercial). But some files in the distribution
42
+ are not written by the author, so that they are not under this terms.
43
+
44
+ They are gc.c(partly), utils.c(partly), regex.[ch], st.[ch] and some
45
+ files under the ./missing directory. See each file for the copying
46
+ condition.
47
+
48
+ 5. The scripts and library files supplied as input to or produced as
49
+ output from the software do not automatically fall under the
50
+ copyright of the software, but belong to whomever generated them,
51
+ and may be sold commercially, and may be aggregated with this
52
+ software.
53
+
54
+ 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
55
+ IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
56
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
57
+ PURPOSE.
58
+
@@ -0,0 +1,31 @@
1
+ == Description
2
+
3
+ Implementation of the TFTP protocol. For more information, see
4
+ lib/net/tftp.rb or generate the documentation:
5
+
6
+ $ rdoc -x setup.rb
7
+
8
+ == Installation
9
+
10
+ 1. Manual install:
11
+
12
+ $ ruby setup.rb config
13
+ $ ruby setup.rb setup
14
+
15
+ Probably become administrator/root
16
+
17
+ # ruby setup.rb install
18
+
19
+ 2. Gem package
20
+
21
+ Create gem
22
+
23
+ $ ruby net-tftp.gemspec
24
+
25
+ Probably become administrator/root
26
+
27
+ # gem install net-tftp.gem
28
+
29
+ == License
30
+
31
+ See LICENSE.txt
@@ -0,0 +1,631 @@
1
+ #! /usr/bin/ruby
2
+
3
+ #--
4
+ # Copyright (c) 2004, Guillaume Marcais (guillaume.marcais@free.fr)
5
+ # All rights reserved.
6
+ # This file is distributed under the Ruby license.
7
+ # http://net-tftp.rubyforge.org
8
+ #++
9
+ #
10
+ # == Description
11
+ # TFTP is used by many devices to upload or download their configuration,
12
+ # firmware or else. It is a very simple file transfer protocol built on top
13
+ # of UDP. It transmits data by chunck of 512 bytes. It waits for an ack after
14
+ # each data packet but does not do any data integrety checks.
15
+ # There is no authentication mechanism nor any way too list the content of
16
+ # the remote directories. It just sends or retrieves files.
17
+ #
18
+ # == Usage
19
+ # Using Net::TFTP::Client is fairly trivial:
20
+ # <pre>
21
+ # <code>
22
+ # require 'net/tftp'
23
+ # t = Net::TFTP::Client.new('localhost')
24
+ # t.getbinaryfile('remote_file', 'local_file')
25
+ # t.putbinaryfile('local_file', 'remote_file')
26
+ # </code>
27
+ # </pre>
28
+ #
29
+ # To use the Net::TFTP::Server:
30
+ # <pre>
31
+ # <code>
32
+ # require 'net/tftp'
33
+ # tftp_server = Net::TFTP::Server.new(:data_directory => "/path/to/directory")
34
+ # tftp_server.start # starts the server and blocks the current thread.
35
+ # </code>
36
+ # </pre>
37
+ # That's pretty much it. +getbinaryfile+ and +putbinaryfile+ can take a
38
+ # block which will be called every time a block is sent/received.
39
+ #
40
+ # == Known limitations
41
+ # * RFC 1350 mention a net-ascii mode. I am not quite sure what transformation
42
+ # on the data should be done and it is not (yet) implemented.
43
+ # * None of the extensions of TFTP are implemented (RFC1782, RFC1783, RFC1784,
44
+ # RFC1785, RFC2347, RFC2348, RFC2349).
45
+
46
+ require 'socket'
47
+ require 'timeout'
48
+ require 'thread'
49
+
50
+ module Net # :nodoc:
51
+
52
+ module TFTP # :nodoc:
53
+
54
+ class TFTPError < StandardError; end
55
+ class TFTPTimeout < TFTPError; end
56
+ class TFTPProtocol < TFTPError
57
+ attr_reader :code
58
+ def initialize(msg, code)
59
+ super(msg)
60
+ @code = code
61
+ end
62
+ end
63
+
64
+ VERSION = "0.2.0"
65
+
66
+ # Errors
67
+ ERROR_DESCRIPTION = [
68
+ "Custom error",
69
+ "File not found",
70
+ "Access violation",
71
+ "Disk full",
72
+ "Illegal TFTP operation",
73
+ "Unknown transfer ID",
74
+ "File already exists",
75
+ "No such user",
76
+ ]
77
+ ERROR_UNDEF = 0
78
+ ERROR_FILE_NOT_FOUND = 1
79
+ ERROR_ACCESS_VIOLATION = 2
80
+ ERROR_DISK_FULL = 3
81
+ ERROR_ILLEGAL_OPERATION = 4
82
+ ERROR_UNKNOWN_TRANSFER_ID = 5
83
+ ERROR_FILE_ALREADY_EXISTS = 6
84
+ ERROR_NO_SUCH_USER = 7
85
+
86
+ # Opcodes
87
+ OP_RRQ = 1
88
+ OP_WRQ = 2
89
+ OP_DATA = 3
90
+ OP_ACK = 4
91
+ OP_ERROR = 5
92
+
93
+ MINSIZE = 4
94
+ MAXSIZE = 516
95
+ DATABLOCK = 512
96
+
97
+ DEFAULTS = {
98
+ :port => (Socket.getservbyname("tftp", "udp") rescue 69),
99
+ :timeout => 5,
100
+ }
101
+
102
+ module PacketOperations
103
+ def rrq_packet(file, mode)
104
+ [OP_RRQ, file, mode].pack("na#{file.size + 1}a#{mode.size + 1}")
105
+ end
106
+
107
+ def wrq_packet(file, mode)
108
+ [OP_WRQ, file, mode].pack("na#{file.size + 1}a#{mode.size + 1}")
109
+ end
110
+
111
+ def data_packet(block, data)
112
+ [OP_DATA, block, data].pack("nna*")
113
+ end
114
+
115
+ def ack_packet(block)
116
+ [OP_ACK, block].pack("nn")
117
+ end
118
+
119
+ def error_packet(code, message = nil)
120
+ message ||= ERROR_DESCRIPTION[code] || ""
121
+ [OP_ERROR, code, message].pack("nna#{message.size + 1}")
122
+ end
123
+
124
+ # Check if the packet is malformed (unknown opcode, too big, etc.),
125
+ # in which case it returns nil.
126
+ # If it is an error packet, raise an TFTPProtocol error.
127
+ # Returns scanned values otherwise.
128
+ def scan_packet(packet)
129
+ return nil if packet.size < MINSIZE || packet.size > MAXSIZE
130
+ opcode = packet.unpack("n")[0]
131
+ block_err = rest = nil
132
+ if opcode == OP_RRQ || opcode == OP_WRQ
133
+ block_err, rest = packet[2..-1].unpack("Z*Z*")
134
+ elsif opcode == OP_ERROR
135
+ block_err, rest = packet[2..-1].unpack("nZ*")
136
+ else
137
+ block_err = packet[2..-1].unpack("n")[0]
138
+ rest = packet[4..-1]
139
+ end
140
+ return nil if opcode.nil? || block_err.nil?
141
+ case opcode
142
+ when OP_RRQ, OP_WRQ
143
+ return [opcode, block_err, rest]
144
+ when OP_DATA
145
+ return [opcode, block_err, rest]
146
+ when OP_ACK
147
+ return [opcode, block_err]
148
+ when OP_ERROR
149
+ err_msg = "%s: %s"
150
+ err_msg %= [ERROR_DESCRIPTION[block_err] || "", rest.chomp("\000")]
151
+ raise TFTPProtocol.new(err_msg, block_err)
152
+ else
153
+ return nil
154
+ end
155
+ end
156
+ end #module PacketOperations
157
+
158
+ class Client
159
+ include PacketOperations
160
+ class << self
161
+ # Alias for new
162
+ def open(host)
163
+ new(host)
164
+ end
165
+
166
+ # Return the number of blocks to send _size_ bytes.
167
+ def size_in_blocks(size)
168
+ s = size / DATABLOCK
169
+ s += 1 unless (size % DATABLOCK) == 0
170
+ s
171
+ end
172
+ end
173
+
174
+ attr_accessor :timeout, :host
175
+
176
+ # Create a TFTP connection object to a host. Note that no actual
177
+ # network connection is made. This methods never fails.
178
+ # Parameters:
179
+ # [:port] The UDP port. See DEFAULTS
180
+ # [:timeout] Timeout in second for each ack packet. See DEFAULTS
181
+ def initialize(host, params = {})
182
+ @host = host
183
+ @port = params[:port] || DEFAULTS[:port]
184
+ @timeout = params[:timeout] || DEFAULTS[:timeout]
185
+ end
186
+
187
+ # Retrieve a file using binary mode.
188
+ # If the localfile name is omitted, it is set to the remotefile.
189
+ # The optional block receives the data in the block and the sequence number
190
+ # of the block starting at 1.
191
+ def getbinaryfile(remotefile, localfile = nil, &block) # :yields: data, seq
192
+ localfile ||= File.basename(remotefile)
193
+ File.open(localfile, "wb") do |f|
194
+ getbinary(remotefile, f, &block)
195
+ end
196
+ end
197
+
198
+ # Retrieve a file using binary mode and send content to an io object
199
+ # The optional block receives the data in the block and the sequence number
200
+ # of the block starting at 1.
201
+ def getbinary(remotefile, io, &block) # :yields: data, seq
202
+ s = UDPSocket.new
203
+ begin
204
+ peer_ip = IPSocket.getaddress(@host)
205
+ rescue
206
+ raise TFTPError, "Cannot find host '#{@host}'"
207
+ end
208
+
209
+ peer_tid = nil
210
+ seq = 1
211
+ from = nil
212
+ data = nil
213
+
214
+ # Initialize request
215
+ s.send(rrq_packet(remotefile, "octet"), 0, peer_ip, @port)
216
+ Timeout::timeout(@timeout, TFTPTimeout) do
217
+ loop do
218
+ packet, from = s.recvfrom(MAXSIZE, 0)
219
+ next unless peer_ip == from[3]
220
+ type, block, data = scan_packet(packet)
221
+ break if (type == OP_DATA) && (block == seq)
222
+ end
223
+ end
224
+ peer_tid = from[1]
225
+
226
+ # Get and write data to io
227
+ loop do
228
+ io.write(data)
229
+ s.send(ack_packet(seq), 0, peer_ip, peer_tid)
230
+ yield(data, seq) if block_given?
231
+ break if data.size < DATABLOCK
232
+
233
+ seq += 1
234
+ Timeout::timeout(@timeout, TFTPTimeout) do
235
+ loop do
236
+ packet, from = s.recvfrom(MAXSIZE, 0)
237
+ next unless peer_ip == from[3]
238
+ if peer_tid != from[1]
239
+ s.send(error_packet(ERROR_UNKNOWN_TRANSFER_ID),
240
+ 0, from[3], from[1])
241
+ next
242
+ end
243
+ type, block, data = scan_packet(packet)
244
+ break if (type == OP_DATA) && (block == seq)
245
+ end
246
+ end
247
+ end
248
+
249
+ return true
250
+ end
251
+
252
+ # Send a file in binary mode. The name of the remotefile is set to
253
+ # the name of the local file if omitted.
254
+ # The optional block receives the data in the block and the sequence number
255
+ # of the block starting at 1.
256
+ def putbinaryfile(localfile, remotefile = nil, &block) # :yields: data, seq
257
+ remotefile ||= File.basename(localfile)
258
+ File.open(localfile, "rb") do |f|
259
+ putbinary(remotefile, f, &block)
260
+ end
261
+ end
262
+
263
+ # Send the content read from io to the remotefile.
264
+ # The optional block receives the data in the block and the sequence number
265
+ # of the block starting at 1.
266
+ def putbinary(remotefile, io, &block) # :yields: data, seq
267
+ s = UDPSocket.new
268
+ peer_ip = IPSocket.getaddress(@host)
269
+
270
+ peer_tid = nil
271
+ seq = 0
272
+ from = nil
273
+ data = nil
274
+
275
+ # Initialize request
276
+ s.send(wrq_packet(remotefile, "octet"), 0, peer_ip, @port)
277
+ Timeout::timeout(@timeout, TFTPTimeout) do
278
+ loop do
279
+ packet, from = s.recvfrom(MAXSIZE, 0)
280
+ next unless peer_ip == from[3]
281
+ type, block, data = scan_packet(packet)
282
+ break if (type == OP_ACK) && (block == seq)
283
+ end
284
+ end
285
+ peer_tid = from[1]
286
+
287
+ loop do
288
+ data = io.read(DATABLOCK) || ""
289
+ seq += 1
290
+ s.send(data_packet(seq, data), 0, peer_ip, peer_tid)
291
+
292
+ Timeout::timeout(@timeout, TFTPTimeout) do
293
+ loop do
294
+ packet, from = s.recvfrom(MAXSIZE, 0)
295
+ next unless peer_ip == from[3]
296
+ if peer_tid != from[1]
297
+ s.send(error_packet(ERROR_UNKNOWN_TRANSFER_ID),
298
+ 0, from[3], from[1])
299
+ next
300
+ end
301
+ type, block, void = scan_packet(packet)
302
+ break if (type == OP_ACK) && (block == seq)
303
+ end
304
+ end
305
+
306
+ yield(data, seq) if block_given?
307
+ break if data.size < DATABLOCK
308
+ end
309
+
310
+ return true
311
+ end
312
+
313
+ end #TFTP
314
+
315
+ # Simple factory for returning RRQ and WRQ source/sinks.
316
+ class DefaultOpFactory
317
+ # Returns a handler for a 'get' file. Throw a TFTPError if the
318
+ # resource is not allowed.
319
+ def rrq_operation_for(file_name, remote_host)
320
+ RRQOperation.new(file_name)
321
+ end
322
+
323
+ # Returns the handler for 'put' file. Throw a TFTPError if the
324
+ # resource is not allowed.
325
+ def wrq_operation_for(file_name, remote_host)
326
+ WRQOperation.new(file_name)
327
+ end
328
+ end
329
+
330
+ class Server
331
+ attr_accessor :options
332
+ include PacketOperations
333
+
334
+ # options: port, timeout, max_threads, data_directory, operation_factory
335
+ def initialize(options = { :port => 69, :timeout => 5, :max_threads => 10 })
336
+ @socket = UDPSocket.open
337
+ @options = options.clone
338
+ @op_factory = @options[:operation_factory] || DefaultOpFactory.new
339
+ @options[:port] ||= DEFAULTS[:port]
340
+ @options[:max_pkt_size] ||= 8000
341
+ @options[:timeout] ||= DEFAULTS[:timeout]
342
+ @socket.bind("0.0.0.0", @options[:port])
343
+ @worker_threads = []
344
+ @queue = [] # queue of [data, remote_addr]
345
+ @mutex = Mutex.new
346
+ @condition_var = ConditionVariable.new
347
+ # Hash of IP:Port => TFTPOperation
348
+ @operations = {}
349
+ end
350
+
351
+ def start
352
+ # Create worker threads
353
+ (@options[:max_threads] || 2).times do |i|
354
+ @worker_threads << Thread.new(self) do |server|
355
+ loop do
356
+ begin
357
+ server.dequeue_and_process
358
+ rescue Exception => e
359
+ puts e
360
+ puts e.backtrace.join("\n")
361
+ end
362
+ end
363
+ end
364
+ end
365
+
366
+ Thread.new(self) do |server|
367
+ loop do
368
+ sleep 6
369
+ begin
370
+ server.remove_expired_operations
371
+ rescue Exception => e
372
+ puts e
373
+ puts e.backtrace.join("\n")
374
+ end
375
+ end
376
+ end
377
+
378
+ loop do
379
+ begin
380
+ data, remote_info = @socket.recvfrom(@options[:max_pkt_size])
381
+ dispatch(data, remote_info)
382
+ rescue Exception => e
383
+ puts "TFTP::Server exception: #{e}\n#{e.backtrace.join('\n')}"
384
+ break
385
+ end
386
+ end
387
+ end
388
+
389
+ def stop
390
+ @worker_threads.each { |thread| thread.kill }
391
+ @worker_threads.clear
392
+ @socket.close
393
+ end
394
+
395
+ def send_reply(block, remote_info)
396
+ # socket ops are 'thread' safe
397
+ @socket.send(block, 0, remote_info[3], remote_info[1])
398
+ end
399
+
400
+ def dispatch(data, remote_info)
401
+ @mutex.synchronize do
402
+ @queue << [data, remote_info]
403
+ @condition_var.signal
404
+ end
405
+ end
406
+
407
+ def work_unit
408
+ unit = nil
409
+ @mutex.synchronize do
410
+ loop do
411
+ unit = @queue.pop
412
+ break unless unit.nil?
413
+ @condition_var.wait(@mutex)
414
+ end
415
+ end
416
+ unit
417
+ end
418
+
419
+ def dequeue_and_process
420
+ data, remote_info = work_unit
421
+ scan = scan_packet(data) # operation, ([file_name, xfer type] || [block_num, data])
422
+
423
+ case scan[0]
424
+ when OP_WRQ
425
+ begin
426
+ add_operation(@op_factory.wrq_operation_for(full_path(scan[1]), remote_info), remote_info)
427
+ send_reply(ack_packet(0), remote_info)
428
+ rescue Exception => e
429
+ puts "*ERROR* #{e}\n#{e.backtrace.join('\n')}"
430
+ error_code = ERROR_ACCESS_VIOLATION
431
+ error_code = e.code if e.is_a?(TFTPProtocol)
432
+ send_reply(error_packet(error_code), remote_info)
433
+ end
434
+
435
+ when OP_RRQ
436
+ begin
437
+ rrq_op = add_operation(@op_factory.rrq_operation_for(full_path(scan[1]), remote_info), remote_info)
438
+ send_reply(data_packet(*rrq_op.data_block), remote_info)
439
+ rescue TFTPError => e
440
+ error_code = ERROR_ACCESS_VIOLATION
441
+ error_code = e.code if e.is_a?(TFTPProtocol)
442
+ send_reply(error_packet(error_code), remote_info)
443
+ end
444
+
445
+ when OP_DATA
446
+ op = operation_for(remote_info)
447
+ if op && op.is_a?(WRQOperation)
448
+ begin
449
+ bytes = op.incoming_data(scan[2], scan[1])
450
+ if bytes < 512
451
+ op.complete
452
+ # We don't remove the operation incase the client loses the last ack.
453
+ # We'll let the expiring wrapper remove it.
454
+ #remove_operation_for(remote_info)
455
+ end
456
+ # We'll always ACK the given packet number since it could be a retry.
457
+ send_reply(ack_packet(scan[1]), remote_info)
458
+ rescue Exception => e
459
+ puts "OP_DATA ERROR: #{e}\n#{e.backtrace.join("\n")}"
460
+ end
461
+ else
462
+ send_reply(error_packet(ERROR_UNKNOWN_TRANSFER_ID), remote_info)
463
+ end
464
+
465
+ when OP_ACK
466
+ op = operation_for(remote_info)
467
+ if op && op.is_a?(RRQOperation)
468
+ send_reply(data_packet(*op.data_block), remote_info)
469
+ else
470
+ send_reply(error_packet(ERROR_UNKNOWN_TRANSFER_ID), remote_info)
471
+ end
472
+ else
473
+ send_reply(error_packet(ERROR_UNKNOWN_TRANSFER_ID), remote_info)
474
+ end
475
+ end
476
+
477
+ def remote_key(remote_info)
478
+ "#{remote_info[3]}:#{remote_info[1]}"
479
+ end
480
+
481
+ def add_operation(op, remote_info)
482
+ @mutex.synchronize do
483
+ # Double the timeout value for the auto-expiring to allow for retry operations
484
+ @operations[remote_key(remote_info)] = ExpiringWrapper.new(op, @options[:timeout] * 2)
485
+ end
486
+ op
487
+ end
488
+
489
+ # Checks for an existing connection/operation for the given
490
+ # IP/port
491
+ def operation_for(remote_info)
492
+ @mutex.synchronize do
493
+ exp_wrapper = @operations[remote_key(remote_info)]
494
+ exp_wrapper.operation if exp_wrapper
495
+ end
496
+ end
497
+
498
+ def remove_operation_for(remote_info)
499
+ @mutex.synchronize do
500
+ @operations.delete(remote_key(remote_info))
501
+ end
502
+ end
503
+
504
+ # Removes operations/connections that haven't had any activity recently
505
+ def remove_expired_operations
506
+ @mutex.synchronize do
507
+ @operations.delete_if { |k,wop| wop.operation.abort if wop.expired? ; wop.expired? }
508
+ end
509
+ end
510
+
511
+ private
512
+ def full_path(file_name)
513
+ # do some cleanup to prevent unwanted directory traversal
514
+ file_name = file_name.gsub("..", "").gsub(/^[\/\\]*/, "")
515
+ result = file_name
516
+ if @options[:data_directory]
517
+ result = "#{File.join(File.expand_path(@options[:data_directory]), file_name)}"
518
+ end
519
+ result
520
+ end
521
+
522
+ end #TFTP::Server
523
+
524
+ # Base class for GET/PUT
525
+ class TFTPOperation
526
+ attr_reader :file_name
527
+
528
+ def initialize(file_name)
529
+ @file_name = file_name
530
+ @fp = File.new(file_name, file_mode)
531
+ @complete = false
532
+ @aborted = false
533
+ end
534
+
535
+ def complete
536
+ unless @complete
537
+ @fp.close unless @fp.closed?
538
+ @complete = true
539
+ end
540
+ end
541
+
542
+ def complete?
543
+ @complete
544
+ end
545
+
546
+ def aborted?
547
+ @aborted
548
+ end
549
+
550
+ def abort
551
+ return false if complete? # Can't abort a completed operation.
552
+ @fp.close unless @fp.closed?
553
+ @aborted = true
554
+ end
555
+ end
556
+
557
+ # PUT
558
+ class WRQOperation < TFTPOperation
559
+ def initialize(file_name, fmode = "wb")
560
+ raise TFTPProtocol.new("File exists", ERROR_FILE_ALREADY_EXISTS) if File.exist?(file_name)
561
+ @file_mode = fmode
562
+ @last_block_num = 0
563
+ super file_name
564
+ end
565
+
566
+ def incoming_data(data, block_num)
567
+ # Ignore writes if we're complete. This case can occur if the final ACK was lost
568
+ if block_num == @last_block_num + 1
569
+ @fp.write(data) unless complete?
570
+ @last_block_num = block_num
571
+ elsif block_num == @last_block_num # Didn't get last ack.
572
+ puts "Client lost ACK. Ignoring resend." if $debug
573
+ else
574
+ # We got a block number that we shouldn't have
575
+ raise TFTPProtocol.new("Unexpected block number #{block_num}. Expected #{@last_block_num + 1}.", ERROR_ILLEGAL_OPERATION)
576
+ end
577
+ data.size
578
+ end
579
+
580
+ def file_mode
581
+ @file_mode
582
+ end
583
+
584
+ def aborted
585
+ super
586
+ File.delete(@fp.path) unless complete?
587
+ end
588
+ end
589
+
590
+ # GET
591
+ # TODO: Handle retry/file repos logic
592
+ class RRQOperation < TFTPOperation
593
+ def initialize(file_name)
594
+ begin
595
+ super
596
+ rescue Errno::ENOENT => e
597
+ raise TFTPProtocol.new(e.message, ERROR_FILE_NOT_FOUND)
598
+ end
599
+ @block_num = 0
600
+ end
601
+
602
+ def data_block(max_size = 512)
603
+ [@block_num += 1, @fp.read(max_size)]
604
+ end
605
+
606
+ def file_mode
607
+ "rb"
608
+ end
609
+ end
610
+
611
+ # Simple wrapper that tracks last access time to allow for
612
+ # expiring of entries. TTL is in seconds.
613
+ class ExpiringWrapper
614
+ def initialize(operation, time_to_live = 10)
615
+ @operation = operation
616
+ @last_access = Time.now
617
+ @time_to_live = time_to_live
618
+ end
619
+
620
+ def operation
621
+ @last_access = Time.now
622
+ @operation
623
+ end
624
+
625
+ def expired?
626
+ Time.now - @last_access >= @time_to_live
627
+ end
628
+ end
629
+
630
+ end #TFTP module
631
+ end #Net module
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: net-tftp_latest_version
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Guillaume Marcais, Spiceworks
9
+ autorequire: net/tftp
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-02-10 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description:
15
+ email: guillaume.marcais@free.fr
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - lib/net/tftp.rb
21
+ - README.txt
22
+ - LICENSE.txt
23
+ - GPL.txt
24
+ homepage: https://github.com/spiceworks/net-tftp
25
+ licenses: []
26
+ post_install_message:
27
+ rdoc_options: []
28
+ require_paths:
29
+ - lib
30
+ required_ruby_version: !ruby/object:Gem::Requirement
31
+ none: false
32
+ requirements:
33
+ - - ! '>='
34
+ - !ruby/object:Gem::Version
35
+ version: '0'
36
+ required_rubygems_version: !ruby/object:Gem::Requirement
37
+ none: false
38
+ requirements:
39
+ - - ! '>='
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ requirements: []
43
+ rubyforge_project:
44
+ rubygems_version: 1.8.23
45
+ signing_key:
46
+ specification_version: 3
47
+ summary: Net::TFTP is a pure Ruby implementation of the Trivial File Transfer Protocol
48
+ (RFC 1350)
49
+ test_files: []