linux-igd-1.0+cvs20070630/0000755000175000017500000000000010760105250014555 5ustar leveretleveretlinux-igd-1.0+cvs20070630/doc/0000755000175000017500000000000010760105250015322 5ustar leveretleveretlinux-igd-1.0+cvs20070630/doc/config_options0000644000175000017500000000112110145464427020273 0ustar leveretleveretuprate ------ Upload speed in bytes, for example: uprate 128000 if not suplied defaults: 131072 downrate -------- Download speed in bytes, for example: uprate 512000 if not suplied defaults: 614400 port_forward ------------ Add forward rules. Forward is by default not ACCEPT. For example: port_forward yes if not suplied defaults: no X_Name ------ Name of the connection, for example: X_Name Local Area Connection if not suplied defaults: Local Area Connection OSMachineName ------------- Name of the machine, for example: OSMachineName Linux IGD if not suplied defaults: Linux IGD linux-igd-1.0+cvs20070630/etc/0000755000175000017500000000000010760105250015330 5ustar leveretleveretlinux-igd-1.0+cvs20070630/etc/gatedesc.xml0000644000175000017500000000635010562464535017653 0ustar leveretleveret 1 0 urn:schemas-upnp-org:device:InternetGatewayDevice:1 Linux Internet Gateway Device Linux UPnP IGD Project http://linux-igd.sourceforge.net IGD Version 1.00 uuid:75802409-bccb-40e7-8e6c-fa095ecce13e image/gif 118 119 8 /ligd.gif urn:schemas-dummy-com:service:Dummy:1 urn:dummy-com:serviceId:dummy1 /dummy /dummy /dummy.xml urn:schemas-upnp-org:device:WANDevice:1 WANDevice Linux UPnP IGD Project http://linux-igd.sourceforge.net WAN Device on Linux IGD Linux IGD 1.00 http://linux-igd.sourceforge.net 1.00 uuid:75802409-bccb-40e7-8e6c-fa095ecce13e Linux IGD urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1 urn:upnp-org:serviceId:WANCommonIFC1 /upnp/control/WANCommonIFC1 /upnp/control/WANCommonIFC1 /gateicfgSCPD.xml urn:schemas-upnp-org:device:WANConnectionDevice:1 WANConnectionDevice Linux UPnP IGD Project http://linux-igd.sourceforge.net WanConnectionDevice on Linux IGD Linux IGD 0.95 http://linux-igd.sourceforge.net 0.95 uuid:75802409-bccb-40e7-8e6c-fa095ecce13e Linux IGD urn:schemas-upnp-org:service:WANIPConnection:1 urn:upnp-org:serviceId:WANIPConn1 /upnp/control/WANIPConn1 /upnp/control/WANIPConn1 /gateconnSCPD.xml linux-igd-1.0+cvs20070630/etc/dummy.xml0000755000175000017500000000030307711613301017207 0ustar leveretleveret 1 0 linux-igd-1.0+cvs20070630/etc/upnpd.rc0000755000175000017500000000247510470455040017022 0ustar leveretleveret#!/bin/bash # # /etc/rc.d/init.d/upnpd # # Starts the upnpd daemon # # chkconfig: 345 95 5 # description: Internet Gateway Device # processname: upnpd # Source function library. . /etc/init.d/functions # defaults ALLOW_MULTICAST=no # Source configuration . /etc/sysconfig/upnpd UPNPD=/usr/sbin/upnpd test -x "$UPNPD" || exit 0 RETVAL=0 # # See how we were called. # prog="upnpd" start() { # Check if upnpd is already running if [ ! -f /var/lock/subsys/upnpd ]; then echo -n $"Starting $prog: " [ "$ALLOW_MULTICAST" != "no" ] && route add -net 239.0.0.0 netmask 255.0.0.0 $INTIFACE daemon "$UPNPD" $EXTIFACE $INTIFACE RETVAL=$? [ $RETVAL -eq 0 ] && touch /var/lock/subsys/upnpd echo fi return $RETVAL } stop() { echo -n $"Stopping $prog: " killproc "$UPNPD" RETVAL=$? [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/upnpd [ "$ALLOW_MULTICAST" != "no" ] && route del -net 239.0.0.0 netmask 255.0.0.0 $INTIFACE echo return $RETVAL } restart() { stop sleep 10 start } reload() { restart } status_at() { status "$UPNPD" } case "$1" in start) start ;; stop) stop ;; reload|restart) restart ;; condrestart) if [ -f /var/lock/subsys/upnpd ]; then restart fi ;; status) status_at ;; *) echo $"Usage: $0 {start|stop|restart|condrestart|status}" exit 1 esac exit $? linux-igd-1.0+cvs20070630/etc/gateicfgSCPD.xml0000644000175000017500000001032507711573267020321 0ustar leveretleveret 1 0 GetCommonLinkProperties NewWANAccessType out WANAccessType NewLayer1UpstreamMaxBitRate out Layer1UpstreamMaxBitRate NewLayer1DownstreamMaxBitRate out Layer1DownstreamMaxBitRate NewPhysicalLinkStatus out PhysicalLinkStatus GetTotalBytesSent NewTotalBytesSent out TotalBytesSent GetTotalBytesReceived NewTotalBytesReceived out TotalBytesReceived GetTotalPacketsSent NewTotalPacketsSent out TotalPacketsSent GetTotalPacketsReceived NewTotalPacketsReceived out TotalPacketsReceived WANAccessType string DSL POTS Cable Ethernet Other Layer1UpstreamMaxBitRate ui4 Layer1DownstreamMaxBitRate ui4 PhysicalLinkStatus string Up Down Initializing Unavailable WANAccessProvider string MaximumActiveConnections ui2 1 1 TotalBytesSent ui4 TotalBytesReceived ui4 TotalPacketsSent ui4 TotalPacketsReceived ui4 linux-igd-1.0+cvs20070630/etc/ligd.gif0000644000175000017500000000173707700660037016757 0ustar leveretleveretGIF89a޼Țݷݾ⑗t}~yπؗyzιiegɹathYsFk˙µÛڲɱLέAद@Ҩ9lᜢvwTD~ӗ˜4e59EsgK慏ËˊtDžb&{wzuUxwpujWpc^f[ems*glXR;Q`UeE C ?6!,HDDfD@- "7O"%064 QEFN83âBQ#Q!s(=`"F}$!B Y4z(/[L#Av A|B `p,W J TpSH-P@k 8#ZNxйt@;linux-igd-1.0+cvs20070630/etc/upnpd.conf0000644000175000017500000000536410641323364017343 0ustar leveretleveret# To change the interfaces used edit: # /etc/sysconfig/upnpd # # The full path and name of the iptables executable, # (enclosed in quotes). # iptables_location = "/sbin/iptables" # # Daemon debug level. Messages are logged via syslog to debug. # 0 - no debug messages # 1 - log errors # 2 - log errors and basic info # 3 - log errors and verbose info # default = 0 debug_mode = 2 # # Should the daemon create rules in the forward chain, or not. # This is necessary if your firewall has a drop or reject # policy in your forward chain. # allowed values: yes,no # default = no create_forward_rules = yes # # Should the daemon insert or append rules in the forward chain. # Normally you will want to insert rules at the beginning of the # forward chain, so that they apply before any drop or reject rules # later in the chain. # This option only applies if "create_forward_rules = yes". # # Tip: If you need to insert rules somewhere in the middle of the # FORWARD chain, instead of first or last, then you should create a # new empty chain, e.g forwardUPnP, and set forward_chain_name to that # chain. Then insert a rule to jump to forwardUPnP in the appropriate # place in the FORWARD chain. (The value of forward_rules_append # probably won't matter much in that case.) # # allowed values: yes,no # default = no forward_rules_append = no # # The name of the chain to put the forward rules in. # This option only applies if "create_forward_rules = yes". # allowed values: a-z, A-Z, _, - # default = FORWARD # forward_chain_name = FORWARD # # The name of the chain to put prerouting rules in. # allowed values: a-z, A-Z, _, - # default = PREROUTING prerouting_chain_name = PREROUTING # # The internet line upstream bit rate reported from # the daemon. Value in bits per second # default = 0 upstream_bitrate = 512000 # # The internet line downstream bit rate reported from # the daemon. Value in bits per second # default = 0 downstream_bitrate = 512000 # # The default duration of port mappings, used when the client # doesn't specify a duration. # Can have the following values: # 0 - no default duration specified # seconds | HH:MM - duration from the time of addition # @seconds | @HH:MM - expire mapping at the specified time of day # default = 0 duration = 86400 # One day # The name of the igd device xml description document # default = gatedesc.xml description_document_name = gatedesc.xml # The path to the xml documents # Do not include the trailing "/" # default = /etc/linuxigd # WARNING! The make install does put the xml files # in /etc/linuxigd, if you change this variable # you have to make sure the xml docs are in the # right place xml_document_path = /etc/linuxigd # The UPnP port to listen on. # default = 0 (first free UPnP port, starting with 49152) listenport = 0 linux-igd-1.0+cvs20070630/etc/gateconnSCPD.xml0000644000175000017500000003176007711573266020353 0ustar leveretleveret 1 0 SetConnectionType NewConnectionType in ConnectionType GetConnectionTypeInfo NewConnectionType out ConnectionType NewPossibleConnectionTypes out PossibleConnectionTypes RequestConnection ForceTermination GetStatusInfo NewConnectionStatus out ConnectionStatus NewLastConnectionError out LastConnectionError NewUptime out Uptime GetNATRSIPStatus NewRSIPAvailable out RSIPAvailable NewNATEnabled out NATEnabled GetGenericPortMappingEntry NewPortMappingIndex in PortMappingNumberOfEntries NewRemoteHost out RemoteHost NewExternalPort out ExternalPort NewProtocol out PortMappingProtocol NewInternalPort out InternalPort NewInternalClient out InternalClient NewEnabled out PortMappingEnabled NewPortMappingDescription out PortMappingDescription NewLeaseDuration out PortMappingLeaseDuration GetSpecificPortMappingEntry NewRemoteHost in RemoteHost NewExternalPort in ExternalPort NewProtocol in PortMappingProtocol NewInternalPort out InternalPort NewInternalClient out InternalClient NewEnabled out PortMappingEnabled NewPortMappingDescription out PortMappingDescription NewLeaseDuration out PortMappingLeaseDuration AddPortMapping NewRemoteHost in RemoteHost NewExternalPort in ExternalPort NewProtocol in PortMappingProtocol NewInternalPort in InternalPort NewInternalClient in InternalClient NewEnabled in PortMappingEnabled NewPortMappingDescription in PortMappingDescription NewLeaseDuration in PortMappingLeaseDuration DeletePortMapping NewRemoteHost in RemoteHost NewExternalPort in ExternalPort NewProtocol in PortMappingProtocol GetExternalIPAddress NewExternalIPAddress out ExternalIPAddress ConnectionType string Unconfigured PossibleConnectionTypes string Unconfigured IP_Routed IP_Bridged ConnectionStatus string Unconfigured Unconfigured Connecting Authenticating PendingDisconnect Disconnecting Disconnected Connected Uptime ui4 0 0 1 RSIPAvailable boolean 0 NATEnabled boolean 1 LastConnectionError string ERROR_NONE ERROR_NONE ERROR_ISP_TIME_OUT ERROR_COMMAND_ABORTED ERROR_NOT_ENABLED_FOR_INTERNET ERROR_BAD_PHONE_NUMBER ERROR_USER_DISCONNECT ERROR_ISP_DISCONNECT ERROR_IDLE_DISCONNECT ERROR_FORCED_DISCONNECT ERROR_SERVER_OUT_OF_RESOURCES ERROR_RESTRICTED_LOGON_HOURS ERROR_ACCOUNT_DISABLED ERROR_ACCOUNT_EXPIRED ERROR_PASSWORD_EXPIRED ERROR_AUTHENTICATION_FAILURE ERROR_NO_DIALTONE ERROR_NO_CARRIER ERROR_NO_ANSWER ERROR_LINE_BUSY ERROR_UNSUPPORTED_BITSPERSECOND ERROR_TOO_MANY_LINE_ERRORS ERROR_IP_CONFIGURATION ERROR_UNKNOWN ExternalIPAddress string RemoteHost string ExternalPort ui2 InternalPort ui2 PortMappingProtocol string TCP UDP InternalClient string PortMappingDescription string PortMappingEnabled boolean PortMappingLeaseDuration ui4 PortMappingNumberOfEntries ui2 linux-igd-1.0+cvs20070630/etc/upnpd.rc.conf0000644000175000017500000000015010470662621017734 0ustar leveretleveret# default upnpd settings # # Internet interface # EXTIFACE="ppp0" # # LAN interface # INTIFACE="eth0" linux-igd-1.0+cvs20070630/TODO0000644000175000017500000000032510562457224015260 0ustar leveretleveretPlanned and desired features: - support for multiple internal interfaces - improved security through validation - detection of connection speed - detection of connection type (ie ppp0 -> ADSL, else cable) linux-igd-1.0+cvs20070630/pmlist.c0000644000175000017500000002314210641323364016241 0ustar leveretleveret#include #include #include #include #include "globals.h" #include "config.h" #include "pmlist.h" #include "gatedevice.h" #include "util.h" #if HAVE_LIBIPTC #include "iptc.h" #endif struct portMap* pmlist_NewNode(int enabled, long int duration, char *remoteHost, char *externalPort, char *internalPort, char *protocol, char *internalClient, char *desc) { struct portMap* temp = (struct portMap*) malloc(sizeof(struct portMap)); temp->m_PortMappingEnabled = enabled; if (remoteHost && strlen(remoteHost) < sizeof(temp->m_RemoteHost)) strcpy(temp->m_RemoteHost, remoteHost); else strcpy(temp->m_RemoteHost, ""); if (strlen(externalPort) < sizeof(temp->m_ExternalPort)) strcpy(temp->m_ExternalPort, externalPort); else strcpy(temp->m_ExternalPort, ""); if (strlen(internalPort) < sizeof(temp->m_InternalPort)) strcpy(temp->m_InternalPort, internalPort); else strcpy(temp->m_InternalPort, ""); if (strlen(protocol) < sizeof(temp->m_PortMappingProtocol)) strcpy(temp->m_PortMappingProtocol, protocol); else strcpy(temp->m_PortMappingProtocol, ""); if (strlen(internalClient) < sizeof(temp->m_InternalClient)) strcpy(temp->m_InternalClient, internalClient); else strcpy(temp->m_InternalClient, ""); if (strlen(desc) < sizeof(temp->m_PortMappingDescription)) strcpy(temp->m_PortMappingDescription, desc); else strcpy(temp->m_PortMappingDescription, ""); temp->m_PortMappingLeaseDuration = duration; temp->next = NULL; temp->prev = NULL; return temp; } struct portMap* pmlist_Find(char *externalPort, char *proto, char *internalClient) { struct portMap* temp; temp = pmlist_Head; if (temp == NULL) return NULL; do { if ( (strcmp(temp->m_ExternalPort, externalPort) == 0) && (strcmp(temp->m_PortMappingProtocol, proto) == 0) && (strcmp(temp->m_InternalClient, internalClient) == 0) ) return temp; // We found a match, return pointer to it else temp = temp->next; } while (temp != NULL); // If we made it here, we didn't find it, so return NULL return NULL; } struct portMap* pmlist_FindByIndex(int index) { int i=0; struct portMap* temp; temp = pmlist_Head; if (temp == NULL) return NULL; do { if (i == index) return temp; else { temp = temp->next; i++; } } while (temp != NULL); return NULL; } struct portMap* pmlist_FindSpecific(char *externalPort, char *protocol) { struct portMap* temp; temp = pmlist_Head; if (temp == NULL) return NULL; do { if ( (strcmp(temp->m_ExternalPort, externalPort) == 0) && (strcmp(temp->m_PortMappingProtocol, protocol) == 0)) return temp; else temp = temp->next; } while (temp != NULL); return NULL; } int pmlist_IsEmtpy(void) { if (pmlist_Head) return 0; else return 1; } int pmlist_Size(void) { struct portMap* temp; int size = 0; temp = pmlist_Head; if (temp == NULL) return 0; while (temp->next) { size++; temp = temp->next; } size++; return size; } int pmlist_FreeList(void) { struct portMap *temp, *next; temp = pmlist_Head; while(temp) { CancelMappingExpiration(temp->expirationEventId); pmlist_DeletePortMapping(temp->m_PortMappingEnabled, temp->m_PortMappingProtocol, temp->m_ExternalPort, temp->m_InternalClient, temp->m_InternalPort); next = temp->next; free(temp); temp = next; } pmlist_Head = pmlist_Tail = NULL; return 1; } int pmlist_PushBack(struct portMap* item) { int action_succeeded = 0; if (pmlist_Tail) // We have a list, place on the end { pmlist_Tail->next = item; item->prev = pmlist_Tail; item->next = NULL; pmlist_Tail = item; action_succeeded = 1; } else // We obviously have no list, because we have no tail :D { pmlist_Head = pmlist_Tail = pmlist_Current = item; item->prev = NULL; item->next = NULL; action_succeeded = 1; trace(3, "appended %d %s %s %s %s %ld", item->m_PortMappingEnabled, item->m_PortMappingProtocol, item->m_ExternalPort, item->m_InternalClient, item->m_InternalPort, item->m_PortMappingLeaseDuration); } if (action_succeeded == 1) { pmlist_AddPortMapping(item->m_PortMappingEnabled, item->m_PortMappingProtocol, item->m_ExternalPort, item->m_InternalClient, item->m_InternalPort); return 1; } else return 0; } int pmlist_Delete(struct portMap* item) { struct portMap *temp; int action_succeeded = 0; temp = pmlist_Find(item->m_ExternalPort, item->m_PortMappingProtocol, item->m_InternalClient); if (temp) // We found the item to delete { CancelMappingExpiration(temp->expirationEventId); pmlist_DeletePortMapping(item->m_PortMappingEnabled, item->m_PortMappingProtocol, item->m_ExternalPort, item->m_InternalClient, item->m_InternalPort); if (temp == pmlist_Head) // We are the head of the list { if (temp->next == NULL) // We're the only node in the list { pmlist_Head = pmlist_Tail = pmlist_Current = NULL; free (temp); action_succeeded = 1; } else // we have a next, so change head to point to it { pmlist_Head = temp->next; pmlist_Head->prev = NULL; free (temp); action_succeeded = 1; } } else if (temp == pmlist_Tail) // We are the Tail, but not the Head so we have prev { pmlist_Tail = pmlist_Tail->prev; free (pmlist_Tail->next); pmlist_Tail->next = NULL; action_succeeded = 1; } else // We exist and we are between two nodes { temp->prev->next = temp->next; temp->next->prev = temp->prev; pmlist_Current = temp->next; // We put current to the right after a extraction free (temp); action_succeeded = 1; } } else // We're deleting something that's not there, so return 0 action_succeeded = 0; return action_succeeded; } int pmlist_AddPortMapping (int enabled, char *protocol, char *externalPort, char *internalClient, char *internalPort) { if (enabled) { char dest[DEST_LEN]; snprintf(dest, DEST_LEN, "%s:%s", internalClient, internalPort); #if HAVE_LIBIPTC char *buffer = malloc(strlen(internalClient) + strlen(internalPort) + 2); if (buffer == NULL) { fprintf(stderr, "failed to malloc memory\n"); return 0; } if (g_vars.createForwardRules) { trace(3, "iptc_add_rule %s %s %s %s %s %s %s", "filter", g_vars.forwardChainName, protocol, internalClient, internalPort, "ACCEPT", g_vars.forwardRulesAppend ? "APPEND" : "INSERT"); iptc_add_rule("filter", g_vars.forwardChainName, protocol, NULL, NULL, NULL, internalClient, NULL, internalPort, "ACCEPT", NULL, g_vars.forwardRulesAppend ? TRUE : FALSE); } trace(3, "iptc_add_rule %s %s %s %s %s %s %s %s", "nat", g_vars.preroutingChainName, protocol, g_vars.extInterfaceName, externalPort, "DNAT", dest, "APPEND"); iptc_add_rule("nat", g_vars.preroutingChainName, protocol, g_vars.extInterfaceName, NULL, NULL, NULL, NULL, externalPort, "DNAT", dest, TRUE); #else int status; if (g_vars.createForwardRules) { char *args[] = {g_vars.iptables, g_vars.forwardRulesAppend ? "-A" : "-I", g_vars.forwardChainName, "-p", protocol, "-d", internalClient, "--dport", internalPort, "-j", "ACCEPT", NULL}; trace(3, "%s %s %s -p %s -d %s --dport %s -j ACCEPT", g_vars.iptables,g_vars.forwardRulesAppend ? "-A" : "-I",g_vars.forwardChainName, protocol, internalClient, internalPort); if (!fork()) { int rc = execv(g_vars.iptables, args); exit(rc); } else { wait(&status); } } { char *args[] = {g_vars.iptables, "-t", "nat", "-A", g_vars.preroutingChainName, "-i", g_vars.extInterfaceName, "-p", protocol, "--dport", externalPort, "-j", "DNAT", "--to", dest, NULL}; trace(3, "%s -t nat -A %s -i %s -p %s --dport %s -j DNAT --to %s", g_vars.iptables, g_vars.preroutingChainName, g_vars.extInterfaceName, protocol, externalPort, dest); if (!fork()) { int rc = execv(g_vars.iptables, args); exit(rc); } else { wait(&status); } } #endif } return 1; } int pmlist_DeletePortMapping(int enabled, char *protocol, char *externalPort, char *internalClient, char *internalPort) { if (enabled) { char dest[DEST_LEN]; snprintf(dest, DEST_LEN, "%s:%s", internalClient, internalPort); #if HAVE_LIBIPTC trace(3, "iptc_delete_rule %s %s %s %s %s %s %s", "nat", g_vars.preroutingChainName, protocol, g_vars.extInterfaceName, externalPort, "DNAT", dest); iptc_delete_rule("nat", g_vars.preroutingChainName, protocol, g_vars.extInterfaceName, NULL, NULL, NULL, NULL, externalPort, "DNAT", dest); if (g_vars.createForwardRules) { trace(3, "iptc_delete_rule %s %s %s %s %s %s", "filter", g_vars.forwardChainName, protocol, internalClient, internalPort, "ACCEPT"); iptc_delete_rule("filter", g_vars.forwardChainName, protocol, NULL, NULL, NULL, internalClient, NULL, internalPort, "ACCEPT", NULL); } #else int status; { char *args[] = {g_vars.iptables, "-t", "nat", "-D", g_vars.preroutingChainName, "-i", g_vars.extInterfaceName, "-p", protocol, "--dport", externalPort, "-j", "DNAT", "--to", dest, NULL}; trace(3, "%s -t nat -D %s -i %s -p %s --dport %s -j DNAT --to %s", g_vars.iptables, g_vars.preroutingChainName, g_vars.extInterfaceName, protocol, externalPort, dest); if (!fork()) { int rc = execv(g_vars.iptables, args); exit(rc); } else { wait(&status); } } if (g_vars.createForwardRules) { char *args[] = {g_vars.iptables, "-D", g_vars.forwardChainName, "-p", protocol, "-d", internalClient, "--dport", internalPort, "-j", "ACCEPT", NULL}; trace(3, "%s -D %s -p %s -d %s --dport %s -j ACCEPT", g_vars.iptables, g_vars.forwardChainName, protocol, internalClient, internalPort); if (!fork()) { int rc = execv(g_vars.iptables, args); exit(rc); } else { wait(&status); } } #endif } return 1; } linux-igd-1.0+cvs20070630/pmlist.h0000644000175000017500000000273110641323364016247 0ustar leveretleveret#ifndef _PMLIST_H_ #define _PMLIST_H_ #define DEST_LEN 100 typedef struct ExpirationEvent { int eventId; char DevUDN[NAME_SIZE]; char ServiceID[NAME_SIZE]; struct portMap *mapping; } expiration_event; struct portMap { int m_PortMappingEnabled; long int m_PortMappingLeaseDuration; char m_RemoteHost[16]; char m_ExternalPort[6]; char m_InternalPort[6]; char m_PortMappingProtocol[4]; char m_InternalClient[16]; char m_PortMappingDescription[50]; int expirationEventId; long int expirationTime; struct portMap* next; struct portMap* prev; } *pmlist_Head, *pmlist_Tail, *pmlist_Current; //struct portMap* pmlist_NewNode(void); struct portMap* pmlist_NewNode(int enabled, long int duration, char *remoteHost, char *externalPort, char *internalPort, char *protocol, char *internalClient, char *desc); struct portMap* pmlist_Find(char *externalPort, char *proto, char *internalClient); struct portMap* pmlist_FindByIndex(int index); struct portMap* pmlist_FindSpecific(char *externalPort, char *protocol); int pmlist_IsEmtpy(void); int pmlist_Size(void); int pmlist_FreeList(void); int pmlist_PushBack(struct portMap* item); int pmlist_Delete(struct portMap* item); int pmlist_AddPortMapping (int enabled, char *protocol, char *externalPort, char *internalClient, char *internalPort); int pmlist_DeletePortMapping(int enabled, char *protocol, char *externalPort, char *internalClient, char *internalPort); #endif // _PMLIST_H_ linux-igd-1.0+cvs20070630/Makefile0000644000175000017500000000173110571010330016211 0ustar leveretleveretPREFIX=/usr LIBUPNP_PREFIX=/usr #LIBIPTC_PREFIX=/usr CC=gcc INCLUDES= -I$(LIBUPNP_PREFIX)/include -I../include LIBS= -lpthread -lupnp -lixml -lthreadutil -L$(LIBUPNP_PREFIX)/lib -L../libs FILES= main.o gatedevice.o pmlist.o util.o config.o CFLAGS += -Wall -g -O2 ifdef HAVE_LIBIPTC ifdef LIBIPTC_PREFIX LIBS += -L$(LIBIPTC_PREFIX)/lib INCLUDES += -I$(LIBIPTC_PREFIX)/include endif LIBS += -liptc INCLUDES += -DHAVE_LIBIPTC FILES += iptc.o endif all: upnpd upnpd: $(FILES) $(CC) $(CFLAGS) $(FILES) $(LIBS) -o $@ @echo "make $@ finished on `date`" %.o: %.c $(CC) $(CFLAGS) $(INCLUDES) -D_GNU_SOURCE -c $< clean: rm -f *.o upnpd install: upnpd install -d /etc/linuxigd install etc/gatedesc.xml /etc/linuxigd install etc/gateconnSCPD.xml /etc/linuxigd install etc/gateicfgSCPD.xml /etc/linuxigd install etc/dummy.xml /etc/linuxigd install upnpd $(PREFIX)/sbin install upnpd.8 $(PREFIX)/share/man/man8 if [ ! -f /etc/upnpd.conf ]; then install etc/upnpd.conf /etc; fi linux-igd-1.0+cvs20070630/LICENSE0000644000175000017500000004313107576456066015615 0ustar leveretleveret GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. linux-igd-1.0+cvs20070630/gatedevice.c0000644000175000017500000007334310562455657017056 0ustar leveretleveret#include #include #include #include #include #include #include #include #include "globals.h" #include "gatedevice.h" #include "pmlist.h" #include "util.h" //Definitions for mapping expiration timer thread static TimerThread gExpirationTimerThread; static ThreadPool gExpirationThreadPool; // MUTEX for locking shared state variables whenver they are changed static ithread_mutex_t DevMutex = PTHREAD_MUTEX_INITIALIZER; // Main event handler for callbacks from the SDK. Determine type of event // and dispatch to the appropriate handler (Note: Get Var Request deprecated int EventHandler(Upnp_EventType EventType, void *Event, void *Cookie) { switch (EventType) { case UPNP_EVENT_SUBSCRIPTION_REQUEST: HandleSubscriptionRequest((struct Upnp_Subscription_Request *) Event); break; // -- Deprecated -- case UPNP_CONTROL_GET_VAR_REQUEST: HandleGetVarRequest((struct Upnp_State_Var_Request *) Event); break; case UPNP_CONTROL_ACTION_REQUEST: HandleActionRequest((struct Upnp_Action_Request *) Event); break; default: trace(1, "Error in EventHandler: Unknown event type %d", EventType); } return (0); } // Grab our UDN from the Description Document. This may not be needed, // the UDN comes with the request, but we leave this for other device initializations int StateTableInit(char *descDocUrl) { IXML_Document *ixmlDescDoc; int ret; if ((ret = UpnpDownloadXmlDoc(descDocUrl, &ixmlDescDoc)) != UPNP_E_SUCCESS) { syslog(LOG_ERR, "Could not parse description document. Exiting ..."); UpnpFinish(); exit(0); } // Get the UDN from the description document, then free the DescDoc's memory gateUDN = GetFirstDocumentItem(ixmlDescDoc, "UDN"); ixmlDocument_free(ixmlDescDoc); // Initialize our linked list of port mappings. pmlist_Head = pmlist_Current = NULL; PortMappingNumberOfEntries = 0; return (ret); } // Handles subscription request for state variable notifications int HandleSubscriptionRequest(struct Upnp_Subscription_Request *sr_event) { IXML_Document *propSet = NULL; ithread_mutex_lock(&DevMutex); if (strcmp(sr_event->UDN, gateUDN) == 0) { // WAN Common Interface Config Device Notifications if (strcmp(sr_event->ServiceId, "urn:upnp-org:serviceId:WANCommonIFC1") == 0) { trace(3, "Recieved request to subscribe to WANCommonIFC1"); UpnpAddToPropertySet(&propSet, "PhysicalLinkStatus", "Up"); UpnpAcceptSubscriptionExt(deviceHandle, sr_event->UDN, sr_event->ServiceId, propSet, sr_event->Sid); ixmlDocument_free(propSet); } // WAN IP Connection Device Notifications else if (strcmp(sr_event->ServiceId, "urn:upnp-org:serviceId:WANIPConn1") == 0) { GetIpAddressStr(ExternalIPAddress, g_vars.extInterfaceName); trace(3, "Received request to subscribe to WANIPConn1"); UpnpAddToPropertySet(&propSet, "PossibleConnectionTypes","IP_Routed"); UpnpAddToPropertySet(&propSet, "ConnectionStatus","Connected"); UpnpAddToPropertySet(&propSet, "ExternalIPAddress", ExternalIPAddress); UpnpAddToPropertySet(&propSet, "PortMappingNumberOfEntries","0"); UpnpAcceptSubscriptionExt(deviceHandle, sr_event->UDN, sr_event->ServiceId, propSet, sr_event->Sid); ixmlDocument_free(propSet); } } ithread_mutex_unlock(&DevMutex); return(1); } int HandleGetVarRequest(struct Upnp_State_Var_Request *gv_request) { // GET VAR REQUEST DEPRECATED FROM UPnP SPECIFICATIONS // Report this in debug and ignore requests. If anyone experiences problems // please let us know. trace(3, "Deprecated Get Variable Request received. Ignoring."); return 1; } int HandleActionRequest(struct Upnp_Action_Request *ca_event) { int result = 0; ithread_mutex_lock(&DevMutex); if (strcmp(ca_event->DevUDN, gateUDN) == 0) { // Common debugging info, hopefully gets removed soon. trace(3, "ActionName = %s", ca_event->ActionName); if (strcmp(ca_event->ServiceID, "urn:upnp-org:serviceId:WANIPConn1") == 0) { if (strcmp(ca_event->ActionName,"GetConnectionTypeInfo") == 0) result = GetConnectionTypeInfo(ca_event); else if (strcmp(ca_event->ActionName,"GetNATRSIPStatus") == 0) result = GetNATRSIPStatus(ca_event); else if (strcmp(ca_event->ActionName,"SetConnectionType") == 0) result = SetConnectionType(ca_event); else if (strcmp(ca_event->ActionName,"RequestConnection") == 0) result = RequestConnection(ca_event); else if (strcmp(ca_event->ActionName,"AddPortMapping") == 0) result = AddPortMapping(ca_event); else if (strcmp(ca_event->ActionName,"GetGenericPortMappingEntry") == 0) result = GetGenericPortMappingEntry(ca_event); else if (strcmp(ca_event->ActionName,"GetSpecificPortMappingEntry") == 0) result = GetSpecificPortMappingEntry(ca_event); else if (strcmp(ca_event->ActionName,"GetExternalIPAddress") == 0) result = GetExternalIPAddress(ca_event); else if (strcmp(ca_event->ActionName,"DeletePortMapping") == 0) result = DeletePortMapping(ca_event); else if (strcmp(ca_event->ActionName,"GetStatusInfo") == 0) result = GetStatusInfo(ca_event); // Intentionally Non-Implemented Functions -- To be added later /*else if (strcmp(ca_event->ActionName,"RequestTermination") == 0) result = RequestTermination(ca_event); else if (strcmp(ca_event->ActionName,"ForceTermination") == 0) result = ForceTermination(ca_event); else if (strcmp(ca_event->ActionName,"SetAutoDisconnectTime") == 0) result = SetAutoDisconnectTime(ca_event); else if (strcmp(ca_event->ActionName,"SetIdleDisconnectTime") == 0) result = SetIdleDisconnectTime(ca_event); else if (strcmp(ca_event->ActionName,"SetWarnDisconnectDelay") == 0) result = SetWarnDisconnectDelay(ca_event); else if (strcmp(ca_event->ActionName,"GetAutoDisconnectTime") == 0) result = GetAutoDisconnectTime(ca_event); else if (strcmp(ca_event->ActionName,"GetIdleDisconnectTime") == 0) result = GetIdleDisconnectTime(ca_event); else if (strcmp(ca_event->ActionName,"GetWarnDisconnectDelay") == 0) result = GetWarnDisconnectDelay(ca_event);*/ else result = InvalidAction(ca_event); } else if (strcmp(ca_event->ServiceID,"urn:upnp-org:serviceId:WANCommonIFC1") == 0) { if (strcmp(ca_event->ActionName,"GetTotalBytesSent") == 0) result = GetTotal(ca_event, STATS_TX_BYTES); else if (strcmp(ca_event->ActionName,"GetTotalBytesReceived") == 0) result = GetTotal(ca_event, STATS_RX_BYTES); else if (strcmp(ca_event->ActionName,"GetTotalPacketsSent") == 0) result = GetTotal(ca_event, STATS_TX_PACKETS); else if (strcmp(ca_event->ActionName,"GetTotalPacketsReceived") == 0) result = GetTotal(ca_event, STATS_RX_PACKETS); else if (strcmp(ca_event->ActionName,"GetCommonLinkProperties") == 0) result = GetCommonLinkProperties(ca_event); else { trace(1, "Invalid Action Request : %s",ca_event->ActionName); result = InvalidAction(ca_event); } } } ithread_mutex_unlock(&DevMutex); return (result); } // Default Action when we receive unknown Action Requests int InvalidAction(struct Upnp_Action_Request *ca_event) { ca_event->ErrCode = 401; strcpy(ca_event->ErrStr, "Invalid Action"); ca_event->ActionResult = NULL; return (ca_event->ErrCode); } // As IP_Routed is the only relevant Connection Type for Linux-IGD // we respond with IP_Routed as both current type and only type int GetConnectionTypeInfo (struct Upnp_Action_Request *ca_event) { char resultStr[RESULT_LEN]; IXML_Document *result; snprintf(resultStr, RESULT_LEN, "\n" "IP_Routed\n" "IP_Routed" ""); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing Response to GetConnectionTypeinfo: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return(ca_event->ErrCode); } // Linux-IGD does not support RSIP. However NAT is of course // so respond with NewNATEnabled = 1 int GetNATRSIPStatus(struct Upnp_Action_Request *ca_event) { char resultStr[RESULT_LEN]; IXML_Document *result; snprintf(resultStr, RESULT_LEN, "\n" "0\n" "1\n" ""); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing Response to GetNATRSIPStatus: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return(ca_event->ErrCode); } // Connection Type is a Read Only Variable as linux-igd is only // a device that supports a NATing IP router (not an Ethernet // bridge). Possible other uses may be explored. int SetConnectionType(struct Upnp_Action_Request *ca_event) { // Ignore requests ca_event->ActionResult = NULL; ca_event->ErrCode = UPNP_E_SUCCESS; return ca_event->ErrCode; } // This function should set the state variable ConnectionStatus to // connecting, and then return synchronously, firing off a thread // asynchronously to actually change the status to connected. However, here we // assume that the external WAN device is configured and connected // outside of linux igd. int RequestConnection(struct Upnp_Action_Request *ca_event) { IXML_Document *propSet = NULL; //Immediatley Set connectionstatus to connected, and lastconnectionerror to none. strcpy(ConnectionStatus,"Connected"); strcpy(LastConnectionError, "ERROR_NONE"); trace(2, "RequestConnection recieved ... Setting Status to %s.", ConnectionStatus); // Build DOM Document with state variable connectionstatus and event it UpnpAddToPropertySet(&propSet, "ConnectionStatus", ConnectionStatus); // Send off notifications of state change UpnpNotifyExt(deviceHandle, ca_event->DevUDN, ca_event->ServiceID, propSet); ca_event->ErrCode = UPNP_E_SUCCESS; return ca_event->ErrCode; } int GetCommonLinkProperties(struct Upnp_Action_Request *ca_event) { char resultStr[RESULT_LEN]; IXML_Document *result; ca_event->ErrCode = UPNP_E_SUCCESS; snprintf(resultStr, RESULT_LEN, "\n" "Cable\n" "%s\n" "%s\n" "Up\n" "",g_vars.upstreamBitrate,g_vars.downstreamBitrate); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing Response to GetCommonLinkProperties: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return(ca_event->ErrCode); } /* get specified statistic from /proc/net/dev */ int GetTotal(struct Upnp_Action_Request *ca_event, stats_t stat) { char dev[IFNAMSIZ], resultStr[RESULT_LEN]; const char *methods[STATS_LIMIT] = { "BytesSent", "BytesReceived", "PacketsSent", "PacketsReceived" }; unsigned long stats[STATS_LIMIT]; FILE *proc; IXML_Document *result; int read; proc = fopen("/proc/net/dev", "r"); if (!proc) { fprintf(stderr, "failed to open\n"); return 0; } /* skip first two lines */ fscanf(proc, "%*[^\n]\n%*[^\n]\n"); /* parse stats */ do read = fscanf(proc, "%[^:]:%lu %lu %*u %*u %*u %*u %*u %*u %lu %lu %*u %*u %*u %*u %*u %*u\n", dev, &stats[STATS_RX_BYTES], &stats[STATS_RX_PACKETS], &stats[STATS_TX_BYTES], &stats[STATS_TX_PACKETS]); while (read != EOF && (read == 5 && strncmp(dev, g_vars.extInterfaceName, IFNAMSIZ) != 0)); fclose(proc); snprintf(resultStr, RESULT_LEN, "\n" "%lu\n" "", methods[stat], methods[stat], stats[stat], methods[stat], methods[stat]); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing response to GetTotal: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return (ca_event->ErrCode); } // Returns connection status related information to the control points int GetStatusInfo(struct Upnp_Action_Request *ca_event) { long int uptime; char resultStr[RESULT_LEN]; IXML_Document *result = NULL; uptime = (time(NULL) - startup_time); snprintf(resultStr, RESULT_LEN, "\n" "Connected\n" "ERROR_NONE\n" "%li\n" "", uptime); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing Response to GetStatusInfo: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return(ca_event->ErrCode); } // Add New Port Map to the IGD int AddPortMapping(struct Upnp_Action_Request *ca_event) { char *remote_host=NULL; char *ext_port=NULL; char *proto=NULL; char *int_port=NULL; char *int_ip=NULL; char *int_duration=NULL; char *bool_enabled=NULL; char *desc=NULL; struct portMap *ret, *new; int result; char num[5]; // Maximum number of port mapping entries 9999 IXML_Document *propSet = NULL; int action_succeeded = 0; char resultStr[RESULT_LEN]; if ( (ext_port = GetFirstDocumentItem(ca_event->ActionRequest, "NewExternalPort") ) && (proto = GetFirstDocumentItem(ca_event->ActionRequest, "NewProtocol") ) && (int_port = GetFirstDocumentItem(ca_event->ActionRequest, "NewInternalPort") ) && (int_ip = GetFirstDocumentItem(ca_event->ActionRequest, "NewInternalClient") ) && (int_duration = GetFirstDocumentItem(ca_event->ActionRequest, "NewLeaseDuration") ) && (bool_enabled = GetFirstDocumentItem(ca_event->ActionRequest, "NewEnabled") ) && (desc = GetFirstDocumentItem(ca_event->ActionRequest, "NewPortMappingDescription") )) { remote_host = GetFirstDocumentItem(ca_event->ActionRequest, "NewRemoteHost"); // If port map with the same External Port, Protocol, and Internal Client exists // then, as per spec, we overwrite it (for simplicity, we delete and re-add at end of list) // Note: This may cause problems with GetGernericPortMappingEntry if a CP expects the overwritten // to be in the same place. if ((ret = pmlist_Find(ext_port, proto, int_ip)) != NULL) { trace(3, "Found port map to already exist. Replacing"); pmlist_Delete(ret); } new = pmlist_NewNode(atoi(bool_enabled), atol(int_duration), "", ext_port, int_port, proto, int_ip, desc); result = pmlist_PushBack(new); if (result==1) { ScheduleMappingExpiration(new,ca_event->DevUDN,ca_event->ServiceID); sprintf(num, "%d", pmlist_Size()); trace(3, "PortMappingNumberOfEntries: %d", pmlist_Size()); UpnpAddToPropertySet(&propSet, "PortMappingNumberOfEntries", num); UpnpNotifyExt(deviceHandle, ca_event->DevUDN, ca_event->ServiceID, propSet); ixmlDocument_free(propSet); trace(2, "AddPortMap: DevUDN: %s ServiceID: %s RemoteHost: %s Prot: %s ExtPort: %s Int: %s.%s", ca_event->DevUDN,ca_event->ServiceID,remote_host, proto, ext_port, int_ip, int_port); action_succeeded = 1; } else { if (result==718) { trace(1,"Failure in GateDeviceAddPortMapping: RemoteHost: %s Prot:%s ExtPort: %s Int: %s.%s\n", remote_host, proto, ext_port, int_ip, int_port); ca_event->ErrCode = 718; strcpy(ca_event->ErrStr, "ConflictInMappingEntry"); ca_event->ActionResult = NULL; } } } else { trace(1, "Failiure in GateDeviceAddPortMapping: Invalid Arguments!"); trace(1, " ExtPort: %s Proto: %s IntPort: %s IntIP: %s Dur: %s Ena: %s Desc: %s", ext_port, proto, int_port, int_ip, int_duration, bool_enabled, desc); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } if (action_succeeded) { ca_event->ErrCode = UPNP_E_SUCCESS; snprintf(resultStr, RESULT_LEN, "\n%s\n", ca_event->ActionName, "urn:schemas-upnp-org:service:WANIPConnection:1", "", ca_event->ActionName); ca_event->ActionResult = ixmlParseBuffer(resultStr); } if (ext_port) free(ext_port); if (int_port) free(int_port); if (proto) free(proto); if (int_ip) free(int_ip); if (bool_enabled) free(bool_enabled); if (desc) free(desc); if (remote_host) free(remote_host); return(ca_event->ErrCode); } int GetGenericPortMappingEntry(struct Upnp_Action_Request *ca_event) { char *mapindex = NULL; struct portMap *temp; char result_param[RESULT_LEN]; char resultStr[RESULT_LEN]; int action_succeeded = 0; if ((mapindex = GetFirstDocumentItem(ca_event->ActionRequest, "NewPortMappingIndex"))) { temp = pmlist_FindByIndex(atoi(mapindex)); if (temp) { snprintf(result_param, RESULT_LEN, "%s%s%s%s%s%d%s%li", temp->m_RemoteHost, temp->m_ExternalPort, temp->m_PortMappingProtocol, temp->m_InternalPort, temp->m_InternalClient, temp->m_PortMappingEnabled, temp->m_PortMappingDescription, temp->m_PortMappingLeaseDuration); action_succeeded = 1; } if (action_succeeded) { ca_event->ErrCode = UPNP_E_SUCCESS; snprintf(resultStr, RESULT_LEN, "\n%s\n", ca_event->ActionName, "urn:schemas-upnp-org:service:WANIPConnection:1",result_param, ca_event->ActionName); ca_event->ActionResult = ixmlParseBuffer(resultStr); } else { ca_event->ErrCode = 713; strcpy(ca_event->ErrStr, "SpecifiedArrayIndexInvalid"); ca_event->ActionResult = NULL; } } else { trace(1, "Failure in GateDeviceGetGenericPortMappingEntry: Invalid Args"); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } if (mapindex) free (mapindex); return (ca_event->ErrCode); } int GetSpecificPortMappingEntry(struct Upnp_Action_Request *ca_event) { char *ext_port=NULL; char *proto=NULL; char result_param[RESULT_LEN]; char resultStr[RESULT_LEN]; int action_succeeded = 0; struct portMap *temp; if ((ext_port = GetFirstDocumentItem(ca_event->ActionRequest, "NewExternalPort")) && (proto = GetFirstDocumentItem(ca_event->ActionRequest,"NewProtocol"))) { if ((strcmp(proto, "TCP") == 0) || (strcmp(proto, "UDP") == 0)) { temp = pmlist_FindSpecific (ext_port, proto); if (temp) { snprintf(result_param, RESULT_LEN, "%s%s%d%s%li", temp->m_InternalPort, temp->m_InternalClient, temp->m_PortMappingEnabled, temp->m_PortMappingDescription, temp->m_PortMappingLeaseDuration); action_succeeded = 1; } if (action_succeeded) { ca_event->ErrCode = UPNP_E_SUCCESS; snprintf(resultStr, RESULT_LEN, "\n%s\n", ca_event->ActionName, "urn:schemas-upnp-org:service:WANIPConnection:1",result_param, ca_event->ActionName); ca_event->ActionResult = ixmlParseBuffer(resultStr); } else { trace(2, "GateDeviceGetSpecificPortMappingEntry: PortMapping Doesn't Exist..."); ca_event->ErrCode = 714; strcpy(ca_event->ErrStr, "NoSuchEntryInArray"); ca_event->ActionResult = NULL; } } else { trace(1, "Failure in GateDeviceGetSpecificPortMappingEntry: Invalid NewProtocol=%s\n",proto); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } } else { trace(1, "Failure in GateDeviceGetSpecificPortMappingEntry: Invalid Args"); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } return (ca_event->ErrCode); } int GetExternalIPAddress(struct Upnp_Action_Request *ca_event) { char resultStr[RESULT_LEN]; IXML_Document *result = NULL; ca_event->ErrCode = UPNP_E_SUCCESS; GetIpAddressStr(ExternalIPAddress, g_vars.extInterfaceName); snprintf(resultStr, RESULT_LEN, "\n" "%s\n" "", ExternalIPAddress); // Create a IXML_Document from resultStr and return with ca_event if ((result = ixmlParseBuffer(resultStr)) != NULL) { ca_event->ActionResult = result; ca_event->ErrCode = UPNP_E_SUCCESS; } else { trace(1, "Error parsing Response to ExternalIPAddress: %s", resultStr); ca_event->ActionResult = NULL; ca_event->ErrCode = 402; } return(ca_event->ErrCode); } int DeletePortMapping(struct Upnp_Action_Request *ca_event) { char *ext_port=NULL; char *proto=NULL; int result=0; char num[5]; char resultStr[RESULT_LEN]; IXML_Document *propSet= NULL; int action_succeeded = 0; struct portMap *temp; if (((ext_port = GetFirstDocumentItem(ca_event->ActionRequest, "NewExternalPort")) && (proto = GetFirstDocumentItem(ca_event->ActionRequest, "NewProtocol")))) { if ((strcmp(proto, "TCP") == 0) || (strcmp(proto, "UDP") == 0)) { if ((temp = pmlist_FindSpecific(ext_port, proto))) result = pmlist_Delete(temp); if (result==1) { trace(2, "DeletePortMap: Proto:%s Port:%s\n",proto, ext_port); sprintf(num,"%d",pmlist_Size()); UpnpAddToPropertySet(&propSet,"PortMappingNumberOfEntries", num); UpnpNotifyExt(deviceHandle, ca_event->DevUDN,ca_event->ServiceID,propSet); ixmlDocument_free(propSet); action_succeeded = 1; } else { trace(1, "Failure in GateDeviceDeletePortMapping: DeletePortMap: Proto:%s Port:%s\n",proto, ext_port); ca_event->ErrCode = 714; strcpy(ca_event->ErrStr, "NoSuchEntryInArray"); ca_event->ActionResult = NULL; } } else { trace(1, "Failure in GateDeviceDeletePortMapping: Invalid NewProtocol=%s\n",proto); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } } else { trace(1, "Failiure in GateDeviceDeletePortMapping: Invalid Arguments!"); ca_event->ErrCode = 402; strcpy(ca_event->ErrStr, "Invalid Args"); ca_event->ActionResult = NULL; } if (action_succeeded) { ca_event->ErrCode = UPNP_E_SUCCESS; snprintf(resultStr, RESULT_LEN, "\n%s\n", ca_event->ActionName, "urn:schemas-upnp-org:service:WANIPConnection:1", "", ca_event->ActionName); ca_event->ActionResult = ixmlParseBuffer(resultStr); } if (ext_port) free(ext_port); if (proto) free(proto); return(ca_event->ErrCode); } // From sampleutil.c included with libupnp char* GetFirstDocumentItem( IN IXML_Document * doc, IN const char *item ) { IXML_NodeList *nodeList = NULL; IXML_Node *textNode = NULL; IXML_Node *tmpNode = NULL; char *ret = NULL; nodeList = ixmlDocument_getElementsByTagName( doc, ( char * )item ); if( nodeList ) { if( ( tmpNode = ixmlNodeList_item( nodeList, 0 ) ) ) { textNode = ixmlNode_getFirstChild( tmpNode ); if (textNode != NULL) { ret = strdup( ixmlNode_getNodeValue( textNode ) ); } } } if( nodeList ) ixmlNodeList_free( nodeList ); return ret; } int ExpirationTimerThreadInit(void) { int retVal; ThreadPoolAttr attr; TPAttrInit( &attr ); TPAttrSetMaxThreads( &attr, MAX_THREADS ); TPAttrSetMinThreads( &attr, MIN_THREADS ); TPAttrSetJobsPerThread( &attr, JOBS_PER_THREAD ); TPAttrSetIdleTime( &attr, THREAD_IDLE_TIME ); if( ThreadPoolInit( &gExpirationThreadPool, &attr ) != UPNP_E_SUCCESS ) { return UPNP_E_INIT_FAILED; } if( ( retVal = TimerThreadInit( &gExpirationTimerThread, &gExpirationThreadPool ) ) != UPNP_E_SUCCESS ) { return retVal; } return 0; } int ExpirationTimerThreadShutdown(void) { return TimerThreadShutdown(&gExpirationTimerThread); } void free_expiration_event(expiration_event *event) { if (event->mapping!=NULL) event->mapping->expirationEventId = -1; free(event); } void ExpireMapping(void *input) { char num[5]; // Maximum number of port mapping entries 9999 IXML_Document *propSet = NULL; expiration_event *event = ( expiration_event * ) input; ithread_mutex_lock(&DevMutex); trace(2, "ExpireMapping: Proto:%s Port:%s\n", event->mapping->m_PortMappingProtocol, event->mapping->m_ExternalPort); //reset the event id before deleting the mapping so that pmlist_Delete //will not call CancelMappingExpiration event->mapping->expirationEventId = -1; pmlist_Delete(event->mapping); sprintf(num, "%d", pmlist_Size()); UpnpAddToPropertySet(&propSet, "PortMappingNumberOfEntries", num); UpnpNotifyExt(deviceHandle, event->DevUDN, event->ServiceID, propSet); ixmlDocument_free(propSet); trace(3, "ExpireMapping: UpnpNotifyExt(deviceHandle,%s,%s,propSet)\n PortMappingNumberOfEntries: %s", event->DevUDN, event->ServiceID, num); free_expiration_event(event); ithread_mutex_unlock(&DevMutex); } int ScheduleMappingExpiration(struct portMap *mapping, char *DevUDN, char *ServiceID) { int retVal = 0; ThreadPoolJob job; expiration_event *event; time_t curtime = time(NULL); if (mapping->m_PortMappingLeaseDuration > 0) { mapping->expirationTime = curtime + mapping->m_PortMappingLeaseDuration; } else { //client did not provide a duration, so use the default duration if (g_vars.duration==0) { return 1; //no default duration set } else if (g_vars.duration>0) { //relative duration mapping->expirationTime = curtime+g_vars.duration; } else { //g_vars.duration < 0 //absolute daily expiration time long int expclock = -1*g_vars.duration; struct tm *loctime = localtime(&curtime); long int curclock = loctime->tm_hour*3600 + loctime->tm_min*60 + loctime->tm_sec; long int diff = expclock-curclock; if (diff<60) //if exptime is in less than a minute (or in the past), schedule it in 24 hours instead diff += 24*60*60; mapping->expirationTime = curtime+diff; } } event = ( expiration_event * ) malloc( sizeof( expiration_event ) ); if( event == NULL ) { return 0; } event->mapping = mapping; if (strlen(DevUDN) < sizeof(event->DevUDN)) strcpy(event->DevUDN, DevUDN); else strcpy(event->DevUDN, ""); if (strlen(ServiceID) < sizeof(event->ServiceID)) strcpy(event->ServiceID, ServiceID); else strcpy(event->ServiceID, ""); TPJobInit( &job, ( start_routine ) ExpireMapping, event ); TPJobSetFreeFunction( &job, ( free_routine ) free_expiration_event ); if( ( retVal = TimerThreadSchedule( &gExpirationTimerThread, mapping->expirationTime, ABS_SEC, &job, SHORT_TERM, &( event->eventId ) ) ) != UPNP_E_SUCCESS ) { free( event ); mapping->expirationEventId = -1; return 0; } mapping->expirationEventId = event->eventId; trace(3,"ScheduleMappingExpiration: DevUDN: %s ServiceID: %s Proto: %s ExtPort: %s Int: %s.%s at: %s eventId: %d",event->DevUDN,event->ServiceID,mapping->m_PortMappingProtocol, mapping->m_ExternalPort, mapping->m_InternalClient, mapping->m_InternalPort, ctime(&(mapping->expirationTime)), event->eventId); return event->eventId; } int CancelMappingExpiration(int expirationEventId) { ThreadPoolJob job; if (expirationEventId<0) return 1; trace(3,"CancelMappingExpiration: eventId: %d",expirationEventId); if (TimerThreadRemove(&gExpirationTimerThread,expirationEventId,&job)==0) { free_expiration_event((expiration_event *)job.arg); } else { trace(1," TimerThreadRemove failed!"); } return 1; } void DeleteAllPortMappings(void) { IXML_Document *propSet = NULL; ithread_mutex_lock(&DevMutex); pmlist_FreeList(); UpnpAddToPropertySet(&propSet, "PortMappingNumberOfEntries", "0"); UpnpNotifyExt(deviceHandle, gateUDN, "urn:upnp-org:serviceId:WANIPConn1", propSet); ixmlDocument_free(propSet); trace(2, "DeleteAllPortMappings: UpnpNotifyExt(deviceHandle,%s,%s,propSet)\n PortMappingNumberOfEntries: %s", gateUDN, "urn:upnp-org:serviceId:WANIPConn1", "0"); ithread_mutex_unlock(&DevMutex); } linux-igd-1.0+cvs20070630/gatedevice.h0000644000175000017500000000466010562455657017057 0ustar leveretleveret#ifndef _GATEDEVICE_H_ #define _GATEDEVICE_H_ 1 #include /* interface statistics */ typedef enum { STATS_TX_BYTES, STATS_RX_BYTES, STATS_TX_PACKETS, STATS_RX_PACKETS, STATS_LIMIT } stats_t; // IGD Device Globals UpnpDevice_Handle deviceHandle; char *gateUDN; long int startup_time; // State Variables char ConnectionType[50]; char PossibleConnectionTypes[50]; char ConnectionStatus[20]; long int StartupTime; char LastConnectionError[35]; long int AutoDisconnectTime; long int IdleDisconnectTime; long int WarnDisconnectDelay; int RSIPAvailable; int NATEnabled; char ExternalIPAddress[20]; int PortMappingNumberOfEntries; int PortMappingEnabled; // Helper routines char* GetFirstDocumentItem( IN IXML_Document * doc, const char *item ); // Linked list for portmapping entries struct portMap *pmlist_Head; struct portMap *pmlist_Current; // WanIPConnection Actions int EventHandler(Upnp_EventType EventType, void *Event, void *Cookie); int StateTableInit(char *descDocUrl); int HandleSubscriptionRequest(struct Upnp_Subscription_Request *sr_event); int HandleGetVarRequest(struct Upnp_State_Var_Request *gv_event); int HandleActionRequest(struct Upnp_Action_Request *ca_event); int GetConnectionTypeInfo(struct Upnp_Action_Request *ca_event); int GetNATRSIPStatus(struct Upnp_Action_Request *ca_event); int SetConnectionType(struct Upnp_Action_Request *ca_event); int RequestConnection(struct Upnp_Action_Request *ca_event); int GetTotal(struct Upnp_Action_Request *ca_event, stats_t stat); int GetCommonLinkProperties(struct Upnp_Action_Request *ca_event); int InvalidAction(struct Upnp_Action_Request *ca_event); int GetStatusInfo(struct Upnp_Action_Request *ca_event); int AddPortMapping(struct Upnp_Action_Request *ca_event); int GetGenericPortMappingEntry(struct Upnp_Action_Request *ca_event); int GetSpecificPortMappingEntry(struct Upnp_Action_Request *ca_event); int GetExternalIPAddress(struct Upnp_Action_Request *ca_event); int DeletePortMapping(struct Upnp_Action_Request *ca_event); // Definitions for mapping expiration timer thread #define THREAD_IDLE_TIME 5000 #define JOBS_PER_THREAD 10 #define MIN_THREADS 2 #define MAX_THREADS 12 int ExpirationTimerThreadInit(void); int ExpirationTimerThreadShutdown(void); int ScheduleMappingExpiration(struct portMap *mapping, char *DevUDN, char *ServiceID); int CancelMappingExpiration(int eventId); void DeleteAllPortMappings(void); #endif //_GATEDEVICE_H linux-igd-1.0+cvs20070630/config.c0000644000175000017500000001767310641323364016212 0ustar leveretleveret#include #include #include #include #include #include "globals.h" #define NMATCH 3 int getConfigOptionArgument(char var[],int varlen, char line[], regmatch_t *submatch) { /* limit buffer operations to varlen - 1 */ int match_length = min(submatch[1].rm_eo-submatch[1].rm_so, varlen - 1); strncpy(var,&line[submatch[1].rm_so],match_length); // Make sure var[] is null terminated var[match_length] = '\0'; return 0; } int getConfigOptionDuration(long int *duration,char line[], regmatch_t *submatch) { long int dur; int absolute_time = submatch[1].rm_eo-submatch[1].rm_so; // >0 if @ was present char num[NUM_LEN]; char *p; /* limit buffer operations to NUM_LEN - 1 */ unsigned int len = min(submatch[2].rm_eo-submatch[2].rm_so, NUM_LEN - 1); strncpy(num, &line[submatch[2].rm_so], len); num[len] = '\0'; if ((p=index(num,':'))==NULL) { dur = atol(num); } else { *p++ = '\0'; dur = atol(num)*3600 + atol(p)*60; } if (absolute_time) dur *= -1; *duration = dur; return 0; } int parseConfigFile(globals_p vars) { FILE *conf_file; regmatch_t submatch[NMATCH]; // Stores the regex submatch start and end index regex_t re_comment; regex_t re_empty_row; regex_t re_iptables_location; regex_t re_debug_mode; regex_t re_create_forward_rules; regex_t re_forward_rules_append; regex_t re_forward_chain_name; regex_t re_prerouting_chain_name; regex_t re_upstream_bitrate; regex_t re_downstream_bitrate; regex_t re_duration; regex_t re_desc_doc; regex_t re_xml_path; regex_t re_listenport; // Make sure all vars are 0 or \0 terminated vars->debug = 0; vars->createForwardRules = 0; vars->forwardRulesAppend = 0; strcpy(vars->iptables,""); strcpy(vars->forwardChainName,""); strcpy(vars->preroutingChainName,""); strcpy(vars->upstreamBitrate,""); strcpy(vars->downstreamBitrate,""); vars->duration = DEFAULT_DURATION; strcpy(vars->descDocName,""); strcpy(vars->xmlPath,""); vars->listenport = 0; // Regexp to match a comment line regcomp(&re_comment,"^[[:blank:]]*#",0); regcomp(&re_empty_row,"^[[:blank:]]*\r?\n$",REG_EXTENDED); // Regexps to match configuration file settings regcomp(&re_iptables_location,"iptables_location[[:blank:]]*=[[:blank:]]*\"([^\"]+)\"",REG_EXTENDED); regcomp(&re_debug_mode,"debug_mode[[:blank:]]*=[[:blank:]]*([[:digit:]])",REG_EXTENDED); regcomp(&re_forward_chain_name,"forward_chain_name[[:blank:]]*=[[:blank:]]*([[:alpha:]_-]+)",REG_EXTENDED); regcomp(&re_prerouting_chain_name,"prerouting_chain_name[[:blank:]]*=[[:blank:]]([[:alpha:]_-]+)",REG_EXTENDED); regcomp(&re_create_forward_rules,"create_forward_rules[[:blank:]]*=[[:blank:]]*(yes|no)",REG_EXTENDED); regcomp(&re_forward_rules_append,"forward_rules_append[[:blank:]]*=[[:blank:]]*(yes|no)",REG_EXTENDED); regcomp(&re_upstream_bitrate,"upstream_bitrate[[:blank:]]*=[[:blank:]]*([[:digit:]]+)",REG_EXTENDED); regcomp(&re_downstream_bitrate,"downstream_bitrate[[:blank:]]*=[[:blank:]]*([[:digit:]]+)",REG_EXTENDED); regcomp(&re_duration,"duration[[:blank:]]*=[[:blank:]]*(@?)([[:digit:]]+|[[:digit:]]{2,}:[[:digit:]]{2})",REG_EXTENDED); regcomp(&re_desc_doc,"description_document_name[[:blank:]]*=[[:blank:]]*([[:alpha:].]{1,20})",REG_EXTENDED); regcomp(&re_xml_path,"xml_document_path[[:blank:]]*=[[:blank:]]*([[:alpha:]_/.]{1,50})",REG_EXTENDED); regcomp(&re_listenport,"listenport[[:blank:]]*=[[:blank:]]*([[:digit:]]+)",REG_EXTENDED); if ((conf_file=fopen(CONF_FILE,"r")) != NULL) { char line[MAX_CONFIG_LINE]; // Walk through the config file line by line while(fgets(line,MAX_CONFIG_LINE,conf_file) != NULL) { // Check if a comment line or an empty one if ( (0 != regexec(&re_comment,line,0,NULL,0) ) && (0 != regexec(&re_empty_row,line,0,NULL,0)) ) { // Chec if iptables_location if (regexec(&re_iptables_location,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->iptables, PATH_LEN, line, submatch); } // Check if create_forward_rules else if (regexec(&re_create_forward_rules,line,NMATCH,submatch,0) == 0) { char tmp[4]; getConfigOptionArgument(tmp,sizeof(tmp),line,submatch); vars->createForwardRules = strcmp(tmp,"yes")==0 ? 1 : 0; } // Check if forward_rules_append else if (regexec(&re_forward_rules_append,line,NMATCH,submatch,0) == 0) { char tmp[4]; getConfigOptionArgument(tmp,sizeof(tmp),line,submatch); vars->forwardRulesAppend = strcmp(tmp,"yes")==0 ? 1 : 0; } // Check forward_chain_name else if (regexec(&re_forward_chain_name,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->forwardChainName, CHAIN_NAME_LEN, line, submatch); } else if (regexec(&re_debug_mode,line,NMATCH,submatch,0) == 0) { char tmp[2]; getConfigOptionArgument(tmp,sizeof(tmp),line,submatch); vars->debug = atoi(tmp); } else if (regexec(&re_prerouting_chain_name,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->preroutingChainName, CHAIN_NAME_LEN, line, submatch); } else if (regexec(&re_upstream_bitrate,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->upstreamBitrate, BITRATE_LEN, line, submatch); } else if (regexec(&re_downstream_bitrate,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->downstreamBitrate, BITRATE_LEN, line, submatch); } else if (regexec(&re_duration,line,NMATCH,submatch,0) == 0) { getConfigOptionDuration(&vars->duration,line,submatch); } else if (regexec(&re_desc_doc,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->descDocName, PATH_LEN, line, submatch); } else if (regexec(&re_xml_path,line,NMATCH,submatch,0) == 0) { getConfigOptionArgument(vars->xmlPath, PATH_LEN, line, submatch); } else if (regexec(&re_listenport,line,NMATCH,submatch,0) == 0) { char tmp[6]; getConfigOptionArgument(tmp,sizeof(tmp),line,submatch); vars->listenport = atoi(tmp); } else { // We end up here if ther is an unknown config directive printf("Unknown config line: %s",line); } } } fclose(conf_file); } regfree(&re_comment); regfree(&re_empty_row); regfree(&re_iptables_location); regfree(&re_debug_mode); regfree(&re_create_forward_rules); regfree(&re_forward_rules_append); regfree(&re_forward_chain_name); regfree(&re_prerouting_chain_name); regfree(&re_upstream_bitrate); regfree(&re_downstream_bitrate); regfree(&re_duration); regfree(&re_desc_doc); regfree(&re_xml_path); regfree(&re_listenport); // Set default values for options not found in config file if (strnlen(vars->forwardChainName, CHAIN_NAME_LEN) == 0) { // No forward chain name was set in conf file, set it to default snprintf(vars->forwardChainName, CHAIN_NAME_LEN, IPTABLES_DEFAULT_FORWARD_CHAIN); } if (strnlen(vars->preroutingChainName, CHAIN_NAME_LEN) == 0) { // No prerouting chain name was set in conf file, set it to default snprintf(vars->preroutingChainName, CHAIN_NAME_LEN, IPTABLES_DEFAULT_PREROUTING_CHAIN); } if (strnlen(vars->upstreamBitrate, BITRATE_LEN) == 0) { // No upstream_bitrate was found in the conf file, set it to default snprintf(vars->upstreamBitrate, BITRATE_LEN, DEFAULT_UPSTREAM_BITRATE); } if (strnlen(vars->downstreamBitrate, BITRATE_LEN) == 0) { // No downstream bitrate was found in the conf file, set it to default snprintf(vars->downstreamBitrate, BITRATE_LEN, DEFAULT_DOWNSTREAM_BITRATE); } if (strnlen(vars->descDocName, PATH_LEN) == 0) { snprintf(vars->descDocName, PATH_LEN, DESC_DOC_DEFAULT); } if (strnlen(vars->xmlPath, PATH_LEN) == 0) { snprintf(vars->xmlPath, PATH_LEN, XML_PATH_DEFAULT); } if (strnlen(vars->iptables, PATH_LEN) == 0) { // Can't find the iptables executable, return -1 to // indicate en error return -1; } else { return 0; } } linux-igd-1.0+cvs20070630/config.h0000644000175000017500000000014210370245003016166 0ustar leveretleveret#ifndef _CONFIG_H_ #define _CONFIG_H_ int parseConfigFile(globals_p vars); #endif // _CONFIG_H_ linux-igd-1.0+cvs20070630/iptc.c0000644000175000017500000003010610501303404015652 0ustar leveretleveret#if HAVE_LIBIPTC #include #include #include #include #include #include #include #include #include /* inet_addr */ #include "globals.h" #include "util.h" #include "iptc.h" struct ipt_natinfo { struct ipt_entry_target t; struct ip_nat_multi_range mr; }; struct ipt_entry_match *get_tcp_match(const char *sports, const char *dports, unsigned int *nfcache); struct ipt_entry_match *get_udp_match(const char *sports, const char *dports, unsigned int *nfcache); struct ipt_entry_target *get_dnat_target(const char *input, unsigned int *nfcache); static u_int16_t parse_port(const char *port); static void parse_ports(const char *portstring, u_int16_t *ports); static int service_to_port(const char *name); static void parse_range(const char *input, struct ip_nat_range *range); static struct ipt_natinfo *append_range(struct ipt_natinfo *info, const struct ip_nat_range *range); static int matchcmp(const struct ipt_entry_match *match, const char *srcports, const char *destports); void iptc_add_rule(const char *table, const char *chain, const char *protocol, const char *iniface, const char *outiface, const char *src, const char *dest, const char *srcports, const char *destports, const char *target, const char *dnat_to, const int append) { iptc_handle_t handle; struct ipt_entry *chain_entry; struct ipt_entry_match *entry_match = NULL; struct ipt_entry_target *entry_target = NULL; ipt_chainlabel labelit; long match_size; int result = 0; chain_entry = calloc(1, sizeof(*chain_entry)); if (src) { chain_entry->ip.src.s_addr = inet_addr(src); chain_entry->ip.smsk.s_addr = inet_addr("255.255.255.255"); } if (dest) { chain_entry->ip.dst.s_addr = inet_addr(dest); chain_entry->ip.dmsk.s_addr = inet_addr("255.255.255.255"); } if (iniface) strncpy(chain_entry->ip.iniface, iniface, IFNAMSIZ); if (outiface) strncpy(chain_entry->ip.outiface, outiface, IFNAMSIZ); if (strcmp(protocol, "TCP") == 0) { chain_entry->ip.proto = IPPROTO_TCP; entry_match = get_tcp_match(srcports, destports, &chain_entry->nfcache); } else if (strcmp(protocol, "UDP") == 0) { chain_entry->ip.proto = IPPROTO_UDP; entry_match = get_udp_match(srcports, destports, &chain_entry->nfcache); } else { trace(1, "Unsupported protocol: %s", protocol); return; } if (strcmp(target, "") == 0 || strcmp(target, IPTC_LABEL_ACCEPT) == 0 || strcmp(target, IPTC_LABEL_DROP) == 0 || strcmp(target, IPTC_LABEL_QUEUE) == 0 || strcmp(target, IPTC_LABEL_RETURN) == 0) { size_t size; size = IPT_ALIGN(sizeof(struct ipt_entry_target)) + IPT_ALIGN(sizeof(int)); entry_target = calloc(1, size); entry_target->u.user.target_size = size; strncpy(entry_target->u.user.name, target, IPT_FUNCTION_MAXNAMELEN); } else if (strcmp(target, "DNAT") == 0) { entry_target = get_dnat_target(dnat_to, &chain_entry->nfcache); } if (entry_match) match_size = entry_match->u.match_size; else match_size = 0; chain_entry = realloc(chain_entry, sizeof(*chain_entry) + match_size + entry_target->u.target_size); memcpy(chain_entry->elems + match_size, entry_target, entry_target->u.target_size); chain_entry->target_offset = sizeof(*chain_entry) + match_size; chain_entry->next_offset = sizeof(*chain_entry) + match_size + entry_target->u.target_size; if (entry_match) memcpy(chain_entry->elems, entry_match, match_size); handle = iptc_init(table); if (!handle) { trace(1, "libiptc error: Can't initialize table %s, %s", table, iptc_strerror(errno)); return; } strncpy(labelit, chain, sizeof(ipt_chainlabel)); result = iptc_is_chain(chain, handle); if (!result) { trace(1, "libiptc error: Chain %s does not exist!", chain); return; } if (append) result = iptc_append_entry(labelit, chain_entry, &handle); else result = iptc_insert_entry(labelit, chain_entry, 0, &handle); if (!result) { trace(1, "libiptc error: Can't add, %s", iptc_strerror(errno)); return; } result = iptc_commit(&handle); if (!result) { trace(1, "libiptc error: Commit error, %s", iptc_strerror(errno)); return; } else trace(3, "added new rule to block successfully"); if (entry_match) free(entry_match); free(entry_target); free(chain_entry); } void iptc_delete_rule(const char *table, const char *chain, const char *protocol, const char *iniface, const char *outiface, const char *src, const char *dest, const char *srcports, const char *destports, const char *target, const char *dnat_to) { iptc_handle_t handle; const struct ipt_entry *e; ipt_chainlabel labelit; int i, result; unsigned long int s_src = INADDR_NONE, s_dest = INADDR_NONE; if (src) s_src = inet_addr(src); if (dest) s_dest = inet_addr(dest); handle = iptc_init(table); if (!handle) { trace(1, "libiptc error: Can't initialize table %s, %s", table, iptc_strerror(errno)); return; } strncpy(labelit, chain, sizeof(ipt_chainlabel)); result = iptc_is_chain(chain, handle); if (!result) { trace(1, "libiptc error: Chain %s does not exist!", chain); return; } /* check through rules to find match */ for (e = iptc_first_rule(chain, &handle), i=0; e; e = iptc_next_rule(e, &handle), i++) { if (s_src != INADDR_NONE && e->ip.src.s_addr != s_src) continue; if (s_dest != INADDR_NONE && e->ip.dst.s_addr != s_dest) continue; if (iniface && strcmp(e->ip.iniface, iniface) != 0) continue; if (outiface && strcmp(e->ip.outiface, outiface) != 0) continue; if (protocol && strcmp(protocol, "TCP") == 0 && e->ip.proto != IPPROTO_TCP) continue; if (protocol && strcmp(protocol, "UDP") == 0 && e->ip.proto != IPPROTO_UDP) continue; if ((srcports || destports) && IPT_MATCH_ITERATE(e, matchcmp, srcports, destports) == 0) continue; if (target && strcmp(target, iptc_get_target(e, &handle)) != 0) continue; if (dnat_to && strcmp(target, "DNAT") == 0) { struct ipt_entry_target *t; struct ip_nat_multi_range *mr; struct ip_nat_range *r, range; t = (void *) e+e->target_offset; mr = (void *) &t->data; if (mr->rangesize != 1) continue; /* we have only single dnat_to target now */ r = mr->range; parse_range(dnat_to, &range); if (r->flags == range.flags && r->min_ip == range.min_ip && r->max_ip == range.max_ip && r->min.all == range.min.all && r->max.all == range.max.all) { break; } } break; } if (!e) return; result = iptc_delete_num_entry(chain, i, &handle); if (!result) { trace(1, "libiptc error: Delete error, %s", iptc_strerror(errno)); return; } result = iptc_commit(&handle); if (!result) { trace(1, "libiptc error: Commit error, %s", iptc_strerror(errno)); return; } else trace(3, "deleted rule from block successfully"); } static int matchcmp(const struct ipt_entry_match *match, const char *srcports, const char *destports) { u_int16_t temp[2]; if (strcmp(match->u.user.name, "tcp") == 0) { struct ipt_tcp *tcpinfo = (struct ipt_tcp *)match->data; if (srcports) { parse_ports(srcports, temp); if (temp[0] != tcpinfo->spts[0] || temp[1] != tcpinfo->spts[1]) return 0; } if (destports) { parse_ports(destports, temp); if (temp[0] != tcpinfo->dpts[0] || temp[1] != tcpinfo->dpts[1]) return 0; } return 1; } else if (strcmp(match->u.user.name, "udp") == 0) { struct ipt_udp *udpinfo = (struct ipt_udp *)match->data; if (srcports) { parse_ports(srcports, temp); if (temp[0] != udpinfo->spts[0] || temp[1] != udpinfo->spts[1]) return 0; } if (destports) { parse_ports(destports, temp); if (temp[0] != udpinfo->dpts[0] || temp[1] != udpinfo->dpts[1]) return 0; } return 1; } else return 0; } /* These functions are used to create structs */ struct ipt_entry_match * get_tcp_match(const char *sports, const char *dports, unsigned int *nfcache) { struct ipt_entry_match *match; struct ipt_tcp *tcpinfo; size_t size; size = IPT_ALIGN(sizeof(*match)) + IPT_ALIGN(sizeof(*tcpinfo)); match = calloc(1, size); match->u.match_size = size; strncpy(match->u.user.name, "tcp", IPT_FUNCTION_MAXNAMELEN); tcpinfo = (struct ipt_tcp *)match->data; tcpinfo->spts[1] = tcpinfo->dpts[1] = 0xFFFF; if (sports) { *nfcache |= NFC_IP_SRC_PT; parse_ports(sports, tcpinfo->spts); } if (dports) { *nfcache |= NFC_IP_DST_PT; parse_ports(dports, tcpinfo->dpts); } return match; } struct ipt_entry_match * get_udp_match(const char *sports, const char *dports, unsigned int *nfcache) { struct ipt_entry_match *match; struct ipt_udp *udpinfo; size_t size; size = IPT_ALIGN(sizeof(*match)) + IPT_ALIGN(sizeof(*udpinfo)); match = calloc(1, size); match->u.match_size = size; strncpy(match->u.user.name, "udp", IPT_FUNCTION_MAXNAMELEN); udpinfo = (struct ipt_udp *)match->data; udpinfo->spts[1] = udpinfo->dpts[1] = 0xFFFF; if (sports) { *nfcache |= NFC_IP_SRC_PT; parse_ports(sports, udpinfo->spts); } if (dports) { *nfcache |= NFC_IP_DST_PT; parse_ports(dports, udpinfo->dpts); } return match; } struct ipt_entry_target * get_dnat_target(const char *input, unsigned int *nfcache) { struct ipt_entry_target *target; struct ipt_natinfo *info; struct ip_nat_range range; char *buffer; size_t size; /* Can't cache this */ *nfcache |= NFC_UNKNOWN; buffer = strdup(input); size = IPT_ALIGN(sizeof(*target)) + IPT_ALIGN(sizeof(struct ip_nat_multi_range)); target = calloc(1, size); target->u.target_size = size; strncpy(target->u.user.name, "DNAT", IPT_FUNCTION_MAXNAMELEN); info = (void *)target; parse_range(buffer, &range); target = &(append_range(info, &range)->t); free(buffer); return target; } /* Copied and modified from libipt_tcp.c and libipt_udp.c */ static u_int16_t parse_port(const char *port) { unsigned int portnum; if ((portnum = service_to_port(port)) != -1) { return (u_int16_t)portnum; } else { return atoi(port); } } static void parse_ports(const char *portstring, u_int16_t *ports) { char *buffer; char *cp; buffer = strdup(portstring); if ((cp = strchr(buffer, ':')) == NULL) ports[0] = ports[1] = parse_port(buffer); else { *cp = '\0'; cp++; ports[0] = buffer[0] ? parse_port(buffer) : 0; ports[1] = cp[0] ? parse_port(cp) : 0xFFFF; } free(buffer); } static int service_to_port(const char *name) { struct servent *service; if ((service = getservbyname(name, "tcp")) != NULL) return ntohs((unsigned short) service->s_port); return -1; } /* Copied and modified from libipt_DNAT.c */ static void parse_range(const char *input, struct ip_nat_range *range) { char *colon, *dash, *buffer; in_addr_t ip; buffer = strdup(input); memset(range, 0, sizeof(*range)); colon = strchr(buffer, ':'); if (colon) { int port; range->flags |= IP_NAT_RANGE_PROTO_SPECIFIED; port = atoi(colon+1); dash = strchr(colon, '-'); if (!dash) { range->min.all = range->max.all = htons(port); } else { int maxport; maxport = atoi(dash + 1); range->min.all = htons(port); range->max.all = htons(maxport); } /* Starts with a colon? No IP info...*/ if (colon == buffer) { free(buffer); return; } *colon = '\0'; } range->flags |= IP_NAT_RANGE_MAP_IPS; dash = strchr(buffer, '-'); if (colon && dash && dash > colon) dash = NULL; if (dash) *dash = '\0'; ip = inet_addr(buffer); range->min_ip = ip; if (dash) { ip = inet_addr(dash+1); range->max_ip = ip; } else range->max_ip = range->min_ip; free(buffer); return; } static struct ipt_natinfo * append_range(struct ipt_natinfo *info, const struct ip_nat_range *range) { unsigned int size; /* One ip_nat_range already included in ip_nat_multi_range */ size = IPT_ALIGN(sizeof(*info) + info->mr.rangesize * sizeof(*range)); info = realloc(info, size); info->t.u.target_size = size; info->mr.range[info->mr.rangesize] = *range; info->mr.rangesize++; return info; } #endif linux-igd-1.0+cvs20070630/iptc.h0000644000175000017500000000174010370245003015665 0ustar leveretleveret#ifndef _IPTC_H_ #define _IPTC_H_ void iptc_add_rule(const char *table, const char *chain, const char *protocol, const char *iiface, const char *oiface, const char *src, const char *dest, const char *srcports, const char *destports, const char *target, const char *dnat_to, const int append); void iptc_delete_rule(const char *table, const char *chain, const char *protocol, const char *iniface, const char *outiface, const char *src, const char *dest, const char *srcports, const char *destports, const char *target, const char *dnat_to); #endif // _IPTC_H_ linux-igd-1.0+cvs20070630/main.c0000644000175000017500000001262410641323364015660 0ustar leveretleveret#include #include #include #include #include #include #include #include #include #include #include #include #include "globals.h" #include "config.h" #include "gatedevice.h" #include "util.h" #include "pmlist.h" // Global variables globals g_vars; int main (int argc, char** argv) { char descDocUrl[7+15+1+5+1+sizeof(g_vars.descDocName)+1]; // http://ipaddr:port/docName char intIpAddress[16]; // Server internal ip address sigset_t sigsToCatch; int ret, signum, arg = 1, foreground = 0; if (argc < 3 || argc > 4) { printf("Usage: upnpd [-f] \n"); printf(" -f\tdon't daemonize\n"); printf("Example: upnpd ppp0 eth0\n"); exit(0); } parseConfigFile(&g_vars); // check for '-f' option if (strcmp(argv[arg], "-f") == 0) { foreground = 1; arg++; } // Save interface names for later use strncpy(g_vars.extInterfaceName, argv[arg++], IFNAMSIZ); strncpy(g_vars.intInterfaceName, argv[arg++], IFNAMSIZ); // Get the internal ip address to start the daemon on if (GetIpAddressStr(intIpAddress, g_vars.intInterfaceName) == 0) { fprintf(stderr, "Invalid internal interface name '%s'\n", g_vars.intInterfaceName); exit(EXIT_FAILURE); } if (!foreground) { struct rlimit resourceLimit = { 0, 0 }; pid_t pid, sid; unsigned int i; // Put igd in the background as a daemon process. pid = fork(); if (pid < 0) { perror("Error forking a new process."); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); // become session leader if ((sid = setsid()) < 0) { perror("Error running setsid"); exit(EXIT_FAILURE); } // close all file handles resourceLimit.rlim_max = 0; ret = getrlimit(RLIMIT_NOFILE, &resourceLimit); if (ret == -1) /* shouldn't happen */ { perror("error in getrlimit()"); exit(EXIT_FAILURE); } if (0 == resourceLimit.rlim_max) { fprintf(stderr, "Max number of open file descriptors is 0!!\n"); exit(EXIT_FAILURE); } for (i = 0; i < resourceLimit.rlim_max; i++) close(i); // fork again so child can never acquire a controlling terminal pid = fork(); if (pid < 0) { perror("Error forking a new process."); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); if ((chdir("/")) < 0) { perror("Error setting root directory"); exit(EXIT_FAILURE); } } umask(0); // End Daemon initialization openlog("upnpd", LOG_CONS | LOG_NDELAY | LOG_PID | (foreground ? LOG_PERROR : 0), LOG_LOCAL6); // Initialize UPnP SDK on the internal Interface trace(3, "Initializing UPnP SDK ... "); if ( (ret = UpnpInit(intIpAddress,g_vars.listenport) ) != UPNP_E_SUCCESS) { syslog (LOG_ERR, "Error Initializing UPnP SDK on IP %s port %d",intIpAddress,g_vars.listenport); syslog (LOG_ERR, " UpnpInit returned %d", ret); UpnpFinish(); exit(1); } trace(2, "UPnP SDK Successfully Initialized."); // Set the Device Web Server Base Directory trace(3, "Setting the Web Server Root Directory to %s",g_vars.xmlPath); if ( (ret = UpnpSetWebServerRootDir(g_vars.xmlPath)) != UPNP_E_SUCCESS ) { syslog (LOG_ERR, "Error Setting Web Server Root Directory to: %s", g_vars.xmlPath); syslog (LOG_ERR, " UpnpSetWebServerRootDir returned %d", ret); UpnpFinish(); exit(1); } trace(2, "Succesfully set the Web Server Root Directory."); //initialize the timer thread for expiration of mappings if (ExpirationTimerThreadInit()!=0) { syslog(LOG_ERR,"ExpirationTimerInit failed"); UpnpFinish(); exit(1); } // Form the Description Doc URL to pass to RegisterRootDevice sprintf(descDocUrl, "http://%s:%d/%s", UpnpGetServerIpAddress(), UpnpGetServerPort(), g_vars.descDocName); // Register our IGD as a valid UPnP Root device trace(3, "Registering the root device with descDocUrl %s", descDocUrl); if ( (ret = UpnpRegisterRootDevice(descDocUrl, EventHandler, &deviceHandle, &deviceHandle)) != UPNP_E_SUCCESS ) { syslog(LOG_ERR, "Error registering the root device with descDocUrl: %s", descDocUrl); syslog(LOG_ERR, " UpnpRegisterRootDevice returned %d", ret); UpnpFinish(); exit(1); } trace(2, "IGD root device successfully registered."); // Initialize the state variable table. StateTableInit(descDocUrl); // Record the startup time, for uptime startup_time = time(NULL); // Send out initial advertisements of our device's services with timeouts of 30 minutes if ( (ret = UpnpSendAdvertisement(deviceHandle, 1800) != UPNP_E_SUCCESS )) { syslog(LOG_ERR, "Error Sending Advertisements. Exiting ..."); UpnpFinish(); exit(1); } trace(2, "Advertisements Sent. Listening for requests ... "); // Loop until program exit signals received do { sigemptyset(&sigsToCatch); sigaddset(&sigsToCatch, SIGINT); sigaddset(&sigsToCatch, SIGTERM); sigaddset(&sigsToCatch, SIGUSR1); pthread_sigmask(SIG_SETMASK, &sigsToCatch, NULL); sigwait(&sigsToCatch, &signum); trace(3, "Caught signal %d...\n", signum); switch (signum) { case SIGUSR1: DeleteAllPortMappings(); break; default: break; } } while (signum!=SIGTERM && signum!=SIGINT); trace(2, "Shutting down on signal %d...\n", signum); // Cleanup UPnP SDK and free memory DeleteAllPortMappings(); ExpirationTimerThreadShutdown(); UpnpUnRegisterRootDevice(deviceHandle); UpnpFinish(); // Exit normally return (0); } linux-igd-1.0+cvs20070630/upnpd.80000644000175000017500000000313610434704704016006 0ustar leveretleveret.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH UPNPD 8 "March 5, 2006" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME upnpd \- Linux UPnP Internet Gateway Device daemon. .SH SYNOPSIS .B upnpd .RI .RI .SH DESCRIPTION This manual page documents briefly the .B upnpd command. .PP .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. \fBupnpd\fP is a daemon that daemon that emulates Microsoft's Internet Connection Service (ICS). It implements the UPnP Internet Gateway Device specification (IGD) and allows UPnP aware clients, such as MSN Messenger to work properly from behind a NAT firewall. .SH OPTIONS A summary of options is included below. .TP .B ext_ifname External interface name. .TP .B int_ifname Internal interface name. .SH AUTHOR upnpd was written by Glover George and others. .PP This manual page was written by Jos\['e] Fonseca , for the Debian project (but may be used by others). linux-igd-1.0+cvs20070630/util.c0000644000175000017500000000243310463755040015710 0ustar leveretleveret#include #include #include #include #include #include #include #include #include #include #include "globals.h" static int get_sockfd(void) { static int sockfd = -1; if (sockfd == -1) { if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW)) == -1) { perror("user: socket creating failed"); return (-1); } } return sockfd; } int GetIpAddressStr(char *address, char *ifname) { struct ifreq ifr; struct sockaddr_in *saddr; int fd; int succeeded = 0; fd = get_sockfd(); if (fd >= 0 ) { strncpy(ifr.ifr_name, ifname, IFNAMSIZ); ifr.ifr_addr.sa_family = AF_INET; if (ioctl(fd, SIOCGIFADDR, &ifr) == 0) { saddr = (struct sockaddr_in *)&ifr.ifr_addr; strcpy(address,inet_ntoa(saddr->sin_addr)); succeeded = 1; } else { syslog(LOG_ERR, "Failure obtaining ip address of interface %s", ifname); succeeded = 0; } } return succeeded; } void trace(int debuglevel, const char *format, ...) { va_list ap; va_start(ap,format); if (g_vars.debug>=debuglevel) { vsyslog(LOG_DEBUG,format,ap); } va_end(ap); } linux-igd-1.0+cvs20070630/util.h0000644000175000017500000000026310463755040015714 0ustar leveretleveret#ifndef _UTIL_H_ #define _UTIL_H_ int get_sockfd(void); int GetIpAddressStr(char *address, char *ifname); void trace(int debuglevel, const char *format, ...); #endif //_UTIL_H_ linux-igd-1.0+cvs20070630/INSTALL0000644000175000017500000001404010562460204015610 0ustar leveretleveretSimple Quick Install Guide This install guide is simply a quick helper to let people start testing the new version. It will be replaced soon with more thourough documentation. Installation ------------ This version of the linux-igd is written in C as opposed to previous version that was written in C++. This was done at the requests of many embedded developers, as well as some of our developers. The upnp sdk we now use from Intel is libupnp-1.3.1, and is written in C as well. Everything is a little more uniform now, and should create a smaller, leaner, faster device. Step 1 -- Download and install libupnp-1.3.1 source from http://www.sourceforge.net/projects/upnp. Please install with source only as we haven't tested against any precompiled versions. Also, as the "make install" doesn't quite work as expected, please follow these instructions to install it properly. (Note: See below regarding installing on Fedora Core 5!) 1. tar -xvzf libupnp-1.3.1.tar.gz 2. cd libupnp-1.3.1 3. ./configure 4. make 5. make install This process should install libupnp-1.3.1 to our liking (maybe not someone else's ;-) Step 2 -- Obtain the linux-igd software (if for some reason you're reading this outside the package you should have already gotten, http://linux-igd.sourceforge.net) 1. tar -xvzf linuxigd-1.0.tgz (or whatever the version you have is, or CVS) 2. To compile using the iptables command to manipulate netfilter tables, just say: make To compile with libiptc (part of iptables-devel) to manipulte netfilter tables, say: make HAVE_LIBIPTC=1 If libiptc is installed in a different directory than /usr/lib, e.g. /usr/local/lib, set LIBIPTC_PREFIX: make HAVE_LIBIPTC=1 LIBIPTC_PREFIX=/usr/local If libupnp is installed in a different directory than /usr/lib, e.g. /usr/local/lib, set LIBUPNP_PREFIX: make LIBUPNP_PREFIX=/usr/local 3. make install (if CVS, remove etc/CVS directory, then do) This will install linux-igd as /usr/sbin/upnpd. To install somewhere else, set PREFIX: make PREFIX=/usr/local install System Preparation before starting ---------------------------------- 1. In order for device discovery to function properly, you must add a multicast route to the internal interface like so: # route add -net 239.0.0.0 netmask 255.0.0.0 eth0 (or whatever your internal interface name is - here eth0) 2. If your internal interface is firewalled, then allow multicast packets, eg: # iptables -t filter -I INPUT 1 -s 224.0.0.0/4 -j ACCEPT # iptables -t filter -I INPUT 1 -d 224.0.0.0/4 -j ACCEPT -- Also, if you'd like to see debug information, and please do, as it helps us resolve your conflicts, perform the following steps: A. Add the following lines to bottom of your /etc/syslog.conf file # UPnP IGD messages local6.!=debug /var/log/messages local6.* /var/log/upnpd This will send all non-debug output to /var/log/messages, and all output including debug output to /var/log/upnpd. Modify as you like. B. service syslog restart (or on your system, maybe: /etc/rc.d/init.d/syslog restart or killall -HUP syslog Daemon Startup -------------- Now you should be ready to run the daemon. At this time, your FORWARD rule in iptables should be set to ACCEPT. We'll add the forwarding rules back right away, but first someone needs to tell me what they are, my FORWARD is always accept. Start the daemon with the following: upnpd Example: upnpd eth1 eth0 -- Where eth1 is my external interface name and eth0 is my internal interface name. Where the deamon isn't starting correctly, or exiting soon after with an error, you can start it with 'upnpd -f ', preventing it daemonizing into the background; error messages will be sent to stderr also - this is good for testing, but don't forget to have the multicast route setup for it to accept multicast requests. To check and see if everything starts up ok, in /var/log/debug you should see a few debug messages followed by Advertisements Sent, and possibly some GetNATRSIPStatus and other messages. Another way to check this is to look in your Windows XP client under Network Conections. You should see an Icon for Internet Connection set to enabled in there. If for some reason you don't, first try restarting the daemon. If this doesn't work post a message to the forums and we'll try to help you. REMINDERS and THANK YOUS ------------------------ Truth is I can't remember everyone to thank, but I especially want to thank both Henri Manson and Anders Betner for their development and testing work. Also Eric Wirt, for helping us test, and providing the winning comments for switching to C, alongside many others contributing patches and help. This is a work in progress. This code is simply released now for others to help us debug some problems we are having. Please, help us out by checking the forums, answering problems, and giving any advice and suggestions you can to the open source community. Thanks a lot to the users, and to the over 10,000 downloads, and countless CVS checkouts. If it weren't for the interest in the program, we wouldn't be touching it (ok maybe i would, when i got bored or something) :-) Cheers all Dime ----------------------------------------------------------------------- Notes: Installing on Fedora Core 5 For Fedora Core 5 there are RPMs available for libupnp 1.3.1 and iptables 1.3.5: # yum install iptables-devel libupnp libupnp-devel The files are installed in /usr/lib and /usr/include. One thing about iptables-devel is that it includes libiptc.a, but not the corresponding header files: ipt_kernel_headers.h and libiptc.h. You will have to get hold of them from a source tarball, e.g. http://www.netfilter.org/projects/iptables/files/iptables-1.3.5.tar.bz2. Unpack the source, find the two header files, and place them in an include directory beside linux-igd, like this: $ ls ../include/libiptc/ ipt_kernel_headers.h libiptc.h After that all you have to do is compile upnpd: $ make HAVE_LIBIPTC=1 And as root: # make install /Magnus linux-igd-1.0+cvs20070630/globals.h0000644000175000017500000000405210641323364016360 0ustar leveretleveret#ifndef _GLOBALS_H_ #define _GLOBALS_H_ #include #define CHAIN_NAME_LEN 32 #define BITRATE_LEN 32 #define PATH_LEN 64 #define RESULT_LEN 512 #define NUM_LEN 32 #ifndef min #define min(a,b) ((a) < (b) ? (a) : (b)) #endif struct GLOBALS { char extInterfaceName[IFNAMSIZ]; // The name of the external interface, picked up from the // command line char intInterfaceName[IFNAMSIZ]; // The name of the internal interface, picked from command line // All vars below are read from /etc/upnpd.conf in main.c int debug; // 1 - print debug messages to syslog // 0 - no debug messages char iptables[PATH_LEN]; // The full name and path of the iptables executable, used in pmlist.c char upstreamBitrate[BITRATE_LEN]; // The upstream bitrate reported by the daemon char downstreamBitrate[BITRATE_LEN]; // The downstream bitrate reported by the daemon char forwardChainName[CHAIN_NAME_LEN]; // The name of the iptables chain to put FORWARD rules in char preroutingChainName[CHAIN_NAME_LEN]; // The name of the chain to put PREROUTING rules in int createForwardRules; // 1 - create rules in forward chain // 0 - do not create rules in forward chain int forwardRulesAppend; // 1 - add rules to end of forward chain // 0 - add rules to start of forward chain long int duration; // 0 - no duration // >0 - duration in seconds // <0 - expiration time char descDocName[PATH_LEN]; char xmlPath[PATH_LEN]; int listenport; //The port to listen on }; typedef struct GLOBALS* globals_p; typedef struct GLOBALS globals; extern globals g_vars; #define CONF_FILE "/etc/upnpd.conf" #define MAX_CONFIG_LINE 256 #define IPTABLES_DEFAULT_FORWARD_CHAIN "FORWARD" #define IPTABLES_DEFAULT_PREROUTING_CHAIN "PREROUTING" #define DEFAULT_DURATION 0 #define DEFAULT_UPSTREAM_BITRATE "0" #define DEFAULT_DOWNSTREAM_BITRATE "0" #define DESC_DOC_DEFAULT "gatedesc.xml" #define XML_PATH_DEFAULT "/etc/linuxigd" #endif // _GLOBALS_H_ linux-igd-1.0+cvs20070630/CHANGES0000644000175000017500000001261410641323666015567 0ustar leveretleveret2007-06-30 Magnus Hyllander * Added the listenport option, which lets you select which UPnP port to listen to. The port number is passed to UpnpInit when initializing the UPnP library. This is useful if you are running several UPnP services on your firewall, and only specific ports have been opened. Gmediaserver has this option also, for example. * Renamed the insert_forward_rules option to create_forward_rules to better reflect what it actually does. Fixed the erroneous description of the option. * Added the forward_rules_append to do what people thought insert_forward_rules did, i.e. control whether to append or insert rules in the forward chain. The option description also includes a tip about what to do if neither insert or append is what you need. * Fixed pmlist_AddPortMapping. It was doing different things when using iptables or iptc to create rules. The iptc method was inserting in the forward chain and appending to the prerouting chain, while the iptables method was doing the opposite. Now both methods append to the prerouting chain, and forward_rules_append controls whether to insert or append to the forward chain. * Added trace output when using iptc to add and delete rules (for debug_mode=3). * Fixed the parsing of the create_forward_rules and forward_rules_append options. The regular expression just wouldn't take "no" for an answer :-) 2007-04-23 Rosfran Borges * Removed unused files on the linux-igd_autotools version. 2007-03-26 Rosfran Borges * Created the CVS tag 'linux-igd_autotools', to add all the automake/autotools related issues. * Fixed some installation issues, regarding lib-installing to the correct directory, and copying the header files to the destination dir (make install). * Put 'pkg-config' resource to the Linux IGD library. The name of the PKG-CONFIG resource is 'linux-igd', plus the minor and major version. Actually, the version is '0.1', so the library config file is: 'linux-igd-0.1.pc'. You can type: 'pkg-config --cflags --libs linux-igd-0.1'. * Many adjustments in the automake/autoconf configuration files (configure.ac, Makefile.am) - some autotools misusage fixed. * Fixed some library dependencies. 2007-02-07 Daniel J Blueman * Fixed interface statistics gathering and streamlined into a single function. * linux-igd 1.0 released 2006-10-01 Daniel J Blueman * Fixed compilation on GCC-2.9x, noticed by Vyacheslav Garashchenko. * Use bounded string functions, to protect from overflow exploits/stack-smashing. 2006-08-13 Daniel J Blueman * linux-igd 0.95 released 2006-07-25 Daniel J Blueman * Added option ALLOW_MULTICAST to init script, which when not set to 'no', enables multicast packets to be received by internal interface * Added '-f' option to run in foreground for debugging etc * Validate internal interface name correctly * Other minor tweaks, such as making variables local to block to save on stack space, interface name length fixes 2006-05-23 Daniel J Blueman * Added manpage contributed by Jos Fonseca 2006-05-19 Daniel J Blueman * Protect against bad addresses being passed to inet_addr() * Enable compiler optimization in makefile * Fix compile warnings and uninitialised variable possible use * Some makefile and code cleanups 2006-05-04 mhyllander * Updated installation instructions for libupnp 1.3.1, and also added a note about installing with precompiled libraries on Fedora Core 5. 2006-02-01 mhyllander * Fixed problem with multiple children being forked when using iptables to modify the netfilter tables. upnpd was doing a fork+system without a following exit, so children continued living on. Now a fork+exec+exit is done. * Included a patch from Juho Vh-Herttua to fix inserting of forward rules when using libiptc. http://sourceforge.net/forum/forum.php?thread_id=1270012&forum_id=174960 http://users.tkk.fi/~jvahaher/linux-igd/linux-igd_insert.diff * Added handling of port mapping duration. Port mappings will be automatically removed when they expire. If the client doesn't set a duration, a default duration can be used. The default duration can either be set as a relative time (e.g. two hours), or as an absolute time of day (e.g. 04:00 every day). * You can force upnpd to delete all port mappings by sending it the SIGUSR1 signal. The SIGINT and SIGTERM signals terminate upnpd. * Made parsing of the configuration file more secure by guarding against buffer overflow. * In the configuration file, the path to the iptables command is now specified between quotes, to allow all characters to be used in the path. * syslog messages are now sent to local6. Trace output is sent to LOG_DEBUG. You can specify the log level in the configuration file by setting debug_mode between 0 (no output) and 3 (all output). * added an example init.d script: etc/upnpd.rc. * Some code cleanups, like only defining globals in one place (i.e. not in an include file), and some improvements to the Makefile.