Browse Source

Add documentation to networking code

Samuel Čavoj 2 years ago
parent
commit
17af6d0972
1 changed files with 38 additions and 0 deletions
  1. 38 0
      network.c

+ 38 - 0
network.c

@@ -6,6 +6,15 @@
 #include <errno.h>
 #include <arpa/inet.h>
 
+/**
+ * Try to read exactly `n` bytes from a file descriptor.
+ * Returns -1 on error, otherwise number of bytes read.
+ * The return value can be smaller than `n` if the
+ * file descriptor encounters EOF.
+ *
+ * In case of error, errno is set by underlying call to
+ * read(), but the number of succesfully read bytes is lost.
+ */
 ssize_t read_nbytes(int fd, size_t n, uint8_t* buffer) {
     size_t read_bytes = 0;
     int res;
@@ -22,6 +31,12 @@ ssize_t read_nbytes(int fd, size_t n, uint8_t* buffer) {
     return read_bytes;
 }
 
+/**
+ * Try to read a single serialized packet from a file descriptor.
+ * Returns -1 on error, with errno appropriately set.
+ * Returns 0 if EOF was encountered before the end of packet.
+ * Otherwise returns the type field of the packet.
+ */
 int recv_packet(int fd, uint8_t* buf, size_t* n) {
     uint16_t size;
     if (*n < sizeof(size)) {
@@ -33,8 +48,10 @@ int recv_packet(int fd, uint8_t* buf, size_t* n) {
         return res;
     }
     if (res < (ssize_t)sizeof(size)) {
+        // Stream ended before we could read size of packet.
         return 0;
     }
+    // Size of packet including the size field itself.
     size = ntohs(*((uint16_t*)buf));
     if (size > *n) {
         errno = ENOBUFS;
@@ -45,6 +62,7 @@ int recv_packet(int fd, uint8_t* buf, size_t* n) {
         return res;
     }
     if (res == 0) {
+        // Stream ended before we could read packet in full.
         return 0;
     }
     *n = sizeof(size)+res;
@@ -52,6 +70,12 @@ int recv_packet(int fd, uint8_t* buf, size_t* n) {
     return buf[2];
 }
 
+/**
+ * Read and discard data from file descriptor until EOF.
+ * Returns the number of bytes read.
+ *
+ * Useful in a shutdown procedure.
+ */
 int recv_dump_all(int fd) {
     char buf[PKT_SIZE_MAX];
     int s;
@@ -59,11 +83,25 @@ int recv_dump_all(int fd) {
     return s;
 }
 
+/**
+ * Equivalent to a single recv with length of PKT_SIZE_MAX,
+ * but discard the resulting data.
+ *
+ * Useful in a shutdown procedure.
+ */
 int recv_dump(int fd) {
     char buf[PKT_SIZE_MAX];
     return recv(fd, buf, PKT_SIZE_MAX, 0);
 }
 
+
+/**
+ * Transmit a single packet (or any arbitrary buffer) taking
+ * care of partial sends.
+ *
+ * Returns the number of bytes sent. If this is less than
+ * `length`, an error has occured, and errno is set by underlying send.
+ */
 size_t send_packet(int fd, uint8_t* buf, size_t length) {
     size_t sent = 0;
     int n;