sockio.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include "sockio.h"
  2. // get char from client socket
  3. int sgetc(int clnt_sock, struct buffer *recv_buf)
  4. {
  5. if (recv_buf->ptr == recv_buf->len)
  6. {
  7. ssize_t n = read(clnt_sock, recv_buf->buf, BUF_SIZE);
  8. if (n == -1)
  9. {
  10. return -1;
  11. }
  12. if (n == 0) // avoid confusion with '\0'
  13. {
  14. return -2;
  15. }
  16. recv_buf->ptr = 0;
  17. recv_buf->len = n;
  18. }
  19. return (uint8_t)recv_buf->buf[recv_buf->ptr++]; // avoid confusion with '\xff'
  20. }
  21. // get line from client socket
  22. int sgetline(int clnt_sock, struct buffer *recv_buf, struct buffer *line_buf)
  23. {
  24. int cr = 0;
  25. for (line_buf->len = 0;;)
  26. {
  27. int c = sgetc(clnt_sock, recv_buf);
  28. if (c < 0)
  29. {
  30. return c;
  31. }
  32. line_buf->buf[line_buf->len++] = c;
  33. if (c == '\r')
  34. {
  35. cr = 1;
  36. }
  37. else if (c == '\n' && cr)
  38. {
  39. break;
  40. }
  41. else
  42. {
  43. cr = 0;
  44. }
  45. }
  46. line_buf->buf[line_buf->len] = '\0';
  47. return line_buf->len;
  48. }
  49. // flush send buffer
  50. int sflush(int clnt_sock, struct buffer *send_buf)
  51. {
  52. uint16_t len = send_buf->len;
  53. for (; send_buf->len;)
  54. {
  55. ssize_t n = write(clnt_sock, send_buf->buf + len - send_buf->len, send_buf->len);
  56. if (n == -1)
  57. {
  58. return -1;
  59. }
  60. send_buf->len -= n;
  61. }
  62. return len;
  63. }
  64. // put char to client socket
  65. int sputc(int clnt_sock, struct buffer *send_buf, char c)
  66. {
  67. if (send_buf->len == BUF_SIZE && sflush(clnt_sock, send_buf) == -1)
  68. {
  69. return -1;
  70. }
  71. send_buf->buf[send_buf->len++] = c;
  72. return (uint8_t)c; // avoid confusion with '\xff'
  73. }
  74. // put line to client socket
  75. int sputline(int clnt_sock, struct buffer *send_buf, struct buffer *line_buf)
  76. {
  77. for (char *s = line_buf->buf; s < line_buf->buf + line_buf->len; s++)
  78. {
  79. int c = sputc(clnt_sock, send_buf, *s);
  80. if (c == -1)
  81. {
  82. return -1;
  83. }
  84. }
  85. return line_buf->len;
  86. }