服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

tftp 服务器

几个月前写的,今天改了一下,只有服务器端.
参考:tftp协议规范
tftp uml

tftpserver.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
 * 创建日期 2004-8-30-11:31:14
 *
 */
package starfire.tftp;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 * <a href="http://www.longen.org/s-z/details-z/tftpprotocol.htm">tftp 协议规范 </a>
 * 
 * @author <a href="mailto:starfire@bit.edu.cn">starfire </a>
 *  
 */
public class tftpserver extends thread {

    public static final int default_port = 69;

    private hashmap map = new hashmap();

    private file root;

    private int port = default_port;

    private datagramsocket ds;

    private timer timer = new timer(true);

    public tftpserver() {
        this(".");
    }

    public tftpserver(string rootpath, int port) {
        this(rootpath);
        this.port = port;
    }

    public tftpserver(string rootpath) {
        this.root = new file(rootpath);
        try {
            this.root = this.root.getcanonicalfile();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    public void run() {
        try {
            ds = new datagramsocket(new inetsocketaddress(port));
        } catch (socketexception e) {
            system.out.println("error when create datagram socket:"
                    + e.getmessage());
            return;
        }
        system.out.println("root path:" + root.getpath());
        byte[] buf = new byte[516];
        datagrampacket packet = new datagrampacket(buf, 516);
        while (true) {
            try {
                ds.receive(packet);
                system.out.println("recv packet:");
                tftppacketutil.displaybytes(packet.getdata());//
                process(packet);
            } catch (ioexception e1) {
                e1.printstacktrace();
            }
        }
    }

    protected void process(datagrampacket packet) {
        try {
            byte[] buf = new byte[packet.getlength()];
            system.arraycopy(packet.getdata(), 0, buf, 0, buf.length);
            tftppacket tfp = tftppacketutil.decode(buf);
            inetsocketaddress address = new inetsocketaddress(packet
                    .getaddress(), packet.getport());
            string key = address.gethostname() + ":" + address.getport();
            system.out.println("key=" + key);
            system.out.println("packet:" + tfp);
            if (tfp.getoperatecode() == tftppacket.rrq
                    || tfp.getoperatecode() == tftppacket.wrq) {
                client client = new client(address);
                boolean result = client.doaccept((rwpacket) tfp);
                if (result) {
                    map.put(key, client);
                }
            } else if (tfp.getoperatecode() == tftppacket.data) {
                client client = (client) map.get(key);
                if (client == null) {
                    return;
                }
                boolean result = client.doprocess((datapacket) tfp);
                if (result) {
                    map.remove(key);
                    client.destroy();
                }
            } else if (tfp.getoperatecode() == tftppacket.ack) {
                client client = (client) map.get(key);
                if (client == null) {
                    return;
                }
                boolean result = client.doprocess((ackpacket) tfp);
                if (result) {
                    map.remove(key);
                    client.destroy();
                }
            } else if (tfp.getoperatecode() == tftppacket.error) {
                system.out.println(tfp);
                client client = (client) map.remove(key);
                client.destroy();
            }
        } catch (badpacketformatexception e) {
            e.printstacktrace();
            system.out.println("recv unknown packet.");
        }
    }

    protected void send(inetsocketaddress address, byte[] data) {
        datagrampacket packet = new datagrampacket(data, data.length, address
                .getaddress(), address.getport());
        try {
            ds.send(packet);
            system.out.println("send packet:");
            tftppacketutil.displaybytes(data);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    class client {
        public static final int default_data_size = 512;

        public static final int default_time_out = 1000;

        private inetsocketaddress address;

        private string filename;

        private int block;

        private boolean checked;//上次发送的包已收到回应

        private randomaccessfile raf;

        private boolean accepted = false;

        private byte[] buf = new byte[default_data_size];

        private byte[] data;

        private int times = 0;//每几次重发

        private resendtask task;

        public client(inetsocketaddress address) {
            this.address = address;
        }

        public void destroy() {
            if (task != null) {
                task.cancel();
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
                raf = null;
            }
        }

        /**
         * if accept,return true;else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doaccept(rwpacket packet) {
            this.filename = packet.getfilename();
            if (accepted) {
                return true;
            }
            if (packet.getoperatecode() == tftppacket.rrq) {
                try {
                    file file = new file(root, filename);
                    system.out.println(file.getpath() + " " + file.exists());
                    raf = new randomaccessfile(file, "r");
                    data = new byte[default_data_size];
                    int size = raf.read(data);
                    datapacket dp = new datapacket();
                    dp.setblock(1);
                    if (size != default_data_size) {
                        byte[] buf = new byte[size];
                        system.arraycopy(data, 0, buf, 0, size);
                        data = buf;
                    }
                    dp.setdata(data);
                    data = tftppacketutil.encode(dp);
                    send(address, data);
                    block = 1;
                    task = new resendtask(address, data);
                    timer.schedule(task, default_time_out);
                } catch (filenotfoundexception e) {
                    system.out
                            .println("file:" + e.getmessage() + " not found.");
                    errorpacket ep = new errorpacket();
                    ep.seterrorcode(errorpacket.file_not_found_code);
                    byte[] data = tftppacketutil.encode(ep);
                    send(address, data);
                    return false;
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            } else {
                file file = new file(root, filename);
                if (file.exists()) {
                    errorpacket ep = new errorpacket();
                    ep.seterrorcode(errorpacket.file_exist_code);
                    ep.seterrormessage("file:" + filename + " has exist");
                    byte[] data = tftppacketutil.encode(ep);
                    send(address, data);
                    return false;
                }
                try {
                    file.createnewfile();
                    raf = new randomaccessfile(file, "rwd");
                } catch (ioexception e) {
                    system.out.println("create file:" + filename + " failed.");
                    errorpacket ep = new errorpacket();
                    ep.seterrorcode(errorpacket.not_defined_code);
                    byte[] data = tftppacketutil.encode(ep);
                    send(address, data);
                    return false;
                }
                ackpacket ap = new ackpacket();
                ap.setblock(0);
                data = tftppacketutil.encode(ap);
                send(address, data);
                task = new resendtask(address, data);
                timer.schedule(task, default_time_out);
            }
            accepted = true;
            return accepted;
        }

        /**
         * if transfer end,return true,else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doprocess(ackpacket packet) {
            if (task != null) {
                task.cancel();
                task = null;
            }
            if (packet.getblock() == block) {
                try {
                    if (raf == null
                            || raf.length() <= block * default_data_size) {
                        return true;
                    }
                    raf.seek(block * default_data_size);
                    int size = raf.read(buf);
                    data = buf;
                    if (size < default_data_size) {
                        data = new byte[size];
                        system.arraycopy(buf, 0, data, 0, size);
                        raf.close();
                        raf = null;
                    }
                    datapacket dp = new datapacket();
                    block++;
                    dp.setblock(block);
                    dp.setdata(data);
                    data = tftppacketutil.encode(dp);
                    send(address, data);
                    tftppacketutil.displaybytes(data);
                    task = new resendtask(address, data);
                    timer.schedule(task, default_time_out);
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
            return false;
        }

        /**
         * if transfer end,return true,else return false.
         * 
         * @param packet
         * @return
         */
        public boolean doprocess(datapacket packet) {
            if (task != null) {
                task.cancel();
                task = null;
            }
            byte[] data = packet.getdata();
            if (packet.getblock() != block + 1) {
                return false;
            }
            block++;
            ackpacket ap = new ackpacket();
            ap.setblock(block);
            if (data != null) {
                try {
                    raf.write(data);
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
            if (data == null || data.length < default_data_size) {
                try {
                    raf.close();
                    raf = null;
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
            data = tftppacketutil.encode(ap);
            send(address, data);
            task = new resendtask(address, data);
            timer.schedule(task, default_time_out);
            return packet.getdata() == null
                    || packet.getdata().length < default_data_size;
        }

    }

    class resendtask extends java.util.timertask {
        private inetsocketaddress address;

        private byte[] data;

        private int times = 1;

        public resendtask(inetsocketaddress address, byte[] data) {
            this.address = address;
            this.data = data;
        }
        
        public resendtask(inetsocketaddress address, byte[] data,int times) {
            this.address = address;
            this.data = data;
            this.times = times;
        }

        public void run() {
            send(address, data);
            if (times < 3) {//最多发3次
                timer.schedule(new resendtask(address,data,times+1), (int) (math.pow(2, times+1))
                        * client.default_time_out);
            }
        }

        public byte[] getdata() {
            return data;
        }
    }

    public static void main(string[] args) {
        new tftpserver("e://").start();
    }

    /**
     * @return
     */
    public file getroot() {
        return root;
    }

    /**
     * @return
     */
    public int getport() {
        return port;
    }

    /**
     * @param i
     */
    public void setport(int i) {
        port = i;
    }

}

tftppacketutil.java
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
 * 创建日期 2004-8-30-12:49:20
 *
 */
package starfire.tftp;

/**
 * @author <a href="mailto:starfire@bit.edu.cn">starfire</a>
 *
 */
public final class tftppacketutil {
  
  private tftppacketutil() {
    
  }

  public static tftppacket decode(byte[] buf) throws badpacketformatexception {
    if (buf==null || buf.length<4) {
      throw new badpacketformatexception("packet too small");
    }
    int operatecode = buf[1];
    if (operatecode<tftppacket.rrq || operatecode>tftppacket.error) {
      throw new badpacketformatexception("unknown operate code");
    }
    switch (operatecode) {
      case tftppacket.rrq:
      case tftppacket.wrq:
        return decoderwpacket(buf);
      case tftppacket.data:
        return decodedatapacket(buf);
      case tftppacket.ack:
        return decodeackpacket(buf);
      case tftppacket.error:
        return decodeerrorpacket(buf);
    }
    return null;
  }
  
  /**
   * 2 bytes       2 bytes string 1 byte
   * -----------------------------------------
   * | opcode | errorcode | errmsg | 0 |
   * -----------------------------------------
   */
  private static tftppacket decodeerrorpacket(byte[] buf) throws badpacketformatexception {
    if (buf.length<4) {
      throw new badpacketformatexception("ack packet must >= 4 bytes");
    }
    errorpacket packet = new errorpacket();
    packet.setoperatecode(tftppacket.error);
    packet.seterrorcode(buf[2]<<8+buf[3]);
    int end = 4;
    int i = 4;
    for (;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i!=buf.length) {
      string str = new string(buf,4,end-4);
      packet.seterrormessage(str);
    }
    return packet;
  }


  /**
   * 2 bytes 2 bytes
   * ---------------------
   * | opcode | block # |
   * ---------------------
   * @param buf
   * @return
   */
  private static tftppacket decodeackpacket(byte[] buf) throws badpacketformatexception {
    displaybytes(buf);
    if (buf.length<4) {
      throw new badpacketformatexception("ack packet must be 4 bytes");
    }
    ackpacket packet = new ackpacket();
    packet.setoperatecode(tftppacket.ack);
    //system.out.println("buf[2]="+buf[2]+" buf[3]="+buf[3]+" total="+(buf[2]*256+buf[3]));
    packet.setblock(byte2int(buf[2])*256+byte2int(buf[3]));
    //system.out.println("block:"+packet.getblock());
    return packet;
  }


  /**
   * 2 bytes   2 bytes   n bytes
   * ----------------------------------
   * | opcode | block # | data |
   * ----------------------------------
   * @param buf
   * @return
   */
  private static tftppacket decodedatapacket(byte[] buf) throws badpacketformatexception  {
    if (buf.length<4) {
      throw new badpacketformatexception("bad data packet");
    }
    datapacket packet = new datapacket();
    packet.setoperatecode(tftppacket.data);
    packet.setblock(byte2int(buf[2])*256+byte2int(buf[3]));
    //system.out.println("decode data packet,block:"+packet.getblock());
    byte[] data = new byte[buf.length-4];
    system.arraycopy(buf,4,data,0,data.length);
    packet.setdata(data);
    return packet;
  }
  
  private static int byte2int(byte b) {
    if ((b&0x80)!=0) {
      return 128+(b&0x7f);
    }
    else {
      return b;
    }
  }


  /**
   * rrq,wrq packet format
   *  2 bytes    string   1 byte string 1 byte
   *  ------------------------------------------------
   *  | opcode | filename | 0 | mode | 0 |
   *  ------------------------------------------------
   * @param buf
   * @return
   */
  private static tftppacket decoderwpacket(byte[] buf) throws badpacketformatexception {
    rwpacket packet = new rwpacket();
    packet.setoperatecode((int)buf[1]);
    int start = 2;
    int end = 2;
    int i;
    for (i=start;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i==buf.length) {
      throw new badpacketformatexception();
    }
    packet.setfilename(new string(buf,start,end-start));
    start = end+1;
    end = start;
    for (i=start;i<buf.length;i++) {
      if (buf[i]==0) {
        end = i;
        break;
      }
    }
    if (i==buf.length) {
      throw new badpacketformatexception();
    }
    packet.setmode(new string(buf,start,end-start));
    return packet;
  }


  public static byte[] encode(tftppacket packet) {
    int operatecode = packet.getoperatecode();
    switch (operatecode) {
      case tftppacket.rrq:
      case tftppacket.wrq:
        return encoderwpacket((rwpacket)packet);
      case tftppacket.data:
        return encodedatapacket((datapacket)packet);
      case tftppacket.ack:
        return encodeackpacket((ackpacket)packet);
      case tftppacket.error:
        return encodeerrorpacket((errorpacket)packet);
      
    }
    return null;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeerrorpacket(errorpacket packet) {
    byte[] messagebytes = null;
    if (packet.geterrormessage()!=null) {
      messagebytes = packet.geterrormessage().getbytes();
    }
    int size = messagebytes==null?0:messagebytes.length;
    size += 2+2+1;
    byte[] buf = new byte[size];
    buf[1] = (byte)(tftppacket.error&0xff);
    int errorcode = packet.geterrorcode();
    buf[2] = (byte)((errorcode>>8)&0xff);
    buf[3] = (byte)(errorcode&0xff);
    if (messagebytes!=null) {
      system.arraycopy(messagebytes,0,buf,4,messagebytes.length);
    }
    return buf;
  }


  /**
   * @param packet
   * @return
   */
  private static byte[] encodeackpacket(ackpacket packet) {
    byte[] buf = new byte[4];
    buf[1] = (byte)(tftppacket.ack&0xff);
    int block = packet.getblock();
    buf[2] = (byte)((block>>8)&0xff);
    buf[3] = (byte)(block&0xff);
    return buf;
  }


  /**
   * @param packet
   * @return
   */
  private static