slip_common.h 2.2 KB

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