1 /*
2  * SpanDSP - a series of DSP components for telephony
3  *
4  * hdlc.c
5  *
6  * Written by Steve Underwood <steveu@coppice.org>
7  *
8  * Copyright (C) 2003 Steve Underwood
9  *
10  * All rights reserved.
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Lesser General Public License version 2.1,
14  * as published by the Free Software Foundation.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this program; if not, write to the Free Software
23  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  *
25  * $Id: hdlc.c,v 1.60 2008/05/13 13:17:22 steveu Exp $
26  */
27 
28 /*! \file */
29 
30 #if defined(HAVE_CONFIG_H)
31 #include <config.h>
32 #endif
33 
34 #include <stdlib.h>
35 #include <inttypes.h>
36 #include <string.h>
37 #include <stdio.h>
38 
39 #include "spandsp/telephony.h"
40 #include "spandsp/async.h"
41 #include "spandsp/crc.h"
42 #include "spandsp/bit_operations.h"
43 #include "spandsp/hdlc.h"
44 
rx_special_condition(hdlc_rx_state_t * s,int condition)45 static void rx_special_condition(hdlc_rx_state_t *s, int condition)
46 {
47     /* Special conditions */
48     switch (condition)
49     {
50     case PUTBIT_CARRIER_UP:
51     case PUTBIT_TRAINING_SUCCEEDED:
52         /* Reset the HDLC receiver. */
53         s->raw_bit_stream = 0;
54         s->len = 0;
55         s->num_bits = 0;
56         s->flags_seen = 0;
57         s->framing_ok_announced = FALSE;
58         /* Fall through */
59     case PUTBIT_TRAINING_IN_PROGRESS:
60     case PUTBIT_TRAINING_FAILED:
61     case PUTBIT_CARRIER_DOWN:
62     case PUTBIT_END_OF_DATA:
63         s->frame_handler(s->user_data, NULL, condition, TRUE);
64         break;
65     default:
66         //printf("Eh!\n");
67         break;
68     }
69 }
70 /*- End of function --------------------------------------------------------*/
71 
octet_set_and_count(hdlc_rx_state_t * s)72 static __inline__ void octet_set_and_count(hdlc_rx_state_t *s)
73 {
74     if (s->octet_count_report_interval == 0)
75         return;
76 
77     /* If we are not in octet counting mode, we start it.
78        If we are in octet counting mode, we update it. */
79     if (s->octet_counting_mode)
80     {
81         if (--s->octet_count <= 0)
82         {
83             s->octet_count = s->octet_count_report_interval;
84             s->frame_handler(s->user_data, NULL, PUTBIT_OCTET_REPORT, TRUE);
85         }
86     }
87     else
88     {
89         s->octet_counting_mode = TRUE;
90         s->octet_count = s->octet_count_report_interval;
91     }
92 }
93 /*- End of function --------------------------------------------------------*/
94 
octet_count(hdlc_rx_state_t * s)95 static __inline__ void octet_count(hdlc_rx_state_t *s)
96 {
97     if (s->octet_count_report_interval == 0)
98         return;
99 
100     /* If we are not in octet counting mode, we start it.
101        If we are in octet counting mode, we update it. */
102     if (s->octet_counting_mode)
103     {
104         if (--s->octet_count <= 0)
105         {
106             s->octet_count = s->octet_count_report_interval;
107             s->frame_handler(s->user_data, NULL, PUTBIT_OCTET_REPORT, TRUE);
108         }
109     }
110 }
111 /*- End of function --------------------------------------------------------*/
112 
rx_flag_or_abort(hdlc_rx_state_t * s)113 static void rx_flag_or_abort(hdlc_rx_state_t *s)
114 {
115     if ((s->raw_bit_stream & 0x8000))
116     {
117         /* Hit HDLC abort */
118         s->rx_aborts++;
119         s->frame_handler(s->user_data, NULL, PUTBIT_ABORT, TRUE);
120         /* If we have not yet seen enough flags, restart the count. If we
121            are beyond that point, just back off one step, so we need to see
122            another flag before proceeding to collect frame octets. */
123         if (s->flags_seen < s->framing_ok_threshold)
124             s->flags_seen = 0;
125         else
126             s->flags_seen = s->framing_ok_threshold - 1;
127         /* An abort starts octet counting */
128         octet_set_and_count(s);
129     }
130     else
131     {
132         /* Hit HDLC flag */
133         /* A flag clears octet counting */
134         s->octet_counting_mode = FALSE;
135         if (s->flags_seen >= s->framing_ok_threshold)
136         {
137             /* We may have a frame, or we may have back to back flags */
138             if (s->len)
139             {
140                 if (s->num_bits == 7  &&  s->len >= s->crc_bytes  &&  s->len <= s->max_frame_len)
141                 {
142                     if ((s->crc_bytes == 2  &&  crc_itu16_check(s->buffer, s->len))
143                         ||
144                         (s->crc_bytes != 2  &&  crc_itu32_check(s->buffer, s->len)))
145                     {
146                         s->rx_frames++;
147                         s->rx_bytes += s->len - s->crc_bytes;
148                         s->len -= s->crc_bytes;
149                         s->frame_handler(s->user_data, s->buffer, s->len, TRUE);
150                     }
151                     else
152                     {
153                         s->rx_crc_errors++;
154                         if (s->report_bad_frames)
155                         {
156                             s->len -= s->crc_bytes;
157                             s->frame_handler(s->user_data, s->buffer, s->len, FALSE);
158                         }
159                     }
160                 }
161                 else
162                 {
163                     /* Frame too short or too long, or the flag is misaligned with its octets. */
164                     if (s->report_bad_frames)
165                     {
166                         /* Don't let the length go below zero, or it will be confused
167                            with one of the special conditions. */
168                         if (s->len >= s->crc_bytes)
169                             s->len -= s->crc_bytes;
170                         else
171                             s->len = 0;
172                         s->frame_handler(s->user_data, s->buffer, s->len, FALSE);
173                     }
174                     s->rx_length_errors++;
175                 }
176             }
177         }
178         else
179         {
180             /* Check the flags are back-to-back when testing for valid preamble. This
181                greatly reduces the chances of false preamble detection, and anything
182                which doesn't send them back-to-back is badly broken. */
183             if (s->num_bits != 7)
184                 s->flags_seen = 0;
185             if (++s->flags_seen >= s->framing_ok_threshold  &&  !s->framing_ok_announced)
186             {
187                 s->frame_handler(s->user_data, NULL, PUTBIT_FRAMING_OK, TRUE);
188                 s->framing_ok_announced = TRUE;
189             }
190         }
191     }
192     s->len = 0;
193     s->num_bits = 0;
194 }
195 /*- End of function --------------------------------------------------------*/
196 
hdlc_rx_put_bit_core(hdlc_rx_state_t * s)197 static __inline__ void hdlc_rx_put_bit_core(hdlc_rx_state_t *s)
198 {
199     if ((s->raw_bit_stream & 0x3F00) == 0x3E00)
200     {
201         /* Its time to either skip a bit, for stuffing, or process a
202            flag or abort */
203         if ((s->raw_bit_stream & 0x4000))
204             rx_flag_or_abort(s);
205         return;
206     }
207     s->num_bits++;
208     if (s->flags_seen < s->framing_ok_threshold)
209     {
210         if ((s->num_bits & 0x7) == 0)
211             octet_count(s);
212         return;
213     }
214     s->byte_in_progress = (s->byte_in_progress | (s->raw_bit_stream & 0x100)) >> 1;
215     if (s->num_bits == 8)
216     {
217         /* Ensure we do not accept an overlength frame, and especially that
218            we do not overflow our buffer */
219         if (s->len < s->max_frame_len)
220         {
221             s->buffer[s->len++] = (uint8_t) s->byte_in_progress;
222         }
223         else
224         {
225             /* This is too long. Abandon the frame, and wait for the next
226                flag octet. */
227             s->len = sizeof(s->buffer) + 1;
228             s->flags_seen = s->framing_ok_threshold - 1;
229             octet_set_and_count(s);
230         }
231         s->num_bits = 0;
232     }
233 }
234 /*- End of function --------------------------------------------------------*/
235 
hdlc_rx_put_bit(hdlc_rx_state_t * s,int new_bit)236 void hdlc_rx_put_bit(hdlc_rx_state_t *s, int new_bit)
237 {
238     if (new_bit < 0)
239     {
240         rx_special_condition(s, new_bit);
241         return;
242     }
243     s->raw_bit_stream = (s->raw_bit_stream << 1) | ((new_bit << 8) & 0x100);
244     hdlc_rx_put_bit_core(s);
245 }
246 /*- End of function --------------------------------------------------------*/
247 
hdlc_rx_put_byte(hdlc_rx_state_t * s,int new_byte)248 void hdlc_rx_put_byte(hdlc_rx_state_t *s, int new_byte)
249 {
250     int i;
251 
252     if (new_byte < 0)
253     {
254         rx_special_condition(s, new_byte);
255         return;
256     }
257     s->raw_bit_stream |= new_byte;
258     for (i = 0;  i < 8;  i++)
259     {
260         s->raw_bit_stream <<= 1;
261         hdlc_rx_put_bit_core(s);
262     }
263 }
264 /*- End of function --------------------------------------------------------*/
265 
hdlc_rx_put(hdlc_rx_state_t * s,const uint8_t buf[],int len)266 void hdlc_rx_put(hdlc_rx_state_t *s, const uint8_t buf[], int len)
267 {
268     int i;
269 
270     for (i = 0;  i < len;  i++)
271         hdlc_rx_put_byte(s, buf[i]);
272 }
273 /*- End of function --------------------------------------------------------*/
274 
hdlc_rx_set_max_frame_len(hdlc_rx_state_t * s,size_t max_len)275 void hdlc_rx_set_max_frame_len(hdlc_rx_state_t *s, size_t max_len)
276 {
277     max_len += s->crc_bytes;
278     s->max_frame_len = (max_len <= sizeof(s->buffer))  ?  max_len  :  sizeof(s->buffer);
279 }
280 /*- End of function --------------------------------------------------------*/
281 
hdlc_rx_set_octet_counting_report_interval(hdlc_rx_state_t * s,int interval)282 void hdlc_rx_set_octet_counting_report_interval(hdlc_rx_state_t *s, int interval)
283 {
284     s->octet_count_report_interval = interval;
285 }
286 /*- End of function --------------------------------------------------------*/
287 
hdlc_rx_init(hdlc_rx_state_t * s,int crc32,int report_bad_frames,int framing_ok_threshold,hdlc_frame_handler_t handler,void * user_data)288 hdlc_rx_state_t *hdlc_rx_init(hdlc_rx_state_t *s,
289                               int crc32,
290                               int report_bad_frames,
291                               int framing_ok_threshold,
292                               hdlc_frame_handler_t handler,
293                               void *user_data)
294 {
295     if (s == NULL)
296     {
297         if ((s = (hdlc_rx_state_t *) malloc(sizeof(*s))) == NULL)
298             return NULL;
299     }
300     memset(s, 0, sizeof(*s));
301     s->frame_handler = handler;
302     s->user_data = user_data;
303     s->crc_bytes = (crc32)  ?  4  :  2;
304     s->report_bad_frames = report_bad_frames;
305     s->framing_ok_threshold = (framing_ok_threshold < 1)  ?  1  :  framing_ok_threshold;
306     s->max_frame_len = sizeof(s->buffer);
307     return s;
308 }
309 /*- End of function --------------------------------------------------------*/
310 
hdlc_rx_get_stats(hdlc_rx_state_t * s,hdlc_rx_stats_t * t)311 int hdlc_rx_get_stats(hdlc_rx_state_t *s,
312                       hdlc_rx_stats_t *t)
313 {
314     t->bytes = s->rx_bytes;
315     t->good_frames = s->rx_frames;
316     t->crc_errors = s->rx_crc_errors;
317     t->length_errors = s->rx_length_errors;
318     t->aborts = s->rx_aborts;
319     return 0;
320 }
321 /*- End of function --------------------------------------------------------*/
322 
hdlc_tx_frame(hdlc_tx_state_t * s,const uint8_t * frame,size_t len)323 int hdlc_tx_frame(hdlc_tx_state_t *s, const uint8_t *frame, size_t len)
324 {
325     if (len <= 0)
326     {
327         s->tx_end = TRUE;
328         return 0;
329     }
330     if (s->len + len > s->max_frame_len)
331         return -1;
332     if (s->progressive)
333     {
334         /* Only lock out if we are in the CRC section. */
335         if (s->pos >= HDLC_MAXFRAME_LEN)
336             return -1;
337     }
338     else
339     {
340         /* Lock out if there is anything in the buffer. */
341         if (s->len)
342             return -1;
343     }
344     memcpy(s->buffer + s->len, frame, len);
345     if (s->crc_bytes == 2)
346         s->crc = crc_itu16_calc(frame, len, (uint16_t) s->crc);
347     else
348         s->crc = crc_itu32_calc(frame, len, s->crc);
349     if (s->progressive)
350         s->len += len;
351     else
352         s->len = len;
353     s->tx_end = FALSE;
354     return 0;
355 }
356 /*- End of function --------------------------------------------------------*/
357 
hdlc_tx_flags(hdlc_tx_state_t * s,int len)358 int hdlc_tx_flags(hdlc_tx_state_t *s, int len)
359 {
360     /* Some HDLC applications require the ability to force a period of HDLC
361        flag words. */
362     if (s->pos)
363         return -1;
364     if (len < 0)
365         s->flag_octets += -len;
366     else
367         s->flag_octets = len;
368     s->report_flag_underflow = TRUE;
369     s->tx_end = FALSE;
370     return 0;
371 }
372 /*- End of function --------------------------------------------------------*/
373 
hdlc_tx_abort(hdlc_tx_state_t * s)374 int hdlc_tx_abort(hdlc_tx_state_t *s)
375 {
376     /* TODO: This is a really crude way of just fudging an abort out for simple
377              test purposes. */
378     s->flag_octets++;
379     s->abort_octets++;
380     return -1;
381 }
382 /*- End of function --------------------------------------------------------*/
383 
hdlc_tx_corrupt_frame(hdlc_tx_state_t * s)384 int hdlc_tx_corrupt_frame(hdlc_tx_state_t *s)
385 {
386     if (s->len <= 0)
387         return -1;
388     s->crc ^= 0xFFFF;
389     s->buffer[HDLC_MAXFRAME_LEN] ^= 0xFF;
390     s->buffer[HDLC_MAXFRAME_LEN + 1] ^= 0xFF;
391     s->buffer[HDLC_MAXFRAME_LEN + 2] ^= 0xFF;
392     s->buffer[HDLC_MAXFRAME_LEN + 3] ^= 0xFF;
393     return 0;
394 }
395 /*- End of function --------------------------------------------------------*/
396 
hdlc_tx_get_byte(hdlc_tx_state_t * s)397 int hdlc_tx_get_byte(hdlc_tx_state_t *s)
398 {
399     int i;
400     int byte_in_progress;
401     int txbyte;
402 
403     if (s->flag_octets > 0)
404     {
405         /* We are in a timed flag section (preamble, inter frame gap, etc.) */
406         if (--s->flag_octets <= 0  &&  s->report_flag_underflow)
407         {
408             s->report_flag_underflow = FALSE;
409             if (s->len == 0)
410             {
411                 /* The timed flags have finished, there is nothing else queued to go,
412                    and we have been told to report this underflow. */
413                 if (s->underflow_handler)
414                     s->underflow_handler(s->user_data);
415             }
416         }
417         if (s->abort_octets)
418         {
419             s->abort_octets = 0;
420             return 0x7F;
421         }
422         return s->idle_octet;
423     }
424     if (s->len)
425     {
426         if (s->num_bits >= 8)
427         {
428             s->num_bits -= 8;
429             return (s->octets_in_progress >> s->num_bits) & 0xFF;
430         }
431         if (s->pos >= s->len)
432         {
433             if (s->pos == s->len)
434             {
435                 s->crc ^= 0xFFFFFFFF;
436                 s->buffer[HDLC_MAXFRAME_LEN] = (uint8_t) s->crc;
437                 s->buffer[HDLC_MAXFRAME_LEN + 1] = (uint8_t) (s->crc >> 8);
438                 if (s->crc_bytes == 4)
439                 {
440                     s->buffer[HDLC_MAXFRAME_LEN + 2] = (uint8_t) (s->crc >> 16);
441                     s->buffer[HDLC_MAXFRAME_LEN + 3] = (uint8_t) (s->crc >> 24);
442                 }
443                 s->pos = HDLC_MAXFRAME_LEN;
444             }
445             else if (s->pos == HDLC_MAXFRAME_LEN + s->crc_bytes)
446             {
447                 /* Finish off the current byte with some flag bits. If we are at the
448                    start of a byte we need a at least one whole byte of flag to ensure
449                    we cannot end up with back to back frames, and no flag octet at all */
450                 txbyte = (uint8_t) ((s->octets_in_progress << (8 - s->num_bits)) | (0x7E >> s->num_bits));
451                 /* Create a rotated octet of flag for idling... */
452                 s->idle_octet = (0x7E7E >> s->num_bits) & 0xFF;
453                 /* ...and the partial flag octet needed to start off the next message. */
454                 s->octets_in_progress = s->idle_octet >> (8 - s->num_bits);
455                 s->flag_octets = s->inter_frame_flags - 1;
456                 s->len = 0;
457                 s->pos = 0;
458                 if (s->crc_bytes == 2)
459                     s->crc = 0xFFFF;
460                 else
461                     s->crc = 0xFFFFFFFF;
462                 /* Report the underflow now. If there are timed flags still in progress, loading the
463                    next frame right now will be harmless. */
464                 s->report_flag_underflow = FALSE;
465                 if (s->underflow_handler)
466                     s->underflow_handler(s->user_data);
467                 /* Make sure we finish off with at least one flag octet, if the underflow report did not result
468                    in a new frame being sent. */
469                 if (s->len == 0  &&  s->flag_octets < 2)
470                     s->flag_octets = 2;
471                 return txbyte;
472             }
473         }
474         byte_in_progress = s->buffer[s->pos++];
475         i = bottom_bit(byte_in_progress | 0x100);
476         s->octets_in_progress <<= i;
477         byte_in_progress >>= i;
478         for (  ;  i < 8;  i++)
479         {
480             s->octets_in_progress = (s->octets_in_progress << 1) | (byte_in_progress & 0x01);
481             byte_in_progress >>= 1;
482             if ((s->octets_in_progress & 0x1F) == 0x1F)
483             {
484                 /* There are 5 ones - stuff */
485                 s->octets_in_progress <<= 1;
486                 s->num_bits++;
487             }
488         }
489         /* An input byte will generate between 8 and 10 output bits */
490         return (s->octets_in_progress >> s->num_bits) & 0xFF;
491     }
492     /* Untimed idling on flags */
493     if (s->tx_end)
494     {
495         s->tx_end = FALSE;
496         return PUTBIT_END_OF_DATA;
497     }
498     return s->idle_octet;
499 }
500 /*- End of function --------------------------------------------------------*/
501 
hdlc_tx_get_bit(hdlc_tx_state_t * s)502 int hdlc_tx_get_bit(hdlc_tx_state_t *s)
503 {
504     int txbit;
505 
506     if (s->bits == 0)
507     {
508         if ((s->byte = hdlc_tx_get_byte(s)) < 0)
509             return s->byte;
510         s->bits = 8;
511     }
512     s->bits--;
513     txbit = (s->byte >> s->bits) & 0x01;
514     return  txbit;
515 }
516 /*- End of function --------------------------------------------------------*/
517 
hdlc_tx_get(hdlc_tx_state_t * s,uint8_t buf[],size_t max_len)518 int hdlc_tx_get(hdlc_tx_state_t *s, uint8_t buf[], size_t max_len)
519 {
520     int i;
521     int x;
522 
523     for (i = 0;  i < max_len;  i++)
524     {
525         if ((x = hdlc_tx_get_byte(s)) == PUTBIT_END_OF_DATA)
526             return i;
527         buf[i] = x;
528     }
529     return i;
530 }
531 /*- End of function --------------------------------------------------------*/
532 
hdlc_tx_set_max_frame_len(hdlc_tx_state_t * s,size_t max_len)533 void hdlc_tx_set_max_frame_len(hdlc_tx_state_t *s, size_t max_len)
534 {
535     s->max_frame_len = (max_len <= HDLC_MAXFRAME_LEN)  ?  max_len  :  HDLC_MAXFRAME_LEN;
536 }
537 /*- End of function --------------------------------------------------------*/
538 
hdlc_tx_init(hdlc_tx_state_t * s,int crc32,int inter_frame_flags,int progressive,hdlc_underflow_handler_t handler,void * user_data)539 hdlc_tx_state_t *hdlc_tx_init(hdlc_tx_state_t *s,
540                               int crc32,
541                               int inter_frame_flags,
542                               int progressive,
543                               hdlc_underflow_handler_t handler,
544                               void *user_data)
545 {
546     if (s == NULL)
547     {
548         if ((s = (hdlc_tx_state_t *) malloc(sizeof(*s))) == NULL)
549             return NULL;
550     }
551     memset(s, 0, sizeof(*s));
552     s->idle_octet = 0x7E;
553     s->underflow_handler = handler;
554     s->user_data = user_data;
555     s->inter_frame_flags = (inter_frame_flags < 1)  ?  1  :  inter_frame_flags;
556     if (crc32)
557     {
558         s->crc_bytes = 4;
559         s->crc = 0xFFFFFFFF;
560     }
561     else
562     {
563         s->crc_bytes = 2;
564         s->crc = 0xFFFF;
565     }
566     s->progressive = progressive;
567     s->max_frame_len = HDLC_MAXFRAME_LEN;
568     return s;
569 }
570 /*- End of function --------------------------------------------------------*/
571 /*- End of file ------------------------------------------------------------*/
572