configure | 2 +- pppd/plugins/Makefile.linux | 1 + pppd/plugins/dhcp/AUTHORS | 21 ++ pppd/plugins/dhcp/COPYING | 339 ++++++++++++++++++++++++ pppd/plugins/dhcp/Makefile.linux | 39 +++ pppd/plugins/dhcp/README | 87 +++++++ pppd/plugins/dhcp/clientpacket.c | 249 ++++++++++++++++++ pppd/plugins/dhcp/clientpacket.h | 12 + pppd/plugins/dhcp/debug.h | 18 ++ pppd/plugins/dhcp/dhcpc.c | 531 ++++++++++++++++++++++++++++++++++++++ pppd/plugins/dhcp/dhcpc.h | 35 +++ pppd/plugins/dhcp/dhcpd.h | 134 ++++++++++ pppd/plugins/dhcp/files.h | 17 ++ pppd/plugins/dhcp/leases.h | 23 ++ pppd/plugins/dhcp/options.c | 231 +++++++++++++++++ pppd/plugins/dhcp/options.h | 40 +++ pppd/plugins/dhcp/packet.c | 209 +++++++++++++++ pppd/plugins/dhcp/packet.h | 41 +++ pppd/plugins/dhcp/socket.c | 163 ++++++++++++ pppd/plugins/dhcp/socket.h | 9 + 20 files changed, 2200 insertions(+), 1 deletions(-) diff --git a/configure b/configure index 56816b8..a9c0ff2 100755 --- a/configure +++ b/configure @@ -195,7 +195,7 @@ if [ -d "$ksrc" ]; then mkmkf $ksrc/Makedefs$compiletype Makedefs.com for dir in pppd pppstats chat pppdump pppd/plugins pppd/plugins/rp-pppoe \ pppd/plugins/radius pppd/plugins/pppoatm \ - pppd/plugins/pppol2tp; do + pppd/plugins/pppol2tp pppd/plugins/dhcp; do mkmkf $dir/Makefile.$makext $dir/Makefile done if [ -f $ksrc/Makefile.$makext$archvariant ]; then diff --git a/pppd/plugins/Makefile.linux b/pppd/plugins/Makefile.linux index 0a7ec7b..ab12aa8 100644 --- a/pppd/plugins/Makefile.linux +++ b/pppd/plugins/Makefile.linux @@ -12,6 +12,7 @@ LIBDIR = $(DESTDIR)/lib/pppd/$(VERSION) SUBDIRS := rp-pppoe pppoatm pppol2tp # Uncomment the next line to include the radius authentication plugin SUBDIRS += radius +SUBDIRS += dhcp PLUGINS := minconn.so passprompt.so passwordfd.so winbind.so # include dependencies if present diff --git a/pppd/plugins/dhcp/AUTHORS b/pppd/plugins/dhcp/AUTHORS new file mode 100644 index 0000000..2e714fb --- /dev/null +++ b/pppd/plugins/dhcp/AUTHORS @@ -0,0 +1,21 @@ + +The PPPD DHCPC plugin was written by Ben McKeegan +and is copyright UK 2002 Netservers.co.uk. Large portions of the code +are derived from the udhcp distribution (version 0.9.7), which is +credited as follows: + + + +Moreton Bay DHCP Server +----------------------- + +Matthew Ramsay +Chris Trew +Russ Dill + +Other Credits: +-------------- +Moreton Bay (http://www.moretonbay.com/) +Lineo (http://opensource.lineo.com) + + diff --git a/pppd/plugins/dhcp/COPYING b/pppd/plugins/dhcp/COPYING new file mode 100644 index 0000000..a43ea21 --- /dev/null +++ b/pppd/plugins/dhcp/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, 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 + + Appendix: 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) 19yy + + 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., 675 Mass Ave, Cambridge, MA 02139, 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) 19yy 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/pppd/plugins/dhcp/Makefile.linux b/pppd/plugins/dhcp/Makefile.linux new file mode 100644 index 0000000..0e30434 --- /dev/null +++ b/pppd/plugins/dhcp/Makefile.linux @@ -0,0 +1,39 @@ +DESTDIR = $(INSTROOT)@DESTDIR@ +MANDIR = $(DESTDIR)/share/man/man8 + +VERSION = $(shell awk -F '"' '/VERSION/ { print $$2; }' ../../patchlevel.h) +LIBDIR = $(DESTDIR)/$(libdir)/pppd/$(VERSION) + +INSTALL = install + +PLUGIN=dhcpc.so +CFLAGS=-I../.. -I../../../include $(COPTS) + +SRCS = dhcpc.c clientpacket.c packet.c socket.c options.c +OBJS = $(SRCS:%.c=%.lo) +LIBS = -shared -Wl,-soname,dhcpc.so +LTLIB = libdhcpc.la + +all: $(PLUGIN) + +install: all + mkdir -p $(LIBDIR) + $(INSTALL) -m 755 dhcpc.so $(LIBDIR) + +$(PLUGIN): $(LTLIB) + $(CC) -o $@ $(OBJS:%.lo=.libs/%.o) $(LIBS) + +$(LTLIB): $(OBJS) + libtool --mode=link --tag=CC $(CC) $(CFLAGS) -o $@ $(OBJS) $(LIBS) + +%.lo: %.c + libtool --mode=compile --tag=CC $(CC) $(CFLAGS) -c $< + + +clean: + rm -f *.o *.lo *.so + +distclean: + rm -f *.o *.lo *.so + +dist-clean: distclean diff --git a/pppd/plugins/dhcp/README b/pppd/plugins/dhcp/README new file mode 100644 index 0000000..3b9fbb2 --- /dev/null +++ b/pppd/plugins/dhcp/README @@ -0,0 +1,87 @@ +DHCPC plugin for PPPD 2.4.2 +=========================== + +Overview: + +This plugin is a hybrid DHCP client and proxy server. It allows a ppp +server to request an IP address from a local or remote DHCP server on +behalf of the client. To the DHCP server it appears to be a DHCP/BOOTP +relay agent. The peer's authentication name is used as the DHCP client +identifier (to allow static leases to be granted to some users). + + + +Installation: + +Place files in a pppd/plugins/dhcp directory of a built and installed PPPD +distribution. Run 'make' followed by 'make install'. + + + +Configuration: + +In your ppp options file, add the line: + + plugin dhcpc.so + + +Following the above line, you should give the options for the plugin: + + + dhcp-interface + + This option specifies which interface DHCP requests should be + broadcast. The default is 'eth0'. + + dhcp-relay-address + + This option specified the local IP address of the system running + this proxy, as should be identified to the DHCP server in the + 'giaddr' field of DHCP requests. Normal server behavor should + be to send DHCP responses to this address. The default is the + primary address bound to the dhcp interface. + + N.B. If you are using ISC DHCPD on the local system, this should + NOT be set to the loopback address (127.0.0.1). The ISC + DHCPD treats this as a special debugging mode and does + behave according to the RFCs. + + dhcp-server + + Address of the DHCP server. Specifying this option will disable + normal DHCP broadcast behaviour and force all requests to be sent + to the specified IP address only. The default behaviour is to + send DHCP broadcasts on the specified dhcp interface. + + dhcp-subnet-selection + + This specifies the address of the network for which to request + leases. (The address should be specified without a netmask.) + Your DHCP server must support the 'Subnet Selection' DHCP + option as per RFC 3011 for this option to work. + + If subnet selection is not used, most DHCP servers will allocate + leases from the same subnet as that in which 'dhcp-relay-address' + resides. + + + + +CURRENT LIMITATIONS + + +Presently, there is a potential problem if a user is able to establish +multiple simultaneous connections under the same login credentials. +Because the username is used as the client identifier, if the user +establishes a second connection without first closing the original +connection, this new connection will still be allocated the same lease and +IP address as the original connection. Clearly only one connection will +be routeable at a time. + +The problem is compounded when either of the connections is closed. This +will trigger a release of the DHCP lease, even though there is still a +current connection using it. The lease could then potentially be +reallocated to another users connection. + +It is my intention to introduce a mechanism in the next version to +overcome this limitation. diff --git a/pppd/plugins/dhcp/clientpacket.c b/pppd/plugins/dhcp/clientpacket.c new file mode 100644 index 0000000..043c8d5 --- /dev/null +++ b/pppd/plugins/dhcp/clientpacket.c @@ -0,0 +1,249 @@ +/* clientpacket.c + * + * Packet generation and dispatching functions for the DHCP client. + * + * Russ Dill July 2001 + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#if __GLIBC__ >=2 && __GLIBC_MINOR >= 1 +#include +#include +#else +#include +#include +#include +#endif +#include +#include +#include +#include +#include + + +#include "dhcpd.h" +#include "packet.h" +#include "options.h" +#include "dhcpc.h" +#include "debug.h" + + +/* Create a random xid */ +unsigned long random_xid(void) +{ + static int initialized; + if (!initialized) { + srand(time(0)); + initialized++; + } + return rand(); +} + + +/* initialize a packet with the proper defaults */ +static void init_packet(struct dhcpMessage *packet, char type) +{ + struct vendor { + char vendor, length; + char str[sizeof("ppp dhcp plugin")]; + } vendor_id = { DHCP_VENDOR, sizeof("ppp dhcp plugin") - 1, "ppp dhcp plugin"}; + + init_header(packet, type); + memcpy(packet->chaddr, client_config.arp, 6); + add_option_string(packet->options, client_config.clientid); + if (client_config.hostname) + add_option_string(packet->options, client_config.hostname); + if (client_config.subnet_selection) + add_simple_option(packet->options, DHCP_SUBNET_SELECTION, + client_config.subnet_selection); + add_option_string(packet->options, (unsigned char *) &vendor_id); + packet->giaddr=client_config.giaddr; +} + + +/* Add a paramater request list for stubborn DHCP servers. Pull the data + * from the struct in options.c. Don't do bounds checking here because it + * goes towards the head of the packet. */ +static void add_requests(struct dhcpMessage *packet) +{ + int end = end_option(packet->options); + int i, len = 0; + + packet->options[end + OPT_CODE] = DHCP_PARAM_REQ; + for (i = 0; options[i].code; i++) + if (options[i].flags & OPTION_REQ) + packet->options[end + OPT_DATA + len++] = options[i].code; + packet->options[end + OPT_LEN] = len; + packet->options[end + OPT_DATA + len] = DHCP_END; + +} + + +/* Broadcast a DHCP discover packet to the network, with an optionally requested IP */ +int send_discover(unsigned long xid, unsigned long requested) +{ + struct dhcpMessage packet; + + init_packet(&packet, DHCPDISCOVER); + packet.xid = xid; + if (requested) + add_simple_option(packet.options, DHCP_REQUESTED_IP, requested); + + add_requests(&packet); + LOG(LOG_DEBUG, "Sending discover..."); + if (client_config.siaddr) + return kernel_packet(&packet, INADDR_ANY, CLIENT_PORT, client_config.siaddr, SERVER_PORT); + else + return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST, + SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex); +} + + +/* Broadcasts a DHCP request message */ +int send_selecting(unsigned long xid, unsigned long server, unsigned long requested) +{ + struct dhcpMessage packet; + struct in_addr addr; + + init_packet(&packet, DHCPREQUEST); + packet.xid = xid; + + add_simple_option(packet.options, DHCP_REQUESTED_IP, requested); + add_simple_option(packet.options, DHCP_SERVER_ID, server); + + add_requests(&packet); + addr.s_addr = requested; + LOG(LOG_DEBUG, "Sending select for %s...", inet_ntoa(addr)); + if (client_config.siaddr) + return kernel_packet(&packet, INADDR_ANY, CLIENT_PORT, client_config.siaddr, SERVER_PORT); + else + return raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST, + SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex); +} + + +/* Unicasts or broadcasts a DHCP renew message */ +int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr) +{ + struct dhcpMessage packet; + int ret = 0; + + init_packet(&packet, DHCPREQUEST); + packet.xid = xid; + packet.ciaddr = ciaddr; + + add_requests(&packet); + LOG(LOG_DEBUG, "Sending renew..."); + if (server) + ret = kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT); + else ret = raw_packet(&packet, INADDR_ANY, CLIENT_PORT, INADDR_BROADCAST, + SERVER_PORT, MAC_BCAST_ADDR, client_config.ifindex); + return ret; +} + + +/* Unicasts a DHCP release message */ +int send_release(unsigned long server, unsigned long ciaddr) +{ + struct dhcpMessage packet; + + init_packet(&packet, DHCPRELEASE); + packet.xid = random_xid(); + packet.ciaddr = ciaddr; + + add_simple_option(packet.options, DHCP_REQUESTED_IP, ciaddr); + add_simple_option(packet.options, DHCP_SERVER_ID, server); + + LOG(LOG_DEBUG, "Sending release..."); + return kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT); +} + + +int get_raw_packet(struct dhcpMessage *payload, int fd) +{ + int bytes; + struct udp_dhcp_packet packet; + u_int32_t source, dest; + u_int16_t check; + + memset(&packet, 0, sizeof(struct udp_dhcp_packet)); + bytes = read(fd, &packet, sizeof(struct udp_dhcp_packet)); + if (bytes < 0) { + DEBUG(LOG_INFO, "couldn't read on raw listening socket -- ignoring"); + usleep(500000); /* possible down interface, looping condition */ + return -1; + } + + if (bytes < (int) (sizeof(struct iphdr) + sizeof(struct udphdr))) { + DEBUG(LOG_INFO, "message too short, ignoring"); + return -1; + } + + if (bytes < ntohs(packet.ip.tot_len)) { + DEBUG(LOG_INFO, "Truncated packet"); + return -1; + } + + /* ignore any extra garbage bytes */ + bytes = ntohs(packet.ip.tot_len); + + /* Make sure its the right packet for us, and that it passes sanity checks */ + if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION || + packet.ip.ihl != sizeof(packet.ip) >> 2 || packet.udp.dest != htons(CLIENT_PORT) || + bytes > (int) sizeof(struct udp_dhcp_packet) || + ntohs(packet.udp.len) != (short) (bytes - sizeof(packet.ip))) { + DEBUG(LOG_INFO, "unrelated/bogus packet"); + return -1; + } + + /* check IP checksum */ + check = packet.ip.check; + packet.ip.check = 0; + if (check != checksum(&(packet.ip), sizeof(packet.ip))) { + DEBUG(LOG_INFO, "bad IP header checksum, ignoring"); + return -1; + } + + /* verify the UDP checksum by replacing the header with a psuedo header */ + source = packet.ip.saddr; + dest = packet.ip.daddr; + check = packet.udp.check; + packet.udp.check = 0; + memset(&packet.ip, 0, sizeof(packet.ip)); + + packet.ip.protocol = IPPROTO_UDP; + packet.ip.saddr = source; + packet.ip.daddr = dest; + packet.ip.tot_len = packet.udp.len; /* cheat on the psuedo-header */ + if (check && check != checksum(&packet, bytes)) { + DEBUG(LOG_ERR, "packet with bad UDP checksum received, ignoring"); + return -1; + } + + memcpy(payload, &(packet.data), bytes - (sizeof(packet.ip) + sizeof(packet.udp))); + + if (ntohl(payload->cookie) != DHCP_MAGIC) { + LOG(LOG_ERR, "received bogus message (bad magic) -- ignoring"); + return -1; + } + DEBUG(LOG_INFO, "oooooh!!! got some!"); + return bytes - (sizeof(packet.ip) + sizeof(packet.udp)); + +} + diff --git a/pppd/plugins/dhcp/clientpacket.h b/pppd/plugins/dhcp/clientpacket.h new file mode 100644 index 0000000..2a6facb --- /dev/null +++ b/pppd/plugins/dhcp/clientpacket.h @@ -0,0 +1,12 @@ +#ifndef _CLIENTPACKET_H +#define _CLIENTPACKET_H + +unsigned long random_xid(void); +int send_discover(unsigned long xid, unsigned long requested); +int send_selecting(unsigned long xid, unsigned long server, unsigned long requested); +int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr); +int send_renew(unsigned long xid, unsigned long server, unsigned long ciaddr); +int send_release(unsigned long server, unsigned long ciaddr); +int get_raw_packet(struct dhcpMessage *payload, int fd); + +#endif diff --git a/pppd/plugins/dhcp/debug.h b/pppd/plugins/dhcp/debug.h new file mode 100644 index 0000000..e01bd0b --- /dev/null +++ b/pppd/plugins/dhcp/debug.h @@ -0,0 +1,18 @@ +#ifndef _DEBUG_H +#define _DEBUG_H + +#include + +#define DEBUG +#ifdef DEBUG +# undef DEBUG +# define DEBUG(level, str, args...) dbglog("DHCPC: " str, ## args) +# define DEBUGGING +#else +# define DEBUG(level, str, args...) do {;} while(0) +#endif + + +#define LOG(level, str, args...) info("DHCPC: " str, ## args) + +#endif diff --git a/pppd/plugins/dhcp/dhcpc.c b/pppd/plugins/dhcp/dhcpc.c new file mode 100644 index 0000000..fcff8b9 --- /dev/null +++ b/pppd/plugins/dhcp/dhcpc.c @@ -0,0 +1,531 @@ +/* dhcpd.c + * + * DHCP Client plugin for pppd + * + * Ben McKeegan August 2002 + * + * Portions derived from udhcp DHCP client by + * + * Russ Dill July 2001 + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#include + +/* #define DHCP_TEST_SHORTLEASE */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pppd.h" + +char pppd_version[] = VERSION; + +#include "dhcpd.h" +#include "dhcpc.h" +#include "options.h" +#include "clientpacket.h" +#include "packet.h" +#include "socket.h" +#include "debug.h" + +static void (*dhcp_old_ip_choose_hook)(u_int32_t *addrp); + +static int dhcp_state; +static u_int32_t requested_ip; /* = 0 */ +u_int32_t assigned_ip; /* value supplied to remote ppp */ +static unsigned long server_addr; +unsigned long lease, renew_timeout; +unsigned long xid = 0; +static int packet_num; /* = 0 */ +static int fd; + +#define LISTEN_NONE 0 +#define LISTEN_KERNEL 1 +#define LISTEN_RAW 2 +static int listen_mode; + +#define DHCP_RX_POLL_INTERVAL 8 + +/* structure retained only for linking against clientpacket.c */ +struct client_config_t client_config = { + /* Default options. */ + abort_if_no_lease: 0, + foreground: 0, + quit_after_lease: 0, + interface: "eth0", + pidfile: NULL, + script: NULL, + clientid: NULL, + hostname: NULL, + ifindex: 0, + arp: "\0\0\0\0\0\0", /* appease gcc-3.0 */ + giaddr: 0, + siaddr: 0, + subnet_selection: 0 +}; + +static char *dhcp_server= NULL; +static char *dhcp_relay_address= NULL; +static char *dhcp_subnet_selection= NULL; +static int dhcp_relay_port= SERVER_PORT; + +static option_t dhcpc_options[] = { + { "dhcp-interface", o_string, &client_config.interface, + "Interface to send DHCP requests on." }, + { "dhcp-server", o_string, &dhcp_server, + "IP address of DHCP server (disable broadcasts)" }, + { "dhcp-relay-address", o_string, &dhcp_relay_address, + "Our address (supplied to server as relay address, defaults to interface address)" }, + { "dhcp-subnet-selection", o_string, &dhcp_subnet_selection, + "Subnet to request addresses for" }, + { "dhcp-relay-port", o_int, &dhcp_relay_port, + "Port we listen on (normally bootps)" }, + { NULL } +}; + + +void change_mode(int new_mode); +void dhcp_process_ack(struct dhcpMessage *packet); +void dhcp_rx(void *dummy); +void dhcp_release(void *ptr, int arg); +void dhcp_renew(void *dummy); +void dhcp_request_new(); +void dhcp_ip_choose(u_int32_t *addrp); +void dhcp_read_options(void); + + +void change_mode(int new_mode) +{ + if (new_mode == LISTEN_RAW && client_config.giaddr) + if (listen_mode == LISTEN_KERNEL) + return; + else + new_mode = LISTEN_KERNEL; + + dbglog("DHCPC: entering %s listen mode on %s", + new_mode ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw") : "none", + client_config.siaddr ? "*" : client_config.interface); + if (fd >= 0) + close(fd); + fd = -1; + listen_mode = new_mode; + if (listen_mode == LISTEN_KERNEL) + fd = listen_socket(INADDR_ANY, + dhcp_relay_port, client_config.siaddr ? NULL : client_config.interface); + else if (listen_mode == LISTEN_RAW) + fd = raw_socket(client_config.ifindex); + + if (listen_mode != LISTEN_NONE && fd < 0) { + fatal("DHCPC: couldn't listen on socket, %s", sys_errlist[errno]); + } + +} + +void dhcp_process_ack(struct dhcpMessage *packet) { + unsigned char *temp; + struct in_addr temp_addr; + + if (!(temp = get_option(packet, DHCP_LEASE_TIME))) { + warn("DHCPC: No lease time with ACK, using 1 hour lease"); + lease = 60 * 60; + } else { + memcpy(&lease, temp, 4); + lease = ntohl(lease); + } + +#ifdef DHCP_TEST_SHORTLEASE + warn("DHCPC: Test mode: shortening lease to 60 seconds!"); + lease=60; +#endif + + /* enter bound state */ + temp_addr.s_addr = packet->yiaddr; + info("DHCPC: Lease of %s obtained, lease time %ld", + inet_ntoa(temp_addr), lease); + + requested_ip = packet->yiaddr; + + dhcp_state = BOUND; + change_mode(LISTEN_NONE); +} + + +void dhcp_rx(void *dummy) { + unsigned char *temp, *message; + unsigned long t2 = 0; + fd_set rfds; + int retval; + struct timeval tv; + int c, len; + struct dhcpMessage packet; + struct in_addr temp_addr; + int pid_fd; + time_t now; + + dbglog("DHCPC: Entering RX Polling function"); + + if (listen_mode != LISTEN_KERNEL) + return; + if (dhcp_state != RENEWING && dhcp_state != REBINDING && dhcp_state != BOUND) + return; + + tv.tv_sec = 0; /* poll only, do not wait */ + tv.tv_usec = 0; + FD_ZERO(&rfds); + FD_SET(fd, &rfds); + + dbglog("DHCPC: Polling for new packets"); + + while(select(fd + 1, &rfds, NULL, NULL, &tv)) { + len = get_packet(&packet, fd); + + if (len == -1 && errno != EINTR) { + dbglog("DHCPC: error on read, %s, reopening socket", sys_errlist[errno]); + change_mode(LISTEN_KERNEL); + } + if (len < 0) continue; + + if (packet.xid != xid) { + dbglog("DHCPC: Ignoring XID %lx (our xid is %lx)", + (unsigned long) packet.xid, xid); + continue; + } + + if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { + dbglog("DHCPC: Could not get option from packet -- ignoring"); + continue; + } + + if ((*message == DHCPOFFER || *message == DHCPACK) && + client_config.subnet_selection && + get_option(&packet, DHCP_SUBNET_SELECTION) == NULL) { + warn("DHCPC: server does not support subnet selection, discarding response"); + continue; + } + + if (dhcp_state == RENEWING || dhcp_state == REBINDING) { + if (*message == DHCPACK) { + dhcp_process_ack(&packet); + if (requested_ip != assigned_ip) { + fatal("DHCPC: Terminating because address has changed!"); + } + untimeout(&dhcp_renew,NULL); + timeout(&dhcp_renew, NULL, lease / 2,0); + return; + } else if (*message == DHCPNAK) { + /* return to init state */ + dhcp_state = RELEASED; + change_mode(LISTEN_NONE); + fatal("DHCP Lease was NAK'd during renewal/rebinding!"); + } + } + } + timeout(&dhcp_rx,NULL,DHCP_RX_POLL_INTERVAL,0); + +} + +void dhcp_release(void *ptr, int arg) +{ + /* send release packet */ + if (dhcp_state == BOUND || dhcp_state == RENEWING || dhcp_state == REBINDING) + send_release(server_addr, requested_ip); /* unicast */ + + change_mode(LISTEN_NONE); + dhcp_state = RELEASED; +} + + +void dhcp_renew(void *dummy) { + static long dhcp_renew_timeout; + static int dhcp_packet_interval; + + dbglog("DHCPC: Entering renewal timer function"); + + if (dhcp_state == BOUND) { + dhcp_state = RENEWING; + change_mode(LISTEN_KERNEL); + timeout(&dhcp_rx,NULL,3,0); + dbglog("DHCPC: Entering renew state"); + /* 1/2 of lease used on entry, timeout renew after another 3/8 of lease */ + dhcp_renew_timeout = (lease * 0x3) >> 3; + dhcp_packet_interval = 2; + } + if (dhcp_state != RENEWING && dhcp_state != REBINDING) + return; + + if (dhcp_renew_timeout <= 0) { + switch(dhcp_state) { + case REBINDING: + fatal("DHCP Timed out rebinding"); + case RENEWING: + /* 1/8 of lease remaining */ + dhcp_renew_timeout = (lease) >> 3; + dhcp_state = REBINDING; + dhcp_packet_interval = 2; + } + } + + if (dhcp_packet_interval < 64) + dhcp_packet_interval *= 2; + + send_renew(xid, dhcp_state==REBINDING ? client_config.siaddr : server_addr, requested_ip); + + dhcp_renew_timeout-=dhcp_packet_interval; + timeout(&dhcp_renew, NULL, dhcp_packet_interval,0); +} + +void dhcp_request_new() { + unsigned long request_timeout = 0; + unsigned char *message,*temp; + unsigned long t1 = 0, t2 = 0; + fd_set rfds; + int retval; + struct timeval tv; + int c, len; + struct dhcpMessage packet; + time_t now; + + if (dhcp_state == BOUND || dhcp_state == RENEWING || dhcp_state == REBINDING) + return; + + dhcp_state = INIT_SELECTING; + len=strlen(peer_authname); + client_config.clientid = malloc(len + 3); + client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID; + client_config.clientid[OPT_LEN] = len + 1; + client_config.clientid[OPT_DATA] = 0; + memcpy(client_config.clientid + 3, peer_authname, len); + + change_mode(LISTEN_KERNEL); + for (;;) { + + tv.tv_sec = request_timeout - time(0); + tv.tv_usec = 0; + FD_ZERO(&rfds); + + if (fd >= 0) FD_SET(fd, &rfds); + + if (tv.tv_sec > 0) { + dbglog("Waiting on select...\n"); + retval = select(fd + 1, &rfds, NULL, NULL, &tv); + } else retval = 0; /* If we already timed out, fall through */ + + now = time(0); + if (retval == 0) { + /* timeout dropped to zero */ + switch (dhcp_state) { + case INIT_SELECTING: + if (packet_num < 3) { + if (packet_num == 0) + xid = random_xid(); + + /* send discover packet */ + send_discover(xid, requested_ip); /* broadcast */ + + request_timeout = now + ((packet_num == 2) ? 10 : 2); + packet_num++; + } else { + info("DHCPC: No lease, failing."); + return; + } + break; + case REQUESTING: + if (packet_num < 3) { + /* send request packet */ + send_selecting(xid, server_addr, requested_ip); /* broadcast */ + + request_timeout = now + ((packet_num == 2) ? 10 : 2); + packet_num++; + } else { + /* timed out, go back to init state */ + dhcp_state = INIT_SELECTING; + request_timeout = now; + packet_num = 0; + } + break; + } + } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) { + /* a packet is ready, read it */ + + if (listen_mode == LISTEN_KERNEL) + len = get_packet(&packet, fd); + else len = get_raw_packet(&packet, fd); + + if (len == -1 && errno != EINTR) { + dbglog("DHCPC: error on read, %s, reopening socket", sys_errlist[errno]); + change_mode(listen_mode); /* just close and reopen */ + } + if (len < 0) continue; + + if (packet.xid != xid) { + dbglog("DHCPC: Ignoring XID %lx (our xid is %lx)", + (unsigned long) packet.xid, xid); + continue; + } + + if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { + warn("DHCPC: couldnt get option from packet -- ignoring"); + continue; + } + + if ((*message == DHCPOFFER || *message == DHCPACK) && + client_config.subnet_selection && + get_option(&packet, DHCP_SUBNET_SELECTION) == NULL) { + warn("DHCPC: server does not support subnet selection, discarding response"); + continue; + } + + switch (dhcp_state) { + case INIT_SELECTING: + /* Must be a DHCPOFFER to one of our xid's */ + if (*message == DHCPOFFER) { + if ((temp = get_option(&packet, DHCP_SERVER_ID))) { + memcpy(&server_addr, temp, 4); + xid = packet.xid; + requested_ip = packet.yiaddr; + + /* enter requesting state */ + dhcp_state = REQUESTING; + request_timeout = now; + packet_num = 0; + } else { + dbglog("DHCPC: No server ID in message"); + } + } + break; + case REQUESTING: + if (*message == DHCPACK) { + dhcp_process_ack(&packet); + assigned_ip = requested_ip; + dbglog("DHCPC: Setting renewal timer for %d seconds", lease /2); + timeout(&dhcp_renew, NULL, lease / 2,0); + return; + } else if (*message == DHCPNAK) { + /* return to init state */ + info("DHCPC: Received DHCP NAK"); + dhcp_state = INIT_SELECTING; + request_timeout = now; + requested_ip = 0; + packet_num = 0; + sleep(3); /* avoid excessive network traffic */ + } + break; + } + } else if (retval == -1 && errno == EINTR) { + /* a signal was caught */ + dbglog("DHCPC: signal caught"); + + } else { + /* An error occured */ + dbglog("DHCPC: error on select, %s, reopening socket", sys_errlist[errno]); + change_mode(listen_mode); /* just close and reopen */ + } + + } + return; +} + +void dhcp_ip_choose(u_int32_t *addrp) { + u_int32_t entryvalue; + + dbglog("DHCPC: ip_choose_hook entered with peer name %s",peer_authname); + + if (dhcp_old_ip_choose_hook) { + dbglog("DHCPC: calling ip_choose_hook for previously loaded module"); + entryvalue= *addrp; + dhcp_old_ip_choose_hook(addrp); + if (*addrp != entryvalue) { + info("DHCPC: A previously loaded module has supplied an IP address. Skipping DHCP."); + return; + } + } + + dhcp_read_options(); + + if (strlen(peer_authname)) + dhcp_request_new(); + + if (dhcp_state == BOUND || dhcp_state == RENEWING || dhcp_state == REBINDING) + *addrp=assigned_ip; + else + fatal("DHCPC: Failed to obtain an IP address. Terminating connection."); + + return; + +} + + +void plugin_init(void) +{ + dhcp_old_ip_choose_hook= ip_choose_hook; + /* we save pointer to ip_choose_hook so we can defer to other modules + that may specify an IP, e.g. radius */ + ip_choose_hook= dhcp_ip_choose; + add_options(dhcpc_options); + add_notifier(&exitnotify, dhcp_release, NULL); + info("DHCPC: plugin initialized"); + +} + + +void dhcp_read_options(void) +{ + struct in_addr sa; + + if (read_interface(client_config.interface, &client_config.ifindex, + &sa.s_addr, client_config.arp) < 0) + fatal("DHCPC: Could not find interface"); + + + if (dhcp_relay_address && !inet_aton(dhcp_relay_address, &sa)) + fatal("DHCPC: Invalid relay address specified."); + + client_config.giaddr=sa.s_addr; + info("DHCPC: Using relay address of '%s'", inet_ntoa(sa)); + + if (dhcp_subnet_selection) + if (inet_aton(dhcp_subnet_selection, &sa)) { + client_config.subnet_selection= sa.s_addr; + info("DHCPC: Requesting subnet '%s'", inet_ntoa(sa)); + } else + fatal("DHCPC: Invalid address in subnet selection option"); + + if (dhcp_server) + if (inet_aton(dhcp_server, &sa)) { + client_config.siaddr= sa.s_addr; + info("DHCPC: Unicasting to server '%s' only", inet_ntoa(sa)); + } else + fatal("DHCPC: Invalid server address specified."); + else + info("DHCPC: Broadcasting to servers on interface '%s'", client_config.interface); + +} + diff --git a/pppd/plugins/dhcp/dhcpc.h b/pppd/plugins/dhcp/dhcpc.h new file mode 100644 index 0000000..0a218a8 --- /dev/null +++ b/pppd/plugins/dhcp/dhcpc.h @@ -0,0 +1,35 @@ +/* dhcpc.h */ +#ifndef _DHCPC_H +#define _DHCPC_H + + +#define INIT_SELECTING 0 +#define REQUESTING 1 +#define BOUND 2 +#define RENEWING 3 +#define REBINDING 4 +#define INIT_REBOOT 5 +#define RENEW_REQUESTED 6 +#define RELEASED 7 + + +struct client_config_t { + char foreground; /* Do not fork */ + char quit_after_lease; /* Quit after obtaining lease */ + char abort_if_no_lease; /* Abort if no lease */ + char *interface; /* The name of the interface to use */ + char *pidfile; /* Optionally store the process ID */ + char *script; /* User script to run at dhcp events */ + unsigned char *clientid; /* Optional client id to use */ + unsigned char *hostname; /* Optional hostname to use */ + int ifindex; /* Index number of the interface to use */ + unsigned char arp[6]; /* Our arp address */ + u_int32_t giaddr; /* Fill in this value on all packets we generate */ + u_int32_t siaddr; /* If defined, only talk to this server (never broadcast) */ + u_int32_t subnet_selection; /* If non zero, send and require SS option */ +}; + +extern struct client_config_t client_config; + + +#endif diff --git a/pppd/plugins/dhcp/dhcpd.h b/pppd/plugins/dhcp/dhcpd.h new file mode 100644 index 0000000..3e421e6 --- /dev/null +++ b/pppd/plugins/dhcp/dhcpd.h @@ -0,0 +1,134 @@ +/* dhcpd.h */ +#ifndef _DHCPD_H +#define _DHCPD_H + +#include +#include + +#include "leases.h" + +/************************************/ +/* Defaults _you_ may want to tweak */ +/************************************/ + +/* the period of time the client is allowed to use that address */ +#define LEASE_TIME (60*60*24*10) /* 10 days of seconds */ + +/* where to find the DHCP server configuration file */ +#define DHCPD_CONF_FILE "/etc/udhcpd.conf" + +/*****************************************************************/ +/* Do not modify below here unless you know what you are doing!! */ +/*****************************************************************/ + +/* DHCP protocol -- see RFC 2131 */ +#define SERVER_PORT 67 +#define CLIENT_PORT 68 + +#define DHCP_MAGIC 0x63825363 + +/* DHCP option codes (partial list) */ +#define DHCP_PADDING 0x00 +#define DHCP_SUBNET 0x01 +#define DHCP_TIME_OFFSET 0x02 +#define DHCP_ROUTER 0x03 +#define DHCP_TIME_SERVER 0x04 +#define DHCP_NAME_SERVER 0x05 +#define DHCP_DNS_SERVER 0x06 +#define DHCP_LOG_SERVER 0x07 +#define DHCP_COOKIE_SERVER 0x08 +#define DHCP_LPR_SERVER 0x09 +#define DHCP_HOST_NAME 0x0c +#define DHCP_BOOT_SIZE 0x0d +#define DHCP_DOMAIN_NAME 0x0f +#define DHCP_SWAP_SERVER 0x10 +#define DHCP_ROOT_PATH 0x11 +#define DHCP_IP_TTL 0x17 +#define DHCP_MTU 0x1a +#define DHCP_BROADCAST 0x1c +#define DHCP_NTP_SERVER 0x2a +#define DHCP_WINS_SERVER 0x2c +#define DHCP_REQUESTED_IP 0x32 +#define DHCP_LEASE_TIME 0x33 +#define DHCP_OPTION_OVER 0x34 +#define DHCP_MESSAGE_TYPE 0x35 +#define DHCP_SERVER_ID 0x36 +#define DHCP_PARAM_REQ 0x37 +#define DHCP_MESSAGE 0x38 +#define DHCP_MAX_SIZE 0x39 +#define DHCP_T1 0x3a +#define DHCP_T2 0x3b +#define DHCP_VENDOR 0x3c +#define DHCP_CLIENT_ID 0x3d +#define DHCP_SUBNET_SELECTION 0x76 + + +#define DHCP_END 0xFF + + +#define BOOTREQUEST 1 +#define BOOTREPLY 2 + +#define ETH_10MB 1 +#define ETH_10MB_LEN 6 + +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNAK 6 +#define DHCPRELEASE 7 +#define DHCPINFORM 8 + +#define BROADCAST_FLAG 0x8000 + +#define OPTION_FIELD 0 +#define FILE_FIELD 1 +#define SNAME_FIELD 2 + +/* miscellaneous defines */ +#define TRUE 1 +#define FALSE 0 +#define MAC_BCAST_ADDR (unsigned char *) "\xff\xff\xff\xff\xff\xff" +#define OPT_CODE 0 +#define OPT_LEN 1 +#define OPT_DATA 2 + +struct option_set { + unsigned char *data; + struct option_set *next; +}; + +struct server_config_t { + u_int32_t server; /* Our IP, in network order */ + u_int32_t start; /* Start address of leases, network order */ + u_int32_t end; /* End of leases, network order */ + struct option_set *options; /* List of DHCP options loaded from the config file */ + char *interface; /* The name of the interface to use */ + int ifindex; /* Index number of the interface to use */ + unsigned char arp[6]; /* Our arp address */ + unsigned long lease; /* lease time in seconds (host order) */ + unsigned long max_leases; /* maximum number of leases (including reserved address) */ + char remaining; /* should the lease file be interpreted as lease time remaining, or + * as the time the lease expires */ + unsigned long auto_time; /* how long should udhcpd wait before writing a config file. + * if this is zero, it will only write one on SIGUSR1 */ + unsigned long decline_time; /* how long an address is reserved if a client returns a + * decline message */ + unsigned long conflict_time; /* how long an arp conflict offender is leased for */ + unsigned long offer_time; /* how long an offered address is reserved */ + unsigned long min_lease; /* minimum lease a client can request*/ + char *lease_file; + char *pidfile; + char *notify_file; /* What to run whenever leases are written */ + u_int32_t siaddr; /* next server bootp option */ + char *sname; /* bootp server name */ + char *boot_file; /* bootp boot file option */ +}; + +extern struct server_config_t server_config; +extern struct dhcpOfferedAddr *leases; + + +#endif diff --git a/pppd/plugins/dhcp/files.h b/pppd/plugins/dhcp/files.h new file mode 100644 index 0000000..c0368aa --- /dev/null +++ b/pppd/plugins/dhcp/files.h @@ -0,0 +1,17 @@ +/* files.h */ +#ifndef _FILES_H +#define _FILES_H + +struct config_keyword { + char keyword[14]; + int (*handler)(char *line, void *var); + void *var; + char def[30]; +}; + + +int read_config(char *file); +void write_leases(int dummy); +void read_leases(char *file); + +#endif diff --git a/pppd/plugins/dhcp/leases.h b/pppd/plugins/dhcp/leases.h new file mode 100644 index 0000000..4a29757 --- /dev/null +++ b/pppd/plugins/dhcp/leases.h @@ -0,0 +1,23 @@ +/* leases.h */ +#ifndef _LEASES_H +#define _LEASES_H + + +struct dhcpOfferedAddr { + u_int8_t chaddr[16]; + u_int32_t yiaddr; /* network order */ + u_int32_t expires; /* host order */ +}; + + +void clear_lease(u_int8_t *chaddr, u_int32_t yiaddr); +struct dhcpOfferedAddr *add_lease(u_int8_t *chaddr, u_int32_t yiaddr, unsigned long lease); +int lease_expired(struct dhcpOfferedAddr *lease); +struct dhcpOfferedAddr *oldest_expired_lease(void); +struct dhcpOfferedAddr *find_lease_by_chaddr(u_int8_t *chaddr); +struct dhcpOfferedAddr *find_lease_by_yiaddr(u_int32_t yiaddr); +u_int32_t find_address(int check_expired); +int check_ip(u_int32_t addr); + + +#endif diff --git a/pppd/plugins/dhcp/options.c b/pppd/plugins/dhcp/options.c new file mode 100644 index 0000000..902a9bd --- /dev/null +++ b/pppd/plugins/dhcp/options.c @@ -0,0 +1,231 @@ +/* + * options.c -- DHCP server option packet tools + * Rewrite by Russ Dill July 2001 + */ + +#include +#include +#include + +#include "debug.h" +#include "dhcpd.h" +#include "files.h" +#include "options.h" +#include "leases.h" + + +/* supported options are easily added here */ +struct dhcp_option options[] = { + /* name[10] flags code */ + {"subnet", OPTION_IP | OPTION_REQ, 0x01}, + {"timezone", OPTION_S32, 0x02}, + {"router", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x03}, + {"timesvr", OPTION_IP | OPTION_LIST, 0x04}, + {"namesvr", OPTION_IP | OPTION_LIST, 0x05}, + {"dns", OPTION_IP | OPTION_LIST | OPTION_REQ, 0x06}, + {"logsvr", OPTION_IP | OPTION_LIST, 0x07}, + {"cookiesvr", OPTION_IP | OPTION_LIST, 0x08}, + {"lprsvr", OPTION_IP | OPTION_LIST, 0x09}, + {"hostname", OPTION_STRING | OPTION_REQ, 0x0c}, + {"bootsize", OPTION_U16, 0x0d}, + {"domain", OPTION_STRING | OPTION_REQ, 0x0f}, + {"swapsvr", OPTION_IP, 0x10}, + {"rootpath", OPTION_STRING, 0x11}, + {"ipttl", OPTION_U8, 0x17}, + {"mtu", OPTION_U16, 0x1a}, + {"broadcast", OPTION_IP | OPTION_REQ, 0x1c}, + {"ntpsrv", OPTION_IP | OPTION_LIST, 0x2a}, + {"wins", OPTION_IP | OPTION_LIST, 0x2c}, + {"requestip", OPTION_IP, 0x32}, + {"lease", OPTION_U32, 0x33}, + {"dhcptype", OPTION_U8, 0x35}, + {"serverid", OPTION_IP, 0x36}, + {"message", OPTION_STRING, 0x38}, + {"tftp", OPTION_STRING, 0x42}, + {"bootfile", OPTION_STRING, 0x43}, + {"subnetsel", OPTION_IP, 0x76}, + {"", 0x00, 0x00} +}; + +/* Lengths of the different option types */ +int option_lengths[] = { + [OPTION_IP] = 4, + [OPTION_IP_PAIR] = 8, + [OPTION_BOOLEAN] = 1, + [OPTION_STRING] = 1, + [OPTION_U8] = 1, + [OPTION_U16] = 2, + [OPTION_S16] = 2, + [OPTION_U32] = 4, + [OPTION_S32] = 4 +}; + + +/* get an option with bounds checking (warning, not aligned). */ +unsigned char *get_option(struct dhcpMessage *packet, int code) +{ + int i, length; + unsigned char *optionptr; + int over = 0, done = 0, curr = OPTION_FIELD; + + optionptr = packet->options; + i = 0; + length = 308; + while (!done) { + if (i >= length) { + LOG(LOG_WARNING, "bogus packet, option fields too long."); + return NULL; + } + if (optionptr[i + OPT_CODE] == code) { + if (i + 1 + optionptr[i + OPT_LEN] >= length) { + LOG(LOG_WARNING, "bogus packet, option fields too long."); + return NULL; + } + return optionptr + i + 2; + } + switch (optionptr[i + OPT_CODE]) { + case DHCP_PADDING: + i++; + break; + case DHCP_OPTION_OVER: + if (i + 1 + optionptr[i + OPT_LEN] >= length) { + LOG(LOG_WARNING, "bogus packet, option fields too long."); + return NULL; + } + over = optionptr[i + 3]; + i += optionptr[OPT_LEN] + 2; + break; + case DHCP_END: + if (curr == OPTION_FIELD && over & FILE_FIELD) { + optionptr = packet->file; + i = 0; + length = 128; + curr = FILE_FIELD; + } else if (curr == FILE_FIELD && over & SNAME_FIELD) { + optionptr = packet->sname; + i = 0; + length = 64; + curr = SNAME_FIELD; + } else done = 1; + break; + default: + i += optionptr[OPT_LEN + i] + 2; + } + } + return NULL; +} + + +/* return the position of the 'end' option (no bounds checking) */ +int end_option(unsigned char *optionptr) +{ + int i = 0; + + while (optionptr[i] != DHCP_END) { + if (optionptr[i] == DHCP_PADDING) i++; + else i += optionptr[i + OPT_LEN] + 2; + } + return i; +} + + +/* add an option string to the options (an option string contains an option code, + * length, then data) */ +int add_option_string(unsigned char *optionptr, unsigned char *string) +{ + int end = end_option(optionptr); + + /* end position + string length + option code/length + end option */ + if (end + string[OPT_LEN] + 2 + 1 >= 308) { + LOG(LOG_ERR, "Option 0x%02x did not fit into the packet!", string[OPT_CODE]); + return 0; + } + DEBUG(LOG_INFO, "adding option 0x%02x", string[OPT_CODE]); + memcpy(optionptr + end, string, string[OPT_LEN] + 2); + optionptr[end + string[OPT_LEN] + 2] = DHCP_END; + return string[OPT_LEN] + 2; +} + + +/* add a one to four byte option to a packet */ +int add_simple_option(unsigned char *optionptr, unsigned char code, u_int32_t data) +{ + char length = 0; + int i; + unsigned char option[2 + 4]; + unsigned char *u8; + u_int16_t *u16; + u_int32_t *u32; + u_int32_t aligned; + u8 = (unsigned char *) &aligned; + u16 = (u_int16_t *) &aligned; + u32 = &aligned; + + for (i = 0; options[i].code; i++) + if (options[i].code == code) { + length = option_lengths[options[i].flags & TYPE_MASK]; + } + + if (!length) { + DEBUG(LOG_ERR, "Could not add option 0x%02x", code); + return 0; + } + + option[OPT_CODE] = code; + option[OPT_LEN] = length; + + switch (length) { + case 1: *u8 = data; break; + case 2: *u16 = data; break; + case 4: *u32 = data; break; + } + memcpy(option + 2, &aligned, length); + return add_option_string(optionptr, option); +} + + +/* find option 'code' in opt_list */ +struct option_set *find_option(struct option_set *opt_list, char code) +{ + while (opt_list && opt_list->data[OPT_CODE] < code) + opt_list = opt_list->next; + + if (opt_list && opt_list->data[OPT_CODE] == code) return opt_list; + else return NULL; +} + + +/* add an option to the opt_list */ +void attach_option(struct option_set **opt_list, struct dhcp_option *option, char *buffer, int length) +{ + struct option_set *existing, *new, **curr; + + /* add it to an existing option */ + if ((existing = find_option(*opt_list, option->code))) { + DEBUG(LOG_INFO, "Attaching option %s to existing member of list", option->name); + if (option->flags & OPTION_LIST) { + if (existing->data[OPT_LEN] + length <= 255) { + existing->data = realloc(existing->data, + existing->data[OPT_LEN] + length + 2); + memcpy(existing->data + existing->data[OPT_LEN] + 2, buffer, length); + existing->data[OPT_LEN] += length; + } /* else, ignore the data, we could put this in a second option in the future */ + } /* else, ignore the new data */ + } else { + DEBUG(LOG_INFO, "Attaching option %s to list", option->name); + + /* make a new option */ + new = malloc(sizeof(struct option_set)); + new->data = malloc(length + 2); + new->data[OPT_CODE] = option->code; + new->data[OPT_LEN] = length; + memcpy(new->data + 2, buffer, length); + + curr = opt_list; + while (*curr && (*curr)->data[OPT_CODE] < option->code) + curr = &(*curr)->next; + + new->next = *curr; + *curr = new; + } +} diff --git a/pppd/plugins/dhcp/options.h b/pppd/plugins/dhcp/options.h new file mode 100644 index 0000000..1fded2e --- /dev/null +++ b/pppd/plugins/dhcp/options.h @@ -0,0 +1,40 @@ +/* options.h */ +#ifndef _OPTIONS_H +#define _OPTIONS_H + +#include "packet.h" + +#define TYPE_MASK 0x0F + +enum { + OPTION_IP=1, + OPTION_IP_PAIR, + OPTION_STRING, + OPTION_BOOLEAN, + OPTION_U8, + OPTION_U16, + OPTION_S16, + OPTION_U32, + OPTION_S32 +}; + +#define OPTION_REQ 0x10 /* have the client request this option */ +#define OPTION_LIST 0x20 /* There can be a list of 1 or more of these */ + +struct dhcp_option { + char name[10]; + char flags; + unsigned char code; +}; + +extern struct dhcp_option options[]; +extern int option_lengths[]; + +unsigned char *get_option(struct dhcpMessage *packet, int code); +int end_option(unsigned char *optionptr); +int add_option_string(unsigned char *optionptr, unsigned char *string); +int add_simple_option(unsigned char *optionptr, unsigned char code, u_int32_t data); +struct option_set *find_option(struct option_set *opt_list, char code); +void attach_option(struct option_set **opt_list, struct dhcp_option *option, char *buffer, int length); + +#endif diff --git a/pppd/plugins/dhcp/packet.c b/pppd/plugins/dhcp/packet.c new file mode 100644 index 0000000..00b5202 --- /dev/null +++ b/pppd/plugins/dhcp/packet.c @@ -0,0 +1,209 @@ +#include +#include +#include +#include +#include +#include +#if __GLIBC__ >=2 && __GLIBC_MINOR >= 1 +#include +#include +#else +#include +#include +#include +#endif +#include + +#include "packet.h" +#include "debug.h" +#include "dhcpd.h" +#include "options.h" + + +void init_header(struct dhcpMessage *packet, char type) +{ + memset(packet, 0, sizeof(struct dhcpMessage)); + switch (type) { + case DHCPDISCOVER: + case DHCPREQUEST: + case DHCPRELEASE: + case DHCPINFORM: + packet->op = BOOTREQUEST; + break; + case DHCPOFFER: + case DHCPACK: + case DHCPNAK: + packet->op = BOOTREPLY; + } + packet->htype = ETH_10MB; + packet->hlen = ETH_10MB_LEN; + packet->cookie = htonl(DHCP_MAGIC); + packet->options[0] = DHCP_END; + add_simple_option(packet->options, DHCP_MESSAGE_TYPE, type); +} + + +/* read a packet from socket fd, return -1 on read error, -2 on packet error */ +int get_packet(struct dhcpMessage *packet, int fd) +{ + int bytes; + int i; + const char broken_vendors[][8] = { + "MSFT 98", + "" + }; + char unsigned *vendor; + + memset(packet, 0, sizeof(struct dhcpMessage)); + bytes = read(fd, packet, sizeof(struct dhcpMessage)); + if (bytes < 0) { + DEBUG(LOG_INFO, "couldn't read on listening socket, ignoring"); + return -1; + } + + if (ntohl(packet->cookie) != DHCP_MAGIC) { + LOG(LOG_ERR, "received bogus message, ignoring"); + return -2; + } + DEBUG(LOG_INFO, "Received a packet"); + + if (packet->op == BOOTREQUEST && (vendor = get_option(packet, DHCP_VENDOR))) { + for (i = 0; broken_vendors[i][0]; i++) { + if (vendor[OPT_LEN - 2] == (unsigned char) strlen(broken_vendors[i]) && + !strncmp(vendor, broken_vendors[i], vendor[OPT_LEN - 2])) { + DEBUG(LOG_INFO, "broken client (%s), forcing broadcast", + broken_vendors[i]); + packet->flags |= htons(BROADCAST_FLAG); + } + } + } + + + return bytes; +} + + +u_int16_t checksum(void *addr, int count) +{ + /* Compute Internet Checksum for "count" bytes + * beginning at location "addr". + */ + register int32_t sum = 0; + u_int16_t *source = (u_int16_t *) addr; + + while( count > 1 ) { + /* This is the inner loop */ + sum += *source++; + count -= 2; + } + + /* Add left-over byte, if any */ + if( count > 0 ) + sum += * (unsigned char *) source; + + /* Fold 32-bit sum to 16 bits */ + while (sum>>16) + sum = (sum & 0xffff) + (sum >> 16); + + return ~sum; +} + + +/* Constuct a ip/udp header for a packet, and specify the source and dest hardware address */ +int raw_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port, + u_int32_t dest_ip, int dest_port, unsigned char *dest_arp, int ifindex) +{ + int fd; + int result; + struct sockaddr_ll dest; + struct udp_dhcp_packet packet; + + if (payload->giaddr && source_port==CLIENT_PORT) + if (dest_ip == INADDR_BROADCAST) + source_ip=payload->giaddr; + else + return kernel_packet(payload,payload->giaddr,CLIENT_PORT,dest_ip,dest_port); + + if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { + DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]); + return -1; + } + + memset(&dest, 0, sizeof(dest)); + memset(&packet, 0, sizeof(packet)); + + dest.sll_family = AF_PACKET; + dest.sll_protocol = htons(ETH_P_IP); + dest.sll_ifindex = ifindex; + dest.sll_halen = 6; + memcpy(dest.sll_addr, dest_arp, 6); + if (bind(fd, (struct sockaddr *)&dest, sizeof(struct sockaddr_ll)) < 0) { + DEBUG(LOG_ERR, "bind call failed: %s", sys_errlist[errno]); + close(fd); + return -1; + } + + packet.ip.protocol = IPPROTO_UDP; + packet.ip.saddr = source_ip; + packet.ip.daddr = dest_ip; + packet.udp.source = htons(source_port); + packet.udp.dest = htons(dest_port); + packet.udp.len = htons(sizeof(packet.udp) + sizeof(struct dhcpMessage)); /* cheat on the psuedo-header */ + packet.ip.tot_len = packet.udp.len; + memcpy(&(packet.data), payload, sizeof(struct dhcpMessage)); + packet.udp.check = checksum(&packet, sizeof(struct udp_dhcp_packet)); + + packet.ip.tot_len = htons(sizeof(struct udp_dhcp_packet)); + packet.ip.ihl = sizeof(packet.ip) >> 2; + packet.ip.version = IPVERSION; + packet.ip.ttl = IPDEFTTL; + packet.ip.check = checksum(&(packet.ip), sizeof(packet.ip)); + + result = sendto(fd, &packet, sizeof(struct udp_dhcp_packet), 0, (struct sockaddr *) &dest, sizeof(dest)); + if (result <= 0) { + DEBUG(LOG_ERR, "write on socket failed: %s", sys_errlist[errno]); + } + close(fd); + return result; +} + + +/* Let the kernel do all the work for packet generation */ +int kernel_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port, + u_int32_t dest_ip, int dest_port) +{ + int n = 1; + int fd, result; + struct sockaddr_in client; + + if (payload->giaddr && source_port==CLIENT_PORT) { + source_ip=payload->giaddr; + } + + if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) + return -1; + + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1) + return -1; + + memset(&client, 0, sizeof(client)); + client.sin_family = AF_INET; + client.sin_port = htons(source_port); + client.sin_addr.s_addr = source_ip; + + if (bind(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1) + return -1; + + memset(&client, 0, sizeof(client)); + client.sin_family = AF_INET; + client.sin_port = htons(dest_port); + client.sin_addr.s_addr = dest_ip; + + if (connect(fd, (struct sockaddr *)&client, sizeof(struct sockaddr)) == -1) + return -1; + + result = write(fd, payload, sizeof(struct dhcpMessage)); + close(fd); + return result; +} + diff --git a/pppd/plugins/dhcp/packet.h b/pppd/plugins/dhcp/packet.h new file mode 100644 index 0000000..1a263ef --- /dev/null +++ b/pppd/plugins/dhcp/packet.h @@ -0,0 +1,41 @@ +#ifndef _PACKET_H +#define _PACKET_H + +#include +#include + +struct dhcpMessage { + u_int8_t op; + u_int8_t htype; + u_int8_t hlen; + u_int8_t hops; + u_int32_t xid; + u_int16_t secs; + u_int16_t flags; + u_int32_t ciaddr; + u_int32_t yiaddr; + u_int32_t siaddr; + u_int32_t giaddr; + u_int8_t chaddr[16]; + u_int8_t sname[64]; + u_int8_t file[128]; + u_int32_t cookie; + u_int8_t options[308]; /* 312 - cookie */ +}; + +struct udp_dhcp_packet { + struct iphdr ip; + struct udphdr udp; + struct dhcpMessage data; +}; + +void init_header(struct dhcpMessage *packet, char type); +int get_packet(struct dhcpMessage *packet, int fd); +u_int16_t checksum(void *addr, int count); +int raw_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port, + u_int32_t dest_ip, int dest_port, unsigned char *dest_arp, int ifindex); +int kernel_packet(struct dhcpMessage *payload, u_int32_t source_ip, int source_port, + u_int32_t dest_ip, int dest_port); + + +#endif diff --git a/pppd/plugins/dhcp/socket.c b/pppd/plugins/dhcp/socket.c new file mode 100644 index 0000000..0234350 --- /dev/null +++ b/pppd/plugins/dhcp/socket.c @@ -0,0 +1,163 @@ +/* + * socket.c -- DHCP server client/server socket creation + * + * Moreton Bay DHCP Server + * Copyright (C) 1999 Matthew Ramsay + * Chris Trew + * + * Rewrite by Russ Dill July 2001 + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if __GLIBC__ >=2 && __GLIBC_MINOR >= 1 +#include +#include +#else +#include +#include +#include +#endif + +#include "debug.h" + +int read_interface(char *interface, int *ifindex, u_int32_t *addr, unsigned char *arp) +{ + int fd; + struct ifreq ifr; + struct sockaddr_in *sin; + + memset(&ifr, 0, sizeof(struct ifreq)); + if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) >= 0) { + ifr.ifr_addr.sa_family = AF_INET; + strcpy(ifr.ifr_name, interface); + + if (addr) { + if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) { + sin = (struct sockaddr_in *) &ifr.ifr_addr; + *addr = sin->sin_addr.s_addr; + DEBUG(LOG_INFO, "%s (our ip) = %s", ifr.ifr_name, inet_ntoa(sin->sin_addr)); + } else { + LOG(LOG_ERR, "SIOCGIFADDR failed!: %s", sys_errlist[errno]); + return -1; + } + } + + if (ioctl(fd, SIOCGIFINDEX, &ifr) == 0) { + DEBUG(LOG_INFO, "adapter index %d", ifr.ifr_ifindex); + *ifindex = ifr.ifr_ifindex; + } else { + LOG(LOG_ERR, "SIOCGIFINDEX failed!: %s", sys_errlist[errno]); + return -1; + } + if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0) { + memcpy(arp, ifr.ifr_hwaddr.sa_data, 6); + DEBUG(LOG_INFO, "adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x", + arp[0], arp[1], arp[2], arp[3], arp[4], arp[5]); + } else { + LOG(LOG_ERR, "SIOCGIFHWADDR failed!: %s", sys_errlist[errno]); + return -1; + } + } else { + LOG(LOG_ERR, "socket failed!: %s", sys_errlist[errno]); + return -1; + } + close(fd); + return 0; +} + + +int listen_socket(unsigned int ip, int port, char *inf) +{ + struct ifreq interface; + int fd; + struct sockaddr_in addr; + int n = 1; + + DEBUG(LOG_INFO, "Opening listen socket on 0x%08x:%d %s\n", ip, port, inf ? inf : "*"); + if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { + DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]); + return -1; + } + + DEBUG(LOG_INFO, "Bound socket %d\n", fd); + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = ip; + + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1) { + close(fd); + return -1; + } + + if (inf != NULL) { + + if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *) &n, sizeof(n)) == -1) { + close(fd); + return -1; + } + + strncpy(interface.ifr_ifrn.ifrn_name, inf, IFNAMSIZ); + if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE,(char *)&interface, sizeof(interface)) < 0) { + close(fd); + return -1; + } + } + + if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) { + close(fd); + return -1; + } + + return fd; +} + + +int raw_socket(int ifindex) +{ + int fd; + struct sockaddr_ll sock; + + DEBUG(LOG_INFO, "Opening raw socket on ifindex %d\n", ifindex); + if ((fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { + DEBUG(LOG_ERR, "socket call failed: %s", sys_errlist[errno]); + return -1; + } + + sock.sll_family = AF_PACKET; + sock.sll_protocol = htons(ETH_P_IP); + sock.sll_ifindex = ifindex; + if (bind(fd, (struct sockaddr *) &sock, sizeof(sock)) < 0) { + DEBUG(LOG_ERR, "bind call failed: %s", sys_errlist[errno]); + close(fd); + return -1; + } + + return fd; + +} + diff --git a/pppd/plugins/dhcp/socket.h b/pppd/plugins/dhcp/socket.h new file mode 100644 index 0000000..333994b --- /dev/null +++ b/pppd/plugins/dhcp/socket.h @@ -0,0 +1,9 @@ +/* socket.h */ +#ifndef _SOCKET_H +#define _SOCKET_H + +int read_interface(char *interface, int *ifindex, u_int32_t *addr, unsigned char *arp); +int listen_socket(unsigned int ip, int port, char *inf); +int raw_socket(int ifindex); + +#endif