From 0051057605aa1681a5e6144f0f590d78d842686a Mon Sep 17 00:00:00 2001 From: Darell Tan Date: Sun, 10 Apr 2011 21:51:52 +0800 Subject: [PATCH] Initial commit. --- .hgignore | 4 + LICENSE.txt | 457 +++++++++++++++++++++++++++ Makefile | 32 ++ README.txt | 57 ++++ mdns.c | 871 ++++++++++++++++++++++++++++++++++++++++++++++++++++ mdns.h | 169 ++++++++++ mdnsd.c | 555 +++++++++++++++++++++++++++++++++ mdnsd.h | 46 +++ testmdnsd.c | 56 ++++ 9 files changed, 2247 insertions(+) create mode 100644 .hgignore create mode 100644 LICENSE.txt create mode 100644 Makefile create mode 100644 README.txt create mode 100644 mdns.c create mode 100644 mdns.h create mode 100644 mdnsd.c create mode 100644 mdnsd.h create mode 100644 testmdnsd.c diff --git a/.hgignore b/.hgignore new file mode 100644 index 0000000..50629aa --- /dev/null +++ b/.hgignore @@ -0,0 +1,4 @@ +syntax: glob + +*.a +*.o diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..8ef9e34 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,457 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, 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 library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete 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 distribute a copy of this License along with the +Library. + + 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 Library or any portion +of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +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 Library, 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 Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you 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. + + If distribution of 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 satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be 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. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library 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. + + 9. 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 Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +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 with +this License. + + 11. 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 Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library 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 Library. + +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. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library 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. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +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 Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +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 + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. 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 LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..65b0049 --- /dev/null +++ b/Makefile @@ -0,0 +1,32 @@ +# +# Makefile for tinysvcmdns +# + +CFLAGS += -Wall -pedantic -std=gnu99 +#CFLAGS += -g +CFLAGS += -O2 -DNDEBUG +LDLIBS = -lpthread + +BIN=testmdnsd + +LIBTINYSVCMDNS_OBJS = mdns.o mdnsd.o + +.PHONY: all clean + +all: $(BIN) libtinysvcmdns.a + +clean: + -$(RM) *.o + -$(RM) *.bin + -$(RM) mdns + -$(RM) $(BIN) + -$(RM) libtinysvcmdns.a + +mdns: mdns.o + +mdnsd: mdns.o mdnsd.o + +testmdnsd: testmdnsd.o libtinysvcmdns.a + +libtinysvcmdns.a: $(patsubst %, libtinysvcmdns.a(%), $(LIBTINYSVCMDNS_OBJS)) + diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..2ec95ef --- /dev/null +++ b/README.txt @@ -0,0 +1,57 @@ +tinysvcmdns +============ +tinysvcmdns is a tiny MDNS responder implementation for publishing services. + +This implementation is only concerned with publishing services, without a +system-wide daemon like Bonjour or Avahi. Its other goal is to be extremely +small, embeddable, and have no external dependencies. + +It only answers queries related to its own hostname (the A record), the +service PTRs, and the "_services.dns-sd._udp.local" name, which advertises +all services on a particular host. + +Services consist of a single SRV and TXT record. + +Decoding of MDNS packets is only done to retrieve the questions and answer RRs. +The purpose for decoding answer RRs is to make sure the service PTR is not +sent out if it is already included in the answer RRs. + +It also only utilizes multicast packets, so no "QU" queries are accepted. + +There is no name collision detection, so this means no queries are generated +before publishing the services. However compliant responders will avoid using +our names, since the implementation will respond to queries that match our +name. + + +TODO +----- + * better, more stable & complete API + * name collision detection + + +FILES +------ + * mdns.c - provides data structures, parsing & encoding of MDNS packets + * mdnsd.c - implements the server socket, communication and thread + * testmdnsd.c - an example that creates an instance until terminated + + +LICENSE +-------- +Copyright (C) 2011 Darell Tan + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library 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 +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + diff --git a/mdns.c b/mdns.c new file mode 100644 index 0000000..75e7314 --- /dev/null +++ b/mdns.c @@ -0,0 +1,871 @@ +/* + * tinysvcmdns - a tiny MDNS implementation for publishing services + * Copyright (C) 2011 Darell Tan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "mdns.h" +#include +#include +#include +#include +#include +#include + + +#define DEFAULT_TTL 120 + + +struct name_comp { + uint8_t *label; // label + size_t pos; // position in msg + + struct name_comp *next; +}; + +// ----- label functions ----- + +// compares 2 names +static inline int cmp_nlabel(const uint8_t *L1, const uint8_t *L2) { + return strcmp((char *) L1, (char *) L2); +} + +// duplicates a name +inline uint8_t *dup_nlabel(const uint8_t *n) { + assert(n[0] <= 63); // prevent mis-use + return (uint8_t *) strdup((char *) n); +} + +// duplicates a label +uint8_t *dup_label(const uint8_t *label) { + int len = *label + 1; + if (len > 63) + return NULL; + uint8_t *newlabel = malloc(len + 1); + strncpy((char *) newlabel, (char *) label, len); + newlabel[len] = '\0'; + return newlabel; +} + +uint8_t *join_nlabel(const uint8_t *n1, const uint8_t *n2) { + int len1, len2; + uint8_t *s; + + assert(n1[0] <= 63 && n2[0] <= 63); // detect misuse + + len1 = strlen((char *) n1); + len2 = strlen((char *) n2); + + s = malloc(len1 + len2 + 1); + strncpy((char *) s, (char *) n1, len1); + strncpy((char *) s+len1, (char *) n2, len2); + s[len1 + len2] = '\0'; + return s; +} + +// returns a human-readable name label in dotted form +char *nlabel_to_str(const uint8_t *name) { + char *label, *labelp; + const uint8_t *p; + + assert(name != NULL); + + label = labelp = malloc(256); + + for (p = name; *p; p++) { + strncpy(labelp, (char *) p + 1, *p); + labelp += *p; + *labelp = '.'; + labelp++; + + p += *p; + } + + *labelp = '\0'; + + return label; +} + +// returns the length of a label field +// does NOT uncompress the field, so it could be as small as 2 bytes +// or 1 for the root +static size_t label_len(uint8_t *pkt_buf, size_t pkt_len, size_t off) { + uint8_t *p; + uint8_t *e = pkt_buf + pkt_len; + size_t len = 0; + + for (p = pkt_buf + off; p < e; p++) { + if (*p == 0) { + return len + 1; + } else if ((*p & 0xC0) == 0xC0) { + return len + 2; + } else { + len += *p + 1; + p += *p; + } + } + + return len; +} + +// creates a label +// free() after use +uint8_t *create_label(const char *txt) { + int len; + uint8_t *s; + + assert(txt != NULL); + len = strlen(txt); + if (len > 63) + return NULL; + + s = malloc(len + 2); + s[0] = len; + strncpy((char *) s + 1, txt, len); + s[len + 1] = '\0'; + + return s; +} + +// creates a uncompressed name label given a DNS name like "apple.b.com" +// free() after use +uint8_t *create_nlabel(const char *name) { + char *label; + char *p, *e, *lenpos; + int len = 0; + + assert(name != NULL); + + len = strlen(name); + label = malloc(len + 1 + 1); + if (label == NULL) + return NULL; + + strncpy((char *) label + 1, name, len); + label[len + 1] = '\0'; + + p = label; + e = p + len; + lenpos = p; + + while (p < e) { + *lenpos = 0; + char *dot = memchr(p + 1, '.', e - p - 1); + if (dot == NULL) + dot = e + 1; + *lenpos = dot - p - 1; + + p = dot; + lenpos = dot; + } + + return (uint8_t *) label; +} + +// copies a label from the buffer into a newly-allocated string +// free() after use +static uint8_t *copy_label(uint8_t *pkt_buf, size_t pkt_len, size_t off) { + int len; + + if (off > pkt_len) + return NULL; + + len = pkt_buf[off] + 1; + if (off + len > pkt_len) { + DEBUG_PRINTF("label length exceeds packet buffer\n"); + return NULL; + } + + return dup_label(pkt_buf + off); +} + +// uncompresses a name +// free() after use +static uint8_t *uncompress_nlabel(uint8_t *pkt_buf, size_t pkt_len, size_t off) { + uint8_t *p; + uint8_t *e = pkt_buf + pkt_len; + size_t len = 0; + char *str, *sp; + if (off >= pkt_len) + return NULL; + + // calculate length of uncompressed label + for (p = pkt_buf + off; *p && p < e; p++) { + size_t llen = 0; + if ((*p & 0xC0) == 0xC0) { + uint8_t *p2 = pkt_buf + (((p[0] & ~0xC0) << 8) | p[1]); + llen = *p2 + 1; + p = p2 + llen - 1; + } else { + llen = *p + 1; + p += llen - 1; + } + len += llen; + } + + str = sp = malloc(len + 1); + if (str == NULL) + return NULL; + + // FIXME: must merge this with above code + for (p = pkt_buf + off; *p && p < e; p++) { + size_t llen = 0; + if ((*p & 0xC0) == 0xC0) { + uint8_t *p2 = pkt_buf + (((p[0] & ~0xC0) << 8) | p[1]); + llen = *p2 + 1; + strncpy(sp, (char *) p2, llen); + p = p2 + llen - 1; + } else { + llen = *p + 1; + strncpy(sp, (char *) p, llen); + p += llen - 1; + } + sp += llen; + } + *sp = '\0'; + + return (uint8_t *) str; +} + +// ----- RR list & group functions ----- + +void rr_entry_destroy(struct rr_entry *rr) { + struct rr_data_txt *txt_rec; + assert(rr); + + // check rr_type and free data elements + switch (rr->type) { + case RR_PTR: + if (rr->data.PTR.name) + free(rr->data.PTR.name); + // don't free entry + break; + + case RR_TXT: + txt_rec = &rr->data.TXT; + while (txt_rec) { + struct rr_data_txt *next = txt_rec->next; + if (txt_rec->txt) + free(txt_rec->txt); + + // only free() if it wasn't part of the struct + if (txt_rec != &rr->data.TXT) + free(txt_rec); + + txt_rec = next; + } + break; + + case RR_SRV: + if (rr->data.SRV.target) + free(rr->data.SRV.target); + break; + + default: + // nothing to free + break; + } + + free(rr->name); + free(rr); +} + +// destroys an RR list (and optionally, items) +void rr_list_destroy(struct rr_list *rr, char destroy_items) { + struct rr_list *rr_next; + + for (; rr; rr = rr_next) { + rr_next = rr->next; + if (destroy_items) + rr_entry_destroy(rr->e); + free(rr); + } +} + +int rr_list_count(struct rr_list *rr) { + int i = 0; + for (; rr; i++, rr = rr->next); + return i; +} + +struct rr_entry *rr_list_remove(struct rr_list **rr_head, struct rr_entry *rr) { + struct rr_list *le = *rr_head, *pe = NULL; + for (; le; le = le->next) { + if (le->e == rr) { + if (pe == NULL) { + *rr_head = le->next; + free(le); + return rr; + } else { + pe->next = le->next; + free(le); + return rr; + } + } + pe = le; + } + return NULL; +} + +// appends an rr_entry to an RR list +// if the RR is already in the list, it will not be added +// RRs are compared by memory location - not its contents +// return value of 0 means item not added +int rr_list_append(struct rr_list **rr_head, struct rr_entry *rr) { + struct rr_list *node = malloc(sizeof(struct rr_list)); + node->e = rr; + node->next = NULL; + + if (*rr_head == NULL) { + *rr_head = node; + } else { + struct rr_list *e = *rr_head, *taile; + for (; e; e = e->next) { + // already in list - don't add + if (e->e == rr) { + free(node); + return 0; + } + if (e->next == NULL) + taile = e; + } + taile->next = node; + } + return 1; +} + +#define FILL_RR_ENTRY(rr, _name, _type) \ + rr->name = _name; \ + rr->type = _type; \ + rr->ttl = DEFAULT_TTL; \ + rr->cache_flush = 1; \ + rr->rr_class = 1; + +struct rr_entry *rr_create_a(uint8_t *name, uint32_t addr) { + DECL_MALLOC_ZERO_STRUCT(rr, rr_entry); + FILL_RR_ENTRY(rr, name, RR_A); + rr->data.A.addr = addr; + return rr; +} + +struct rr_entry *rr_create_srv(uint8_t *name, uint16_t port, uint8_t *target) { + DECL_MALLOC_ZERO_STRUCT(rr, rr_entry); + FILL_RR_ENTRY(rr, name, RR_SRV); + rr->data.SRV.port = port; + rr->data.SRV.target = target; + return rr; +} + +struct rr_entry *rr_create_ptr(uint8_t *name, struct rr_entry *d_rr) { + DECL_MALLOC_ZERO_STRUCT(rr, rr_entry); + FILL_RR_ENTRY(rr, name, RR_PTR); + rr->data.PTR.entry = d_rr; + return rr; +} + +struct rr_entry *rr_create(uint8_t *name, enum rr_type type) { + DECL_MALLOC_ZERO_STRUCT(rr, rr_entry); + FILL_RR_ENTRY(rr, name, type); + return rr; +} + +void rr_set_nsec(struct rr_entry *rr_nsec, enum rr_type type) { + assert(rr_nsec->type = RR_NSEC); + assert((type / 8) < sizeof(rr_nsec->data.NSEC.bitmap)); + + rr_nsec->data.NSEC.bitmap[ type / 8 ] = 1 << (7 - (type % 8)); +} + +void rr_add_txt(struct rr_entry *rr_txt, const char *txt) { + struct rr_data_txt *txt_rec; + assert(rr_txt->type == RR_TXT); + + txt_rec = &rr_txt->data.TXT; + + // is current data filled? + if (txt_rec->txt == NULL) { + txt_rec->txt = create_label(txt); + return; + } + + // find the last node + for (; txt_rec->next; txt_rec = txt_rec->next); + + // create a new empty node + txt_rec->next = malloc(sizeof(struct rr_data_txt)); + + txt_rec = txt_rec->next; + txt_rec->txt = create_label(txt); + txt_rec->next = NULL; +} + +// adds a record to an rr_group +void rr_group_add(struct rr_group **group, struct rr_entry *rr) { + struct rr_group *g; + + assert(rr != NULL); + + if (*group) { + g = rr_group_find(*group, rr->name); + if (g) { + rr_list_append(&g->rr, rr); + return; + } + } + + MALLOC_ZERO_STRUCT(g, rr_group); + g->name = dup_nlabel(rr->name); + rr_list_append(&g->rr, rr); + + // prepend to list + g->next = *group; + *group = g; +} + +// finds a rr_group matching the given name +struct rr_group *rr_group_find(struct rr_group* g, uint8_t *name) { + for (; g; g = g->next) { + if (cmp_nlabel(g->name, name) == 0) + return g; + } + return NULL; +} + +struct rr_entry *rr_entry_find(struct rr_list *rr_list, uint8_t *name, uint16_t type) { + struct rr_list *rr = rr_list; + for (; rr; rr = rr->next) { + if (rr->e->type == type) + return rr->e; + } + return NULL; +} + +void rr_group_destroy(struct rr_group *group) { + struct rr_group *g = group; + + while (g) { + struct rr_group *nextg = g->next; + free(g->name); + rr_list_destroy(g->rr, 1); + free(g); + g = nextg; + } +} + +// initialize the packet for reply +// clears the packet of list structures but not its list items +void mdns_init_reply(struct mdns_pkt *pkt, uint16_t id) { + // copy transaction ID + pkt->id = id; + + // response flags + pkt->flags = MDNS_FLAG_RESP | MDNS_FLAG_AA; + + rr_list_destroy(pkt->rr_qn, 0); + rr_list_destroy(pkt->rr_ans, 0); + rr_list_destroy(pkt->rr_auth, 0); + rr_list_destroy(pkt->rr_add, 0); + + pkt->rr_qn = NULL; + pkt->rr_ans = NULL; + pkt->rr_auth = NULL; + pkt->rr_add = NULL; + + pkt->num_qn = 0; + pkt->num_ans_rr = 0; + pkt->num_auth_rr = 0; + pkt->num_add_rr = 0; +} + +// destroys an mdns_pkt struct, including its contents +void mdns_pkt_destroy(struct mdns_pkt *p) { + rr_list_destroy(p->rr_qn, 1); + rr_list_destroy(p->rr_ans, 1); + rr_list_destroy(p->rr_auth, 1); + rr_list_destroy(p->rr_add, 1); + + free(p); +} + + +// parse the MDNS questions section +// stores the parsed data in the given mdns_pkt struct +static size_t mdns_parse_qn(uint8_t *pkt_buf, size_t pkt_len, size_t off, + struct mdns_pkt *pkt) { + const uint8_t *p = pkt_buf + off; + struct rr_entry *rr; + uint8_t *name; + + assert(pkt != NULL); + + rr = malloc(sizeof(struct rr_entry)); + memset(rr, 0, sizeof(struct rr_entry)); + + name = uncompress_nlabel(pkt_buf, pkt_len, off); + p += label_len(pkt_buf, pkt_len, off); + rr->name = name; + + rr->type = ntohs( * (uint16_t *) p ); + p += sizeof(uint16_t); + + rr->unicast_query = (*p & 0x80) == 0x80; + rr->rr_class = ntohs( * (uint16_t *) p) & ~0x80; + p += sizeof(uint16_t); + + rr_list_append(&pkt->rr_qn, rr); + + return p - (pkt_buf + off); +} + +// parse the MDNS RR section +// stores the parsed data in the given mdns_pkt struct +static size_t mdns_parse_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off, + struct mdns_pkt *pkt) { + const uint8_t *p = pkt_buf + off; + const uint8_t *e = pkt_buf + pkt_len; + struct rr_entry *rr; + uint8_t *name; + size_t rr_data_len = 0; + struct rr_data_txt *txt_rec; + + assert(pkt != NULL); + + if (off > pkt_len) + return 0; + + rr = malloc(sizeof(struct rr_entry)); + memset(rr, 0, sizeof(struct rr_entry)); + + name = uncompress_nlabel(pkt_buf, pkt_len, off); + p += label_len(pkt_buf, pkt_len, off); + rr->name = name; + + rr->type = ntohs( * (uint16_t *) p ); + p += sizeof(uint16_t); + + rr->cache_flush = (*p & 0x80) == 0x80; + rr->rr_class = ntohs( * (uint16_t *) p) & ~0x80; + p += sizeof(uint16_t); + + rr->ttl = ntohl( * (uint32_t *) p ); + p += sizeof(uint32_t); + + // RR data + rr_data_len = ntohs( * (uint16_t *) p ); + p += sizeof(uint16_t); + e = p + rr_data_len; + + // see if we can parse the RR data + switch (rr->type) { + case RR_A: + rr->data.A.addr = ntohl( * (uint32_t *) p ); + p += sizeof(uint32_t); + break; + + case RR_PTR: + rr->data.PTR.name = uncompress_nlabel(pkt_buf, pkt_len, p - pkt_buf); + p += rr_data_len; + break; + + case RR_TXT: + txt_rec = &rr->data.TXT; + while (1) { + txt_rec->txt = copy_label(pkt_buf, pkt_len, p - pkt_buf); + p += txt_rec->txt[0] + 1; + + if (p >= e) + break; + + // allocate another record + txt_rec->next = malloc(sizeof(struct rr_data_txt)); + txt_rec = txt_rec->next; + txt_rec->next = NULL; + } + break; + + default: + // skip to end of RR data + p = e; + } + + rr_list_append(&pkt->rr_ans, rr); + + return p - (pkt_buf + off); +} + +// parse a MDNS packet into an mdns_pkt struct +struct mdns_pkt *mdns_parse_pkt(uint8_t *pkt_buf, size_t pkt_len) { + uint16_t *p = (uint16_t *) pkt_buf; + size_t off; + struct mdns_pkt *pkt; + int i; + + if (pkt_len < 12) + return NULL; + + MALLOC_ZERO_STRUCT(pkt, mdns_pkt); + + // parse header + pkt->id = ntohs(*p); p++; + pkt->flags = ntohs(*p); p++; + pkt->num_qn = ntohs(*p); p++; + pkt->num_ans_rr = ntohs(*p); p++; + pkt->num_auth_rr = ntohs(*p); p++; + pkt->num_add_rr = ntohs(*p); p++; + + off = (uint8_t *) p - pkt_buf; + + // parse questions + for (i = 0; i < pkt->num_qn; i++) { + size_t l = mdns_parse_qn(pkt_buf, pkt_len, off, pkt); + if (! l) { + DEBUG_PRINTF("error parsing question #%d\n", i); + mdns_pkt_destroy(pkt); + return NULL; + } + + off += l; + } + + // parse answer RRs + for (i = 0; i < pkt->num_ans_rr; i++) { + size_t l = mdns_parse_rr(pkt_buf, pkt_len, off, pkt); + if (! l) { + DEBUG_PRINTF("error parsing answer #%d\n", i); + mdns_pkt_destroy(pkt); + return NULL; + } + + off += l; + } + + // TODO: parse the authority and additional RR sections + + return pkt; +} + +// encodes a name (label) into a packet using the name compression scheme +// encoded names will be added to the compression list for subsequent use +static size_t mdns_encode_name(uint8_t *pkt_buf, size_t pkt_len, size_t off, + const uint8_t *name, struct name_comp *comp) { + struct name_comp *c, *c_tail = NULL; + uint8_t *p = pkt_buf + off; + size_t len = 0; + + if (name) { + while (*name) { + // find match for compression + for (c = comp; c; c = c->next) { + if (cmp_nlabel(name, c->label) == 0) { + *(uint16_t *) p = htons(0xC000 | (c->pos & ~0xC000)); + return len + sizeof(uint16_t); + } + + if (c->next == NULL) + c_tail = c; + } + + // copy this segment + int segment_len = *name + 1; + strncpy((char *) p, (char *) name, segment_len); + + // cache the name for subsequent compression + DECL_MALLOC_ZERO_STRUCT(new_c, name_comp); + + new_c->label = (uint8_t *) name; + new_c->pos = p - pkt_buf; + c_tail->next = new_c; + + // advance to next name segment + p += segment_len; + len += segment_len; + name += segment_len; + } + } + + *p = '\0'; // root "label" + len += 1; + + return len; +} + +// encodes an RR entry at the given offset +// returns the size of the entire RR entry +static size_t mdns_encode_rr(uint8_t *pkt_buf, size_t pkt_len, size_t off, + struct rr_entry *rr, struct name_comp *comp) { + uint8_t *p = pkt_buf + off, *p_data; + size_t l; + struct rr_data_txt *txt_rec; + uint8_t *label; + int i; + + assert(off < pkt_len); + + // name + l = mdns_encode_name(pkt_buf, pkt_len, off, rr->name, comp); + assert(l != 0); + p += l; + + // type + *(uint16_t *) p = htons(rr->type); + p += sizeof(uint16_t); + + // class & cache flush + *(uint16_t *) p = htons((rr->rr_class & ~0x8000) | (rr->cache_flush << 15)); + p += sizeof(uint16_t); + + // TTL + *(uint32_t *) p = htonl(rr->ttl); + p += sizeof(uint32_t); + + // data length (filled in later) + p += sizeof(uint16_t); + + // start of data marker + p_data = p; + + switch (rr->type) { + case RR_A: + *(uint32_t *) p = (rr->data.A.addr); + p += sizeof(uint32_t); + break; + + case RR_PTR: + label = rr->data.PTR.name ? + rr->data.PTR.name : + rr->data.PTR.entry->name; + p += mdns_encode_name(pkt_buf, pkt_len, p - pkt_buf, label, comp); + break; + + case RR_TXT: + txt_rec = &rr->data.TXT; + for (; txt_rec; txt_rec = txt_rec->next) { + int len = txt_rec->txt[0] + 1; + strncpy((char *) p, (char *) txt_rec->txt, len); + p += len; + } + break; + + case RR_SRV: + *(uint16_t *) p = htons(rr->data.SRV.priority); + p += sizeof(uint16_t); + + *(uint16_t *) p = htons(rr->data.SRV.weight); + p += sizeof(uint16_t); + + *(uint16_t *) p = htons(rr->data.SRV.port); + p += sizeof(uint16_t); + + p += mdns_encode_name(pkt_buf, pkt_len, p - pkt_buf, + rr->data.SRV.target, comp); + break; + + case RR_NSEC: + p += mdns_encode_name(pkt_buf, pkt_len, p - pkt_buf, + rr->name, comp); + + *p++ = 0; // bitmap window/block number + + *p++ = sizeof(rr->data.NSEC.bitmap); // bitmap length + + for (i = 0; i < sizeof(rr->data.NSEC.bitmap); i++) + *p++ = rr->data.NSEC.bitmap[i]; + + break; + + default: + DEBUG_PRINTF("unhandled rr type 0x%02x\n", rr->type); + } + + // calculate data length based on p + l = p - p_data; + + // fill in the length + *(uint16_t *) (p - l - sizeof(uint16_t)) = htons(l); + + return p - pkt_buf - off; +} + +// encodes a MDNS packet from the given mdns_pkt struct into a buffer +// returns the size of the entire MDNS packet +size_t mdns_encode_pkt(struct mdns_pkt *answer, uint8_t *pkt_buf, size_t pkt_len) { + struct name_comp *comp; + uint16_t *p = (uint16_t *) pkt_buf; + //uint8_t *e = pkt_buf + pkt_len; + size_t off; + int i; + + assert(answer != NULL); + assert(pkt_len >= 12); + + if (p == NULL) + return -1; + + // this is an Answer - number of qns should be zero + assert(answer->num_qn == 0); + + *p++ = htons(answer->id); + *p++ = htons(answer->flags); + *p++ = htons(answer->num_qn); + *p++ = htons(answer->num_ans_rr); + *p++ = htons(answer->num_auth_rr); + *p++ = htons(answer->num_add_rr); + + off = (uint8_t *) p - pkt_buf; + + // allocate list for name compression + comp = malloc(sizeof(struct name_comp)); + if (comp == NULL) + return -1; + memset(comp, 0, sizeof(struct name_comp)); + + // dummy entry + comp->label = (uint8_t *) ""; + comp->pos = 0; + + // skip encoding of qn + + struct rr_list *rr_set[] = { + answer->rr_ans, + answer->rr_auth, + answer->rr_add + }; + + // encode answer, authority and additional RRs + for (i = 0; i < sizeof(rr_set) / sizeof(rr_set[0]); i++) { + struct rr_list *rr = rr_set[i]; + for (; rr; rr = rr->next) { + size_t l = mdns_encode_rr(pkt_buf, pkt_len, off, rr->e, comp); + off += l; + + if (off >= pkt_len) { + DEBUG_PRINTF("packet buffer too small\n"); + return -1; + } + } + + } + + // free name compression list + while (comp) { + struct name_comp *c = comp->next; + free(comp); + comp = c; + } + + return off; +} + diff --git a/mdns.h b/mdns.h new file mode 100644 index 0000000..afd7474 --- /dev/null +++ b/mdns.h @@ -0,0 +1,169 @@ +/* + * tinysvcmdns - a tiny MDNS implementation for publishing services + * Copyright (C) 2011 Darell Tan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __MDNS_H__ +#define __MDNS_H__ + +#include +#include + +#define MALLOC_ZERO_STRUCT(x, type) \ + x = malloc(sizeof(struct type)); \ + memset(x, 0, sizeof(struct type)); + +#define DECL_MALLOC_ZERO_STRUCT(x, type) \ + struct type * MALLOC_ZERO_STRUCT(x, type) + +#ifndef NDEBUG + #define DEBUG_PRINTF(...) printf(__VA_ARGS__) +#else + #define DEBUG_PRINTF(...) ((void) 0) +#endif + + +struct rr_data_srv { + uint16_t priority; + uint16_t weight; + uint16_t port; + uint8_t *target; // host +}; + +struct rr_data_txt { + struct rr_data_txt *next; + uint8_t *txt; +}; + +struct rr_data_nsec { + //uint8_t *name; // same as record + + // NSEC occupies the 47th bit, 5 bytes + //uint8_t bitmap_len; // = 5 + uint8_t bitmap[5]; // network order: first byte contains LSB +}; + +struct rr_data_ptr { + uint8_t *name; // NULL if entry is to be used + struct rr_entry *entry; +}; + +struct rr_data_a { + uint32_t addr; +}; + +struct rr_entry { + uint8_t *name; + + enum rr_type { + RR_A = 0x01, + RR_PTR = 0x0C, + RR_TXT = 0x10, + RR_AAAA = 0x1C, + RR_SRV = 0x21, + RR_NSEC = 0x2F, + RR_ANY = 0xFF, + } type; + + uint32_t ttl; + + // for use in Questions only + char unicast_query; + + // for use in Answers only + char cache_flush; + + uint16_t rr_class; + + // RR data + union { + struct rr_data_nsec NSEC; + struct rr_data_srv SRV; + struct rr_data_txt TXT; + struct rr_data_ptr PTR; + struct rr_data_a A; + } data; +}; + +struct rr_list { + struct rr_entry *e; + struct rr_list *next; +}; + +struct rr_group { + uint8_t *name; + + struct rr_list *rr; + + struct rr_group *next; +}; + +#define MDNS_FLAG_RESP (1 << 15) // Query=0 / Response=1 +#define MDNS_FLAG_AA (1 << 10) // Authoritative +#define MDNS_FLAG_TC (1 << 9) // TrunCation +#define MDNS_FLAG_RD (1 << 8) // Recursion Desired +#define MDNS_FLAG_RA (1 << 7) // Recursion Available +#define MDNS_FLAG_Z (1 << 6) // Reserved (zero) + +#define MDNS_FLAG_GET_RCODE(x) (x & 0x0F) +#define MDNS_FLAG_GET_OPCODE(x) ((x >> 11) & 0x0F) + +struct mdns_pkt { + uint16_t id; // transaction ID + uint16_t flags; + uint16_t num_qn; + uint16_t num_ans_rr; + uint16_t num_auth_rr; + uint16_t num_add_rr; + + struct rr_list *rr_qn; // questions + struct rr_list *rr_ans; // answer RRs + struct rr_list *rr_auth; // authority RRs + struct rr_list *rr_add; // additional RRs +}; + +struct mdns_pkt *mdns_parse_pkt(uint8_t *pkt_buf, size_t pkt_len); + +void mdns_init_reply(struct mdns_pkt *pkt, uint16_t id); +size_t mdns_encode_pkt(struct mdns_pkt *answer, uint8_t *pkt_buf, size_t pkt_len); + +void mdns_pkt_destroy(struct mdns_pkt *p); +void rr_group_destroy(struct rr_group *group); +struct rr_group *rr_group_find(struct rr_group *g, uint8_t *name); +struct rr_entry *rr_entry_find(struct rr_list *rr_list, uint8_t *name, uint16_t type); +void rr_group_add(struct rr_group **group, struct rr_entry *rr); + +int rr_list_count(struct rr_list *rr); +int rr_list_append(struct rr_list **rr_head, struct rr_entry *rr); +struct rr_entry *rr_list_remove(struct rr_list **rr_head, struct rr_entry *rr); +void rr_list_destroy(struct rr_list *rr, char destroy_items); + +struct rr_entry *rr_create_ptr(uint8_t *name, struct rr_entry *d_rr); +struct rr_entry *rr_create_srv(uint8_t *name, uint16_t port, uint8_t *target); +struct rr_entry *rr_create_a(uint8_t *name, uint32_t addr); +struct rr_entry *rr_create(uint8_t *name, enum rr_type type); +void rr_set_nsec(struct rr_entry *rr_nsec, enum rr_type type); +void rr_add_txt(struct rr_entry *rr_txt, const char *txt); + +uint8_t *create_label(const char *txt); +uint8_t *create_nlabel(const char *name); +char *nlabel_to_str(const uint8_t *name); +uint8_t *dup_label(const uint8_t *label); +uint8_t *dup_nlabel(const uint8_t *n); +uint8_t *join_nlabel(const uint8_t *n1, const uint8_t *n2); + +#endif /*!__MDNS_H__*/ diff --git a/mdnsd.c b/mdnsd.c new file mode 100644 index 0000000..1f6b916 --- /dev/null +++ b/mdnsd.c @@ -0,0 +1,555 @@ +/* + * tinysvcmdns - a tiny MDNS implementation for publishing services + * Copyright (C) 2011 Darell Tan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mdns.h" +#include "mdnsd.h" + +#define MDNS_ADDR "224.0.0.251" +#define MDNS_PORT 5353 + +#define PACKET_SIZE 65536 + +#define SERVICES_DNS_SD_NLABEL \ + ((uint8_t *) "\x09_services\x07_dns-sd\x04_udp\x05local") + +struct mdnsd { + pthread_mutex_t data_lock; + int sockfd; + int notify_pipe[2]; + int stop_flag; + + struct rr_group *group; + struct rr_list *announce; + struct rr_list *services; + uint8_t *hostname; +}; + +struct mdns_service { + struct rr_list *entries; +}; + +///////////////////////////////// + + +static void log_message(int loglevel, char *fmt_str, ...) { + va_list ap; + char buf[2048]; + + va_start(ap, fmt_str); + vsnprintf(buf, 2047, fmt_str, ap); + va_end(ap); + buf[2047] = 0; + + fprintf(stderr, "%s\n", buf); +} + +static int create_recv_sock() { + int sd = socket(AF_INET, SOCK_DGRAM, 0); + if (sd < 0) { + log_message(LOG_ERR, "recv socket(): %m"); + return sd; + } + + int r = -1; + + int on = 1; + if ((r = setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on))) < 0) { + log_message(LOG_ERR, "recv setsockopt(SO_REUSEADDR): %m"); + return r; + } + + /* bind to an address */ + struct sockaddr_in serveraddr; + memset(&serveraddr, 0, sizeof(serveraddr)); + serveraddr.sin_family = AF_INET; + serveraddr.sin_port = htons(MDNS_PORT); + serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); /* receive multicast */ + if ((r = bind(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0) { + log_message(LOG_ERR, "recv bind(): %m"); + } + + // add membership to receiving socket + struct ip_mreq mreq; + memset(&mreq, 0, sizeof(struct ip_mreq)); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + mreq.imr_multiaddr.s_addr = inet_addr(MDNS_ADDR); + if ((r = setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) { + log_message(LOG_ERR, "recv setsockopt(IP_ADD_MEMBERSHIP): %m"); + return r; + } + + // enable loopback in case someone else needs the data + if ((r = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *) &on, sizeof(on))) < 0) { + log_message(LOG_ERR, "recv setsockopt(IP_MULTICAST_LOOP): %m"); + return r; + } + + +#ifdef IP_PKTINFO + if ((r = setsockopt(sd, SOL_IP, IP_PKTINFO, (char *) &on, sizeof(on))) < 0) { + log_message(LOG_ERR, "recv setsockopt(IP_PKTINFO): %m"); + return r; + } +#endif + + return sd; +} + +static ssize_t send_packet(int fd, const void *data, size_t len) { + static struct sockaddr_in toaddr; + if (toaddr.sin_family != AF_INET) { + memset(&toaddr, 0, sizeof(struct sockaddr_in)); + toaddr.sin_family = AF_INET; + toaddr.sin_port = htons(MDNS_PORT); + toaddr.sin_addr.s_addr = inet_addr(MDNS_ADDR); + } + + return sendto(fd, data, len, 0, (struct sockaddr *) &toaddr, sizeof(struct sockaddr_in)); +} + + +// populate the specified list which matches the RR name and type +// type can be RR_ANY, which populates all entries EXCEPT RR_NSEC +static int populate_answers(struct mdnsd *svr, struct rr_list **rr_head, uint8_t *name, enum rr_type type) { + int num_ans = 0; + struct rr_entry *rr; + + // check if we have the records + pthread_mutex_lock(&svr->data_lock); + struct rr_group *ans_grp = rr_group_find(svr->group, name); + if (ans_grp == NULL) { + pthread_mutex_unlock(&svr->data_lock); + return num_ans; + } + + // include all records? + if (type == RR_ANY) { + struct rr_list *n = ans_grp->rr; + for (; n; n = n->next) { + // exclude NSEC + if (n->e->type == RR_NSEC) + continue; + + num_ans += rr_list_append(rr_head, n->e); + } + } else { + // match record type + rr = rr_entry_find(ans_grp->rr, name, type); + if (rr) + num_ans += rr_list_append(rr_head, rr); + } + pthread_mutex_unlock(&svr->data_lock); + + return num_ans; +} + +// given a list of RRs, look up related records and add them +static void add_related_rr(struct mdnsd *svr, struct rr_list *list, struct mdns_pkt *reply) { + for (; list; list = list->next) { + struct rr_entry *ans = list->e; + + switch (ans->type) { + case RR_PTR: + // target host A, AAAA records + reply->num_add_rr += populate_answers(svr, &reply->rr_add, + (ans->data.PTR.name ? + ans->data.PTR.name : + ans->data.PTR.entry->name), + RR_ANY); + break; + + case RR_SRV: + // target host A, AAAA records + reply->num_add_rr += populate_answers(svr, &reply->rr_add, + ans->data.SRV.target, RR_ANY); + + // perhaps TXT records of the same name? + // if we use RR_ANY, we risk pulling in the same RR_SRV + reply->num_add_rr += populate_answers(svr, &reply->rr_add, + ans->name, RR_TXT); + break; + + case RR_A: + case RR_AAAA: + reply->num_add_rr += populate_answers(svr, &reply->rr_add, + ans->name, RR_NSEC); + break; + + default: + // nothing to add + break; + } + } +} + +// creates an announce packet given the type name PTR +static void announce_srv(struct mdnsd *svr, struct mdns_pkt *reply, uint8_t *name) { + mdns_init_reply(reply, 0); + + reply->num_ans_rr += populate_answers(svr, &reply->rr_ans, name, RR_PTR); + + // remember to add the services dns-sd PTR too + reply->num_ans_rr += populate_answers(svr, &reply->rr_ans, + SERVICES_DNS_SD_NLABEL, RR_PTR); + + // see if we can match additional records for answers + add_related_rr(svr, reply->rr_ans, reply); + + // additional records for additional records + add_related_rr(svr, reply->rr_add, reply); +} + +// processes the incoming MDNS packet +// returns >0 if processed, 0 otherwise +static int process_mdns_pkt(struct mdnsd *svr, struct mdns_pkt *pkt, struct mdns_pkt *reply) { + int i; + + assert(pkt != NULL); + + // is it standard query? + if ((pkt->flags & MDNS_FLAG_RESP) == 0 && + MDNS_FLAG_GET_OPCODE(pkt->flags) == 0) { + mdns_init_reply(reply, pkt->id); + + DEBUG_PRINTF("flags = %04x, qn = %d, ans = %d, add = %d\n", + pkt->flags, + pkt->num_qn, + pkt->num_ans_rr, + pkt->num_add_rr); + + // loop through questions + struct rr_list *qnl = pkt->rr_qn; + for (i = 0; i < pkt->num_qn; i++, qnl = qnl->next) { + struct rr_entry *qn = qnl->e; + char *namestr = nlabel_to_str(qn->name); + DEBUG_PRINTF("qn #%d: type 0x%02x %s - ", i, qn->type, namestr); + free(namestr); + + // check if it's a unicast query - we ignore those + if (qn->unicast_query) { + DEBUG_PRINTF("skipping unicast query\n"); + continue; + } + + // see if it is in the answers + if (rr_entry_find(pkt->rr_ans, qn->name, qn->type)) { + DEBUG_PRINTF("our record is already in their answers\n"); + continue; + } + + reply->num_ans_rr += populate_answers(svr, &reply->rr_ans, qn->name, qn->type); + + DEBUG_PRINTF("adding %d answers\n", reply->num_ans_rr); + } + + // see if we can match additional records for answers + add_related_rr(svr, reply->rr_ans, reply); + + // additional records for additional records + add_related_rr(svr, reply->rr_add, reply); + + DEBUG_PRINTF("\n"); + + return reply->num_ans_rr; + } + + return 0; +} + +// main loop to receive, process and send out MDNS replies +// also handles MDNS service announces +static void main_loop(struct mdnsd *svr) { + fd_set sockfd_set; + int max_fd = svr->sockfd; + + void *pkt_buffer = malloc(PACKET_SIZE); + + if (svr->notify_pipe[0] > max_fd) + max_fd = svr->notify_pipe[0]; + + struct mdns_pkt *mdns_reply = malloc(sizeof(struct mdns_pkt)); + memset(mdns_reply, 0, sizeof(struct mdns_pkt)); + + while (! svr->stop_flag) { + struct timeval tv = { + .tv_sec = 0, + .tv_usec = 0, + }; + + FD_ZERO(&sockfd_set); + FD_SET(svr->sockfd, &sockfd_set); + FD_SET(svr->notify_pipe[0], &sockfd_set); + select(max_fd + 1, &sockfd_set, NULL, NULL, &tv); + + if (FD_ISSET(svr->sockfd, &sockfd_set)) { + struct sockaddr_in fromaddr; + socklen_t sockaddr_size = sizeof(struct sockaddr_in); + + ssize_t recvsize = recvfrom(svr->sockfd, pkt_buffer, PACKET_SIZE, 0, + (struct sockaddr *) &fromaddr, &sockaddr_size); + if (recvsize < 0) { + log_message(LOG_ERR, "recv(): %m"); + } + + DEBUG_PRINTF("data from=%s size=%ld\n", inet_ntoa(fromaddr.sin_addr), (long) recvsize); + struct mdns_pkt *mdns = mdns_parse_pkt(pkt_buffer, recvsize); + if (mdns != NULL) { + if (process_mdns_pkt(svr, mdns, mdns_reply)) { + size_t replylen = mdns_encode_pkt(mdns_reply, pkt_buffer, PACKET_SIZE); + send_packet(svr->sockfd, pkt_buffer, replylen); + } + + mdns_pkt_destroy(mdns); + } + } + + // send out announces + while (1) { + struct rr_entry *ann_e = NULL; + + // extract from head of list + pthread_mutex_lock(&svr->data_lock); + if (svr->announce) + ann_e = rr_list_remove(&svr->announce, svr->announce->e); + pthread_mutex_unlock(&svr->data_lock); + + if (! ann_e) + break; + + char *namestr = nlabel_to_str(ann_e->name); + DEBUG_PRINTF("sending announce for %s\n", namestr); + free(namestr); + + announce_srv(svr, mdns_reply, ann_e->name); + + if (mdns_reply->num_ans_rr > 0) { + size_t replylen = mdns_encode_pkt(mdns_reply, pkt_buffer, PACKET_SIZE); + send_packet(svr->sockfd, pkt_buffer, replylen); + } + } + } + + // main thread terminating. send out "goodbye packets" for services + mdns_init_reply(mdns_reply, 0); + + pthread_mutex_lock(&svr->data_lock); + struct rr_list *svc_le = svr->services; + for (; svc_le; svc_le = svc_le->next) { + // set TTL to zero + svc_le->e->ttl = 0; + mdns_reply->num_ans_rr += rr_list_append(&mdns_reply->rr_ans, svc_le->e); + } + pthread_mutex_unlock(&svr->data_lock); + + // send out packet + if (mdns_reply->num_ans_rr > 0) { + size_t replylen = mdns_encode_pkt(mdns_reply, pkt_buffer, PACKET_SIZE); + send_packet(svr->sockfd, pkt_buffer, replylen); + } + + // destroy packet + mdns_init_reply(mdns_reply, 0); + free(mdns_reply); + + free(pkt_buffer); + + close(svr->sockfd); + + svr->stop_flag = 2; +} + +///////////////////////////////////////////////////// + + +void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip) { + struct rr_entry *a_e = NULL, + *nsec_e = NULL; + + // currently can't be called twice + // dont ask me what happens if the IP changes + assert(svr->hostname == NULL); + + a_e = rr_create_a(create_nlabel(hostname), ip); + + nsec_e = rr_create(create_nlabel(hostname), RR_NSEC); + rr_set_nsec(nsec_e, RR_A); + + pthread_mutex_lock(&svr->data_lock); + svr->hostname = create_nlabel(hostname); + rr_group_add(&svr->group, a_e); + rr_group_add(&svr->group, nsec_e); + pthread_mutex_unlock(&svr->data_lock); +} + +struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_name, + const char *type, uint16_t port, const char *hostname, const char *txt[]) { + struct rr_entry *txt_e = NULL, + *srv_e = NULL, + *ptr_e = NULL, + *bptr_e = NULL; + uint8_t *target; + uint8_t *inst_nlabel, *type_nlabel, *nlabel; + struct mdns_service *service = malloc(sizeof(struct mdns_service)); + memset(service, 0, sizeof(struct mdns_service)); + + // combine service name + type_nlabel = create_nlabel(type); + inst_nlabel = create_nlabel(instance_name); + nlabel = join_nlabel(inst_nlabel, type_nlabel); + + // create TXT record + if (txt && *txt) { + txt_e = rr_create(dup_nlabel(nlabel), RR_TXT); + rr_list_append(&service->entries, txt_e); + + // add TXTs + for (; *txt; txt++) + rr_add_txt(txt_e, *txt); + } + + // create SRV record + assert(hostname || svr->hostname); // either one as target + target = hostname ? + create_nlabel(hostname) : + dup_nlabel(svr->hostname); + + srv_e = rr_create_srv(dup_nlabel(nlabel), port, target); + rr_list_append(&service->entries, srv_e); + + // create PTR record for type + ptr_e = rr_create_ptr(type_nlabel, srv_e); + + // create services PTR record for type + // this enables the type to show up as a "service" + bptr_e = rr_create_ptr(dup_nlabel(SERVICES_DNS_SD_NLABEL), ptr_e); + + // modify lists here + pthread_mutex_lock(&svr->data_lock); + + if (txt_e) + rr_group_add(&svr->group, txt_e); + rr_group_add(&svr->group, srv_e); + rr_group_add(&svr->group, ptr_e); + rr_group_add(&svr->group, bptr_e); + + // append PTR entry to announce list + rr_list_append(&svr->announce, ptr_e); + rr_list_append(&svr->services, ptr_e); + + pthread_mutex_unlock(&svr->data_lock); + + // don't free type_nlabel - it's with the PTR record + free(nlabel); + free(inst_nlabel); + + // notify server + write(svr->notify_pipe[1], ".", 1); + + return service; +} + +void mdns_service_destroy(struct mdns_service *srv) { + assert(srv != NULL); + rr_list_destroy(srv->entries, 0); + free(srv); +} + +struct mdnsd *mdnsd_start() { + pthread_t tid; + pthread_attr_t attr; + + struct mdnsd *server = malloc(sizeof(struct mdnsd)); + memset(server, 0, sizeof(struct mdnsd)); + + if (pipe(server->notify_pipe) != 0) { + log_message(LOG_ERR, "pipe(): %m\n"); + free(server); + return NULL; + } + + server->sockfd = create_recv_sock(); + if (server->sockfd < 0) { + log_message(LOG_ERR, "unable to create recv socket"); + free(server); + return NULL; + } + + pthread_mutex_init(&server->data_lock, NULL); + + // init thread + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + if (pthread_create(&tid, &attr, (void *(*)(void *)) main_loop, (void *) server) != 0) { + pthread_mutex_destroy(&server->data_lock); + free(server); + return NULL; + } + + return server; +} + +void mdnsd_stop(struct mdnsd *s) { + assert(s != NULL); + + struct timeval tv = { + .tv_sec = 0, + .tv_usec = 500 * 1000, + }; + + s->stop_flag = 1; + write(s->notify_pipe[1], ".", 1); + + while (s->stop_flag != 2) + select(0, NULL, NULL, NULL, &tv); + + close(s->notify_pipe[0]); + close(s->notify_pipe[1]); + + pthread_mutex_destroy(&s->data_lock); + rr_group_destroy(s->group); + rr_list_destroy(s->announce, 0); + rr_list_destroy(s->services, 0); + + if (s->hostname) + free(s->hostname); + + free(s); +} + diff --git a/mdnsd.h b/mdnsd.h new file mode 100644 index 0000000..2a6fb39 --- /dev/null +++ b/mdnsd.h @@ -0,0 +1,46 @@ +/* + * tinysvcmdns - a tiny MDNS implementation for publishing services + * Copyright (C) 2011 Darell Tan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef __MDNSD_H__ +#define __MDNSD_H__ + +#include + +struct mdnsd; +struct mdns_service; + +// starts a MDNS responder instance +// returns NULL if unsuccessful +struct mdnsd *mdnsd_start(); + +// stops the given MDNS responder instance +void mdnsd_stop(struct mdnsd *s); + +// sets the hostname for the given MDNS responder instance +void mdnsd_set_hostname(struct mdnsd *svr, const char *hostname, uint32_t ip); + +// registers a service with the MDNS responder instance +struct mdns_service *mdnsd_register_svc(struct mdnsd *svr, const char *instance_name, + const char *type, uint16_t port, const char *hostname, const char *txt[]); + +// destroys the mdns_service struct returned by mdnsd_register_svc() +void mdns_service_destroy(struct mdns_service *srv); + + +#endif/*!__MDNSD_H__*/ diff --git a/testmdnsd.c b/testmdnsd.c new file mode 100644 index 0000000..0cce98e --- /dev/null +++ b/testmdnsd.c @@ -0,0 +1,56 @@ +/* + * tinysvcmdns - a tiny MDNS implementation for publishing services + * Copyright (C) 2011 Darell Tan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include "mdns.h" +#include "mdnsd.h" + +int main(int argc, char *argv[]) { + // create host entries + char *hostname = "some-random-host.local"; + + struct mdnsd *svr = mdnsd_start(); + if (svr == NULL) { + printf("mdnsd_start() error\n"); + return 1; + } + + printf("mdnsd_start OK. press ENTER to add hostname & service\n"); + getchar(); + + mdnsd_set_hostname(svr, hostname, inet_addr("192.168.0.29")); + + const char *txt[] = { + "path=/mywebsite", + NULL + }; + struct mdns_service *svc = mdnsd_register_svc(svr, "My Website", + "_http._tcp.local", 8080, NULL, txt); + mdns_service_destroy(svc); + + printf("added service and hostname. press ENTER to exit\n"); + getchar(); + + mdnsd_stop(svr); + + return 0; +} +