1 | /*
|
---|
2 | * TFTP.c
|
---|
3 | *
|
---|
4 | * Created: 26.05.2021 17:39:50
|
---|
5 | * Author: Admin
|
---|
6 | */
|
---|
7 |
|
---|
8 | #include "lwip/api.h"
|
---|
9 | #include "tftp_server.h"
|
---|
10 | #include "ff.h"
|
---|
11 | #include "string.h"
|
---|
12 | #include "log_and_debug.h"
|
---|
13 |
|
---|
14 | uint32_t TFTPbyteWrite = 0;
|
---|
15 | uint32_t TFTPbyteRead = 0;
|
---|
16 |
|
---|
17 | static void* tftp_open(const char* fname, const char* mode, u8_t write);
|
---|
18 | static void tftp_close(void* handle);
|
---|
19 | static int tftp_write(void* handle, struct pbuf* p);
|
---|
20 | static int tftp_read(void* handle, void* buf, int bytes);
|
---|
21 |
|
---|
22 | void tftpServer_init(void)
|
---|
23 | {
|
---|
24 | static const struct tftp_context tftp = {
|
---|
25 | tftp_open,
|
---|
26 | tftp_close,
|
---|
27 | tftp_read,
|
---|
28 | tftp_write,
|
---|
29 | };
|
---|
30 |
|
---|
31 | if(tftp_init(&tftp) == ERR_OK) __debug(DEBUG_SERVSE, "TFTP server started: port 69\r\n");
|
---|
32 | }
|
---|
33 |
|
---|
34 | static void* tftp_open(const char* fname, const char* mode, u8_t write)
|
---|
35 | {
|
---|
36 | void *file = NULL;
|
---|
37 | static FIL FSFileTFTP;
|
---|
38 |
|
---|
39 | __debug(DEBUG_SERVSE, "TFTP: path to file %s %s\r\n", fname, write ? "write" : "read");
|
---|
40 |
|
---|
41 | switch(write){
|
---|
42 | case 0:
|
---|
43 | if(f_open(&FSFileTFTP, fname, FA_READ) == FR_OK)file = (void*)&FSFileTFTP;
|
---|
44 | break;
|
---|
45 | case 1:
|
---|
46 | if(f_open(&FSFileTFTP, fname, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)file = (void*)&FSFileTFTP;
|
---|
47 | break;
|
---|
48 | }
|
---|
49 | return file;
|
---|
50 | }
|
---|
51 |
|
---|
52 | static void tftp_close(void* handle)
|
---|
53 | {
|
---|
54 | f_close((FIL*)handle);
|
---|
55 | TFTPbyteWrite = 0;
|
---|
56 | TFTPbyteRead = 0;
|
---|
57 | }
|
---|
58 |
|
---|
59 | static int tftp_write(void* handle, struct pbuf* p)
|
---|
60 | {
|
---|
61 | uint32_t TFTPbyteWritten = 0;
|
---|
62 | if((FIL*)handle == NULL) return -1;
|
---|
63 | f_lseek((FIL*)handle, TFTPbyteWrite);
|
---|
64 | if(f_write((FIL*)handle, p->payload, (UINT)p->len, (UINT*)&TFTPbyteWritten) != FR_OK)return -1;
|
---|
65 | TFTPbyteWrite += p->len;
|
---|
66 | return 0;
|
---|
67 | }
|
---|
68 |
|
---|
69 | static int tftp_read(void* handle, void* buf, int bytes)
|
---|
70 | {
|
---|
71 | uint32_t TFTPbyteReading = 0;
|
---|
72 | if((FIL*)handle == NULL) return -1;
|
---|
73 | f_lseek((FIL*)handle, TFTPbyteRead);
|
---|
74 | if(f_read((FIL*)handle, buf, (UINT)bytes, (UINT*)&TFTPbyteReading) != FR_OK)return -1;
|
---|
75 | TFTPbyteRead += bytes;
|
---|
76 | return TFTPbyteReading;
|
---|
77 | }
|
---|
78 |
|
---|