From 95d7d348316f1ed8d2ff3e37cb7f962abf4a7f84 Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Thu, 24 Jul 2014 22:06:57 +0200 Subject: [PATCH] Start of UTCP. --- COPYING | 339 +++++++++++++++++++++++ Makefile | 11 + UTCP | 48 ++++ selftest.c | 91 ++++++ test.c | 129 +++++++++ utcp.c | 789 +++++++++++++++++++++++++++++++++++++++++++++++++++++ utcp.h | 58 ++++ 7 files changed, 1465 insertions(+) create mode 100644 COPYING create mode 100644 Makefile create mode 100644 UTCP create mode 100644 selftest.c create mode 100644 test.c create mode 100644 utcp.c create mode 100644 utcp.h diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c7232b9 --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +CFLAGS ?= -O0 -Wall -g +CFLAGS += -std=c99 + +test: utcp.c test.c + +selftest: utcp.c selftest.c + +clean: + rm -f *.o test selftest + +.PHONY: clean diff --git a/UTCP b/UTCP new file mode 100644 index 0000000..02496cc --- /dev/null +++ b/UTCP @@ -0,0 +1,48 @@ +This is a light-weight, user-space implementation of RFC 793 (TCP), without any +reliance on an IP layer. It can be used to provide multiple in-order, reliable +streams on top of any datagram layer. + +UTCP does not rely on a specific event system. Instead, the application feeds +it with incoming packets using utcp_recv(), and outgoing data for the streams +using utcp_send(). Most of the rest is handled by callbacks. The application +must however call utcp_timeout() regularly to have UTCP handle packet loss. + +The application should run utcp_init() for every peer it wants to communicate +with. + +DIFFERENCES FROM RFC 793: + +* No checksum. UTCP requires the application to handle packet integrity. +* 32-bit window size. Big window sizes are the default. +* No ECN, PSH, URG +* Ports are a bit strange (for now). + +TODO v1.0: + +* Do ports the same way as real TCP? +* Implement send buffer +* Window scaling +* Handle retransmission +* Do proper modulo 2^32 comparisons of sequence numbers + +TODO v2.0: + +* Nagle +* NAK and SACK +* Congestion window scaling +* Timestamps? + +Future ideas: + +Fast open: + SYN + data? + +Receive-only open: + SYN|FIN + +Fast transaction: + SYN|FIN + request data -> + <- SYN|ACK|FIN + response data + ACK -> + +Does this need special care or can we rely on higher level MACs? diff --git a/selftest.c b/selftest.c new file mode 100644 index 0000000..c1df40f --- /dev/null +++ b/selftest.c @@ -0,0 +1,91 @@ +#include +#include +#include +#include +#include + +#include "utcp.h" + +struct utcp *a; +struct utcp *b; +struct utcp_connection *c; + +int do_recv(struct utcp_connection *x, void *data, size_t len) { + if(!len) { + if(errno) + fprintf(stderr, "%p Error: %s\n", x->utcp, strerror(errno)); + else + fprintf(stderr, "%p Connection closed by peer\n", x->utcp); + if(x != c) { + fprintf(stderr, "closing my side too...\n"); + utcp_close(x); + } + return -1; + } + + if(x == c) + write(0, data, len); + else + utcp_send(x, data, len); + + return 0; +} + +bool do_pre_accept(struct utcp *utcp, void *data, size_t len) { + fprintf(stderr, "pre-accept\n"); + if(len != 2 || strncmp(data, "oi", 2)) + return false; + return true; +} + +void do_accept(struct utcp_connection *c, void *data, size_t len) { + fprintf(stderr, "accept\n"); + utcp_accept(c, do_recv, NULL); +} + +int do_send(struct utcp *utcp, void *data, size_t len) { + static int count = 0; + if(++count > 1000) { + fprintf(stderr, "Too many packets!\n"); + abort(); + } + + if(utcp == a) + return utcp_recv(b, data, len); + else + return utcp_recv(a, data, len); +} + + +int main(int argc, char *argv[]) { + srand(time(NULL)); + + a = utcp_init(do_accept, do_pre_accept, do_send, NULL); + b = utcp_init(NULL, NULL, do_send, NULL); + + fprintf(stderr, "Testing connection to closed port\n\n"); + c = utcp_connect(b, "zomg", 4, do_recv, NULL); + + fprintf(stderr, "\nTesting conection to non-listening side\n\n"); + c = utcp_connect(a, "oi", 2, do_recv, NULL); + + fprintf(stderr, "\nTesting connection to open port, close\n\n"); + c = utcp_connect(b, "oi", 2, do_recv, NULL); + fprintf(stderr, "closing...\n"); + utcp_close(c); + + fprintf(stderr, "\nTesting connection to open port, abort\n\n"); + c = utcp_connect(b, "oi", 2, do_recv, NULL); + fprintf(stderr, "aborting...\n"); + utcp_abort(c); + + fprintf(stderr, "\nTesting connection with data transfer\n\n"); + + c = utcp_connect(b, "oi", 2, do_recv, NULL); + utcp_send(c, "Hello world!\n", 13); + utcp_send(c, "This is a test.\n", 16); + fprintf(stderr, "closing...\n"); + utcp_close(c); + + return 0; +} diff --git a/test.c b/test.c new file mode 100644 index 0000000..0e0cb2e --- /dev/null +++ b/test.c @@ -0,0 +1,129 @@ +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "utcp.h" + +struct utcp_connection *c; +int dir = 3; +bool running = true; + +int do_recv(struct utcp_connection *c, void *data, size_t len) { + if(!data || !len) { + if(errno) + fprintf(stderr, "Error: %s\n", strerror(errno)); + else { + dir &= ~2; + fprintf(stderr, "Connection closed by peer\n"); + } + return 0; + } + return write(0, data, len); +} + +void do_accept(struct utcp_connection *nc, void *data, size_t len) { + utcp_accept(nc, do_recv, NULL); + c = nc; +} + +int do_send(struct utcp *utcp, void *data, size_t len) { + int s = *(int *)utcp->priv; + return send(s, data, len, MSG_DONTWAIT); +} + +int main(int argc, char *argv[]) { + srand(time(NULL)); + + if(argc < 2 || argc > 3) + return 1; + + bool server = argc == 2; + bool connected = false; + + struct addrinfo *ai; + struct addrinfo hint = { + .ai_flags = server ? AI_PASSIVE : 0, + .ai_socktype = SOCK_DGRAM, + }; + + getaddrinfo(server ? NULL : argv[1], server ? argv[1] : argv[2], &hint, &ai); + if(!ai) + return 1; + + int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); + if(s < 0) + return 1; + + if(server) { + if(bind(s, ai->ai_addr, ai->ai_addrlen)) + return 1; + } else { + if(connect(s, ai->ai_addr, ai->ai_addrlen)) + return 1; + connected = true; + } + + struct utcp *u = utcp_init(server ? do_accept : NULL, NULL, do_send, &s); + if(!u) + return 1; + + if(!server) + c = utcp_connect(u, "test", 4, do_recv, NULL); + + struct pollfd fds[2] = { + {.fd = 0, .events = POLLIN | POLLERR | POLLHUP}, + {.fd = s, .events = POLLIN | POLLERR | POLLHUP}, + }; + + char buf[1024]; + + while(dir) { + int r = poll(fds, 2, 1000); + if(!r) { + utcp_timeout(u); + continue; + } + + if(fds[0].revents) { + int len = read(0, buf, sizeof buf); + if(len <= 0) { + fds[0].fd = -1; + dir &= ~1; + if(c) + utcp_shutdown(c, SHUT_WR); + if(len < 0) + break; + else + continue; + } + if(c) + utcp_send(c, buf, len); + } + + if(fds[1].revents) { + struct sockaddr_storage ss; + socklen_t sl; + int len = recvfrom(s, buf, sizeof buf, MSG_DONTWAIT, (struct sockaddr *)&ss, &sl); + if(len <= 0) + break; + if(!connected) + if(!connect(s, (struct sockaddr *)&ss, sl)) + connected = true; + utcp_recv(u, buf, len); + } + }; + + utcp_close(c); + utcp_exit(u); + + return 0; +} diff --git a/utcp.c b/utcp.c new file mode 100644 index 0000000..5db93ea --- /dev/null +++ b/utcp.c @@ -0,0 +1,789 @@ +/* + utcp.c -- Userspace TCP + Copyright (C) 2014 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define UTCP_INTERNAL +#include "utcp.h" + +#define PREP(l) char pkt[(l) + sizeof struct hdr]; struct hdr *hdr = &pkt; + +#define SYN 1 +#define ACK 2 +#define FIN 4 +#define RST 8 + +struct hdr { + uint16_t src; // Source port + uint16_t dst; // Destination port + uint32_t seq; // Sequence number + uint32_t ack; // Acknowledgement number + uint32_t wnd; // Window size + uint16_t ctl; // Flags (SYN, ACK, FIN, RST) + uint16_t aux; // other stuff +}; + +enum state { + CLOSED, + LISTEN, + SYN_SENT, + SYN_RECEIVED, + ESTABLISHED, + FIN_WAIT_1, + FIN_WAIT_2, + CLOSE_WAIT, + CLOSING, + LAST_ACK, + TIME_WAIT +}; + +const char *strstate[] = { + "CLOSED", + "LISTEN", + "SYN_SENT", + "SYN_RECEIVED", + "ESTABLISHED", + "FIN_WAIT_1", + "FIN_WAIT_2", + "CLOSE_WAIT", + "CLOSING", + "LAST_ACK", + "TIME_WAIT" +}; + +struct utcp_connection { + void *priv; + struct utcp *utcp; + bool reapable; + + uint16_t src; + uint16_t dst; + enum state state; + + // The following two structures form the TCB + + struct { + uint32_t una; + uint32_t nxt; + uint32_t wnd; + uint32_t up; + uint32_t wl1; + uint32_t wl2; + uint32_t iss; + } snd; + + struct { + uint32_t nxt; + uint32_t wnd; + uint32_t up; + uint32_t irs; + } rcv; + + utcp_recv_t recv; + + struct timeval conn_timeout; + struct timeval rtrx_timeout; +}; + +struct utcp { + void *priv; + + utcp_accept_t accept; + utcp_pre_accept_t pre_accept; + utcp_send_t send; + + uint16_t mtu; + + struct utcp_connection **connections; + int nconnections; + int nallocated; + int gap; +}; + +static void set_state(struct utcp_connection *c, enum state state) { + c->state = state; + fprintf(stderr, "%p new state: %s\n", c->utcp, strstate[state]); +} + +static void print_packet(void *pkt, size_t len) { + struct hdr hdr; + if(len < sizeof hdr) { + fprintf(stderr, "short packet (%zu bytes)\n", len); + return; + } + + memcpy(&hdr, pkt, sizeof hdr); + fprintf (stderr, "src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd); + if(hdr.ctl & SYN) + fprintf(stderr, "SYN"); + if(hdr.ctl & RST) + fprintf(stderr, "RST"); + if(hdr.ctl & FIN) + fprintf(stderr, "FIN"); + if(hdr.ctl & ACK) + fprintf(stderr, "ACK"); + + if(len > sizeof hdr) { + fprintf(stderr, " data="); + for(int i = sizeof hdr; i < len; i++) { + char *data = pkt; + fprintf(stderr, "%c", data[i] >= 32 ? data[i] : '.'); + } + } + + fprintf(stderr, "\n"); +} + +static struct utcp_connection *allocate_connection(struct utcp *utcp) { + struct utcp_connection *c; + + // Initial allocation? + + if(!utcp->nconnections) { + utcp->nallocated = 4; + utcp->nconnections = 1; // Skip 0 + utcp->connections = calloc(utcp->nallocated, sizeof *utcp->connections); + } + + // If there is a hole in the list of connections, use it. + // Otherwise, add a new connection to the end. + + if(utcp->gap >= 0) { + c = utcp->connections[utcp->gap] = calloc(1, sizeof *c); + c->src = utcp->gap; + while(++utcp->gap < utcp->nconnections) + if(!utcp->connections[utcp->gap]) + break; + + if(utcp->gap >= utcp->nconnections) + utcp->gap = -1; + } else { + // Too many connections? + + if(utcp->nconnections >= 65536) { + errno = ENOMEM; + return NULL; + } + + // Need to reserve more memory? + + if(utcp->nconnections >= utcp->nallocated) { + utcp->nallocated *= 2; + utcp->connections = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections); + } + + c = utcp->connections[utcp->nconnections] = calloc(1, sizeof *c); + c->src = utcp->nconnections++; + } + + c->snd.iss = rand(); + c->snd.una = c->snd.iss; + c->snd.nxt = c->snd.iss + 1; + c->rcv.wnd = utcp->mtu; + c->utcp = utcp; + return c; +} + +static struct utcp_connection *find_connection(struct utcp *utcp, uint16_t src) { + if(src < utcp->nconnections && utcp->connections[src]) + return utcp->connections[src]; + + errno = EINVAL; + return NULL; +} + +static void free_connection(struct utcp_connection *c) { + if(!c) + return; + if(c->utcp->gap < 0 || c->src < c->utcp->gap) + c->utcp->gap = c->src; + c->utcp->connections[c->src] = NULL; + free(c); +} + +struct utcp_connection *utcp_connect(struct utcp *utcp, void *data, size_t len, utcp_recv_t recv, void *priv) { + struct utcp_connection *c = allocate_connection(utcp); + if(!c) + return NULL; + + c->recv = recv; + + struct { + struct hdr hdr; + char data[len]; + } pkt; + + pkt.hdr.src = c->src; + pkt.hdr.dst = 0; + pkt.hdr.seq = c->snd.iss; + pkt.hdr.ack = 0; + pkt.hdr.ctl = SYN; + pkt.hdr.wnd = c->rcv.wnd; + memcpy(pkt.data, data, len); + + set_state(c, SYN_SENT); + + utcp->send(utcp, &pkt, sizeof pkt.hdr + len); + + // Set timeout? + + return c; +} + +void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) { + if(c->reapable || c->state != SYN_RECEIVED) { + fprintf(stderr, "Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]); + return; + } + + fprintf(stderr, "%p accepted, %p %p\n", c, recv, priv); + c->recv = recv; + c->priv = priv; + set_state(c, ESTABLISHED); +} + +int utcp_send(struct utcp_connection *c, void *data, size_t len) { + if(c->reapable) { + fprintf(stderr, "Error: send() called on closed connection %p\n", c); + errno = EBADF; + return -1; + } + + switch(c->state) { + case CLOSED: + case LISTEN: + case SYN_SENT: + case SYN_RECEIVED: + fprintf(stderr, "Error: send() called on unconnected connection %p\n", c); + errno = ENOTCONN; + return -1; + case ESTABLISHED: + case CLOSE_WAIT: + break; + case FIN_WAIT_1: + case FIN_WAIT_2: + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + fprintf(stderr, "Error: send() called on closing connection %p\n", c); + errno = EPIPE; + return -1; + } + + struct { + struct hdr hdr; + char data[len]; + } pkt; + + pkt.hdr.src = c->src; + pkt.hdr.dst = c->dst; + pkt.hdr.seq = c->snd.nxt; + pkt.hdr.ack = c->rcv.nxt; + pkt.hdr.wnd = c->snd.wnd; + pkt.hdr.ctl = ACK; + + memcpy(pkt.data, data, len); + + c->snd.nxt += len; + + c->utcp->send(c->utcp, &pkt, sizeof pkt.hdr + len); + // + // Can we add it to the send window? + + // Do we need to kick some timers? + + return 0; +} + +static void swap_ports(struct hdr *hdr) { + uint16_t tmp = hdr->src; + hdr->src = hdr->dst; + hdr->dst = tmp; +} + +int utcp_recv(struct utcp *utcp, void *data, size_t len) { + fprintf(stderr, "%p got: ", utcp); + print_packet(data, len); + + struct hdr hdr; + if(len < sizeof hdr) { + errno = EBADMSG; + return -1; + } + + memcpy(&hdr, data, sizeof hdr); + data += sizeof hdr; + len -= sizeof hdr; + + if(hdr.ctl & ~(SYN | ACK | RST | FIN)) { + errno = EBADMSG; + return -1; + } + + struct utcp_connection *c = find_connection(utcp, hdr.dst); + + // Is it for a new connection? + + if(!c) { + if(hdr.ctl & RST) + return 0; + + if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept && (!utcp->pre_accept || utcp->pre_accept(utcp, data, len)) && (c = allocate_connection(utcp))) { // LISTEN + // Return SYN+ACK + c->snd.wnd = hdr.wnd; + c->rcv.irs = hdr.seq; + c->snd.iss = rand(); + c->snd.una = c->snd.iss; + c->snd.nxt = c->snd.iss + 1; + c->rcv.nxt = c->rcv.irs + 1; + set_state(c, SYN_RECEIVED); + + hdr.dst = c->dst = hdr.src; + hdr.src = c->src; + hdr.ack = c->rcv.irs + 1; + hdr.seq = c->snd.iss; + hdr.ctl = SYN | ACK; + utcp->send(utcp, &hdr, sizeof hdr); + return 0; + } else { // CLOSED + len = 1; + goto reset; + } + } + + fprintf(stderr, "%p state %s\n", c->utcp, strstate[c->state]); + + if(c->state == CLOSED) { + fprintf(stderr, "Error: packet recv()d on closed connection %p\n", c); + errno = EBADF; + return -1; + } + + // It is for an existing connection. + + if(c->state == SYN_SENT) { + if(hdr.ctl & ACK) { + if(hdr.ack <= c->snd.iss || hdr.ack > c->snd.nxt) { + fprintf(stderr, "Invalid ACK, %u %u %u\n", hdr.ack, c->snd.iss, c->snd.nxt); + goto reset; + } + } + if(hdr.ctl & RST) { + if(!(hdr.ctl & ACK)) + return 0; + set_state(c, CLOSED); + errno = ECONNREFUSED; + c->recv(c, NULL, 0); + return 0; + } + if(hdr.ctl & SYN) { + c->dst = hdr.src; + c->rcv.nxt = hdr.seq + 1; + c->rcv.irs = hdr.seq; + c->snd.wnd = hdr.wnd; + + if(hdr.ctl & ACK) + c->snd.una = hdr.ack; + if(c->snd.una > c->snd.iss) { + set_state(c, ESTABLISHED); + // TODO: signal app? + swap_ports(&hdr); + hdr.seq = c->snd.nxt; + hdr.ack = c->rcv.nxt; + hdr.ctl = ACK; + } else { + set_state(c, SYN_RECEIVED); + swap_ports(&hdr); + hdr.seq = c->snd.iss; + hdr.ack = c->rcv.nxt; + hdr.ctl = SYN | ACK; + } + utcp->send(utcp, &hdr, sizeof hdr); + // TODO: queue any data? + } + + return 0; + } + + bool acceptable; + + if(len == 0) + if(c->rcv.wnd == 0) + acceptable = hdr.seq == c->rcv.nxt; + else + acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd); + else + if(c->rcv.wnd == 0) + acceptable = false; + else + acceptable = (hdr.seq >= c->rcv.nxt && hdr.seq < c->rcv.nxt + c->rcv.wnd) + || (hdr.seq + len - 1 >= c->rcv.nxt && hdr.seq + len - 1 < c->rcv.nxt + c->rcv.wnd); + + if(!acceptable) { + fprintf(stderr, "Packet not acceptable, %u %u %u %zu\n", hdr.seq, c->rcv.nxt, c->rcv.wnd, len); + if(hdr.ctl & RST) + return 0; + goto ack_and_drop; + } + + c->snd.wnd = hdr.wnd; + + // TODO: check whether segment really starts at rcv.nxt, otherwise trim it. + + if(hdr.ctl & RST) { + switch(c->state) { + case SYN_RECEIVED: + // TODO: delete connection? + break; + case ESTABLISHED: + case FIN_WAIT_1: + case FIN_WAIT_2: + case CLOSE_WAIT: + set_state(c, CLOSED); + errno = ECONNRESET; + c->recv(c, NULL, 0); + break; + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + // TODO: delete connection? + break; + default: + // TODO: wtf? + return 0; + } + set_state(c, CLOSED); + return 0; + } + + if(hdr.ctl & SYN) { + switch(c->state) { + case SYN_RECEIVED: + case ESTABLISHED: + case FIN_WAIT_1: + case FIN_WAIT_2: + case CLOSE_WAIT: + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + set_state(c, CLOSED); + errno = ECONNRESET; + c->recv(c, NULL, 0); + goto reset; + break; + default: + // TODO: wtf? + return 0; + } + } + + if(!(hdr.ctl & ACK)) + return 0; + + switch(c->state) { + case SYN_RECEIVED: + if(hdr.ack >= c->snd.una && hdr.ack <= c->snd.nxt) + c->utcp->accept(c, NULL, 0); + + if(c->state != ESTABLISHED) + goto reset; + break; + case ESTABLISHED: + case CLOSE_WAIT: + if(hdr.ack < c->snd.una) + return 0; + if(hdr.ack > c->snd.nxt) + goto ack_and_drop; + if(hdr.ack > c->snd.una && hdr.ack <= c->snd.nxt) { + c->snd.una = hdr.ack; + if(c->snd.wl1 < hdr.seq || (c->snd.wl1 == hdr.seq && c->snd.wl2 <= hdr.ack)) { + c->snd.wnd = hdr.wnd; + c->snd.wl1 = hdr.seq; + c->snd.wl2 = hdr.ack; + } + } + break; + case FIN_WAIT_1: + if(hdr.ack == c->snd.nxt) + set_state(c, FIN_WAIT_2); + break; + case FIN_WAIT_2: + // TODO: If nothing left to send, close. + break; + case CLOSING: + if(hdr.ack == c->snd.nxt) { + set_state(c, TIME_WAIT); + } + break; + case LAST_ACK: + if(hdr.ack == c->snd.nxt) { + set_state(c, CLOSED); + } + return 0; + case TIME_WAIT: + // TODO: retransmission of remote FIN, ACK and restart 2 MSL timeout + break; + default: + goto reset; + } + + // Process data + + switch(c->state) { + case ESTABLISHED: + case FIN_WAIT_1: + case FIN_WAIT_2: + // TODO: process the data, see page 74 + break; + case CLOSE_WAIT: + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + break; + default: + abort(); + } + + if(hdr.ctl & FIN) { + switch(c->state) { + case CLOSED: + case LISTEN: + case SYN_SENT: + return 0; + case SYN_RECEIVED: + case ESTABLISHED: + set_state(c, CLOSE_WAIT); + c->rcv.nxt++; + goto ack_and_drop; + case FIN_WAIT_1: + set_state(c, CLOSING); + c->rcv.nxt++; + goto ack_and_drop; + case FIN_WAIT_2: + set_state(c, TIME_WAIT); + c->rcv.nxt++; + goto ack_and_drop; + case CLOSE_WAIT: + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + break; + default: + abort(); + } + } + + // Process the data + + if(len && c->recv) { + c->recv(c, data, len); + c->rcv.nxt += len; + goto ack_and_drop; + } + + return 0; + +reset: + swap_ports(&hdr); + hdr.wnd = 0; + if(hdr.ctl & ACK) { + hdr.seq = hdr.ack; + hdr.ctl = RST; + } else { + hdr.ack = hdr.seq + len; + hdr.seq = 0; + hdr.ctl = RST | ACK; + } + utcp->send(utcp, &hdr, sizeof hdr); + return 0; + +ack_and_drop: + swap_ports(&hdr); + hdr.seq = c->snd.nxt; + hdr.ack = c->rcv.nxt; + hdr.ctl = ACK; + utcp->send(utcp, &hdr, sizeof hdr); + if(c->state == CLOSE_WAIT || c->state == TIME_WAIT) { + errno = 0; + c->recv(c, NULL, 0); + } + return 0; +} + +void utcp_shutdown(struct utcp_connection *c, int dir) { + if(c->reapable) { + fprintf(stderr, "Error: shutdown() called on closed connection %p\n", c); + return; + } + + // TODO: handle dir + + switch(c->state) { + case CLOSED: + return; + case LISTEN: + case SYN_SENT: + set_state(c, CLOSED); + return; + + case SYN_RECEIVED: + case ESTABLISHED: + set_state(c, FIN_WAIT_1); + break; + case FIN_WAIT_1: + case FIN_WAIT_2: + return; + case CLOSE_WAIT: + set_state(c, LAST_ACK); + break; + + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + return; + } + + // Send FIN + + struct hdr hdr; + + hdr.src = c->src; + hdr.dst = c->dst; + hdr.seq = c->snd.nxt; + hdr.ack = c->rcv.nxt; + hdr.wnd = c->snd.wnd; + hdr.ctl = FIN | ACK; + + c->snd.nxt += 1; + + c->utcp->send(c->utcp, &hdr, sizeof hdr); +} + +void utcp_close(struct utcp_connection *c) { + utcp_shutdown(c, SHUT_RDWR); + c->reapable = true; +} + +void utcp_abort(struct utcp_connection *c) { + if(c->reapable) { + fprintf(stderr, "Error: abort() called on closed connection %p\n", c); + return; + } + + c->reapable = true; + + switch(c->state) { + case CLOSED: + return; + case LISTEN: + case SYN_SENT: + case CLOSING: + case LAST_ACK: + case TIME_WAIT: + set_state(c, CLOSED); + return; + + case SYN_RECEIVED: + case ESTABLISHED: + case FIN_WAIT_1: + case FIN_WAIT_2: + case CLOSE_WAIT: + set_state(c, CLOSED); + break; + } + + // Send RST + + struct hdr hdr; + + hdr.src = c->src; + hdr.dst = c->dst; + hdr.seq = c->snd.nxt; + hdr.ack = 0; + hdr.wnd = 0; + hdr.ctl = RST; + + c->utcp->send(c->utcp, &hdr, sizeof hdr); +} + +void utcp_timeout(struct utcp *utcp) { + struct timeval now; + gettimeofday(&now, NULL); + + for(int i = 0; i < utcp->nconnections; i++) { + struct utcp_connection *c = utcp->connections[i]; + if(!c) + continue; + + if(c->reapable) { + fprintf(stderr, "Reaping %p\n", c); + free_connection(c); + continue; + } + + if(c->state == CLOSED) + return; + + if(c->conn_timeout.tv_sec && timercmp(&c->conn_timeout, &now, <)) { + if(!c->reapable) { + errno = ETIMEDOUT; + c->recv(c, NULL, 0); + } + c->state = CLOSED; + return; + } + + if(c->rtrx_timeout.tv_sec && timercmp(&c->rtrx_timeout, &now, <)) { + // TODO: retransmit stuff; + } + } +} + +struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) { + struct utcp *utcp = calloc(1, sizeof *utcp); + if(!utcp) + return NULL; + + utcp->accept = accept; + utcp->pre_accept = pre_accept; + utcp->send = send; + utcp->priv = priv; + utcp->gap = -1; + utcp->mtu = 1000; + + return utcp; +} + +void utcp_exit(struct utcp *utcp) { + if(!utcp) + return; + for(int i = 0; i < utcp->nconnections; i++) + free_connection(utcp->connections[i]); + free(utcp); +} diff --git a/utcp.h b/utcp.h new file mode 100644 index 0000000..a404b43 --- /dev/null +++ b/utcp.h @@ -0,0 +1,58 @@ +/* + utcp.h -- Userspace TCP + Copyright (C) 2014 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#ifndef UTCP_H +#define UTCP_H + +#include +#include +#include + +#ifndef UTCP_INTERNAL +struct utcp { + void *priv; +}; + +struct utcp_connection { + void *priv; + struct utcp *utcp; +}; +#else +struct utcp; +struct utcp_connection; +#endif + +typedef bool (*utcp_pre_accept_t)(struct utcp *utcp, void *data, size_t len); +typedef void (*utcp_accept_t)(struct utcp_connection *utcp_connection, void *data, size_t len); + +typedef int (*utcp_send_t)(struct utcp *utcp, void *data, size_t len); +typedef int (*utcp_recv_t)(struct utcp_connection *connection, void *data, size_t len); + +extern struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv); +extern void utcp_exit(struct utcp *utcp); +extern struct utcp_connection *utcp_connect(struct utcp *utcp, void *data, size_t len, utcp_recv_t recv, void *priv); +extern void utcp_accept(struct utcp_connection *utcp, utcp_recv_t recv, void *priv); +extern int utcp_send(struct utcp_connection *connection, void *data, size_t len); +extern int utcp_recv(struct utcp *utcp, void *data, size_t len); +extern void utcp_close(struct utcp_connection *connection); +extern void utcp_abort(struct utcp_connection *connection); +extern void utcp_shutdown(struct utcp_connection *connection, int how); +extern void utcp_timeout(struct utcp *utcp); + +#endif -- 2.39.5