#include "sockio.h" // get char from client socket int sgetc(int clnt_sock, struct buffer *recv_buf) { if (recv_buf->ptr == recv_buf->len) { ssize_t n = read(clnt_sock, recv_buf->buf, BUF_SIZE); if (n == -1) { return -1; } if (n == 0) // avoid confusion with '\0' { return -2; } recv_buf->ptr = 0; recv_buf->len = n; } return (uint8_t)recv_buf->buf[recv_buf->ptr++]; // avoid confusion with '\xff' } // get line from client socket int sgetline(int clnt_sock, struct buffer *recv_buf, struct buffer *line_buf) { int cr = 0; for (line_buf->len = 0;;) { int c = sgetc(clnt_sock, recv_buf); if (c < 0) { return c; } line_buf->buf[line_buf->len++] = c; if (c == '\r') { cr = 1; } else if (c == '\n' && cr) { break; } else { cr = 0; } } line_buf->buf[line_buf->len] = '\0'; return line_buf->len; } // flush send buffer int sflush(int clnt_sock, struct buffer *send_buf) { uint16_t len = send_buf->len; for (; send_buf->len;) { ssize_t n = write(clnt_sock, send_buf->buf + len - send_buf->len, send_buf->len); if (n == -1) { return -1; } send_buf->len -= n; } return len; } // put char to client socket int sputc(int clnt_sock, struct buffer *send_buf, char c) { if (send_buf->len == BUF_SIZE && sflush(clnt_sock, send_buf) == -1) { return -1; } send_buf->buf[send_buf->len++] = c; return (uint8_t)c; // avoid confusion with '\xff' } // put line to client socket int sputline(int clnt_sock, struct buffer *send_buf, struct buffer *line_buf) { for (char *s = line_buf->buf; s < line_buf->buf + line_buf->len; s++) { int c = sputc(clnt_sock, send_buf, *s); if (c == -1) { return -1; } } return line_buf->len; }