Update preset.
[bertos.git] / bertos / net / ax25.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 2009 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  * \brief Simple AX25 data link layer implementation.
33  *
34  * For now, only UI frames without any Layer 3 protocol are handled.
35  * This however is enough to send/receive APRS packets.
36  *
37  * \author Francesco Sacchi <batt@develer.com>
38  *
39  */
40
41 #include "ax25.h"
42 #include "cfg/cfg_ax25.h"
43
44 #include <algo/crc_ccitt.h>
45
46 #define LOG_LEVEL  AX25_LOG_LEVEL
47 #define LOG_FORMAT AX25_LOG_FORMAT
48 #include <cfg/log.h>
49
50 #include <string.h> //memset, memcmp
51 #include <ctype.h>  //isalnum, toupper
52
53 #if CONFIG_AX25_RPT_LST
54         #define AX25_SET_REPEATED(msg, idx, val) \
55                 do \
56                 { \
57                         if (val) \
58                                 (msg)->rpt_flags |= BV(idx) ; \
59                         else \
60                                 (msg)->rpt_flags &= ~BV(idx) ; \
61                 } while(0) 
62 #endif
63
64 #define DECODE_CALL(buf, addr) \
65         for (unsigned i = 0; i < sizeof((addr)); i++) \
66         { \
67                 char c = (*(buf)++ >> 1); \
68                 (addr)[i] = (c == ' ') ? '\x0' : c; \
69         }
70
71 static void ax25_decode(AX25Ctx *ctx)
72 {
73         AX25Msg msg;
74         uint8_t *buf = ctx->buf;
75
76         DECODE_CALL(buf, msg.dst.call);
77         msg.dst.ssid = (*buf++ >> 1) & 0x0F;
78
79         DECODE_CALL(buf, msg.src.call);
80         msg.src.ssid = (*buf >> 1) & 0x0F;
81
82         LOG_INFO("SRC[%.6s-%d], DST[%.6s-%d]\n", msg.src.call, msg.src.ssid, msg.dst.call, msg.dst.ssid);
83
84         /* Repeater addresses */
85         #if CONFIG_AX25_RPT_LST
86                 for (msg.rpt_cnt = 0; !(*buf++ & 0x01) && (msg.rpt_cnt < countof(msg.rpt_lst)); msg.rpt_cnt++)
87                 {
88                         DECODE_CALL(buf, msg.rpt_lst[msg.rpt_cnt].call);
89                         msg.rpt_lst[msg.rpt_cnt].ssid = (*buf >> 1) & 0x0F;
90                         AX25_SET_REPEATED(&msg, msg.rpt_cnt, (*buf & 0x80));
91
92                         LOG_INFO("RPT%d[%.6s-%d]%c\n", msg.rpt_cnt, 
93                                 msg.rpt_lst[msg.rpt_cnt].call, 
94                                 msg.rpt_lst[msg.rpt_cnt].ssid,
95                                 (AX25_REPEATED(&msg, msg.rpt_cnt) ? '*' : ' '));
96                 }
97         #else
98                 while (!(*buf++ & 0x01))
99                 {
100                         char rpt[6];
101                         uint8_t ssid;
102                         DECODE_CALL(buf, rpt);
103                         ssid = (*buf >> 1) & 0x0F;
104                         LOG_INFO("RPT[%.6s-%d]\n", rpt, ssid);
105                 }
106         #endif
107
108         msg.ctrl = *buf++;
109         if (msg.ctrl != AX25_CTRL_UI)
110         {
111                 LOG_WARN("Only UI frames are handled, got [%02X]\n", msg.ctrl);
112                 return;
113         }
114
115         msg.pid = *buf++;
116         if (msg.pid != AX25_PID_NOLAYER3)
117         {
118                 LOG_WARN("Only frames without layer3 protocol are handled, got [%02X]\n", msg.pid);
119                 return;
120         }
121
122         msg.len = ctx->frm_len - 2 - (buf - ctx->buf);
123         msg.info = buf;
124         LOG_INFO("DATA: %.*s\n", msg.len, msg.info);
125
126         if (ctx->hook)
127                 ctx->hook(&msg);
128 }
129
130
131 /**
132  * Check if there are any AX25 messages to be processed.
133  * This function read available characters from the medium and search for
134  * any AX25 messages.
135  * If a message is found it is decoded and the linked callback executed.
136  * This function may be blocking if there are no available chars and the KFile
137  * used in \a ctx to access the medium is configured in blocking mode.
138  *
139  * \param ctx AX25 context to operate on.
140  */
141 void ax25_poll(AX25Ctx *ctx)
142 {
143         int c;
144
145         while ((c = kfile_getc(ctx->ch)) != EOF)
146         {
147                 if (!ctx->escape && c == HDLC_FLAG)
148                 {
149                         if (ctx->frm_len >= AX25_MIN_FRAME_LEN)
150                         {
151                                 if (ctx->crc_in == AX25_CRC_CORRECT)
152                                 {
153                                         LOG_INFO("Frame found!\n");
154                                         ax25_decode(ctx);
155                                 }
156                                 else
157                                 {
158                                         LOG_INFO("CRC error, computed [%04X]\n", ctx->crc_in);
159                                 }
160                         }
161                         ctx->sync = true;
162                         ctx->crc_in = CRC_CCITT_INIT_VAL;
163                         ctx->frm_len = 0;
164                         continue;
165                 }
166
167                 if (!ctx->escape && c == HDLC_RESET)
168                 {
169                         LOG_INFO("HDLC reset\n");
170                         ctx->sync = false;
171                         continue;
172                 }
173
174                 if (!ctx->escape && c == AX25_ESC)
175                 {
176                         ctx->escape = true;
177                         continue;
178                 }
179
180                 if (ctx->sync)
181                 {
182                         if (ctx->frm_len < CONFIG_AX25_FRAME_BUF_LEN)
183                         {
184                                 ctx->buf[ctx->frm_len++] = c;
185                                 ctx->crc_in = updcrc_ccitt(c, ctx->crc_in);
186                         }
187                         else
188                         {
189                                 LOG_INFO("Buffer overrun");
190                                 ctx->sync = false;
191                         }
192                 }
193                 ctx->escape = false;
194         }
195
196         if (kfile_error(ctx->ch))
197         {
198                 LOG_ERR("Channel error [%04x]\n", kfile_error(ctx->ch));
199                 kfile_clearerr(ctx->ch);
200         }
201 }
202
203 static void ax25_putchar(AX25Ctx *ctx, uint8_t c)
204 {
205         if (c == HDLC_FLAG || c == HDLC_RESET
206                 || c == AX25_ESC)
207                 kfile_putc(AX25_ESC, ctx->ch);
208         ctx->crc_out = updcrc_ccitt(c, ctx->crc_out);
209         kfile_putc(c, ctx->ch);
210 }
211
212 static void ax25_sendCall(AX25Ctx *ctx, const AX25Call *addr, bool last)
213 {
214         unsigned len = MIN(sizeof(addr->call), strlen(addr->call));
215
216         for (unsigned i = 0; i < len; i++)
217         {
218                 uint8_t c = addr->call[i];
219                 ASSERT(isalnum(c) || c == ' ');
220                 c = toupper(c);
221                 ax25_putchar(ctx, c << 1);
222         }
223
224         /* Fill with spaces the rest of the CALL if it's shorter */
225         if (len < sizeof(addr->call))
226                 for (unsigned i = 0; i < sizeof(addr->call) - len; i++)
227                         ax25_putchar(ctx, ' ' << 1);
228
229         /* The bit7 "has-been-repeated" flag is not implemented here */
230         /* Bits6:5 should be set to 1 for all SSIDs (0x60) */
231         /* The bit0 of last call SSID should be set to 1 */
232         uint8_t ssid = 0x60 | (addr->ssid << 1) | (last ? 0x01 : 0);
233         ax25_putchar(ctx, ssid);
234 }
235
236 /**
237  * Send an AX25 frame on the channel through a specific path.
238  * \param ctx AX25 context to operate on.
239  * \param path An array of callsigns used as path, \see AX25_PATH for
240  *        an handy way to create a path.
241  * \param path_len callsigns path lenght.
242  * \param _buf payload buffer.
243  * \param len length of the payload.
244  */
245 void ax25_sendVia(AX25Ctx *ctx, const AX25Call *path, size_t path_len, const void *_buf, size_t len)
246 {
247         const uint8_t *buf = (const uint8_t *)_buf;
248         ASSERT(path);
249         ASSERT(path_len >= 2);
250
251         ctx->crc_out = CRC_CCITT_INIT_VAL;
252         kfile_putc(HDLC_FLAG, ctx->ch);
253
254
255         /* Send call */
256         for (size_t i = 0; i < path_len; i++)
257                 ax25_sendCall(ctx, &path[i], (i == path_len - 1));
258
259         ax25_putchar(ctx, AX25_CTRL_UI);
260         ax25_putchar(ctx, AX25_PID_NOLAYER3);
261
262         while (len--)
263                 ax25_putchar(ctx, *buf++);
264
265         /*
266          * According to AX25 protocol,
267          * CRC is sent in reverse order!
268          */
269         uint8_t crcl = (ctx->crc_out & 0xff) ^ 0xff;
270         uint8_t crch = (ctx->crc_out >> 8) ^ 0xff;
271         ax25_putchar(ctx, crcl);
272         ax25_putchar(ctx, crch);
273
274         ASSERT(ctx->crc_out == AX25_CRC_CORRECT);
275
276         kfile_putc(HDLC_FLAG, ctx->ch);
277 }
278
279 static void print_call(KFile *ch, const AX25Call *call)
280 {
281         kfile_printf(ch, "%.6s", call->call);
282         if (call->ssid)
283                 kfile_printf(ch, "-%d", call->ssid);
284 }
285
286 /**
287  * Print a AX25 message in TNC-2 packet monitor format.
288  * \param ch a kfile channel where the message will be printed.
289  * \param msg the message to be printed.
290  */
291 void ax25_print(KFile *ch, const AX25Msg *msg)
292 {
293         print_call(ch, &msg->src);
294         kfile_putc('>', ch);
295         print_call(ch, &msg->dst);
296
297         #if CONFIG_AX25_RPT_LST
298         for (int i = 0; i < msg->rpt_cnt; i++)
299         {
300                 kfile_putc(',', ch);
301                 print_call(ch, &msg->rpt_lst[i]);
302                 /* Print a '*' if packet has already been transmitted 
303                  * by this repeater */
304                 if (AX25_REPEATED(msg, i))
305                         kfile_putc('*', ch);
306         }
307         #endif
308
309         kfile_printf(ch, ":%.*s\n", msg->len, msg->info);
310 }
311
312
313 /**
314  * Init the AX25 protocol decoder.
315  *
316  * \param ctx AX25 context to init.
317  * \param channel Used to gain access to the physical medium
318  * \param hook Callback function called when a message is received
319  */
320 void ax25_init(AX25Ctx *ctx, KFile *channel, ax25_callback_t hook)
321 {
322         ASSERT(ctx);
323         ASSERT(channel);
324
325         memset(ctx, 0, sizeof(*ctx));
326         ctx->ch = channel;
327         ctx->hook = hook;
328         ctx->crc_in = ctx->crc_out = CRC_CCITT_INIT_VAL;
329 }