slip_common.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __UM_SLIP_COMMON_H
  3. #define __UM_SLIP_COMMON_H
  4. #define BUF_SIZE 1500
  5. /* two bytes each for a (pathological) max packet of escaped chars + *
  6. * terminating END char + initial END char */
  7. #define ENC_BUF_SIZE (2 * BUF_SIZE + 2)
  8. /* SLIP protocol characters. */
  9. #define SLIP_END 0300 /* indicates end of frame */
  10. #define SLIP_ESC 0333 /* indicates byte stuffing */
  11. #define SLIP_ESC_END 0334 /* ESC ESC_END means END 'data' */
  12. #define SLIP_ESC_ESC 0335 /* ESC ESC_ESC means ESC 'data' */
  13. static inline int slip_unesc(unsigned char c, unsigned char *buf, int *pos,
  14. int *esc)
  15. {
  16. int ret;
  17. switch(c){
  18. case SLIP_END:
  19. *esc = 0;
  20. ret=*pos;
  21. *pos=0;
  22. return(ret);
  23. case SLIP_ESC:
  24. *esc = 1;
  25. return(0);
  26. case SLIP_ESC_ESC:
  27. if(*esc){
  28. *esc = 0;
  29. c = SLIP_ESC;
  30. }
  31. break;
  32. case SLIP_ESC_END:
  33. if(*esc){
  34. *esc = 0;
  35. c = SLIP_END;
  36. }
  37. break;
  38. }
  39. buf[(*pos)++] = c;
  40. return(0);
  41. }
  42. static inline int slip_esc(unsigned char *s, unsigned char *d, int len)
  43. {
  44. unsigned char *ptr = d;
  45. unsigned char c;
  46. /*
  47. * Send an initial END character to flush out any
  48. * data that may have accumulated in the receiver
  49. * due to line noise.
  50. */
  51. *ptr++ = SLIP_END;
  52. /*
  53. * For each byte in the packet, send the appropriate
  54. * character sequence, according to the SLIP protocol.
  55. */
  56. while (len-- > 0) {
  57. switch(c = *s++) {
  58. case SLIP_END:
  59. *ptr++ = SLIP_ESC;
  60. *ptr++ = SLIP_ESC_END;
  61. break;
  62. case SLIP_ESC:
  63. *ptr++ = SLIP_ESC;
  64. *ptr++ = SLIP_ESC_ESC;
  65. break;
  66. default:
  67. *ptr++ = c;
  68. break;
  69. }
  70. }
  71. *ptr++ = SLIP_END;
  72. return (ptr - d);
  73. }
  74. struct slip_proto {
  75. unsigned char ibuf[ENC_BUF_SIZE];
  76. unsigned char obuf[ENC_BUF_SIZE];
  77. int more; /* more data: do not read fd until ibuf has been drained */
  78. int pos;
  79. int esc;
  80. };
  81. static inline void slip_proto_init(struct slip_proto * slip)
  82. {
  83. memset(slip->ibuf, 0, sizeof(slip->ibuf));
  84. memset(slip->obuf, 0, sizeof(slip->obuf));
  85. slip->more = 0;
  86. slip->pos = 0;
  87. slip->esc = 0;
  88. }
  89. extern int slip_proto_read(int fd, void *buf, int len,
  90. struct slip_proto *slip);
  91. extern int slip_proto_write(int fd, void *buf, int len,
  92. struct slip_proto *slip);
  93. #endif