-
Notifications
You must be signed in to change notification settings - Fork 1
/
tftp.ts
69 lines (60 loc) · 2.05 KB
/
tftp.ts
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
import tftp from 'tftp';
import { EventEmitter } from 'events'
export class CiscoTFTPServer extends EventEmitter {
private tftpServer: TFTPServer;
private fileSendTable: {[filename: string]: Buffer} = {};
private fileRecvTable: {[filename: string]: (stream: TFTPReq) => void} = {};
private systemIPv4Address: string;
constructor(systemIPv4Address: string) {
super();
this.systemIPv4Address = systemIPv4Address;
this.tftpServer = tftp.createServer({
host: '0.0.0.0',
port :69,
}, (req, res) => {
this.reqHandler(req, res);
});
}
// Helper function from Axios.JS
private combineURLs(baseURL: string, relativeURL: string): string {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
private reqHandler(req: TFTPReq, res: TFTPRes): void {
if (req.method === 'PUT') {
const ent = this.fileRecvTable[req.file];
if (ent == null) {
req.abort(tftp.ENOPUT);
} else {
ent(req);
}
} else if (req.method === 'GET') {
const ent = this.fileSendTable[req.file];
delete this.fileSendTable[req.file];
if (ent == null) {
req.abort(tftp.ENOENT);
} else {
res.setSize(ent.length);
res.write(ent);
}
} else {
req.abort(tftp.EIO);
}
}
public listen(): void {
this.tftpServer.listen();
}
public close(): void {
this.tftpServer.close();
}
public getCiscoTFTPURL(file: string): string {
return this.combineURLs(`tftp://${this.systemIPv4Address}/`, file);
}
public addFileToServe(filename: string, data: Buffer): void {
this.fileSendTable[filename] = data;
}
public reserveFileToRecv(filename: string, listener: (stream: NodeJS.ReadableStream) => void): void {
this.fileRecvTable[filename] = listener;
}
}