From fbb8c27761964f3ee87f859bfbb57db75849cd1a Mon Sep 17 00:00:00 2001 From: Ludovic Pouzenc Date: Fri, 17 Jun 2016 11:31:16 +0200 Subject: Initial import : make-boot-image.sh operationnal. Dumb mcastseed. --- mcastseed/AUTHORS | 3 + mcastseed/COPYING | 340 ++++++++++++++++++++++++++++++++++++ mcastseed/ChangeLog | 0 mcastseed/Makefile.am | 7 + mcastseed/README | 1 + mcastseed/README.md | 9 + mcastseed/configure.ac | 48 ++++++ mcastseed/src/Makefile.am | 12 ++ mcastseed/src/mcastleech.c | 227 ++++++++++++++++++++++++ mcastseed/src/mcastseed.c | 421 +++++++++++++++++++++++++++++++++++++++++++++ mcastseed/src/msock.c | 371 +++++++++++++++++++++++++++++++++++++++ mcastseed/src/msock.h | 74 ++++++++ 12 files changed, 1513 insertions(+) create mode 100644 mcastseed/AUTHORS create mode 100644 mcastseed/COPYING create mode 100644 mcastseed/ChangeLog create mode 100644 mcastseed/Makefile.am create mode 120000 mcastseed/README create mode 100644 mcastseed/README.md create mode 100644 mcastseed/configure.ac create mode 100644 mcastseed/src/Makefile.am create mode 100644 mcastseed/src/mcastleech.c create mode 100644 mcastseed/src/mcastseed.c create mode 100644 mcastseed/src/msock.c create mode 100644 mcastseed/src/msock.h (limited to 'mcastseed') diff --git a/mcastseed/AUTHORS b/mcastseed/AUTHORS new file mode 100644 index 0000000..c338cf6 --- /dev/null +++ b/mcastseed/AUTHORS @@ -0,0 +1,3 @@ +Ludovic Pouzenc +Christian Beier +tmouse, http://cboard.cprogramming.com/showthread.php?t=67469 diff --git a/mcastseed/COPYING b/mcastseed/COPYING new file mode 100644 index 0000000..d60c31a --- /dev/null +++ b/mcastseed/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library General +Public License instead of this License. diff --git a/mcastseed/ChangeLog b/mcastseed/ChangeLog new file mode 100644 index 0000000..e69de29 diff --git a/mcastseed/Makefile.am b/mcastseed/Makefile.am new file mode 100644 index 0000000..0f59806 --- /dev/null +++ b/mcastseed/Makefile.am @@ -0,0 +1,7 @@ +## Process this file with automake to produce Makefile.in + + +SUBDIRS = \ + src + + diff --git a/mcastseed/README b/mcastseed/README new file mode 120000 index 0000000..42061c0 --- /dev/null +++ b/mcastseed/README @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/mcastseed/README.md b/mcastseed/README.md new file mode 100644 index 0000000..98ddff0 --- /dev/null +++ b/mcastseed/README.md @@ -0,0 +1,9 @@ + +This is a simple multicast file transfer with TCP back-chat. +Greatly inspired from https://github.com/bk138/Multicast-Client-Server-Example + +Tested on GNU/Linux Debian 8, may usable under other OS without big efforts (patches appreciated). + +# Building +To compile, use + autoreconf -fi && ./configure && make diff --git a/mcastseed/configure.ac b/mcastseed/configure.ac new file mode 100644 index 0000000..ad1db27 --- /dev/null +++ b/mcastseed/configure.ac @@ -0,0 +1,48 @@ +dnl Process this file with autoconf to produce a configure script. + +AC_INIT(mcastseeder, 0.1) + +# Args deprecated http://www.gnu.org/software/automake/manual/automake.html#Modernize-AM_005fINIT_005fAUTOMAKE-invocation +AM_INIT_AUTOMAKE #(AC_PACKAGE_NAME, AC_PACKAGE_VERSION) +AM_CONFIG_HEADER(config.h) +AM_MAINTAINER_MODE + + + +AC_CANONICAL_HOST +case $host_os in + darwin*) + HOST_IS_DARWIN="yes" + ;; + *mingw32*) + HOST_IS_WINDOWS="yes" + ;; + *) + HOST_IS_DARWIN="no" + HOST_IS_WINDOWS="no" + ;; +esac + + + +if test "$HOST_IS_WINDOWS" = "yes"; then + WSOCKLIB="-lws2_32" + AC_SUBST(WSOCKLIB) +fi + + +AM_CONDITIONAL(MINGW, [ test "$HOST_IS_WINDOWS" = "yes" ]) +AM_CONDITIONAL(DARWIN, [ test "$HOST_IS_DARWIN" = "yes" ]) + +AC_ISC_POSIX +AC_HEADER_STDC +AC_PROG_CPP +AC_PROG_CC +AM_PROG_CC_STDC +AM_PROG_CC_C_O + + +AC_OUTPUT([ +Makefile +src/Makefile +]) diff --git a/mcastseed/src/Makefile.am b/mcastseed/src/Makefile.am new file mode 100644 index 0000000..b28166c --- /dev/null +++ b/mcastseed/src/Makefile.am @@ -0,0 +1,12 @@ +## Process this file with automake to produce Makefile.in + +AM_CFLAGS =\ + -Wall \ + -g + +bin_PROGRAMS = mcastseed mcastleech + +mcastseed_SOURCES = mcastseed.c msock.c +mcastleech_SOURCES = mcastleech.c msock.c + +LDADD = @WSOCKLIB@ diff --git a/mcastseed/src/mcastleech.c b/mcastseed/src/mcastleech.c new file mode 100644 index 0000000..d19bff9 --- /dev/null +++ b/mcastseed/src/mcastleech.c @@ -0,0 +1,227 @@ +/* client.c + * Greatly inspired from examples written by tmouse, July 2005 + * http://cboard.cprogramming.com/showthread.php?t=67469 + * Modified to run multi-platform by Christian Beier . + */ + +#ifndef __MINGW32__ +#include +#endif +#include +#include +#include +#include +#include "msock.h" + +#define MULTICAST_RECV_BUF 10240 +#define MULTICAST_SO_RCVBUF 425984 +#define DEFAULT_MCAST_IP_STR "ff02::114" +#define DEFAULT_PORT_STR "9000" + +/* Cmdline Arguments */ +char *prog_name = NULL; +char *mcast_ip = NULL; +char *port = NULL; + +/* Sockets as global, used everywhere, even in die() */ +SOCKET mcast_sock = (SOCKET) -1; /* Multicast socket for receiving data */ +SOCKET ucast_sock = (SOCKET) -1; /* Unicast socket for give feedback to server */ + +/* Buffer used for earch recvfrom() */ +char recvbuf[MULTICAST_RECV_BUF]; + +/* Strings to print out representation of various states of the program */ +const char * const state_str[] = { + "exiting", + "wait_hello_and_connect_back", + "wait_start_and_start_job", + "receive_data", + "finalize_job", + "is_there_more_job" +}; + +/* Some boring funcs you didn't want to read now */ +void die(char* msg); +void usage(char *msg); +void arg_parse(int argc, char* argv[]); + +/* Parts of the "protocol", definitions are after main() */ +int wait_hello_and_connect_back(); +int wait_start_and_start_job(); +int receive_data(); +int finalize_job(); +int is_there_more_job(); + + +int main(int argc, char* argv[]) { + int state = 1; /* state of the "protocol" state machine */ + int res; + + arg_parse(argc, argv); + + /* Finite state machine */ + while ( state > 0 ) { + fprintf(stderr, "Now in %s state\n", state_str[state]); + switch ( state ) { + case 1: state = (wait_hello_and_connect_back() == 0)?2:1; break; + case 2: state = (wait_start_and_start_job() == 0)?2:3; break; + case 3: res = receive_data(); + if (res==0) state = 4; + else if (res==1) state=3; + else state = -1; + break; + case 4: state = (finalize_job() == 0)?5:-2; break; + case 5: state = (is_there_more_job() == 0)?2:0; break; + } + } + + if ( mcast_sock > 0 ) { + close(mcast_sock); + } + + if ( state < 0 ) + return -state; + + return EXIT_SUCCESS; +} + + +int wait_hello_and_connect_back() { + /* Buffers for host and service strings after resolve */ + char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; + /* Server address, filled by system after first recvfrom */ + struct sockaddr_storage peer_addr; + socklen_t peer_addr_len; + /* Various needed variables */ + ssize_t nread; + int res; + + /* Setup mcast_sock */ + if ( mcast_sock > 0 ) { + close(mcast_sock); + mcast_sock = 0; + } + mcast_sock = mcast_recv_socket(mcast_ip, port, MULTICAST_SO_RCVBUF); + if(mcast_sock < 0) + usage("Could not setup multicast socket. Wrong args given ?"); + + /* Wait for a single datagram from the server (for sync, no check on contain) */ + peer_addr_len = sizeof(struct sockaddr_storage); + nread = recvfrom(mcast_sock, recvbuf, MULTICAST_RECV_BUF, 0, (struct sockaddr *) &peer_addr, &peer_addr_len); + if (nread < 0 ) { + perror("recvfrom() failed"); + return -1; + } + /* Get peer informations as strings from peer_addr */ + res = getnameinfo((struct sockaddr *) &peer_addr, peer_addr_len, + hbuf, NI_MAXHOST, sbuf, NI_MAXSERV, NI_NUMERICSERV); + if ( res != 0 ) { + fprintf(stderr, "getnameinfo: %s\n", gai_strerror(res)); + return -2; + } + /* Connect back to the server, with reliable unicast */ + if ( ucast_sock > 0 ) { + close(ucast_sock); + } + ucast_sock = ucast_client_socket(hbuf,port); + if(ucast_sock < 0) { + fprintf(stderr, "Could not setup unicast socket or connect to %s:%s\n", hbuf, port); + return -3; + } + + return 0; +} + +int wait_start_and_start_job() { + ssize_t nread, nwrite; + + /* Wait for a "start" datagram from the server */ + nread = recvfrom(mcast_sock, recvbuf, MULTICAST_RECV_BUF, 0, NULL, 0); + if (nread < 0 ) { + perror("recvfrom() failed"); + return -1; + } + if ( nread >= 5 && strncmp("start", recvbuf, 5) == 0 ) { + + nwrite = write(ucast_sock, "ready", 5); + if ( nwrite < 0 ) { + fprintf(stderr, "write() failed\n"); + return -2; + } + if (nwrite != 5) { + fprintf(stderr, "write() short\n"); + return -3; + } + + return 1; + } + + return 0; +} + +int receive_data() { + ssize_t nread; + uint32_t seq; + uint16_t datalen; + + /* Wait for a "dataN" datagram from the server */ + nread = recvfrom(mcast_sock, recvbuf, MULTICAST_RECV_BUF, 0, NULL, 0); + if (nread < 0 ) { + perror("recvfrom() failed"); + return -1; + } + if ( nread >= 10 && strncmp("data", recvbuf, 4) == 0 ) { + seq = ntohl( *( (uint32_t *) recvbuf+1 ) ); + datalen = ntohs( *( (uint16_t *) recvbuf+4 ) ); + //fprintf(stderr, "debug seq==%i, datalen==%hi\n", seq, datalen); + if ( nread != (10 + datalen) ) { + fprintf(stderr, "debug nread==%zi, (10 + datalen)==%i\n", nread, (10 + datalen)); + //TODO nack ? + return -2; + } + fprintf(stdout, "data #%i, ", seq); + fwrite(recvbuf+10, datalen, 1, stdout); + fflush(stdout); + //TODO buffer zero copy, ack + return 1; + } + + return 0; +} + +int finalize_job() { + return 0; +} +int is_there_more_job() { + return 1; +} + + + + +void die(char* msg) { + fprintf(stderr, "%s\n", msg); + if (mcast_sock > 0) + close(mcast_sock); + if (ucast_sock > 0) + close(ucast_sock); + exit(EXIT_FAILURE); +} + +void usage(char *msg) { + char ubuf[256]; + if ( msg != NULL ) + fprintf(stderr, "%s\n", msg); + ubuf[0] = '\0'; + snprintf(ubuf, 255, "Usage: %s [port] [mcast_ip]\n", prog_name); + die(ubuf); +} + +void arg_parse(int argc, char* argv[]) { + prog_name = argv[0]; + if ( argc > 3 ) + usage("Too many arguments"); + port = (argc >= 2)?argv[1]:DEFAULT_PORT_STR; + mcast_ip = (argc >= 3)?argv[2]:DEFAULT_MCAST_IP_STR; +} + diff --git a/mcastseed/src/mcastseed.c b/mcastseed/src/mcastseed.c new file mode 100644 index 0000000..da73353 --- /dev/null +++ b/mcastseed/src/mcastseed.c @@ -0,0 +1,421 @@ +/* server.c + * Greatly inspired from examples written by tmouse, July 2005 + * http://cboard.cprogramming.com/showthread.php?t=67469 + * Modified to run multi-platform by Christian Beier . + */ + +#ifndef __MINGW32__ +#include /* for usleep() */ +#endif +#include +#include +#include "msock.h" + +#define READ_BUF_LEN 256 +#define MAX_PENDING_CONNECTIONS 256 +#define MAX_CLIENTS 256 +#define DEFAULT_MCAST_IP_STR "ff02::114" +#define DEFAULT_PORT_STR "9000" +#define DEFAULT_MCAST_TTL 1 + +/* Cmdline Arguments */ +char *prog_name = NULL; +char *mcast_ip = NULL; +char *port = NULL; +int mcast_ttl = 0; + +/* Sockets as global, used everywhere, even in die() */ +SOCKET mcast_sock = (SOCKET) -1; /* Multicast socket for sending data */ +SOCKET ucast_sock = (SOCKET) -1; /* Unicast socket for havee feedback from clients */ + +/* Socket related data */ +struct addrinfo *mcast_addr = NULL; +struct client { + SOCKET sock; + struct sockaddr addr; + int state; +} clients[MAX_CLIENTS]; +int clients_next = 0; + +/* Buffer used for earch read() */ +char readbuf[READ_BUF_LEN]; + +/* Strings to print out representation of various states of the program */ +const char * const state_str[] = { + "exiting", + "send_hello", + "accept_pending_clients_or_wait_a_bit", + "start_job", + "send_data", + "wait_all_finalize_job", + "is_there_more_job" +}; + +/* Some boring funcs you didn't want to read now */ +void die(char* msg); +void usage(char *msg); +void arg_parse(int argc, char* argv[]); +void unsetup_sockets(); +void setup_sockets(); + +/* Parts of the "protocol", definitions are after main() */ +int send_hello(); +int accept_pending_clients_or_wait_a_bit(); +int start_job(); +int send_data(); +int wait_all_finalize_job(); +int is_there_more_job(); + +int main(int argc, char *argv[]) { + int state = 1; /* state of the "protocol" state machine */ + int res; + arg_parse(argc, argv); + setup_sockets(); + + /* Finite state machine */ + while ( state > 0 ) { + fprintf(stderr, "Now in %s state\n", state_str[state]); + switch ( state ) { + case 1: res = send_hello(); state = (res==0)?2:-1; break; + case 2: res = accept_pending_clients_or_wait_a_bit(); + if (res==0) state = 2; // Some clients has just come in, try to get more + else if (res==1) state = 1; // Nothing new. Keep accepting clients after another hello + else if (res==2) state = 3; // Wanted clients are accepted + else state = -2; + break; + case 3: res = start_job(); + if (res==0) state = 3; // Keep trying to convince every client to start + else if (res==1) state = 4; // All clients have started the job pipe + else if (res==2) state = 4; // There is dead clients but all alive are ready to go + else state = -3; + break; + case 4: res = send_data(); + if (res==0) state = 4; + else if (res==1) state = 5; // All data sent + else state = -4; + break; + case 5: res = wait_all_finalize_job(); + if (res==0) state = 5; + else if (res==1) state = 6; + else state = -5; + case 6: res = is_there_more_job(); + if (res==0) state = 0; + else if (res==1) state = 3; + else state = -6; + break; + } + } + + unsetup_sockets(); + + if ( state < 0 ) + return -state; + + return EXIT_SUCCESS; +} + +int send_hello() { + ssize_t nwrite; + const char *payload = "hello"; + int paylen = strlen(payload); + + nwrite = sendto(mcast_sock, payload, paylen, 0, mcast_addr->ai_addr, mcast_addr->ai_addrlen); + if ( nwrite < 0 ) { + perror("sendto() failed"); + return -1; + } + if ( nwrite < paylen ) { + fprintf(stderr, "%s", "Short packet sent"); + } + + return 0; +} + +int accept_pending_clients_or_wait_a_bit() { + struct timeval timeout; + fd_set readfds, exceptfds; + ssize_t nread; + int res; + + FD_ZERO(&readfds); + FD_ZERO(&exceptfds); + FD_SET(0,&readfds); // Read from stdin. Will never work as is on Windows, requires threads and so. + FD_SET(ucast_sock,&readfds); + FD_SET(ucast_sock,&exceptfds); + timeout.tv_sec = 2; + timeout.tv_usec = 0; + + res = select(ucast_sock+1, &readfds, NULL, &exceptfds, &timeout); + if ( res < 0 ) { + perror("select() failed"); + return -1; + } + + if ( res > 0 ) { + if (FD_ISSET(ucast_sock, &readfds)) { + //TODO : this assumes that the event is an accept() while ones could be send data there + if ( clients_next >= MAX_CLIENTS ) { + fprintf(stderr, "%s\n", "Bouncing client, MAX_CLIENTS reached"); + close(accept(ucast_sock, NULL, 0)); + } else { + socklen_t addrlen = sizeof(struct sockaddr); + clients[clients_next].sock = accept(ucast_sock, &(clients[clients_next].addr), &addrlen); + clients[clients_next].state = 0; + printf("Connected client on fd %i\n", clients[clients_next].sock); + clients_next++; + } + } + //TODO : drop this keybord read with accept(), this is not portable + if ( FD_ISSET(0, &readfds)) { + nread = read(0, readbuf, READ_BUF_LEN); + if ( nread <= 0 ) { + fprintf(stderr, "%s\n", "lost stdin"); + } + // User wants to go now + return 2; + } + if (FD_ISSET(ucast_sock, &exceptfds)) { + fprintf(stderr, "%s\n", "unhandled except on ucast_sock"); + return -2; + } + } + if (res == 0 ) { + // nothing happened before timeout + return 1; + } + return 0; +} + +int start_job() { + struct timeval timeout; + fd_set readfds, exceptfds; + ssize_t nread, nwrite; + int all_ready, all_non_dead_ready; + int i, res; + SOCKET client_sock; + const char *payload = "start"; + int paylen = strlen(payload); + + nwrite = sendto(mcast_sock, payload, paylen, 0, mcast_addr->ai_addr, mcast_addr->ai_addrlen); + if ( nwrite < 0 ) { + perror("sendto() failed"); + return -1; + } + if ( nwrite < paylen ) { + fprintf(stderr, "%s", "Short packet sent"); + } + + all_ready = 1; + all_non_dead_ready = 1; + + FD_ZERO(&readfds); + FD_ZERO(&exceptfds); + for ( i=0; i 0 ) { + for ( i=0; iai_addr, mcast_addr->ai_addrlen); + if ( nwrite < 0 ) { + perror("sendto() failed"); + return -1; + } + if ( nwrite < paylen ) { + fprintf(stderr, "%s", "Short packet sent"); + } + + return 1; +} + + +int wait_all_finalize_job() { + struct timeval timeout; + fd_set readfds, exceptfds; + ssize_t nread, nwrite; + int all_non_dead_done; + int i, res; + SOCKET client_sock; + const char *payload = "final"; + int paylen = strlen(payload); + + nwrite = sendto(mcast_sock, payload, paylen, 0, mcast_addr->ai_addr, mcast_addr->ai_addrlen); + if ( nwrite < 0 ) { + perror("sendto() failed"); + return -1; + } + if ( nwrite < paylen ) { + fprintf(stderr, "%s", "Short packet sent"); + } + + all_non_dead_done = 1; + + FD_ZERO(&readfds); + FD_ZERO(&exceptfds); + for ( i=0; i 0 ) { + for ( i=0; i 0) + close(mcast_sock); + if (ucast_sock > 0) + close(ucast_sock); + exit(EXIT_FAILURE); +} + +void usage(char *msg) { + char ubuf[256]; + if ( msg != NULL ) + fprintf(stderr, "%s\n", msg); + ubuf[0] = '\0'; + snprintf(ubuf, 255, "Usage: %s [port] [mcast_ip] [mcast_ttl]\n", prog_name); + die(ubuf); +} + +void arg_parse(int argc, char* argv[]) { + prog_name = argv[0]; + if ( argc > 3 ) + usage("Too many arguments"); + port = (argc >= 2)?argv[1]:DEFAULT_PORT_STR; + mcast_ip = (argc >= 3)?argv[2]:DEFAULT_MCAST_IP_STR; + mcast_ttl = (argc >= 4)?atoi(argv[3]):DEFAULT_MCAST_TTL; + if ( mcast_ttl < 1 || mcast_ttl > 64 ) + mcast_ttl = 1; +} + +void unsetup_sockets() { + if ( ucast_sock > 0 ) { + close(ucast_sock); + ucast_sock = 0; + } + + if ( mcast_sock > 0 ) { + close(mcast_sock); + mcast_sock = 0; + if ( mcast_addr ) { + freeaddrinfo(mcast_addr); + mcast_addr = 0; + } + } +} + +void setup_sockets() { + /* Setup ucast_sock */ + ucast_sock = ucast_server_socket(port, MAX_PENDING_CONNECTIONS); + if(ucast_sock < 0) + usage("Could not setup unicast socket. Wrong args given ?"); + + /* Setup mcast_sock */ + mcast_sock = mcast_send_socket(mcast_ip, port, mcast_ttl, &mcast_addr); + if(mcast_sock < 0) + usage("Could not setup multicast socket. Wrong args given ?"); +} + diff --git a/mcastseed/src/msock.c b/mcastseed/src/msock.c new file mode 100644 index 0000000..8274710 --- /dev/null +++ b/mcastseed/src/msock.c @@ -0,0 +1,371 @@ +/* + msock.c - multicast socket creation routines + + (C) 2016 Christian Beier + +*/ + +#ifndef __MINGW32__ +#include +#endif +#include +#include +#include + +#include "msock.h" + +SOCKET mcast_send_socket(char* multicastIP, char* multicastPort, int multicastTTL, struct addrinfo **multicastAddr) { + + SOCKET sock; + struct addrinfo hints = { 0 }; /* Hints for name lookup */ + + +#ifdef WIN32 + WSADATA trash; + if(WSAStartup(MAKEWORD(2,0),&trash)!=0) + DieWithError("Couldn't init Windows Sockets\n"); +#endif + + + /* + Resolve destination address for multicast datagrams + */ + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_flags = AI_NUMERICHOST; + int status; + if ((status = getaddrinfo(multicastIP, multicastPort, &hints, multicastAddr)) != 0 ) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); + return -1; + } + + + + /* + Create socket for sending multicast datagrams + */ + if ( (sock = socket((*multicastAddr)->ai_family, (*multicastAddr)->ai_socktype, 0)) < 0 ) { + perror("socket() failed"); + freeaddrinfo(*multicastAddr); + return -1; + } + + /* + Set TTL of multicast packet + */ + if ( setsockopt(sock, + (*multicastAddr)->ai_family == PF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, + (*multicastAddr)->ai_family == PF_INET6 ? IPV6_MULTICAST_HOPS : IP_MULTICAST_TTL, + (char*) &multicastTTL, sizeof(multicastTTL)) != 0 ) { + perror("setsockopt() failed"); + freeaddrinfo(*multicastAddr); + return -1; + } + + + /* + set the sending interface + */ + if((*multicastAddr)->ai_family == PF_INET) { + in_addr_t iface = INADDR_ANY; /* well, yeah, any */ + if(setsockopt (sock, + IPPROTO_IP, + IP_MULTICAST_IF, + (char*)&iface, sizeof(iface)) != 0) { + perror("interface setsockopt() sending interface"); + freeaddrinfo(*multicastAddr); + return -1; + } + + } + if((*multicastAddr)->ai_family == PF_INET6) { + unsigned int ifindex = 0; /* 0 means 'default interface'*/ + if(setsockopt (sock, + IPPROTO_IPV6, + IPV6_MULTICAST_IF, + (char*)&ifindex, sizeof(ifindex)) != 0) { + perror("interface setsockopt() sending interface"); + freeaddrinfo(*multicastAddr); + return -1; + } + + } + + + return sock; + +} + + + +SOCKET mcast_recv_socket(char* multicastIP, char* multicastPort, int multicastRecvBufSize) { + + SOCKET sock; + struct addrinfo hints = { 0 }; /* Hints for name lookup */ + struct addrinfo* localAddr = 0; /* Local address to bind to */ + struct addrinfo* multicastAddr = 0; /* Multicast Address */ + int yes=1; + +#ifdef WIN32 + WSADATA trash; + if(WSAStartup(MAKEWORD(2,0),&trash)!=0) + DieWithError("Couldn't init Windows Sockets\n"); +#endif + + + /* Resolve the multicast group address */ + hints.ai_family = PF_UNSPEC; + hints.ai_flags = AI_NUMERICHOST; + int status; + if ((status = getaddrinfo(multicastIP, NULL, &hints, &multicastAddr)) != 0) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); + goto error; + } + + + /* + Get a local address with the same family (IPv4 or IPv6) as our multicast group + This is for receiving on a certain port. + */ + hints.ai_family = multicastAddr->ai_family; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_flags = AI_PASSIVE; /* Return an address we can bind to */ + if ( getaddrinfo(NULL, multicastPort, &hints, &localAddr) != 0 ) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); + goto error; + } + + + /* Create socket for receiving datagrams */ + if ( (sock = socket(localAddr->ai_family, localAddr->ai_socktype, 0)) < 0 ) { + perror("socket() failed"); + goto error; + } + + + + /* + * Enable SO_REUSEADDR to allow multiple instances of this + * application to receive copies of the multicast datagrams. + */ + if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(int)) == -1) { + perror("setsockopt"); + goto error; + } + + /* Bind the local address to the multicast port */ + if ( bind(sock, localAddr->ai_addr, localAddr->ai_addrlen) != 0 ) { + perror("bind() failed"); + goto error; + } + + /* get/set socket receive buffer */ + int optval=0; + socklen_t optval_len = sizeof(optval); + int dfltrcvbuf; + if(getsockopt(sock, SOL_SOCKET, SO_RCVBUF,(char*)&optval, &optval_len) !=0) { + perror("getsockopt"); + goto error; + } + dfltrcvbuf = optval; + optval = multicastRecvBufSize; + if(setsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char*)&optval,sizeof(optval)) != 0) { + perror("setsockopt"); + goto error; + } + if(getsockopt(sock, SOL_SOCKET, SO_RCVBUF,(char*)&optval, &optval_len) != 0) { + perror("getsockopt"); + goto error; + } + printf("tried to set socket receive buffer from %d to %d, got %d\n", + dfltrcvbuf, multicastRecvBufSize, optval); + + + + + /* Join the multicast group. We do this seperately depending on whether we + * are using IPv4 or IPv6. + */ + if ( multicastAddr->ai_family == PF_INET && + multicastAddr->ai_addrlen == sizeof(struct sockaddr_in) ) /* IPv4 */ + { + struct ip_mreq multicastRequest; /* Multicast address join structure */ + + /* Specify the multicast group */ + memcpy(&multicastRequest.imr_multiaddr, + &((struct sockaddr_in*)(multicastAddr->ai_addr))->sin_addr, + sizeof(multicastRequest.imr_multiaddr)); + + /* Accept multicast from any interface */ + multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY); + + /* Join the multicast address */ + if ( setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) { + perror("setsockopt() failed"); + goto error; + } + } + else if ( multicastAddr->ai_family == PF_INET6 && + multicastAddr->ai_addrlen == sizeof(struct sockaddr_in6) ) /* IPv6 */ + { + struct ipv6_mreq multicastRequest; /* Multicast address join structure */ + + /* Specify the multicast group */ + memcpy(&multicastRequest.ipv6mr_multiaddr, + &((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr, + sizeof(multicastRequest.ipv6mr_multiaddr)); + + /* Accept multicast from any interface */ + multicastRequest.ipv6mr_interface = 0; + + /* Join the multicast address */ + if ( setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) { + perror("setsockopt() failed"); + goto error; + } + } + else { + perror("Neither IPv4 or IPv6"); + goto error; + } + + + + if(localAddr) + freeaddrinfo(localAddr); + if(multicastAddr) + freeaddrinfo(multicastAddr); + + return sock; + + error: + if(localAddr) + freeaddrinfo(localAddr); + if(multicastAddr) + freeaddrinfo(multicastAddr); + + return -1; +} + +SOCKET ucast_client_socket(char* serverIP, char* serverPort) { + + SOCKET sock; + struct addrinfo *serverAddr; + struct addrinfo hints = { 0 }; /* Hints for name lookup */ + + +#ifdef WIN32 + WSADATA trash; + if(WSAStartup(MAKEWORD(2,0),&trash)!=0) + DieWithError("Couldn't init Windows Sockets\n"); +#endif + + + /* + Resolve destination address + */ + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_NUMERICHOST; + int status; + if ((status = getaddrinfo(serverIP, serverPort, &hints, &serverAddr)) != 0 ) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); + return -1; + } + + /* + Create socket + */ + if ( (sock = socket(serverAddr->ai_family, serverAddr->ai_socktype, 0)) < 0 ) { + perror("socket() failed"); + freeaddrinfo(serverAddr); + return -1; + } + + /* + Connect it to the remote server + */ + if ( connect(sock, serverAddr->ai_addr, serverAddr->ai_addrlen) < 0 ) { + perror("connect() failed"); + close(sock); + freeaddrinfo(serverAddr); + return -1; + } + + freeaddrinfo(serverAddr); + return sock; +} + +SOCKET ucast_server_socket(char* serverPort, int maxPendingConnections) { + + SOCKET sock; + struct addrinfo *serverAddr; + struct addrinfo hints = { 0 }; /* Hints for name lookup */ + + +#ifdef WIN32 + WSADATA trash; + if(WSAStartup(MAKEWORD(2,0),&trash)!=0) + DieWithError("Couldn't init Windows Sockets\n"); +#endif + + + /* + Prepare an addrinfo struct for a local socket + */ + hints.ai_family = PF_INET6; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + int status; + if ((status = getaddrinfo(NULL, serverPort, &hints, &serverAddr)) != 0 ) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status)); + return -1; + } + /* + Create socket + */ + if ( (sock = socket(serverAddr->ai_family, serverAddr->ai_socktype, serverAddr->ai_protocol)) < 0 ) { + perror("socket() failed"); + freeaddrinfo(serverAddr); + return -1; + } + + /* + Accepts also IPv4 traffic if the socket is INET6 + */ + if(serverAddr->ai_family == PF_INET6) { + unsigned int no = 0; + if(setsockopt (sock, + IPPROTO_IPV6, + IPV6_V6ONLY, + (char*)&no, sizeof(no)) != 0) { + perror("setsockopt() !IPV6_V6ONLY failed"); + freeaddrinfo(serverAddr); + return -1; + } + } + + /* + Bind socket to local address/port + */ + if ( bind(sock, serverAddr->ai_addr, serverAddr->ai_addrlen) < 0 ) { + perror("bind() failed"); + close(sock); + freeaddrinfo(serverAddr); + return -1; + } + + freeaddrinfo(serverAddr); + /* + Start listening incoming connections + */ + if ( listen(sock, maxPendingConnections) < 0 ) { + perror("listen() failed"); + close(sock); + } + + return sock; +} diff --git a/mcastseed/src/msock.h b/mcastseed/src/msock.h new file mode 100644 index 0000000..07e1fad --- /dev/null +++ b/mcastseed/src/msock.h @@ -0,0 +1,74 @@ +/* + msock.h - multicast socket creation routines + + (C) 2016 Christian Beier + +*/ + + +#ifndef MSOCK_H +#define MSOCK_H + +/* this is for windows compat */ +#define SOCKET int + +#ifdef __MINGW32__ +#undef SOCKET +#undef socklen_t +#define WINVER 0x0501 +#include +#define EWOULDBLOCK WSAEWOULDBLOCK +#define close closesocket +#define socklen_t int +typedef unsigned int in_addr_t; +#else +#include +#include +#include +#include +#include +#include +#endif + +/* Define IPV6_ADD_MEMBERSHIP for FreeBSD and Mac OS X */ +#ifndef IPV6_ADD_MEMBERSHIP +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#endif + + + +/** + Creates a socket suitable for sending multicast datagrams via sendto(). + + On success, a socket is returned and multicastAddr set with the right info for sendto() calls. + On error, -1 is returned. +*/ +SOCKET mcast_send_socket(char* multicastIP, char* multicastPort, int multicastTTL, struct addrinfo **multicastAddr); + +/** + Creates a socket suitable for receiving multicast datagrams via recvfrom(). Also sets socket recv buffer. + + On success, returns socket. + On fail, returns -1. + */ +SOCKET mcast_recv_socket(char* multicastIP, char* multicastPort, int multicastRecvBufSize); + +/** + Creates a TCP socket that connects to serverIP:serverPort. + Meant to give feedback to a mcast sender. + + On success, returns socket. + On error, -1 is returned. + */ +SOCKET ucast_client_socket(char* serverIP, char* serverPort); + +/** + Creates a TCP socket that binds locally serverPort. + Meant to receive feedback to a mcast sender. + + On success, returns socket. + On error, -1 is returned. + */ +SOCKET ucast_server_socket(char* serverPort, int maxPendingConnections); + +#endif -- cgit v1.2.3