Add TFTP server module.
[bertos.git] / bertos / net / tftp.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2010 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief TFTP protocol implementation
34  *
35  * \author Luca Ottaviano <lottaviano@develer.com>
36  */
37
38 #include "tftp.h"
39 #include "cfg/cfg_tftp.h"
40 #define LOG_LEVEL   TFTP_LOG_LEVEL
41 #define LOG_FORMAT  TFTP_LOG_FORMAT
42 #include <cfg/log.h>
43
44 //#include <lwip/in.h>
45 #include <lwip/inet.h>
46 #include <lwip/sockets.h>
47 #include <string.h> //memset
48
49 #define TFTP_PACKET_SIZE 516
50
51 #define DECLARE_TIMEOUT(name, timeout) \
52         struct timeval name; \
53         name.tv_sec = timeout / 1000; \
54         name.tv_usec = (timeout % 1000) * 1000;
55
56 #define KFT_TFTPSESSION MAKE_ID('T', 'F', 'T', 'P')
57 INLINE TftpSession *TFTP_CAST(KFile *fd)
58 {
59         ASSERT(fd->_type == KFT_TFTPSESSION);
60         return (TftpSession *)containerof(fd, TftpSession, kfile_request);
61 }
62
63 /*
64  * Check if received data is correct and send ACK if ok.
65  */
66 static int checkPacket(TftpSession *ctx, const Tftpframe *frame)
67 {
68         LOG_INFO("Checking block %hd\n", ctx->block);
69         if (ntohs(frame->hdr.opcode) != TFTP_DATA)
70         {
71                 LOG_INFO("Opcode != TFTP_DATA (%hd != %d)\n", ntohs(frame->hdr.opcode), TFTP_DATA);
72                 return -1;
73         }
74         if (ntohs(frame->hdr.th_u.block) != ctx->block + 1)
75                 return -1;
76
77         ctx->block++;
78         // if everything was ok, send ACK
79         // ACK is already in network order
80         struct ackframe ack;
81         ack.opcode = TFTP_ACK;
82         ack.block_num = htons(ctx->block);
83         ssize_t rc = lwip_sendto(ctx->sock, &ack, 4, 0, (struct sockaddr *)&ctx->addr, ctx->addr_len);
84         if (rc == 4)
85                 return rc;
86         else
87                 return -1;
88 }
89
90 /*
91  * Return >0 if there's something to read in ctx, 0 on timeout, -1 on errors
92  */
93 static int tftp_waitEvent(TftpSession *ctx, struct timeval *timeout)
94 {
95         fd_set inset;
96         FD_ZERO(&inset);
97         FD_SET(ctx->sock, &inset);
98         struct timeval tmp = *timeout;
99         return lwip_select(ctx->sock + 1, &inset, NULL, NULL, &tmp);
100 }
101
102 /*
103  * Read a block from TFTP.
104  * \param size Must be exactly 516 bytes
105  * \param timeout Time to wait the network connection, may be NULL to wait forever
106  * \return Number of bytes read if success, TFTP_ERR_TIMEOUT on timeout, TFTP_ERR otherwise
107  */
108 static ssize_t tftp_readPacket(TftpSession *ctx, Tftpframe *frame, mtime_t timeout)
109 {
110         DECLARE_TIMEOUT(wait_tm, timeout);
111
112         int res = tftp_waitEvent(ctx, &wait_tm);
113         if (res == 0)
114                 return TFTP_ERR_TIMEOUT;
115         if (res == -1)
116                 return TFTP_ERR;
117
118         ssize_t rlen = lwip_recvfrom(ctx->sock, frame, sizeof(Tftpframe), 0, NULL, NULL);
119         LOG_INFO("Received %zd bytes\n", rlen);
120         if (rlen > 0 && (checkPacket(ctx, frame) > 0))
121                 return rlen;
122         else
123                 return TFTP_ERR;
124 }
125
126 static size_t tftp_read(struct KFile *fd, void *buf, size_t size)
127 {
128         TftpSession *fds = TFTP_CAST(fd);
129         uint8_t *_buf = (uint8_t *) buf;
130         size_t read_bytes = 0;
131         size_t offset = fds->valid_data - fds->bytes_available;
132
133         if (fds->pending_ack)
134         {
135                 ASSERT(fds->block == 0);
136                 struct ackframe ack;
137                 ack.opcode = TFTP_ACK;
138                 ack.block_num = fds->block;
139                 lwip_sendto(fds->sock, &ack, 4, 0, (struct sockaddr *)&fds->addr, fds->addr_len);
140                 fds->pending_ack = false;
141         }
142
143         if (fds->bytes_available < size)
144         {
145                 /* check if we were called again after an error */
146                 if (fds->bytes_available > 0)
147                 {
148                         memcpy(_buf, fds->frame.data + offset, fds->bytes_available);
149                         LOG_INFO("ba < size. Copied %zd bytes from offset %zd\n", fds->bytes_available, offset);
150                         /* adjust buf and size */
151                         _buf += fds->bytes_available;
152                         size -= fds->bytes_available;
153                         read_bytes += fds->bytes_available;
154                 }
155
156                 if (!fds->is_xfer_end)
157                 {
158                         LOG_INFO("Waiting for new TFTP packet\n");
159                         /* get more data, we can wait since the function is blocking */
160                         ssize_t rd = tftp_readPacket(fds, &fds->frame, fds->timeout);
161                         if (rd < 0)
162                         {
163                                 fds->bytes_available = 0;
164                                 fds->error = rd;
165                                 return 0;
166                         }
167                         else
168                         {
169                                 if (rd < TFTP_PACKET_SIZE)
170                                 {
171                                         fds->is_xfer_end = true;
172                                         LOG_INFO("Received the last packet\n");
173                                 }
174                                 fds->bytes_available = (size_t)rd - sizeof(struct TftpHeader);
175                                 fds->valid_data = fds->bytes_available;
176                                 offset = 0;
177                         }
178                 }
179                 else
180                 {
181                         LOG_INFO("Transfer finished\n");
182                         fds->bytes_available -= fds->bytes_available;
183                         fds->valid_data = 0;
184                         return read_bytes;
185                 }
186         }
187
188         /* check how many bytes we need to copy */
189         size_t res = MIN(fds->bytes_available, size);
190         LOG_INFO("Copying %zd bytes from offset %zd\n", res, offset);
191         memcpy(_buf, fds->frame.data + offset, res);
192         fds->bytes_available -= res;
193         read_bytes += res;
194         return read_bytes;
195 }
196
197 static int tftp_error(struct KFile *fd)
198 {
199         TftpSession *fds = TFTP_CAST(fd);
200         return fds->error;
201 }
202
203 static void tftp_clearerr(struct KFile *fd)
204 {
205         TftpSession *fds = TFTP_CAST(fd);
206         fds->error = 0;
207 }
208
209 static int tftp_close(struct KFile *fd)
210 {
211         TftpSession *fds = TFTP_CAST(fd);
212         struct errframe err;
213         if (fds->pending_ack)
214         {
215                 err.opcode = TFTP_PROTOERR;
216                 err.errcode = TFTP_PROTOERR_ACCESS_VIOLATION;
217                 err.str = '\0';
218                 lwip_sendto(fds->sock, &err, 5, 0, (struct sockaddr *)&fds->addr, fds->addr_len);
219                 LOG_INFO("Closed connection upon user request\n");
220         }
221         return 0;
222 }
223
224 static void resetTftpState(TftpSession *ctx)
225 {
226         ctx->block = 0;
227         ctx->error = 0;
228         ctx->bytes_available = 0;
229         ctx->valid_data = 0;
230         ctx->is_xfer_end = false;
231         ctx->pending_ack = false;
232 }
233
234 /**
235  * Listen for incoming tftp sessions.
236  *
237  * \note Only write requests are accepted.
238  *
239  * \param ctx Initialized TftpChannel
240  * \param filename String to be filled with file name to be written
241  * \param len Length of the filename
242  * \param mode Open mode for the returned KFile
243  * \return KFile pointer to read from
244  */
245 KFile *tftp_listen(TftpSession *ctx, char *filename, size_t len, TftpOpenMode *mode)
246 {
247         DECLARE_TIMEOUT(wait_tm, ctx->timeout);
248         resetTftpState(ctx);
249
250         int res = tftp_waitEvent(ctx, &wait_tm);
251         if (res == 0)
252         {
253                 ctx->error = TFTP_ERR_TIMEOUT;
254                 return NULL;
255         }
256         if (res == -1)
257         {
258                 ctx->error = TFTP_ERR;
259                 return NULL;
260         }
261
262         // listen onto TFTP port
263         ctx->addr_len = sizeof(ctx->addr);
264         ssize_t rd = 0;
265         if ((rd = lwip_recvfrom(ctx->sock, &ctx->frame, sizeof(Tftpframe), 0, (struct sockaddr *)&ctx->addr, &ctx->addr_len)) > 0)
266         {
267                 // check if the packet is WRQ, otherwise discard the packet
268                 if (ctx->frame.hdr.opcode == TFTP_WRQ)
269                 {
270                         *mode = TFTP_WRITE;
271                         ctx->pending_ack = true;
272                         strncpy(filename, (char *)&ctx->frame.hdr.th_u, len);
273                         filename[len - 1] = '\0';
274                         ctx->error = 0;
275                         return &ctx->kfile_request;
276                 }
277                 else
278                         *mode = TFTP_READ;
279         }
280         ctx->error = TFTP_ERR;
281         return NULL;
282 }
283
284 /**
285  * Init a server session
286  *
287  * Create a IPv4 session on all addresses and port \a port.
288  *
289  * \param ctx Context to be initialized as server
290  * \param port Port to listen incoming connections
291  * \param timeout Timeout to be used for tftp connections
292  * \return 0 if successful, -1 otherwise
293  */
294 int tftp_init(TftpSession *ctx, unsigned short port, mtime_t timeout)
295 {
296         DB(ctx->kfile_request._type = KFT_TFTPSESSION);
297         ctx->kfile_request.read = tftp_read;
298         ctx->kfile_request.error = tftp_error;
299         ctx->kfile_request.clearerr = tftp_clearerr;
300         ctx->kfile_request.close = tftp_close;
301         resetTftpState(ctx);
302
303         /* Unused kfile methods */
304         ctx->kfile_request.seek = NULL;
305         ctx->kfile_request.write = NULL;
306         ctx->kfile_request.flush = NULL;
307         ctx->kfile_request.reopen = NULL;
308
309         struct sockaddr_in sa;
310         sa.sin_family = AF_INET;
311         sa.sin_addr.s_addr = htonl(INADDR_ANY);
312         sa.sin_port = htons(port);
313         ctx->timeout = timeout;
314
315         ctx->sock = lwip_socket(AF_INET, SOCK_DGRAM, 0);
316         if (ctx->sock == -1)
317         {
318                 LOG_INFO("TFTP socket error\n");
319                 return -1;
320         }
321
322         if(lwip_bind(ctx->sock, (struct sockaddr *)&sa, sizeof(sa)))
323         {
324                 LOG_INFO("Error binding socket\n");
325                 return -1;
326         }
327         return 0;
328 }
329