sockio.c 2.0 KB

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