code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* $Id: testgetgateway.c,v 1.4 2008/07/02 22:33:06 nanard Exp $ */ /* libnatpmp * Copyright (c) 2007, Thomas BERNARD <miniupnp@free.fr> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #ifdef WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <arpa/inet.h> #endif #include "getgateway.h" int main(int argc, char * * argv) { struct in_addr gatewayaddr; int r; #ifdef WIN32 uint32_t temp = 0; r = getdefaultgateway(&temp); gatewayaddr.S_un.S_addr = temp; #else r = getdefaultgateway(&(gatewayaddr.s_addr)); #endif if(r>=0) printf("default gateway : %s\n", inet_ntoa(gatewayaddr)); else fprintf(stderr, "getdefaultgateway() failed\n"); return 0; }
118controlsman-testtest
TCMPortMapper/framework/libnatpmp/testgetgateway.c
C
mit
1,382
/* $Id: natpmp.h,v 1.10 2008/07/02 22:33:06 nanard Exp $ */ /* libnatpmp * Copyright (c) 2007-2008, Thomas BERNARD <miniupnp@free.fr> * http://miniupnp.free.fr/libnatpmp.html * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __NATPMP_H__ #define __NATPMP_H__ /* NAT-PMP Port as defined by the NAT-PMP draft */ #define NATPMP_PORT (5351) #include <time.h> #include <sys/time.h> #ifdef WIN32 #include <winsock2.h> #include <stdint.h> #define in_addr_t uint32_t #else #include <netinet/in.h> #endif #include "declspec.h" typedef struct { int s; /* socket */ in_addr_t gateway; /* default gateway (IPv4) */ int has_pending_request; unsigned char pending_request[12]; int pending_request_len; int try_number; struct timeval retry_time; } natpmp_t; typedef struct { uint16_t type; /* NATPMP_RESPTYPE_* */ uint16_t resultcode; /* NAT-PMP response code */ uint32_t epoch; /* Seconds since start of epoch */ union { struct { //in_addr_t addr; struct in_addr addr; } publicaddress; struct { uint16_t privateport; uint16_t mappedpublicport; uint32_t lifetime; } newportmapping; } pnu; } natpmpresp_t; /* possible values for type field of natpmpresp_t */ #define NATPMP_RESPTYPE_PUBLICADDRESS (0) #define NATPMP_RESPTYPE_UDPPORTMAPPING (1) #define NATPMP_RESPTYPE_TCPPORTMAPPING (2) /* Values to pass to sendnewportmappingrequest() */ #define NATPMP_PROTOCOL_UDP (1) #define NATPMP_PROTOCOL_TCP (2) /* return values */ /* NATPMP_ERR_INVALIDARGS : invalid arguments passed to the function */ #define NATPMP_ERR_INVALIDARGS (-1) /* NATPMP_ERR_SOCKETERROR : socket() failed. check errno for details */ #define NATPMP_ERR_SOCKETERROR (-2) /* NATPMP_ERR_CANNOTGETGATEWAY : can't get default gateway IP */ #define NATPMP_ERR_CANNOTGETGATEWAY (-3) /* NATPMP_ERR_CLOSEERR : close() failed. check errno for details */ #define NATPMP_ERR_CLOSEERR (-4) /* NATPMP_ERR_RECVFROM : recvfrom() failed. check errno for details */ #define NATPMP_ERR_RECVFROM (-5) /* NATPMP_ERR_NOPENDINGREQ : readnatpmpresponseorretry() called while * no NAT-PMP request was pending */ #define NATPMP_ERR_NOPENDINGREQ (-6) /* NATPMP_ERR_NOGATEWAYSUPPORT : the gateway does not support NAT-PMP */ #define NATPMP_ERR_NOGATEWAYSUPPORT (-7) /* NATPMP_ERR_CONNECTERR : connect() failed. check errno for details */ #define NATPMP_ERR_CONNECTERR (-8) /* NATPMP_ERR_WRONGPACKETSOURCE : packet not received from the network gateway */ #define NATPMP_ERR_WRONGPACKETSOURCE (-9) /* NATPMP_ERR_SENDERR : send() failed. check errno for details */ #define NATPMP_ERR_SENDERR (-10) /* NATPMP_ERR_FCNTLERROR : fcntl() failed. check errno for details */ #define NATPMP_ERR_FCNTLERROR (-11) /* NATPMP_ERR_GETTIMEOFDAYERR : gettimeofday() failed. check errno for details */ #define NATPMP_ERR_GETTIMEOFDAYERR (-12) /* */ #define NATPMP_ERR_UNSUPPORTEDVERSION (-14) #define NATPMP_ERR_UNSUPPORTEDOPCODE (-15) /* Errors from the server : */ #define NATPMP_ERR_UNDEFINEDERROR (-49) #define NATPMP_ERR_NOTAUTHORIZED (-51) #define NATPMP_ERR_NETWORKFAILURE (-52) #define NATPMP_ERR_OUTOFRESOURCES (-53) /* NATPMP_TRYAGAIN : no data available for the moment. try again later */ #define NATPMP_TRYAGAIN (-100) /* initnatpmp() * initialize a natpmp_t object * Return values : * 0 = OK * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_SOCKETERROR * NATPMP_ERR_FCNTLERROR * NATPMP_ERR_CANNOTGETGATEWAY * NATPMP_ERR_CONNECTERR */ LIBSPEC int initnatpmp(natpmp_t * p); /* closenatpmp() * close resources associated with a natpmp_t object * Return values : * 0 = OK * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_CLOSEERR */ LIBSPEC int closenatpmp(natpmp_t * p); /* sendpublicaddressrequest() * send a public address NAT-PMP request to the network gateway * Return values : * 2 = OK (size of the request) * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_SENDERR */ LIBSPEC int sendpublicaddressrequest(natpmp_t * p); /* sendnewportmappingrequest() * send a new port mapping NAT-PMP request to the network gateway * Arguments : * protocol is either NATPMP_PROTOCOL_TCP or NATPMP_PROTOCOL_UDP, * lifetime is in seconds. * To remove a port mapping, set lifetime to zero. * To remove all port mappings to the host, set lifetime and both ports * to zero. * Return values : * 12 = OK (size of the request) * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_SENDERR */ LIBSPEC int sendnewportmappingrequest(natpmp_t * p, int protocol, uint16_t privateport, uint16_t publicport, uint32_t lifetime); /* getnatpmprequesttimeout() * fills the timeval structure with the timeout duration of the * currently pending NAT-PMP request. * Return values : * 0 = OK * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_GETTIMEOFDAYERR * NATPMP_ERR_NOPENDINGREQ */ LIBSPEC int getnatpmprequesttimeout(natpmp_t * p, struct timeval * timeout); /* readnatpmpresponseorretry() * fills the natpmpresp_t structure if possible * Return values : * 0 = OK * NATPMP_TRYAGAIN * NATPMP_ERR_INVALIDARGS * NATPMP_ERR_NOPENDINGREQ * NATPMP_ERR_NOGATEWAYSUPPORT * NATPMP_ERR_RECVFROM * NATPMP_ERR_WRONGPACKETSOURCE * NATPMP_ERR_UNSUPPORTEDVERSION * NATPMP_ERR_UNSUPPORTEDOPCODE * NATPMP_ERR_NOTAUTHORIZED * NATPMP_ERR_NETWORKFAILURE * NATPMP_ERR_OUTOFRESOURCES * NATPMP_ERR_UNSUPPORTEDOPCODE * NATPMP_ERR_UNDEFINEDERROR */ LIBSPEC int readnatpmpresponseorretry(natpmp_t * p, natpmpresp_t * response); #ifdef ENABLE_STRNATPMPERR LIBSPEC const char * strnatpmperr(int t); #endif #endif
118controlsman-testtest
TCMPortMapper/framework/libnatpmp/natpmp.h
C
mit
6,152
@echo Compile getgateway gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR getgateway.c gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR testgetgateway.c gcc -o testgetgateway getgateway.o testgetgateway.o -lws2_32 @echo Compile natpmp: gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR getgateway.c gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR natpmp.c gcc -c -Wall -Os -DWIN32 -DSTATICLIB -DENABLE_STRNATPMPERR natpmpc.c gcc -c -Wall -Os -DWIN32 wingettimeofday.c gcc -o natpmpc getgateway.o natpmp.o natpmpc.o wingettimeofday.o -lws2_32 @echo Create natpmp.dll: gcc -c -Wall -Os -DWIN32 -DENABLE_STRNATPMPERR -DNATPMP_EXPORTS getgateway.c gcc -c -Wall -Os -DWIN32 -DENABLE_STRNATPMPERR -DNATPMP_EXPORTS natpmp.c dllwrap -k --driver-name gcc --def natpmp.def --output-def natpmp.dll.def --implib natpmp.lib -o natpmp.dll getgateway.o natpmp.o wingettimeofday.o -lws2_32
118controlsman-testtest
TCMPortMapper/framework/libnatpmp/build.bat
Batchfile
mit
917
#ifndef __DECLSPEC_H__ #define __DECLSPEC_H__ #if defined(WIN32) && !defined(STATICLIB) #ifdef NATPMP_EXPORTS #define LIBSPEC __declspec(dllexport) #else #define LIBSPEC __declspec(dllimport) #endif #else #define LIBSPEC #endif #endif
118controlsman-testtest
TCMPortMapper/framework/libnatpmp/declspec.h
C
mit
246
/* $Id: getgateway.c,v 1.12 2008/10/06 10:04:16 nanard Exp $ */ /* libnatpmp * Copyright (c) 2007-2008, Thomas BERNARD <miniupnp@free.fr> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <ctype.h> #ifndef WIN32 #include <netinet/in.h> #endif #include <sys/param.h> /* There is no portable method to get the default route gateway. * So below are three differents functions implementing this. * Parsing /proc/net/route is for linux. * sysctl is the way to access such informations on BSD systems. * Many systems should provide route information through raw PF_ROUTE * sockets. */ #ifdef __linux__ #define USE_PROC_NET_ROUTE #undef USE_SOCKET_ROUTE #undef USE_SYSCTL_NET_ROUTE #endif #ifdef BSD #undef USE_PROC_NET_ROUTE #define USE_SOCKET_ROUTE #undef USE_SYSCTL_NET_ROUTE #endif #ifdef __APPLE__ #undef USE_PROC_NET_ROUTE #undef USE_SOCKET_ROUTE #define USE_SYSCTL_NET_ROUTE #endif #if (defined(sun) && defined(__SVR4)) #undef USE_PROC_NET_ROUTE #define USE_SOCKET_ROUTE #undef USE_SYSCTL_NET_ROUTE #endif #ifdef WIN32 #undef USE_PROC_NET_ROUTE #undef USE_SOCKET_ROUTE #undef USE_SYSCTL_NET_ROUTE #define USE_WIN32_CODE #endif #ifdef USE_SYSCTL_NET_ROUTE #include <stdlib.h> #include <sys/sysctl.h> #include <sys/socket.h> #include <net/route.h> #endif #ifdef USE_SOCKET_ROUTE #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <net/if.h> #include <net/route.h> #endif #ifdef WIN32 #include <unknwn.h> #include <winreg.h> #define MAX_KEY_LENGTH 255 #define MAX_VALUE_LENGTH 16383 #endif #include "getgateway.h" #ifndef WIN32 #define SUCCESS (0) #define FAILED (-1) #endif #ifdef USE_PROC_NET_ROUTE int getdefaultgateway(in_addr_t * addr) { long d, g; char buf[256]; int line = 0; FILE * f; char * p; f = fopen("/proc/net/route", "r"); if(!f) return FAILED; while(fgets(buf, sizeof(buf), f)) { if(line > 0) { p = buf; while(*p && !isspace(*p)) p++; while(*p && isspace(*p)) p++; if(sscanf(p, "%lx%lx", &d, &g)==2) { if(d == 0) { /* default */ *addr = g; fclose(f); return SUCCESS; } } } line++; } /* default route not found ! */ if(f) fclose(f); return FAILED; } #endif /* #ifdef USE_PROC_NET_ROUTE */ #ifdef USE_SYSCTL_NET_ROUTE #define ROUNDUP(a) \ ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long)) int getdefaultgateway(in_addr_t * addr) { #if 0 /* net.route.0.inet.dump.0.0 ? */ int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0, 0/*tableid*/}; #endif /* net.route.0.inet.flags.gateway */ int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY}; size_t l; char * buf, * p; struct rt_msghdr * rt; struct sockaddr * sa; struct sockaddr * sa_tab[RTAX_MAX]; int i; int r = FAILED; if(sysctl(mib, sizeof(mib)/sizeof(int), 0, &l, 0, 0) < 0) { return FAILED; } if(l>0) { buf = malloc(l); if(sysctl(mib, sizeof(mib)/sizeof(int), buf, &l, 0, 0) < 0) { free(buf); return FAILED; } for(p=buf; p<buf+l; p+=rt->rtm_msglen) { rt = (struct rt_msghdr *)p; sa = (struct sockaddr *)(rt + 1); for(i=0; i<RTAX_MAX; i++) { if(rt->rtm_addrs & (1 << i)) { sa_tab[i] = sa; sa = (struct sockaddr *)((char *)sa + ROUNDUP(sa->sa_len)); } else { sa_tab[i] = NULL; } } if( ((rt->rtm_addrs & (RTA_DST|RTA_GATEWAY)) == (RTA_DST|RTA_GATEWAY)) && sa_tab[RTAX_DST]->sa_family == AF_INET && sa_tab[RTAX_GATEWAY]->sa_family == AF_INET) { if(((struct sockaddr_in *)sa_tab[RTAX_DST])->sin_addr.s_addr == 0) { *addr = ((struct sockaddr_in *)(sa_tab[RTAX_GATEWAY]))->sin_addr.s_addr; r = SUCCESS; } } } free(buf); } return r; } #endif /* #ifdef USE_SYSCTL_NET_ROUTE */ #ifdef USE_SOCKET_ROUTE /* Thanks to Darren Kenny for this code */ #define NEXTADDR(w, u) \ if (rtm_addrs & (w)) {\ l = sizeof(struct sockaddr); memmove(cp, &(u), l); cp += l;\ } #define rtm m_rtmsg.m_rtm struct { struct rt_msghdr m_rtm; char m_space[512]; } m_rtmsg; int getdefaultgateway(in_addr_t *addr) { int s, seq, l, rtm_addrs, i; pid_t pid; struct sockaddr so_dst, so_mask; char *cp = m_rtmsg.m_space; struct sockaddr *gate = NULL, *sa; struct rt_msghdr *msg_hdr; pid = getpid(); seq = 0; rtm_addrs = RTA_DST | RTA_NETMASK; memset(&so_dst, 0, sizeof(so_dst)); memset(&so_mask, 0, sizeof(so_mask)); memset(&rtm, 0, sizeof(struct rt_msghdr)); rtm.rtm_type = RTM_GET; rtm.rtm_flags = RTF_UP | RTF_GATEWAY; rtm.rtm_version = RTM_VERSION; rtm.rtm_seq = ++seq; rtm.rtm_addrs = rtm_addrs; so_dst.sa_family = AF_INET; so_mask.sa_family = AF_INET; NEXTADDR(RTA_DST, so_dst); NEXTADDR(RTA_NETMASK, so_mask); rtm.rtm_msglen = l = cp - (char *)&m_rtmsg; s = socket(PF_ROUTE, SOCK_RAW, 0); if (write(s, (char *)&m_rtmsg, l) < 0) { close(s); return FAILED; } do { l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg)); } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid)); close(s); msg_hdr = &rtm; cp = ((char *)(msg_hdr + 1)); if (msg_hdr->rtm_addrs) { for (i = 1; i; i <<= 1) if (i & msg_hdr->rtm_addrs) { sa = (struct sockaddr *)cp; if (i == RTA_GATEWAY ) gate = sa; cp += sizeof(struct sockaddr); } } else { return FAILED; } if (gate != NULL ) { *addr = ((struct sockaddr_in *)gate)->sin_addr.s_addr; return SUCCESS; } else { return FAILED; } } #endif /* #ifdef USE_SOCKET_ROUTE */ #ifdef USE_WIN32_CODE int getdefaultgateway(in_addr_t * addr) { HKEY networkCardsKey; HKEY networkCardKey; HKEY interfacesKey; HKEY interfaceKey; DWORD i = 0; DWORD numSubKeys = 0; TCHAR keyName[MAX_KEY_LENGTH]; DWORD keyNameLength = MAX_KEY_LENGTH; TCHAR keyValue[MAX_VALUE_LENGTH]; DWORD keyValueLength = MAX_VALUE_LENGTH; DWORD keyValueType = REG_SZ; TCHAR gatewayValue[MAX_VALUE_LENGTH]; DWORD gatewayValueLength = MAX_VALUE_LENGTH; DWORD gatewayValueType = REG_MULTI_SZ; int done = 0; char networkCardsPath[] = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards"; char interfacesPath[] = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces"; // The windows registry lists its primary network devices in the following location: // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards // // Each network device has its own subfolder, named with an index, with various properties: // -NetworkCards // -5 // -Description = Broadcom 802.11n Network Adapter // -ServiceName = {E35A72F8-5065-4097-8DFE-C7790774EE4D} // -8 // -Description = Marvell Yukon 88E8058 PCI-E Gigabit Ethernet Controller // -ServiceName = {86226414-5545-4335-A9D1-5BD7120119AD} // // The above service name is the name of a subfolder within: // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces // // There may be more subfolders in this interfaces path than listed in the network cards path above: // -Interfaces // -{3a539854-6a70-11db-887c-806e6f6e6963} // -DhcpIPAddress = 0.0.0.0 // -[more] // -{E35A72F8-5065-4097-8DFE-C7790774EE4D} // -DhcpIPAddress = 10.0.1.4 // -DhcpDefaultGateway = 10.0.1.1 // -[more] // -{86226414-5545-4335-A9D1-5BD7120119AD} // -DhcpIpAddress = 10.0.1.5 // -DhcpDefaultGateay = 10.0.1.1 // -[more] // // In order to extract this information, we enumerate each network card, and extract the ServiceName value. // This is then used to open the interface subfolder, and attempt to extract a DhcpDefaultGateway value. // Once one is found, we're done. // // It may be possible to simply enumerate the interface folders until we find one with a DhcpDefaultGateway value. // However, the technique used is the technique most cited on the web, and we assume it to be more correct. if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predifined key networkCardsPath, // Name of registry subkey to open 0, // Reserved - must be zero KEY_READ, // Mask - desired access rights &networkCardsKey)) // Pointer to output key { // Unable to open network cards keys return -1; } if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predefined key interfacesPath, // Name of registry subkey to open 0, // Reserved - must be zero KEY_READ, // Mask - desired access rights &interfacesKey)) // Pointer to output key { // Unable to open interfaces key RegCloseKey(networkCardsKey); return -1; } // Figure out how many subfolders are within the NetworkCards folder RegQueryInfoKey(networkCardsKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //printf( "Number of subkeys: %u\n", (unsigned int)numSubKeys); // Enumrate through each subfolder within the NetworkCards folder for(i = 0; i < numSubKeys && !done; i++) { keyNameLength = MAX_KEY_LENGTH; if(ERROR_SUCCESS == RegEnumKeyEx(networkCardsKey, // Open registry key i, // Index of subkey to retrieve keyName, // Buffer that receives the name of the subkey &keyNameLength, // Variable that receives the size of the above buffer NULL, // Reserved - must be NULL NULL, // Buffer that receives the class string NULL, // Variable that receives the size of the above buffer NULL)) // Variable that receives the last write time of subkey { if(RegOpenKeyEx(networkCardsKey, keyName, 0, KEY_READ, &networkCardKey) == ERROR_SUCCESS) { keyValueLength = MAX_VALUE_LENGTH; if(ERROR_SUCCESS == RegQueryValueEx(networkCardKey, // Open registry key "ServiceName", // Name of key to query NULL, // Reserved - must be NULL &keyValueType, // Receives value type keyValue, // Receives value &keyValueLength)) // Receives value length in bytes { //printf("keyValue: %s\n", keyValue); if(RegOpenKeyEx(interfacesKey, keyValue, 0, KEY_READ, &interfaceKey) == ERROR_SUCCESS) { gatewayValueLength = MAX_VALUE_LENGTH; if(ERROR_SUCCESS == RegQueryValueEx(interfaceKey, // Open registry key "DhcpDefaultGateway", // Name of key to query NULL, // Reserved - must be NULL &gatewayValueType, // Receives value type gatewayValue, // Receives value &gatewayValueLength)) // Receives value length in bytes { // Check to make sure it's a string if(gatewayValueType == REG_MULTI_SZ || gatewayValueType == REG_SZ) { //printf("gatewayValue: %s\n", gatewayValue); done = 1; } } RegCloseKey(interfaceKey); } } RegCloseKey(networkCardKey); } } } RegCloseKey(interfacesKey); RegCloseKey(networkCardsKey); if(done) { *addr = inet_addr(gatewayValue); return 0; } return -1; } #endif /* #ifdef USE_WIN32_CODE */
118controlsman-testtest
TCMPortMapper/framework/libnatpmp/getgateway.c
C
mit
12,668
// // TCMNATPMPPortMapper.h // Encapsulates libnatpmp, listens for router changes // // Copyright (c) 2007-2008 TheCodingMonkeys: // Martin Pittenauer, Dominik Wagner, <http://codingmonkeys.de> // Some rights reserved: <http://opensource.org/licenses/mit-license.php> // #import "TCMPortMapper.h" #import "natpmp.h" extern NSString * const TCMNATPMPPortMapperDidFailNotification; extern NSString * const TCMNATPMPPortMapperDidGetExternalIPAddressNotification; extern NSString * const TCMNATPMPPortMapperDidBeginWorkingNotification; extern NSString * const TCMNATPMPPortMapperDidEndWorkingNotification ; extern NSString * const TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification; typedef enum { TCMExternalIPThreadID = 0, TCMUpdatingMappingThreadID = 1, } TCMPortMappingThreadID; @interface TCMNATPMPPortMapper : NSObject { NSLock *natPMPThreadIsRunningLock; int IPAddressThreadShouldQuitAndRestart; BOOL UpdatePortMappingsThreadShouldQuit; BOOL UpdatePortMappingsThreadShouldRestart; TCMPortMappingThreadID runningThreadID; NSTimer *_updateTimer; NSTimeInterval _updateInterval; NSString *_lastExternalIPSenderAddress; NSString *_lastBroadcastedExternalIP; CFSocketRef _externalAddressChangeListeningSocket; } - (void)refresh; - (void)stop; - (void)updatePortMappings; - (void)stopBlocking; - (void)ensureListeningToExternalIPAddressChanges; - (void)stopListeningToExternalIPAddressChanges; @end
118controlsman-testtest
TCMPortMapper/framework/TCMNATPMPPortMapper.h
Objective-C
mit
1,478
// // TCMPortMapper.h // Establishes port mapping via upnp or natpmp // // Copyright (c) 2007-2008 TheCodingMonkeys: // Martin Pittenauer, Dominik Wagner, <http://codingmonkeys.de> // Some rights reserved: <http://opensource.org/licenses/mit-license.php> // #import <Foundation/Foundation.h> #import <errno.h> #import <string.h> #import <unistd.h> extern NSString * const TCMPortMapperExternalIPAddressDidChange; extern NSString * const TCMPortMapperWillStartSearchForRouterNotification; extern NSString * const TCMPortMapperDidFinishSearchForRouterNotification; extern NSString * const TCMPortMapperDidStartWorkNotification; extern NSString * const TCMPortMapperDidFinishWorkNotification; extern NSString * const TCMPortMapperDidReceiveUPNPMappingTableNotification; extern NSString * const TCMPortMappingDidChangeMappingStatusNotification; extern NSString * const TCMNATPMPPortMapProtocol; extern NSString * const TCMUPNPPortMapProtocol; extern NSString * const TCMNoPortMapProtocol; typedef enum { TCMPortMappingStatusUnmapped = 0, TCMPortMappingStatusTrying = 1, TCMPortMappingStatusMapped = 2 } TCMPortMappingStatus; typedef enum { TCMPortMappingTransportProtocolUDP = 1, TCMPortMappingTransportProtocolTCP = 2, TCMPortMappingTransportProtocolBoth = 3 } TCMPortMappingTransportProtocol; @interface TCMPortMapping : NSObject { int _localPort; int _externalPort; int _desiredExternalPort; id _userInfo; TCMPortMappingStatus _mappingStatus; TCMPortMappingTransportProtocol _transportProtocol; } + (id)portMappingWithLocalPort:(int)aPrivatePort desiredExternalPort:(int)aPublicPort transportProtocol:(int)aTransportProtocol userInfo:(id)aUserInfo; - (id)initWithLocalPort:(int)aPrivatePort desiredExternalPort:(int)aPublicPort transportProtocol:(int)aTransportProtocol userInfo:(id)aUserInfo; - (int)desiredExternalPort; - (id)userInfo; - (TCMPortMappingStatus)mappingStatus; - (void)setMappingStatus:(TCMPortMappingStatus)aStatus; - (TCMPortMappingTransportProtocol)transportProtocol; - (void)setTransportProtocol:(TCMPortMappingTransportProtocol)aProtocol; - (void)setExternalPort:(int)aPublicPort; - (int)externalPort; - (int)localPort; @end @class IXSCNotificationManager; @class TCMNATPMPPortMapper; @class TCMUPNPPortMapper; @interface TCMPortMapper : NSObject { TCMNATPMPPortMapper *_NATPMPPortMapper; TCMUPNPPortMapper *_UPNPPortMapper; NSMutableSet *_portMappings; NSMutableSet *_removeMappingQueue; IXSCNotificationManager *_systemConfigNotificationManager; BOOL _isRunning; NSString *_localIPAddress; NSString *_externalIPAddress; int _NATPMPStatus; int _UPNPStatus; NSString *_mappingProtocol; NSString *_routerName; int _workCount; BOOL _localIPOnRouterSubnet; BOOL _sendUPNPMappingTableNotification; NSString *_userID; NSMutableSet *_upnpPortMappingsToRemove; NSTimer *_upnpPortMapperTimer; BOOL _ignoreNetworkChanges; BOOL _refreshIsScheduled; } + (TCMPortMapper *)sharedInstance; + (NSString *)manufacturerForHardwareAddress:(NSString *)aMACAddress; + (NSString *)sizereducableHashOfString:(NSString *)inString; - (NSSet *)portMappings; - (NSMutableSet *)removeMappingQueue; - (void)addPortMapping:(TCMPortMapping *)aMapping; - (void)removePortMapping:(TCMPortMapping *)aMapping; - (void)refresh; - (BOOL)isAtWork; - (BOOL)isRunning; - (void)start; - (void)stop; - (void)stopBlocking; // will request the complete UPNPMappingTable and deliver it using a TCMPortMapperDidReceiveUPNPMappingTableNotification with "mappingTable" in the userInfo Dictionary (if current router is a UPNP router) - (void)requestUPNPMappingTable; // this is mainly for Port Map.app and can remove any mappings that can be removed using UPNP (including mappings from other hosts). aMappingList is an Array of Dictionaries with the key @"protocol" and @"publicPort". - (void)removeUPNPMappings:(NSArray *)aMappingList; // needed for generating a UPNP port mapping description that differs for each user - (NSString *)userID; - (void)setUserID:(NSString *)aUserID; // we provide a half length md5 has for convenience // we could use full length but the description field of the routers might be limited - (void)hashUserID:(NSString *)aUserIDToHash; - (NSString *)externalIPAddress; - (NSString *)localIPAddress; - (NSString *)localBonjourHostName; - (void)setMappingProtocol:(NSString *)aProtocol; - (NSString *)mappingProtocol; - (void)setRouterName:(NSString *)aRouterName; - (NSString *)routerName; - (NSString *)routerIPAddress; - (NSString *)routerHardwareAddress; // private accessors - (NSMutableSet *)_upnpPortMappingsToRemove; @end
118controlsman-testtest
TCMPortMapper/framework/TCMPortMapper.h
Objective-C
mit
4,697
#import "NSNotificationCenterThreadingAdditions.h" #import <pthread.h> @implementation NSNotificationCenter (NSNotificationCenterThreadingAdditions) + (void)_postNotification:(NSNotification *)aNotification { [[self defaultCenter] postNotification:aNotification]; } + (void)_postNotificationViaDictionary:(NSDictionary *)anInfoDictionary { NSString *name = [anInfoDictionary objectForKey:@"name"]; id object = [anInfoDictionary objectForKey:@"object"]; [[self defaultCenter] postNotificationName:name object:object userInfo:nil]; [anInfoDictionary release]; } - (void)postNotificationOnMainThread:(NSNotification *)aNotification { if( pthread_main_np() ) return [self postNotification:aNotification]; [[self class] performSelectorOnMainThread:@selector( _postNotification: ) withObject:aNotification waitUntilDone:NO]; } - (void) postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject { if( pthread_main_np() ) return [self postNotificationName:aName object:anObject userInfo:nil]; NSMutableDictionary *info = [[NSMutableDictionary allocWithZone:nil] initWithCapacity:2]; if (aName) { [info setObject:aName forKey:@"name"]; } if (anObject) { [info setObject:anObject forKey:@"object"]; } [[self class] performSelectorOnMainThread:@selector(_postNotificationViaDictionary:) withObject:info waitUntilDone:NO]; } @end
118controlsman-testtest
TCMPortMapper/framework/NSNotificationCenterThreadingAdditions.m
Objective-C
mit
1,570
#import "TCMUPNPPortMapper.h" #import <SystemConfiguration/SystemConfiguration.h> #import <SystemConfiguration/SCSchemaDefinitions.h> #import "NSNotificationCenterThreadingAdditions.h" #define PREFIX_MATCH_MIN_LENGTH 6 //static void PrintHeader(void) // // Prints an explanation of the flag coding. //{ // fprintf(stdout, "t = kSCNetworkFlagsTransientConnection\n"); // fprintf(stdout, "r = kSCNetworkFlagsReachable\n"); // fprintf(stdout, "c = kSCNetworkFlagsConnectionRequired\n"); // fprintf(stdout, "C = kSCNetworkFlagsConnectionAutomatic\n"); // fprintf(stdout, "i = kSCNetworkFlagsInterventionRequired\n"); // fprintf(stdout, "l = kSCNetworkFlagsIsLocalAddress\n"); // fprintf(stdout, "d = kSCNetworkFlagsIsDirect\n"); // fprintf(stdout, "\n"); //} NSString * const TCMUPNPPortMapperDidFailNotification = @"TCMNATPMPPortMapperDidFailNotification"; NSString * const TCMUPNPPortMapperDidGetExternalIPAddressNotification = @"TCMNATPMPPortMapperDidGetExternalIPAddressNotification"; // these notifications come in pairs. TCMPortmapper must reference count them and unify them to a notification pair that does not need to be reference counted NSString * const TCMUPNPPortMapperDidBeginWorkingNotification =@"TCMUPNPPortMapperDidBeginWorkingNotification"; NSString * const TCMUPNPPortMapperDidEndWorkingNotification =@"TCMUPNPPortMapperDidEndWorkingNotification"; @implementation TCMUPNPPortMapper - (id)init { if ((self=[super init])) { _threadIsRunningLock = [NSLock new]; if ([_threadIsRunningLock respondsToSelector:@selector(setName:)]) [_threadIsRunningLock performSelector:@selector(setName:) withObject:@"UPNP-ThreadRunningLock"]; } return self; } - (void)dealloc { [_threadIsRunningLock release]; [_latestUPNPPortMappingsList release]; [super dealloc]; } - (void)setLatestUPNPPortMappingsList:(NSArray *)aLatestList { if (aLatestList != _latestUPNPPortMappingsList) { id tmp = _latestUPNPPortMappingsList; _latestUPNPPortMappingsList = [aLatestList retain]; [tmp autorelease]; } } - (NSArray *)latestUPNPPortMappingsList { return [[_latestUPNPPortMappingsList retain] autorelease]; } - (void)refresh { if ([_threadIsRunningLock tryLock]) { refreshThreadShouldQuit=NO; UpdatePortMappingsThreadShouldQuit = NO; runningThreadID = TCMExternalIPThreadID; [NSThread detachNewThreadSelector:@selector(refreshInThread) toTarget:self withObject:nil]; [_threadIsRunningLock unlock]; #ifdef DEBUG NSLog(@"%s detachedThread",__FUNCTION__); #endif } else { if (runningThreadID == TCMExternalIPThreadID) { refreshThreadShouldQuit=YES; #ifdef DEBUG NSLog(@"%s thread should quit",__FUNCTION__); #endif } else if (runningThreadID == TCMUpdatingMappingThreadID) { UpdatePortMappingsThreadShouldQuit = YES; } } } - (NSString *)portMappingDescription { static NSString *description = nil; if (!description) { NSString *prefix = @"cPM"; NSMutableArray *descriptionComponents=[NSMutableArray array]; NSString *component = [[[[NSBundle mainBundle] bundlePath] lastPathComponent] stringByDeletingPathExtension]; NSString *userID = [[TCMPortMapper sharedInstance] userID]; if (component) { // make sure _ and . are the only non alphanumeric characters in the name so we don't run into problems with routers which change the description (eg. avm routers) NSCharacterSet *saveSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"]; NSScanner *scanner = [NSScanner scannerWithString:component]; [scanner setCharactersToBeSkipped:[saveSet invertedSet]]; NSString *scannedString = nil; while ([scanner scanCharactersFromSet:saveSet intoString:&scannedString]) { [descriptionComponents addObject:scannedString]; } } NSString *appComponent = [descriptionComponents componentsJoinedByString:@"."]; [descriptionComponents removeAllObjects]; // there seems to be a hard limit of 40 characters at in the vigor routers - so length is of essence // however since there seems to be a hard limit of 11 at at least one other router we need to take further action int maxLength = 40; maxLength -= [prefix length]; maxLength -= [userID length]; maxLength -= 2; if ([appComponent length] > maxLength) { appComponent = [appComponent substringToIndex:maxLength]; } [descriptionComponents addObject:prefix]; if (appComponent) [descriptionComponents addObject:appComponent]; if (userID) { [descriptionComponents addObject:userID]; } if (!description) { // hash all that stuff again and put it up in front (at least 6 characters) so wen can rely on prefix matches for routers that are bad bad boys and support only very few characters as description. but keep the rest to stay descriptive for debugging. NSString *preliminaryDescription = [descriptionComponents componentsJoinedByString:@"."]; NSString *hashString = [TCMPortMapper sizereducableHashOfString:preliminaryDescription]; if ([hashString length] > PREFIX_MATCH_MIN_LENGTH) hashString = [hashString substringToIndex:PREFIX_MATCH_MIN_LENGTH]; [descriptionComponents insertObject:hashString atIndex:0]; description = [[descriptionComponents componentsJoinedByString:@"."] retain]; // NSLog(@"%s description: %@",__FUNCTION__,description); } } return description; } - (BOOL)doesPortMappingDescriptionBelongToMe:(NSString *)inDescription { NSString *myDescription = [self portMappingDescription]; BOOL result = ([inDescription length] >= PREFIX_MATCH_MIN_LENGTH && ([myDescription hasPrefix:inDescription] || [inDescription isEqualToString:[myDescription substringFromIndex:PREFIX_MATCH_MIN_LENGTH +1]])); // second part of the OR is for backwards compatibility only // NSLog(@"%s %@ vs %@ : %@ (%@)",__FUNCTION__,myDescription,inDescription,result?@"YES":@"NO",[myDescription substringFromIndex:PREFIX_MATCH_MIN_LENGTH +1]); return result; } - (void)postDidEndWorkingNotification { [[NSNotificationCenter defaultCenter] postNotificationName:TCMUPNPPortMapperDidEndWorkingNotification object:self]; } - (void)postDelayedDidEndWorkingNotification { [self performSelector:@selector(postDidEndWorkingNotification) withObject:nil afterDelay:0.5]; } // example device description root urls: // FritzBox: http://192.168.178.1:49000/igddesc.xml - desc: http://192.168.178.1:49000/fboxdesc.xml // Linksys: http://10.0.1.1:49152/gateway.xml // we need to cache these for better response time of the update mappings thread - (void)refreshInThread { [_threadIsRunningLock lock]; NSAutoreleasePool *pool = [NSAutoreleasePool new]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMUPNPPortMapperDidBeginWorkingNotification object:self]; struct UPNPDev * devlist = 0; const char * multicastif = 0; const char * minissdpdpath = 0; char lanaddr[16]; /* my ip address on the LAN */ char externalIPAddress[16]; BOOL didFail=NO; NSString *errorString = nil; if (( devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0) )) { if(devlist) { // let us check all of the devices for reachability BOOL foundIDGDevice = NO; struct UPNPDev * device; #ifdef DEBUG NSLog(@"List of UPNP devices found on the network :\n"); #endif NSMutableArray *URLsToTry = [NSMutableArray array]; NSMutableSet *triedURLSet = [NSMutableSet set]; for(device = devlist; device && !foundIDGDevice; device = device->pNext) { NSURL *descURL = [NSURL URLWithString:[NSString stringWithUTF8String:device->descURL]]; SCNetworkConnectionFlags status; Boolean success = SCNetworkCheckReachabilityByName([[descURL host] UTF8String], &status); #ifndef NDEBUG NSLog(@"UPnP: %@ %c%c%c%c%c%c%c host:%s st:%s", success ? @"YES" : @" NO", (status & kSCNetworkFlagsTransientConnection) ? 't' : '-', (status & kSCNetworkFlagsReachable) ? 'r' : '-', (status & kSCNetworkFlagsConnectionRequired) ? 'c' : '-', (status & kSCNetworkFlagsConnectionAutomatic) ? 'C' : '-', (status & kSCNetworkFlagsInterventionRequired) ? 'i' : '-', (status & kSCNetworkFlagsIsLocalAddress) ? 'l' : '-', (status & kSCNetworkFlagsIsDirect) ? 'd' : '-', device->descURL, device->st ); #endif // only connect to directly reachable hosts which we haven't tried yet (if you are multihoming then you get all of the announcement twice if (success && (status & kSCNetworkFlagsIsDirect)) { if (![triedURLSet containsObject:descURL]) { [triedURLSet addObject:descURL]; if ([[descURL host] isEqualToString:[[TCMPortMapper sharedInstance] routerIPAddress]]) { [URLsToTry insertObject:descURL atIndex:0]; } else { [URLsToTry addObject:descURL]; } } } } NSEnumerator *URLEnumerator = [URLsToTry objectEnumerator]; NSURL *descURL = nil; while ((descURL = [URLEnumerator nextObject])) { #ifndef NDEBUG NSLog(@"UPnP: trying URL:%@",descURL); #endif // freeing the url still seems like a good idea - why isn't it? if (_urls.controlURL) FreeUPNPUrls(&_urls); // get the new control URLs - this call mallocs the control URLs if (UPNP_GetIGDFromUrl([[descURL absoluteString] UTF8String],&_urls,&_igddata,lanaddr,sizeof(lanaddr))) { int r = UPNP_GetExternalIPAddress(_urls.controlURL, _igddata.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) { didFail = YES; errorString = [NSString stringWithFormat:@"GetExternalIPAddress() returned %d", r]; } else { if(externalIPAddress[0]) { NSString *ipString = [NSString stringWithUTF8String:externalIPAddress]; NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:ipString forKey:@"externalIPAddress"]; NSString *routerName = [NSString stringWithUTF8String:_igddata.modeldescription]; if (routerName) [userInfo setObject:routerName forKey:@"routerName"]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMUPNPPortMapperDidGetExternalIPAddressNotification object:self userInfo:userInfo]]; foundIDGDevice = YES; didFail = NO; break; } else { didFail = YES; errorString = @"No external IP address!"; } } } } if (!foundIDGDevice) { didFail = YES; errorString = @"No IDG Device found on the network!"; } } else { didFail = YES; errorString = @"No IDG Device found on the network!"; } freeUPNPDevlist(devlist); devlist = 0; } else { didFail = YES; errorString = @"No IDG Device found on the network!"; } [_threadIsRunningLock unlock]; if (refreshThreadShouldQuit) { #ifdef DEBUG NSLog(@"%s thread quit prematurely",__FUNCTION__); #endif [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:0]; } else { if (didFail) { #ifdef DEBUG NSLog(@"%s didFailWithError: %@",__FUNCTION__, errorString); #endif [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMUPNPPortMapperDidFailNotification object:self]]; } else { [self performSelectorOnMainThread:@selector(updatePortMappings) withObject:nil waitUntilDone:0]; } } // the delaying bridges the small time gap between this thread and the update thread [self performSelectorOnMainThread:@selector(postDelayedDidEndWorkingNotification) withObject:nil waitUntilDone:NO]; [pool release]; } - (void)updatePortMappings { if ([_threadIsRunningLock tryLock]) { UpdatePortMappingsThreadShouldRestart=NO; runningThreadID = TCMUpdatingMappingThreadID; [NSThread detachNewThreadSelector:@selector(updatePortMappingsInThread) toTarget:self withObject:nil]; [_threadIsRunningLock unlock]; #ifdef DEBUG NSLog(@"%s detachedThread",__FUNCTION__); #endif } else { if (runningThreadID == TCMUpdatingMappingThreadID) { UpdatePortMappingsThreadShouldRestart = YES; } } } - (BOOL)applyPortMapping:(TCMPortMapping *)aPortMapping remove:(BOOL)shouldRemove UPNPURLs:(struct UPNPUrls *)aURLs IGDDatas:(struct IGDdatas *)aIGDData reservedExternalPortNumbers:(NSIndexSet *)aExternalPortSet { BOOL didFail = NO; //NSLog(@"%s %@",__FUNCTION__,aPortMapping); [aPortMapping setMappingStatus:TCMPortMappingStatusTrying]; if (shouldRemove) { if ([aPortMapping transportProtocol] & TCMPortMappingTransportProtocolTCP) { UPNP_DeletePortMapping(aURLs->controlURL, aIGDData->servicetype,[[NSString stringWithFormat:@"%d",[aPortMapping externalPort]] UTF8String], "TCP",NULL); } if ([aPortMapping transportProtocol] & TCMPortMappingTransportProtocolUDP) { UPNP_DeletePortMapping(aURLs->controlURL, aIGDData->servicetype,[[NSString stringWithFormat:@"%d",[aPortMapping externalPort]] UTF8String], "UDP",NULL); } [aPortMapping setMappingStatus:TCMPortMappingStatusUnmapped]; return YES; } else { // We should add it int mappedPort = [aPortMapping desiredExternalPort]; int protocol = TCMPortMappingTransportProtocolUDP; for (protocol = TCMPortMappingTransportProtocolUDP; protocol <= TCMPortMappingTransportProtocolTCP; protocol++) { if ([aPortMapping transportProtocol] & protocol) { int r = 0; do { while ([aExternalPortSet containsIndex:mappedPort] && mappedPort<[aPortMapping desiredExternalPort]+40) { mappedPort++; } r = UPNP_AddPortMapping(aURLs->controlURL, aIGDData->servicetype,[[NSString stringWithFormat:@"%d",mappedPort] UTF8String],[[NSString stringWithFormat:@"%d",[aPortMapping localPort]] UTF8String], [[[TCMPortMapper sharedInstance] localIPAddress] UTF8String], [[self portMappingDescription] UTF8String], protocol==TCMPortMappingTransportProtocolUDP?"UDP":"TCP",NULL); if (r!=UPNPCOMMAND_SUCCESS) { NSString *errorString = [NSString stringWithFormat:@"%d",r]; switch (r) { case 718: errorString = [errorString stringByAppendingString:@": ConflictInMappingEntry"]; #ifdef DEBUG NSLog(@"%s mapping of external port %d failed, trying %d next",__FUNCTION__,mappedPort,mappedPort+1); #endif if (protocol == TCMPortMappingTransportProtocolTCP && ([aPortMapping transportProtocol] & TCMPortMappingTransportProtocolUDP)) { UPNP_DeletePortMapping(aURLs->controlURL, aIGDData->servicetype,[[NSString stringWithFormat:@"%d",mappedPort] UTF8String], "UDP",NULL); protocol = TCMPortMappingTransportProtocolUDP; } mappedPort++; break; case 724: errorString = [errorString stringByAppendingString:@": SamePortValuesRequired"]; break; case 725: errorString = [errorString stringByAppendingString:@": OnlyPermanentLeasesSupported"]; break; case 727: errorString = [errorString stringByAppendingString:@": ExternalPortOnlySupportsWildcard"]; break; } if (r!=718) NSLog(@"%s error occured while mapping: %@",__FUNCTION__, errorString); } } while (r!=UPNPCOMMAND_SUCCESS && r==718 && mappedPort<=[aPortMapping desiredExternalPort]+40); if (r!=UPNPCOMMAND_SUCCESS) { didFail = YES; [aPortMapping setMappingStatus:TCMPortMappingStatusUnmapped]; } else { #ifndef DEBUG #ifndef NDEBUG NSLog(@"UPnP: mapped local %@ port %d to external port %d",protocol==TCMPortMappingTransportProtocolUDP?@"UDP":@"TCP",[aPortMapping localPort],mappedPort); #endif #endif #ifdef DEBUG NSLog(@"%s mapping successful: %@ - %d %@",__FUNCTION__,aPortMapping,mappedPort,protocol==TCMPortMappingTransportProtocolUDP?@"UDP":@"TCP"); #endif [aPortMapping setExternalPort:mappedPort]; [aPortMapping setMappingStatus:TCMPortMappingStatusMapped]; } } } } return !didFail; } - (void)updatePortMappingsInThread { [_threadIsRunningLock lock]; NSAutoreleasePool *pool = [NSAutoreleasePool new]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMUPNPPortMapperDidBeginWorkingNotification object:self]; BOOL didFail=NO; TCMPortMapper *pm=[TCMPortMapper sharedInstance]; NSMutableSet *mappingsSet = [pm removeMappingQueue]; NSSet *mappingsToAdd = [pm portMappings]; // we need to safeguard mappings that others might have made // (upnp is quite generous in giving us what we want, even if // other mappings are there, especially when from the same local IP) NSMutableIndexSet *reservedPortNumbers = [[NSMutableIndexSet new] autorelease]; // get port mapping list as reference first NSMutableArray *latestUPNPPortMappingsList = [NSMutableArray array]; { int r; int i = 0; char index[6]; char intClient[16]; char intPort[6]; char extPort[6]; char protocol[4]; char desc[80]; char enabled[6]; char rHost[64]; char duration[16]; /*unsigned int num=0; UPNP_GetPortMappingNumberOfEntries(urls->controlURL, data->servicetype, &num); printf("PortMappingNumberOfEntries : %u\n", num);*/ do { snprintf(index, 6, "%d", i); rHost[0] = '\0'; enabled[0] = '\0'; duration[0] = '\0'; desc[0] = '\0'; extPort[0] = '\0'; intPort[0] = '\0'; intClient[0] = '\0'; r = UPNP_GetGenericPortMappingEntry(_urls.controlURL, _igddata.servicetype, index, extPort, intClient, intPort, protocol, desc, enabled, rHost, duration); if(r==UPNPCOMMAND_SUCCESS) { #ifndef NDEBUG NSLog(@"UPnP: %2d %s %5s->%s:%-5s '%s' '%s'", i, protocol, extPort, intClient, intPort, desc, rHost); #endif NSString *ipAddress = [NSString stringWithUTF8String:intClient]; NSString *portMappingDescription = [NSString stringWithUTF8String:desc]; int localPort = atoi(intPort); int publicPort = atoi(extPort); [latestUPNPPortMappingsList addObject:[NSDictionary dictionaryWithObjectsAndKeys: ipAddress,@"ipAddress", [NSNumber numberWithInt:localPort],@"localPort", [NSNumber numberWithInt:publicPort],@"publicPort", [NSString stringWithUTF8String:protocol],@"protocol", portMappingDescription,@"description", nil] ]; if ([self doesPortMappingDescriptionBelongToMe:portMappingDescription] && [ipAddress isEqualToString:[pm localIPAddress]]) { NSString *transportProtocol = [NSString stringWithUTF8String:protocol]; // check if we want this mapping, if not remove it, if yes set mapping status BOOL isWanted = NO; @synchronized (mappingsToAdd) { NSEnumerator *mappings = [mappingsToAdd objectEnumerator]; TCMPortMapping *mapping = nil; while ((mapping = [mappings nextObject])) { if ([mapping localPort]==localPort && ([mapping transportProtocol] & ([transportProtocol isEqualToString:@"UDP"]?TCMPortMappingTransportProtocolUDP:TCMPortMappingTransportProtocolTCP)) ) { isWanted = YES; [mapping setExternalPort:publicPort]; if ([mapping mappingStatus]!=TCMPortMappingStatusMapped && [mapping transportProtocol]!=TCMPortMappingTransportProtocolBoth) { [mapping setMappingStatus:TCMPortMappingStatusMapped]; [reservedPortNumbers addIndex:publicPort]; } break; } } } // NSLog(@"%s -------------> about to %@ port mapping %@",__FUNCTION__,isWanted?@"KEEP":@"DELETE",portMappingDescription); if (!isWanted) { r=UPNP_DeletePortMapping(_urls.controlURL, _igddata.servicetype,extPort,protocol,NULL); if (r==UPNPCOMMAND_SUCCESS) i--; } } else { // the portmapping is from someone else - so respect it! [reservedPortNumbers addIndex:atoi(extPort)]; } } i++; } while(r==UPNPCOMMAND_SUCCESS && !UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart); [self setLatestUPNPPortMappingsList:latestUPNPPortMappingsList]; } while (!UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart) { TCMPortMapping *mappingToRemove=nil; @synchronized (mappingsSet) { mappingToRemove = [mappingsSet anyObject]; } if (!mappingToRemove) break; if ([mappingToRemove mappingStatus] == TCMPortMappingStatusMapped) { [mappingToRemove setMappingStatus:TCMPortMappingStatusUnmapped]; // the actual unmapping took place above already } @synchronized (mappingsSet) { [mappingsSet removeObject:mappingToRemove]; } } // in this section we can also remove port mappings from others - this is mainly for Port Map.app to clean up stale mappings from other apps NSMutableSet *upnpRemoveSet = [pm _upnpPortMappingsToRemove]; while (!UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart) { NSDictionary *mappingToRemove=nil; @synchronized (upnpRemoveSet) { mappingToRemove = [upnpRemoveSet anyObject]; } if (!mappingToRemove) break; char *publicPort = (char *)[[NSString stringWithFormat:@"%d",[[mappingToRemove objectForKey:@"publicPort"] intValue]] UTF8String]; char *protocol = (char *)[[mappingToRemove objectForKey:@"protocol"] UTF8String]; UPNP_DeletePortMapping(_urls.controlURL,_igddata.servicetype,publicPort,protocol,NULL); @synchronized (upnpRemoveSet) { [upnpRemoveSet removeObject:mappingToRemove]; } } while (!UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart) { TCMPortMapping *mappingToApply; @synchronized (mappingsToAdd) { mappingToApply = nil; NSEnumerator *mappings = [mappingsToAdd objectEnumerator]; TCMPortMapping *mapping = nil; BOOL isRunning = [pm isRunning]; while ((mapping = [mappings nextObject])) { if ([mapping mappingStatus] == TCMPortMappingStatusUnmapped && isRunning) { mappingToApply = mapping; break; } else if ([mapping mappingStatus] == TCMPortMappingStatusMapped && !isRunning) { mappingToApply = mapping; break; } } } if (!mappingToApply) break; if (![self applyPortMapping:mappingToApply remove:[pm isRunning]?NO:YES UPNPURLs:&_urls IGDDatas:&_igddata reservedExternalPortNumbers:reservedPortNumbers]) { didFail = YES; [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMUPNPPortMapperDidFailNotification object:self]]; break; }; } [_threadIsRunningLock unlock]; if (UpdatePortMappingsThreadShouldQuit) { [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:YES]; } else if (UpdatePortMappingsThreadShouldRestart) { [self performSelectorOnMainThread:@selector(updatePortMappings) withObject:nil waitUntilDone:YES]; } // this tiny delay should take account of the cases where we restart the loop (e.g. removing a port mapping and then stopping the portmapper) [self performSelectorOnMainThread:@selector(postDelayedDidEndWorkingNotification) withObject:nil waitUntilDone:NO]; [pool release]; } - (void)stop { [self updatePortMappings]; } - (void)stopBlocking { refreshThreadShouldQuit=YES; UpdatePortMappingsThreadShouldQuit = YES; UpdatePortMappingsThreadShouldRestart=NO; [_threadIsRunningLock lock]; NSSet *mappingsToStop = [[TCMPortMapper sharedInstance] portMappings]; @synchronized (mappingsToStop) { NSEnumerator *mappings = [mappingsToStop objectEnumerator]; TCMPortMapping *mapping = nil; while ((mapping = [mappings nextObject])) { if ([mapping mappingStatus] == TCMPortMappingStatusMapped) { int protocol = TCMPortMappingTransportProtocolUDP; for (protocol = TCMPortMappingTransportProtocolUDP; protocol <= TCMPortMappingTransportProtocolTCP; protocol++) { if (protocol & [mapping transportProtocol]) { UPNP_DeletePortMapping(_urls.controlURL, _igddata.servicetype, [[NSString stringWithFormat:@"%d",[mapping externalPort]] UTF8String], (protocol==TCMPortMappingTransportProtocolUDP)?"UDP":"TCP",NULL); } } [mapping setMappingStatus:TCMPortMappingStatusUnmapped]; } } } [_threadIsRunningLock unlock]; refreshThreadShouldQuit=YES; UpdatePortMappingsThreadShouldQuit = YES; UpdatePortMappingsThreadShouldRestart=NO; } @end
118controlsman-testtest
TCMPortMapper/framework/TCMUPNPPortMapper.m
Objective-C
mit
27,709
#import "TCMNATPMPPortMapper.h" #import "NSNotificationCenterThreadingAdditions.h" #import "natpmp.h" #import <netinet/in.h> #import <netinet6/in6.h> #import <net/if.h> #import <arpa/inet.h> #import <sys/socket.h> NSString * const TCMNATPMPPortMapperDidFailNotification = @"TCMNATPMPPortMapperDidFailNotification"; NSString * const TCMNATPMPPortMapperDidGetExternalIPAddressNotification = @"TCMNATPMPPortMapperDidGetExternalIPAddressNotification"; NSString * const TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification = @"TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification"; // these notifications come in pairs. TCMPortmapper must reference count them and unify them to a notification pair that does not need to be reference counted NSString * const TCMNATPMPPortMapperDidBeginWorkingNotification =@"TCMNATPMPPortMapperDidBeginWorkingNotification"; NSString * const TCMNATPMPPortMapperDidEndWorkingNotification =@"TCMNATPMPPortMapperDidEndWorkingNotification"; #define PORTMAPREFRESHSHOULDNOTRESTART 2 static TCMNATPMPPortMapper *S_sharedInstance; static void readData ( CFSocketRef aSocket, CFSocketCallBackType aCallbackType, CFDataRef anAddress, const void *data, void *info ); @interface NSString (NSStringNATPortMapperAdditions) + (NSString *)stringWithAddressData:(NSData *)aData; @end @implementation NSString (NSStringNATPortMapperAdditions) + (NSString *)stringWithAddressData:(NSData *)aData { struct sockaddr *socketAddress = (struct sockaddr *)[aData bytes]; // IPv6 Addresses are "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" at max, which is 40 bytes (0-terminated) // IPv4 Addresses are "255.255.255.255" at max which is smaller char stringBuffer[MAX(INET6_ADDRSTRLEN,INET_ADDRSTRLEN)]; NSString *addressAsString = nil; if (socketAddress->sa_family == AF_INET) { if (inet_ntop(AF_INET, &(((struct sockaddr_in *)socketAddress)->sin_addr), stringBuffer, INET_ADDRSTRLEN)) { addressAsString = [NSString stringWithUTF8String:stringBuffer]; } else { addressAsString = @"IPv4 un-ntopable"; } int port = ntohs(((struct sockaddr_in *)socketAddress)->sin_port); addressAsString = [addressAsString stringByAppendingFormat:@":%d", port]; } else if (socketAddress->sa_family == AF_INET6) { if (inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)socketAddress)->sin6_addr), stringBuffer, INET6_ADDRSTRLEN)) { addressAsString = [NSString stringWithUTF8String:stringBuffer]; } else { addressAsString = @"IPv6 un-ntopable"; } int port = ntohs(((struct sockaddr_in6 *)socketAddress)->sin6_port); // Suggested IPv6 format (see http://www.faqs.org/rfcs/rfc2732.html) char interfaceName[IF_NAMESIZE]; if ([addressAsString hasPrefix:@"fe80"] && if_indextoname(((struct sockaddr_in6 *)socketAddress)->sin6_scope_id,interfaceName)) { NSString *zoneID = [NSString stringWithUTF8String:interfaceName]; addressAsString = [NSString stringWithFormat:@"[%@%%%@]:%d", addressAsString, zoneID, port]; } else { addressAsString = [NSString stringWithFormat:@"[%@]:%d", addressAsString, port]; } } else { addressAsString = @"neither IPv6 nor IPv4"; } return [[addressAsString copy] autorelease]; } @end @implementation TCMNATPMPPortMapper + (TCMNATPMPPortMapper *)sharedInstance { if (!S_sharedInstance) { S_sharedInstance = [self new]; } return S_sharedInstance; } - (id)init { if (S_sharedInstance) { [self dealloc]; return S_sharedInstance; } if ((self=[super init])) { natPMPThreadIsRunningLock = [NSLock new]; if ([natPMPThreadIsRunningLock respondsToSelector:@selector(setName:)]) [(id)natPMPThreadIsRunningLock performSelector:@selector(setName:) withObject:@"NATPMPThreadRunningLock"]; } return self; } - (void)dealloc { [natPMPThreadIsRunningLock release]; [super dealloc]; } - (void)ensureListeningToExternalIPAddressChanges { if (!_externalAddressChangeListeningSocket) { // add UDP listener for public ip update packets // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Vers = 0 | OP = 128 + 0 | Result Code | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Seconds Since Start of Epoch | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Public IP Address (a.b.c.d) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ CFSocketContext socketContext; bzero(&socketContext, sizeof(CFSocketContext)); socketContext.info = self; _externalAddressChangeListeningSocket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketDataCallBack, readData, &socketContext); if (_externalAddressChangeListeningSocket) { // SO_REUSEPORT is enough for allowing multiple clients to listen to the same address/port combination int yes = 1; int result = setsockopt(CFSocketGetNative(_externalAddressChangeListeningSocket), SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); if (result == -1) { NSLog(@"Could not setsockopt to SO_REUSEPORT: %d / %s", errno, strerror(errno)); } CFDataRef addressData = NULL; struct sockaddr_in socketAddress; bzero(&socketAddress, sizeof(struct sockaddr_in)); socketAddress.sin_len = sizeof(struct sockaddr_in); socketAddress.sin_family = PF_INET; socketAddress.sin_port = htons(5350); socketAddress.sin_addr.s_addr = inet_addr("224.0.0.1"); addressData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&socketAddress, sizeof(struct sockaddr_in)); if (addressData == NULL) { NSLog(@"Could not create addressData for NAT-PMP external ip address change notification listening"); } else { CFSocketError err = CFSocketSetAddress(_externalAddressChangeListeningSocket, addressData); if (err != kCFSocketSuccess) { NSLog(@"%s could not set address on socket",__FUNCTION__); } else { CFRunLoopRef currentRunLoop = [[NSRunLoop currentRunLoop] getCFRunLoop]; CFRunLoopSourceRef runLoopSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _externalAddressChangeListeningSocket, 0); if (runLoopSource) { CFRunLoopAddSource(currentRunLoop, runLoopSource, kCFRunLoopCommonModes); CFRelease(runLoopSource); } } CFRelease(addressData); } addressData = NULL; } else { NSLog(@"Could not create listening socket for NAT-PMP external ip address change notifications (UDP 224.0.0.1:5350)"); } } } - (void)stopListeningToExternalIPAddressChanges { #ifdef DEBUG NSLog(@"%s, socket:%p",__FUNCTION__,_externalAddressChangeListeningSocket); #endif if (_externalAddressChangeListeningSocket) { CFSocketInvalidate(_externalAddressChangeListeningSocket); CFRelease(_externalAddressChangeListeningSocket); _externalAddressChangeListeningSocket = NULL; } } - (void)stop { if ([_updateTimer isValid]) { [_updateTimer invalidate]; [_updateTimer release]; _updateTimer = nil; } [self stopListeningToExternalIPAddressChanges]; if (![natPMPThreadIsRunningLock tryLock] && (runningThreadID == TCMExternalIPThreadID)) { // stop that one IPAddressThreadShouldQuitAndRestart = PORTMAPREFRESHSHOULDNOTRESTART; } else { [natPMPThreadIsRunningLock unlock]; // restart update to remove mappings before stopping [self updatePortMappings]; } } - (void)refresh { // ensure running of external ip address change listener [self ensureListeningToExternalIPAddressChanges]; // Run externalipAddress in Thread if ([natPMPThreadIsRunningLock tryLock]) { _updateInterval = 3600 / 2.; IPAddressThreadShouldQuitAndRestart=NO; UpdatePortMappingsThreadShouldQuit = NO; runningThreadID = TCMExternalIPThreadID; [NSThread detachNewThreadSelector:@selector(refreshExternalIPInThread) toTarget:self withObject:nil]; [natPMPThreadIsRunningLock unlock]; } else { if (runningThreadID == TCMExternalIPThreadID) { IPAddressThreadShouldQuitAndRestart=YES; } else if (runningThreadID == TCMUpdatingMappingThreadID) { UpdatePortMappingsThreadShouldQuit = YES; } } } - (void)adjustUpdateTimer { if ([_updateTimer isValid]) { [_updateTimer invalidate]; } [_updateTimer autorelease]; _updateTimer = [[NSTimer scheduledTimerWithTimeInterval:_updateInterval target:self selector:@selector(updatePortMappings) userInfo:nil repeats:NO] retain]; } /* Standardablauf: - refresh -> löst einen Thread mit refreshExternalIPInThread aus -> am erfolgreichen ende dieses threads wird ein updatePortMappings auf dem mainthread aufgerufen - Fall 1: nichts läuft bereits -> alles ist gut - Fall 2: ein thread mit refreshExternalIPInThread läuft -> dieser Thread wird abgebrochen und danach erneut refresh aufgerufen - Fall 3: ein thread mit updatePortMappingsInThread läuft -> der updatePortMappingsInThread sollte abgebrochen werden, und danach ein refresh aufgerufen werden - updatePortMappings -> löst einen Thread mit updatePortMappings aus -> am erfolgreichen ende dieses Threads wird ein adjustUpdateTimer auf dem mainthread aufgerufen - Fall 1: nichts läuft bereits -> alles ist gut - Fall 2: ein refreshExternalIPInThread läuft -> alles wird gut, wir tun nix - Fall 3: ein thread mit updatePortMappingsInThread läuft -> updatePortMappingsInThread sollte von vorne beginnen */ - (void)updatePortMappings { if ([natPMPThreadIsRunningLock tryLock]) { UpdatePortMappingsThreadShouldRestart=NO; runningThreadID = TCMUpdatingMappingThreadID; [NSThread detachNewThreadSelector:@selector(updatePortMappingsInThread) toTarget:self withObject:nil]; [natPMPThreadIsRunningLock unlock]; } else { if (runningThreadID == TCMUpdatingMappingThreadID) { UpdatePortMappingsThreadShouldRestart = YES; } } } - (BOOL)applyPortMapping:(TCMPortMapping *)aPortMapping remove:(BOOL)shouldRemove natpmp:(natpmp_t *)aNatPMPt { natpmpresp_t response; int r; //int sav_errno; struct timeval timeout; fd_set fds; if (!shouldRemove) [aPortMapping setMappingStatus:TCMPortMappingStatusTrying]; TCMPortMappingTransportProtocol protocol = [aPortMapping transportProtocol]; int i; for (i=1;i<=2;i++) { if ((i == protocol)||(protocol == TCMPortMappingTransportProtocolBoth)) { r = sendnewportmappingrequest(aNatPMPt, (i==TCMPortMappingTransportProtocolUDP)?NATPMP_PROTOCOL_UDP:NATPMP_PROTOCOL_TCP, [aPortMapping localPort],[aPortMapping desiredExternalPort], shouldRemove?0:3600); do { FD_ZERO(&fds); FD_SET(aNatPMPt->s, &fds); getnatpmprequesttimeout(aNatPMPt, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(aNatPMPt, &response); } while(r==NATPMP_TRYAGAIN); if (r<0) { [aPortMapping setMappingStatus:TCMPortMappingStatusUnmapped]; return NO; } } } // update PortMapping if (shouldRemove) { [aPortMapping setMappingStatus:TCMPortMappingStatusUnmapped]; } else { _updateInterval = MIN(_updateInterval,response.pnu.newportmapping.lifetime/2.); if (_updateInterval < 60.) { NSLog(@"%s caution - new port mapping had a lifetime < 120. : %u - %@",__FUNCTION__,response.pnu.newportmapping.lifetime, aPortMapping); _updateInterval = 60.; } [aPortMapping setExternalPort:response.pnu.newportmapping.mappedpublicport]; [aPortMapping setMappingStatus:TCMPortMappingStatusMapped]; } /* TODO : check response.type ! */ // printf("Mapped public port %hu to localport %hu liftime %u\n", response.newportmapping.mappedpublicport, response.newportmapping.privateport, response.newportmapping.lifetime); //printf("epoch = %u\n", response.epoch); return YES; } - (void)updatePortMappingsInThread { [natPMPThreadIsRunningLock lock]; NSAutoreleasePool *pool = [NSAutoreleasePool new]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMNATPMPPortMapperDidBeginWorkingNotification object:self]; natpmp_t natpmp; initnatpmp(&natpmp); NSMutableSet *mappingsSet = [[TCMPortMapper sharedInstance] removeMappingQueue]; while (!UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart) { TCMPortMapping *mappingToRemove=nil; @synchronized (mappingsSet) { mappingToRemove = [mappingsSet anyObject]; } if (!mappingToRemove) break; if ([mappingToRemove mappingStatus] == TCMPortMappingStatusMapped) { [self applyPortMapping:mappingToRemove remove:YES natpmp:&natpmp]; } @synchronized (mappingsSet) { [mappingsSet removeObject:mappingToRemove]; } } TCMPortMapper *pm=[TCMPortMapper sharedInstance]; NSSet *mappingsToAdd = [pm portMappings]; // Refresh exisiting mappings NSSet *existingMappings; @synchronized (mappingsToAdd) { existingMappings = [[mappingsToAdd copy] autorelease]; } NSEnumerator *existingMappingsEnumerator = [existingMappings objectEnumerator]; TCMPortMapping *mappingToRefresh; while ((mappingToRefresh = [existingMappingsEnumerator nextObject])) { if ([mappingToRefresh mappingStatus] == TCMPortMappingStatusMapped && [pm isRunning]) { if (![self applyPortMapping:mappingToRefresh remove:NO natpmp:&natpmp]) { [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMNATPMPPortMapperDidFailNotification object:self]]; break; } } if (UpdatePortMappingsThreadShouldQuit || UpdatePortMappingsThreadShouldRestart) break; } // Add new mapping or remove existing mappings when not running. while (!UpdatePortMappingsThreadShouldQuit && !UpdatePortMappingsThreadShouldRestart) { TCMPortMapping *mappingToApply; @synchronized (mappingsToAdd) { mappingToApply = nil; NSEnumerator *mappings = [mappingsToAdd objectEnumerator]; TCMPortMapping *mapping = nil; BOOL isRunning = [pm isRunning]; while ((mapping = [mappings nextObject])) { if ([mapping mappingStatus] == TCMPortMappingStatusUnmapped && isRunning) { mappingToApply = mapping; break; } else if ([mapping mappingStatus] == TCMPortMappingStatusMapped && !isRunning) { mappingToApply = mapping; break; } } } if (!mappingToApply) break; if (![self applyPortMapping:mappingToApply remove:[pm isRunning]?NO:YES natpmp:&natpmp]) { [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMNATPMPPortMapperDidFailNotification object:self]]; break; }; } closenatpmp(&natpmp); [natPMPThreadIsRunningLock unlock]; if (UpdatePortMappingsThreadShouldQuit) { [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:NO]; } else if (UpdatePortMappingsThreadShouldRestart) { [self performSelectorOnMainThread:@selector(updatePortMappings) withObject:nil waitUntilDone:NO]; } else { if ([pm isRunning]) { [self performSelectorOnMainThread:@selector(adjustUpdateTimer) withObject:nil waitUntilDone:NO]; } } [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMNATPMPPortMapperDidEndWorkingNotification object:self]; [pool release]; } - (void)refreshExternalIPInThread { [natPMPThreadIsRunningLock lock]; NSAutoreleasePool *pool = [NSAutoreleasePool new]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMNATPMPPortMapperDidBeginWorkingNotification object:self]; natpmp_t natpmp; natpmpresp_t response; int r; struct timeval timeout; fd_set fds; BOOL didFail=NO; r = initnatpmp(&natpmp); if(r<0) { didFail = YES; } else { r = sendpublicaddressrequest(&natpmp); if(r<0) { didFail = YES; } else { #ifdef DEBUG int count = 0; #endif do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); #ifdef DEBUG NSLog(@"NATPMP refreshExternalIP try #%d",++count); #endif select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); if (IPAddressThreadShouldQuitAndRestart) { #ifdef DEBUG NSLog(@"%s ----------------- thread quit prematurely",__FUNCTION__); #endif [natPMPThreadIsRunningLock unlock]; if (IPAddressThreadShouldQuitAndRestart != PORTMAPREFRESHSHOULDNOTRESTART) { [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:0]; } closenatpmp(&natpmp); [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMNATPMPPortMapperDidEndWorkingNotification object:self]; [pool release]; return; } } while(r==NATPMP_TRYAGAIN); if(r<0 && r != NATPMP_ERR_NETWORKFAILURE) { didFail = YES; #ifndef NDEBUG NSLog(@"%s NAT-PMP: IP refresh did fail: %d",__FUNCTION__,r); #endif } else { NSString *ipString = [NSString stringWithFormat:@"%s", inet_ntoa(response.pnu.publicaddress.addr)]; if (r == NATPMP_ERR_NETWORKFAILURE) { ipString = @"0.0.0.0"; // citing the RFC: // If the result code is non-zero, the value of External IP // Address is undefined (MUST be set to zero on transmission, and MUST // be ignored on reception). // so we use 0.0.0.0 at this stage. also because that is what the airport is broadcasting. // we externally can savely display 0.0.0.0 as not having an external ip } /* TODO : check that response.type == 0 */ #ifndef NDEBUG NSLog(@"NAT-PMP: found IP:%@",ipString); #endif [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMNATPMPPortMapperDidGetExternalIPAddressNotification object:self userInfo:[NSDictionary dictionaryWithObject:ipString forKey:@"externalIPAddress"]]]; } } } closenatpmp(&natpmp); [natPMPThreadIsRunningLock unlock]; if (IPAddressThreadShouldQuitAndRestart) { #ifndef DEBUG NSLog(@"%s thread quit prematurely",__FUNCTION__); #endif if (IPAddressThreadShouldQuitAndRestart != PORTMAPREFRESHSHOULDNOTRESTART) { [self performSelectorOnMainThread:@selector(refresh) withObject:nil waitUntilDone:0]; } } else { if (didFail) { [self performSelectorOnMainThread:@selector(stopListeningToExternalIPAddressChanges) withObject:nil waitUntilDone:NO]; [[NSNotificationCenter defaultCenter] postNotificationOnMainThread:[NSNotification notificationWithName:TCMNATPMPPortMapperDidFailNotification object:self]]; } else { [self performSelectorOnMainThread:@selector(updatePortMappings) withObject:nil waitUntilDone:0]; } } [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMNATPMPPortMapperDidEndWorkingNotification object:self]; [pool release]; } - (void)stopBlocking { UpdatePortMappingsThreadShouldQuit = YES; IPAddressThreadShouldQuitAndRestart = YES; [self stopListeningToExternalIPAddressChanges]; [natPMPThreadIsRunningLock lock]; NSSet *mappingsToStop = [[TCMPortMapper sharedInstance] portMappings]; natpmp_t natpmp; initnatpmp(&natpmp); @synchronized (mappingsToStop) { NSEnumerator *mappings = [mappingsToStop objectEnumerator]; TCMPortMapping *mapping = nil; while ((mapping = [mappings nextObject])) { if ([mapping mappingStatus] == TCMPortMappingStatusMapped) { [self applyPortMapping:mapping remove:YES natpmp:&natpmp]; [mapping setMappingStatus:TCMPortMappingStatusUnmapped]; } } } [natPMPThreadIsRunningLock unlock]; } - (void)didReceiveExternalIP:(NSString *)anExternalIPAddress fromSenderAddress:(NSString *)aSenderAddressString secondsSinceEpoch:(int)aSecondsSinceEpoch { if (anExternalIPAddress!=nil && aSenderAddressString!=nil && (![_lastBroadcastedExternalIP isEqualToString:anExternalIPAddress] || ![_lastExternalIPSenderAddress isEqualToString:aSenderAddressString])) { [_lastBroadcastedExternalIP release]; _lastBroadcastedExternalIP = [anExternalIPAddress copy]; [_lastExternalIPSenderAddress release]; _lastExternalIPSenderAddress = [aSenderAddressString copy]; [[NSNotificationCenter defaultCenter] postNotificationName:TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys: _lastBroadcastedExternalIP,@"externalIP", _lastExternalIPSenderAddress,@"senderAddress", [NSNumber numberWithInt:aSecondsSinceEpoch],@"secondsSinceStartOfEpoch", nil] ]; } } @end static void readData ( CFSocketRef aSocket, CFSocketCallBackType aCallbackType, CFDataRef anAddress, const void *aData, void *anInfo ) { NSData *data = (NSData *)aData; TCMNATPMPPortMapper *natpmpMapper = (TCMNATPMPPortMapper *)anInfo; if ([data length]==12) { NSString *senderAddressAndPort = [NSString stringWithAddressData:(NSData *)anAddress]; NSString *senderAddress = [[senderAddressAndPort componentsSeparatedByString:@":"] objectAtIndex:0]; // add UDP listener for public ip update packets // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Vers = 0 | OP = 128 + 0 | Result Code | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Seconds Since Start of Epoch | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Public IP Address (a.b.c.d) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ char buffer[INET_ADDRSTRLEN]; unsigned char *bytes = (unsigned char *)[data bytes]; inet_ntop(AF_INET, &(bytes[8]), buffer, INET_ADDRSTRLEN); NSString *newIPAddress = [NSString stringWithUTF8String:buffer]; int secondsSinceEpoch = ntohl(*((int32_t *)&(bytes[4]))); #ifndef NDEBUG NSLog(@"%s sender:%@ new:%@ seconds:%d",__FUNCTION__,senderAddressAndPort, newIPAddress, secondsSinceEpoch); #endif [natpmpMapper didReceiveExternalIP:newIPAddress fromSenderAddress:senderAddress secondsSinceEpoch:secondsSinceEpoch]; } }
118controlsman-testtest
TCMPortMapper/framework/TCMNATPMPPortMapper.m
Objective-C
mit
24,877
/* * Written by Theo Hultberg (theo@iconara.net) 2004-03-09 with help from Boaz Stuller. * This code is in the public domain, provided that this notice remains. * Fixes and additions in Nov 2008 by Dominik Wagner */ #import "IXSCNotificationManager.h" /*! * @function _IXSCNotificationCallback * @abstract Callback for the dynamic store, just calls keysChanged: on * the notification center. */ void _IXSCNotificationCallback( SCDynamicStoreRef store, CFArrayRef changedKeys, void *info ) { NSEnumerator *keysE = [(NSArray *)changedKeys objectEnumerator]; NSString *key = nil; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; while ( key = [keysE nextObject] ) { [nc postNotificationName:key object:(id)info userInfo:[(NSDictionary *)SCDynamicStoreCopyValue(store, (CFStringRef) key) autorelease]]; } } @implementation IXSCNotificationManager - (void)setObservedKeys:(NSArray *)inKeyArray regExes:(NSArray *)inRegExeArray { BOOL success = SCDynamicStoreSetNotificationKeys( dynStore, (CFArrayRef)inKeyArray, (CFArrayRef)inRegExeArray ); if (!success) NSLog(@"%s desired keys could not be observed.",__FUNCTION__); } - (id)init { self = [super init]; if ( self ) { SCDynamicStoreContext context = { 0, (void *)self, NULL, NULL, NULL }; dynStore = SCDynamicStoreCreate( NULL, (CFStringRef) [[NSBundle mainBundle] bundleIdentifier], _IXSCNotificationCallback, &context ); rlSrc = SCDynamicStoreCreateRunLoopSource(NULL,dynStore,0); CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop], rlSrc, kCFRunLoopCommonModes); [self setObservedKeys:nil regExes:[NSArray arrayWithObject:@".*"]]; } return self; } - (void)dealloc { CFRunLoopRemoveSource([[NSRunLoop currentRunLoop] getCFRunLoop], rlSrc, kCFRunLoopCommonModes); CFRelease(rlSrc); CFRelease(dynStore); [super dealloc]; } @end
118controlsman-testtest
TCMPortMapper/framework/IXSCNotificationManager.m
Objective-C
mit
1,929
#! /usr/bin/python # $Id: testupnpigd.py,v 1.4 2008/10/11 10:27:20 nanard Exp $ # MiniUPnP project # Author : Thomas Bernard # This Sample code is public domain. # website : http://miniupnp.tuxfamily.org/ # import the python miniupnpc module import miniupnpc import socket import BaseHTTPServer # function definition def list_redirections(): i = 0 while True: p = u.getgenericportmapping(i) if p==None: break print i, p i = i + 1 #define the handler class for HTTP connections class handler_class(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write("OK MON GARS") # create the object u = miniupnpc.UPnP() #print 'inital(default) values :' #print ' discoverdelay', u.discoverdelay #print ' lanaddr', u.lanaddr #print ' multicastif', u.multicastif #print ' minissdpdsocket', u.minissdpdsocket u.discoverdelay = 200; try: print 'Discovering... delay=%ums' % u.discoverdelay ndevices = u.discover() print ndevices, 'device(s) detected' # select an igd u.selectigd() # display information about the IGD and the internet connection print 'local ip address :', u.lanaddr externalipaddress = u.externalipaddress() print 'external ip address :', externalipaddress print u.statusinfo(), u.connectiontype() #instanciate a HTTPd object. The port is assigned by the system. httpd = BaseHTTPServer.HTTPServer((u.lanaddr, 0), handler_class) eport = httpd.server_port # find a free port for the redirection r = u.getspecificportmapping(eport, 'TCP') while r != None and eport < 65536: eport = eport + 1 r = u.getspecificportmapping(eport, 'TCP') print 'trying to redirect %s port %u TCP => %s port %u TCP' % (externalipaddress, eport, u.lanaddr, httpd.server_port) b = u.addportmapping(eport, 'TCP', u.lanaddr, httpd.server_port, 'UPnP IGD Tester port %u' % eport, '') if b: print 'Success. Now waiting for some HTTP request on http://%s:%u' % (externalipaddress ,eport) try: httpd.handle_request() httpd.server_close() except KeyboardInterrupt, details: print "CTRL-C exception!", details b = u.deleteportmapping(eport, 'TCP') if b: print 'Successfully deleted port mapping' else: print 'Failed to remove port mapping' else: print 'Failed' httpd.server_close() except Exception, e: print 'Exception :', e
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/testupnpigd.py
Python
mit
2,364
/* $Id: upnperrors.h,v 1.2 2008/07/02 23:31:15 nanard Exp $ */ /* (c) 2007 Thomas Bernard * All rights reserved. * MiniUPnP Project. * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * This software is subjet to the conditions detailed in the * provided LICENCE file. */ #ifndef __UPNPERRORS_H__ #define __UPNPERRORS_H__ #include "declspec.h" #ifdef __cplusplus extern "C" { #endif /* strupnperror() * Return a string description of the UPnP error code * or NULL for undefinded errors */ LIBSPEC const char * strupnperror(int err); #ifdef __cplusplus } #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnperrors.h
C
mit
591
# $Id: Makefile,v 1.48 2008/12/18 17:46:13 nanard Exp $ # MiniUPnP Project # http://miniupnp.free.fr/ # (c) 2005-2007 Thomas Bernard # to install use : # $ PREFIX=/tmp/dummylocation make install # or # $ INSTALLPREFIX=/usr/local make install # or # make install (will go to /usr/bin, /usr/lib, etc...) CC ?= gcc #AR = gar #CFLAGS = -fPIC -O -Wall -g -DDEBUG CFLAGS ?= -fPIC -O -Wall -DNDEBUG INSTALL = install #following libs are needed on Solaris #LDLIBS=-lsocket -lnsl -lresolv # APIVERSION is used to build SONAME APIVERSION = 4 SRCS = igd_desc_parse.c miniupnpc.c minixml.c minisoap.c miniwget.c \ upnpc.c upnpcommands.c upnpreplyparse.c testminixml.c \ minixmlvalid.c testupnpreplyparse.c minissdpc.c \ upnperrors.c testigddescparse.c LIBOBJS = miniwget.o minixml.o igd_desc_parse.o minisoap.o \ miniupnpc.o upnpreplyparse.o upnpcommands.o minissdpc.o \ upnperrors.o OBJS = $(patsubst %.c,%.o,$(SRCS)) # HEADERS to install HEADERS = miniupnpc.h miniwget.h upnpcommands.h igd_desc_parse.h \ upnpreplyparse.h upnperrors.h declspec.h LIBRARY = libminiupnpc.a SHAREDLIBRARY = libminiupnpc.so SONAME = $(SHAREDLIBRARY).$(APIVERSION) EXECUTABLES = upnpc-static upnpc-shared \ testminixml minixmlvalid testupnpreplyparse \ testigddescparse INSTALLPREFIX ?= $(PREFIX)/usr INSTALLDIRINC = $(INSTALLPREFIX)/include/miniupnpc INSTALLDIRLIB = $(INSTALLPREFIX)/lib INSTALLDIRBIN = $(INSTALLPREFIX)/bin .PHONY: install clean depend all installpythonmodule all: validateminixml $(LIBRARY) $(EXECUTABLES) pythonmodule: $(LIBRARY) miniupnpcmodule.c setup.py python setup.py build touch $@ installpythonmodule: pythonmodule python setup.py install validateminixml: minixmlvalid @echo "minixml validation test" ./minixmlvalid touch $@ clean: $(RM) $(LIBRARY) $(SHAREDLIBRARY) $(EXECUTABLES) $(OBJS) # clean python stuff $(RM) pythonmodule validateminixml $(RM) -r build/ dist/ #python setup.py clean install: $(LIBRARY) $(SHAREDLIBRARY) $(INSTALL) -d $(INSTALLDIRINC) $(INSTALL) -m 644 $(HEADERS) $(INSTALLDIRINC) $(INSTALL) -d $(INSTALLDIRLIB) $(INSTALL) -m 644 $(LIBRARY) $(INSTALLDIRLIB) $(INSTALL) -m 644 $(SHAREDLIBRARY) $(INSTALLDIRLIB)/$(SONAME) $(INSTALL) -d $(INSTALLDIRBIN) $(INSTALL) -m 755 upnpc-shared $(INSTALLDIRBIN)/upnpc ln -fs $(SONAME) $(INSTALLDIRLIB)/$(SHAREDLIBRARY) cleaninstall: $(RM) -r $(INSTALLDIRINC) $(RM) $(INSTALLDIRLIB)/$(LIBRARY) $(RM) $(INSTALLDIRLIB)/$(SHAREDLIBRARY) depend: makedepend -Y -- $(CFLAGS) -- $(SRCS) 2>/dev/null $(LIBRARY): $(LIBOBJS) $(AR) crs $@ $? $(SHAREDLIBRARY): $(LIBOBJS) $(CC) -shared -Wl,-soname,$(SONAME) -o $@ $^ upnpc-static: upnpc.o $(LIBRARY) $(CC) -o $@ $^ upnpc-shared: upnpc.o $(SHAREDLIBRARY) $(CC) -o $@ $^ testminixml: minixml.o igd_desc_parse.o testminixml.o minixmlvalid: minixml.o minixmlvalid.o testupnpreplyparse: testupnpreplyparse.o minixml.o upnpreplyparse.o testigddescparse: testigddescparse.o igd_desc_parse.o minixml.o # DO NOT DELETE THIS LINE -- make depend depends on it. igd_desc_parse.o: igd_desc_parse.h miniupnpc.o: miniupnpc.h declspec.h igd_desc_parse.h minissdpc.h miniwget.h miniupnpc.o: minisoap.h minixml.h upnpcommands.h upnpreplyparse.h minixml.o: minixml.h minisoap.o: minisoap.h miniupnpcstrings.h miniwget.o: miniupnpc.h declspec.h igd_desc_parse.h miniupnpcstrings.h upnpc.o: miniwget.h declspec.h miniupnpc.h igd_desc_parse.h upnpcommands.h upnpc.o: upnpreplyparse.h upnperrors.h upnpcommands.o: upnpcommands.h upnpreplyparse.h declspec.h miniupnpc.h upnpcommands.o: igd_desc_parse.h upnpreplyparse.o: upnpreplyparse.h minixml.h testminixml.o: minixml.h igd_desc_parse.h minixmlvalid.o: minixml.h testupnpreplyparse.o: upnpreplyparse.h minissdpc.o: minissdpc.h miniupnpc.h declspec.h igd_desc_parse.h codelength.h upnperrors.o: upnperrors.h declspec.h upnpcommands.h upnpreplyparse.h testigddescparse.o: igd_desc_parse.h minixml.h
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/Makefile
Makefile
mit
3,935
#! /usr/bin/python # $Id: setup.py,v 1.3 2009/04/17 20:59:42 nanard Exp $ # the MiniUPnP Project (c) 2007 Thomas Bernard # http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ # # python script to build the miniupnpc module under unix # # replace libminiupnpc.a by libminiupnpc.so for shared library usage from distutils.core import setup, Extension setup(name="miniupnpc", version="1.3", ext_modules=[ Extension(name="miniupnpc", sources=["miniupnpcmodule.c"], extra_objects=["libminiupnpc.a"]) ])
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/setup.py
Python
mit
540
/* $Id: codelength.h,v 1.1 2008/10/06 22:04:06 nanard Exp $ */ /* Project : miniupnp * Author : Thomas BERNARD * copyright (c) 2005-2008 Thomas Bernard * This software is subjet to the conditions detailed in the * provided LICENCE file. */ #ifndef __CODELENGTH_H__ #define __CODELENGTH_H__ /* Encode length by using 7bit per Byte : * Most significant bit of each byte specifies that the * following byte is part of the code */ #define DECODELENGTH(n, p) n = 0; \ do { n = (n << 7) | (*p & 0x7f); } \ while(*(p++)&0x80); #define CODELENGTH(n, p) if(n>=268435456) *(p++) = (n >> 28) | 0x80; \ if(n>=2097152) *(p++) = (n >> 21) | 0x80; \ if(n>=16384) *(p++) = (n >> 14) | 0x80; \ if(n>=128) *(p++) = (n >> 7) | 0x80; \ *(p++) = n & 0x7f; #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/codelength.h
C
mit
906
/* $Id: igd_desc_parse.c,v 1.8 2008/04/23 11:51:06 nanard Exp $ */ /* Project : miniupnp * http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2005-2008 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #include "igd_desc_parse.h" #include <stdio.h> #include <string.h> /* TODO : rewrite this code so it correctly handle descriptions with * both WANIPConnection and/or WANPPPConnection */ /* Start element handler : * update nesting level counter and copy element name */ void IGDstartelt(void * d, const char * name, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; memcpy( datas->cureltname, name, l); datas->cureltname[l] = '\0'; datas->level++; if( (l==7) && !memcmp(name, "service", l) ) { datas->controlurl_tmp[0] = '\0'; datas->eventsuburl_tmp[0] = '\0'; datas->scpdurl_tmp[0] = '\0'; datas->servicetype_tmp[0] = '\0'; } } /* End element handler : * update nesting level counter and update parser state if * service element is parsed */ void IGDendelt(void * d, const char * name, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; datas->level--; /*printf("endelt %2d %.*s\n", datas->level, l, name);*/ if( (l==7) && !memcmp(name, "service", l) ) { /* if( datas->state < 1 && !strcmp(datas->servicetype, // "urn:schemas-upnp-org:service:WANIPConnection:1") ) "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1")) datas->state ++; */ if(0==strcmp(datas->servicetype_tmp, "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1")) { memcpy(datas->controlurl_CIF, datas->controlurl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->eventsuburl_CIF, datas->eventsuburl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->scpdurl_CIF, datas->scpdurl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->servicetype_CIF, datas->servicetype_tmp, MINIUPNPC_URL_MAXSIZE); } else if(0==strcmp(datas->servicetype_tmp, "urn:schemas-upnp-org:service:WANIPConnection:1") || 0==strcmp(datas->servicetype_tmp, "urn:schemas-upnp-org:service:WANPPPConnection:1") ) { memcpy(datas->controlurl, datas->controlurl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->eventsuburl, datas->eventsuburl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->scpdurl, datas->scpdurl_tmp, MINIUPNPC_URL_MAXSIZE); memcpy(datas->servicetype, datas->servicetype_tmp, MINIUPNPC_URL_MAXSIZE); } } } /* Data handler : * copy data depending on the current element name and state */ void IGDdata(void * d, const char * data, int l) { struct IGDdatas * datas = (struct IGDdatas *)d; char * dstmember = 0; /*printf("%2d %s : %.*s\n", datas->level, datas->cureltname, l, data); */ if( !strcmp(datas->cureltname, "URLBase") ) dstmember = datas->urlbase; else if (!strcmp(datas->cureltname, "modelDescription") && datas->level <= 3) dstmember = datas->modeldescription; else if( !strcmp(datas->cureltname, "serviceType") ) dstmember = datas->servicetype_tmp; else if( !strcmp(datas->cureltname, "controlURL") ) dstmember = datas->controlurl_tmp; else if( !strcmp(datas->cureltname, "eventSubURL") ) dstmember = datas->eventsuburl_tmp; else if( !strcmp(datas->cureltname, "SCPDURL") ) dstmember = datas->scpdurl_tmp; /* else if( !strcmp(datas->cureltname, "deviceType") ) dstmember = datas->devicetype_tmp;*/ if(dstmember) { if(l>=MINIUPNPC_URL_MAXSIZE) l = MINIUPNPC_URL_MAXSIZE-1; memcpy(dstmember, data, l); dstmember[l] = '\0'; } } void printIGD(struct IGDdatas * d) { printf("urlbase = %s\n", d->urlbase); printf("WAN Device (Common interface config) :\n"); /*printf(" deviceType = %s\n", d->devicetype_CIF);*/ printf(" serviceType = %s\n", d->servicetype_CIF); printf(" controlURL = %s\n", d->controlurl_CIF); printf(" eventSubURL = %s\n", d->eventsuburl_CIF); printf(" SCPDURL = %s\n", d->scpdurl_CIF); printf("WAN Connection Device (IP or PPP Connection):\n"); /*printf(" deviceType = %s\n", d->devicetype);*/ printf(" servicetype = %s\n", d->servicetype); printf(" controlURL = %s\n", d->controlurl); printf(" eventSubURL = %s\n", d->eventsuburl); printf(" SCPDURL = %s\n", d->scpdurl); }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/igd_desc_parse.c
C
mit
4,194
#! /bin/sh # $Id: updateminiupnpcstrings.sh,v 1.2 2009/06/04 09:13:53 nanard Exp $ FILE=miniupnpcstrings.h # detecting the OS name and version OS_NAME=`uname -s` OS_VERSION=`uname -r` if [ -f /etc/debian_version ]; then OS_NAME=Debian OS_VERSION=`cat /etc/debian_version` fi # use lsb_release (Linux Standard Base) when available LSB_RELEASE=`which lsb_release` if [ 0 -eq $? ]; then OS_NAME=`${LSB_RELEASE} -i -s` OS_VERSION=`${LSB_RELEASE} -r -s` case $OS_NAME in Debian) #OS_VERSION=`${LSB_RELEASE} -c -s` ;; Ubuntu) #OS_VERSION=`${LSB_RELEASE} -c -s` ;; esac fi echo "Detected OS [$OS_NAME] version [$OS_VERSION]" EXPR="s/OS_STRING \".*\"/OS_STRING \"${OS_NAME}\/${OS_VERSION}\"/" #echo $EXPR echo "Backuping $FILE to $FILE.bak." cp $FILE $FILE.bak echo "setting OS_STRING macro value to ${OS_NAME}/${OS_VERSION} in $FILE." cat $FILE.bak | sed -e "$EXPR" > $FILE
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/updateminiupnpcstrings.sh
Shell
mit
894
/* $Id: upnpcommands.c,v 1.24 2009/04/17 21:21:19 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005-2009 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "upnpcommands.h" #include "miniupnpc.h" static UNSIGNED_INTEGER my_atoui(const char * s) { return s ? ((UNSIGNED_INTEGER)STRTOUI(s, NULL, 0)) : 0; } /* * */ UNSIGNED_INTEGER UPNP_GetTotalBytesSent(const char * controlURL, const char * servicetype) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; unsigned int r = 0; char * p; simpleUPnPcommand(-1, controlURL, servicetype, "GetTotalBytesSent", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); /*DisplayNameValueList(buffer, bufsize);*/ p = GetValueFromNameValueList(&pdata, "NewTotalBytesSent"); r = my_atoui(p); ClearNameValueList(&pdata); return r; } /* * */ UNSIGNED_INTEGER UPNP_GetTotalBytesReceived(const char * controlURL, const char * servicetype) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; unsigned int r = 0; char * p; simpleUPnPcommand(-1, controlURL, servicetype, "GetTotalBytesReceived", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); /*DisplayNameValueList(buffer, bufsize);*/ p = GetValueFromNameValueList(&pdata, "NewTotalBytesReceived"); r = my_atoui(p); ClearNameValueList(&pdata); return r; } /* * */ UNSIGNED_INTEGER UPNP_GetTotalPacketsSent(const char * controlURL, const char * servicetype) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; unsigned int r = 0; char * p; simpleUPnPcommand(-1, controlURL, servicetype, "GetTotalPacketsSent", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); /*DisplayNameValueList(buffer, bufsize);*/ p = GetValueFromNameValueList(&pdata, "NewTotalPacketsSent"); r = my_atoui(p); ClearNameValueList(&pdata); return r; } /* * */ UNSIGNED_INTEGER UPNP_GetTotalPacketsReceived(const char * controlURL, const char * servicetype) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; unsigned int r = 0; char * p; simpleUPnPcommand(-1, controlURL, servicetype, "GetTotalPacketsReceived", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); /*DisplayNameValueList(buffer, bufsize);*/ p = GetValueFromNameValueList(&pdata, "NewTotalPacketsReceived"); r = my_atoui(p); ClearNameValueList(&pdata); return r; } /* UPNP_GetStatusInfo() call the corresponding UPNP method * returns the current status and uptime */ int UPNP_GetStatusInfo(const char * controlURL, const char * servicetype, char * status, unsigned int * uptime, char * lastconnerror) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; char * p; char * up; char * err; int ret = UPNPCOMMAND_UNKNOWN_ERROR; if(!status && !uptime) return UPNPCOMMAND_INVALID_ARGS; simpleUPnPcommand(-1, controlURL, servicetype, "GetStatusInfo", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); /*DisplayNameValueList(buffer, bufsize);*/ up = GetValueFromNameValueList(&pdata, "NewUptime"); p = GetValueFromNameValueList(&pdata, "NewConnectionStatus"); err = GetValueFromNameValueList(&pdata, "NewLastConnectionError"); if(p && up) ret = UPNPCOMMAND_SUCCESS; if(status) { if(p){ strncpy(status, p, 64 ); status[63] = '\0'; }else status[0]= '\0'; } if(uptime) { if(up) sscanf(up,"%u",uptime); else uptime = 0; } if(lastconnerror) { if(err) { strncpy(lastconnerror, err, 64 ); lastconnerror[63] = '\0'; } else lastconnerror[0] = '\0'; } p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); return ret; } /* UPNP_GetConnectionTypeInfo() call the corresponding UPNP method * returns the connection type */ int UPNP_GetConnectionTypeInfo(const char * controlURL, const char * servicetype, char * connectionType) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; char * p; int ret = UPNPCOMMAND_UNKNOWN_ERROR; if(!connectionType) return UPNPCOMMAND_INVALID_ARGS; simpleUPnPcommand(-1, controlURL, servicetype, "GetConnectionTypeInfo", 0, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); p = GetValueFromNameValueList(&pdata, "NewConnectionType"); /*p = GetValueFromNameValueList(&pdata, "NewPossibleConnectionTypes");*/ /* PossibleConnectionTypes will have several values.... */ if(p) { strncpy(connectionType, p, 64 ); connectionType[63] = '\0'; ret = UPNPCOMMAND_SUCCESS; } else connectionType[0] = '\0'; p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); return ret; } /* UPNP_GetLinkLayerMaxBitRate() call the corresponding UPNP method. * Returns 2 values: Downloadlink bandwidth and Uplink bandwidth. * One of the values can be null * Note : GetLinkLayerMaxBitRates belongs to WANPPPConnection:1 only * We can use the GetCommonLinkProperties from WANCommonInterfaceConfig:1 */ int UPNP_GetLinkLayerMaxBitRates(const char * controlURL, const char * servicetype, unsigned int * bitrateDown, unsigned int* bitrateUp) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; int ret = UPNPCOMMAND_UNKNOWN_ERROR; char * down; char * up; char * p; if(!bitrateDown && !bitrateUp) return UPNPCOMMAND_INVALID_ARGS; /* shouldn't we use GetCommonLinkProperties ? */ simpleUPnPcommand(-1, controlURL, servicetype, "GetCommonLinkProperties", 0, buffer, &bufsize); /*"GetLinkLayerMaxBitRates", 0, buffer, &bufsize);*/ /*DisplayNameValueList(buffer, bufsize);*/ ParseNameValue(buffer, bufsize, &pdata); /*down = GetValueFromNameValueList(&pdata, "NewDownstreamMaxBitRate");*/ /*up = GetValueFromNameValueList(&pdata, "NewUpstreamMaxBitRate");*/ down = GetValueFromNameValueList(&pdata, "NewLayer1DownstreamMaxBitRate"); up = GetValueFromNameValueList(&pdata, "NewLayer1UpstreamMaxBitRate"); /*GetValueFromNameValueList(&pdata, "NewWANAccessType");*/ /*GetValueFromNameValueList(&pdata, "NewPhysicalLinkSatus");*/ if(down && up) ret = UPNPCOMMAND_SUCCESS; if(bitrateDown) { if(down) sscanf(down,"%u",bitrateDown); else *bitrateDown = 0; } if(bitrateUp) { if(up) sscanf(up,"%u",bitrateUp); else *bitrateUp = 0; } p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); return ret; } /* UPNP_GetExternalIPAddress() call the corresponding UPNP method. * if the third arg is not null the value is copied to it. * at least 16 bytes must be available * * Return values : * 0 : SUCCESS * NON ZERO : ERROR Either an UPnP error code or an unknown error. * * 402 Invalid Args - See UPnP Device Architecture section on Control. * 501 Action Failed - See UPnP Device Architecture section on Control. */ int UPNP_GetExternalIPAddress(const char * controlURL, const char * servicetype, char * extIpAdd) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; char * p; int ret = UPNPCOMMAND_UNKNOWN_ERROR; if(!extIpAdd || !controlURL || !servicetype) return UPNPCOMMAND_INVALID_ARGS; simpleUPnPcommand(-1, controlURL, servicetype, "GetExternalIPAddress", 0, buffer, &bufsize); /*DisplayNameValueList(buffer, bufsize);*/ ParseNameValue(buffer, bufsize, &pdata); /*printf("external ip = %s\n", GetValueFromNameValueList(&pdata, "NewExternalIPAddress") );*/ p = GetValueFromNameValueList(&pdata, "NewExternalIPAddress"); if(p) { strncpy(extIpAdd, p, 16 ); extIpAdd[15] = '\0'; ret = UPNPCOMMAND_SUCCESS; } else extIpAdd[0] = '\0'; p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); return ret; } int UPNP_AddPortMapping(const char * controlURL, const char * servicetype, const char * extPort, const char * inPort, const char * inClient, const char * desc, const char * proto, const char * remoteHost) { struct UPNParg * AddPortMappingArgs; char buffer[4096]; int bufsize = 4096; struct NameValueParserData pdata; const char * resVal; int ret; if(!inPort || !inClient || !proto || !extPort) return UPNPCOMMAND_INVALID_ARGS; AddPortMappingArgs = calloc(9, sizeof(struct UPNParg)); AddPortMappingArgs[0].elt = "NewRemoteHost"; AddPortMappingArgs[0].val = remoteHost; AddPortMappingArgs[1].elt = "NewExternalPort"; AddPortMappingArgs[1].val = extPort; AddPortMappingArgs[2].elt = "NewProtocol"; AddPortMappingArgs[2].val = proto; AddPortMappingArgs[3].elt = "NewInternalPort"; AddPortMappingArgs[3].val = inPort; AddPortMappingArgs[4].elt = "NewInternalClient"; AddPortMappingArgs[4].val = inClient; AddPortMappingArgs[5].elt = "NewEnabled"; AddPortMappingArgs[5].val = "1"; AddPortMappingArgs[6].elt = "NewPortMappingDescription"; AddPortMappingArgs[6].val = desc?desc:"libminiupnpc"; AddPortMappingArgs[7].elt = "NewLeaseDuration"; AddPortMappingArgs[7].val = "0"; simpleUPnPcommand(-1, controlURL, servicetype, "AddPortMapping", AddPortMappingArgs, buffer, &bufsize); /*DisplayNameValueList(buffer, bufsize);*/ /*buffer[bufsize] = '\0';*/ /*puts(buffer);*/ ParseNameValue(buffer, bufsize, &pdata); resVal = GetValueFromNameValueList(&pdata, "errorCode"); if(resVal) { /*printf("AddPortMapping errorCode = '%s'\n", resVal); */ ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(resVal, "%d", &ret); } else { ret = UPNPCOMMAND_SUCCESS; } ClearNameValueList(&pdata); free(AddPortMappingArgs); return ret; } int UPNP_DeletePortMapping(const char * controlURL, const char * servicetype, const char * extPort, const char * proto, const char * remoteHost) { /*struct NameValueParserData pdata;*/ struct UPNParg * DeletePortMappingArgs; char buffer[4096]; int bufsize = 4096; struct NameValueParserData pdata; const char * resVal; int ret; if(!extPort || !proto) return UPNPCOMMAND_INVALID_ARGS; DeletePortMappingArgs = calloc(4, sizeof(struct UPNParg)); DeletePortMappingArgs[0].elt = "NewRemoteHost"; DeletePortMappingArgs[0].val = remoteHost; DeletePortMappingArgs[1].elt = "NewExternalPort"; DeletePortMappingArgs[1].val = extPort; DeletePortMappingArgs[2].elt = "NewProtocol"; DeletePortMappingArgs[2].val = proto; simpleUPnPcommand(-1, controlURL, servicetype, "DeletePortMapping", DeletePortMappingArgs, buffer, &bufsize); /*DisplayNameValueList(buffer, bufsize);*/ ParseNameValue(buffer, bufsize, &pdata); resVal = GetValueFromNameValueList(&pdata, "errorCode"); if(resVal) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(resVal, "%d", &ret); } else { ret = UPNPCOMMAND_SUCCESS; } ClearNameValueList(&pdata); free(DeletePortMappingArgs); return ret; } int UPNP_GetGenericPortMappingEntry(const char * controlURL, const char * servicetype, const char * index, char * extPort, char * intClient, char * intPort, char * protocol, char * desc, char * enabled, char * rHost, char * duration) { struct NameValueParserData pdata; struct UPNParg * GetPortMappingArgs; char buffer[4096]; int bufsize = 4096; char * p; int r = UPNPCOMMAND_UNKNOWN_ERROR; if(!index) return UPNPCOMMAND_INVALID_ARGS; intClient[0] = '\0'; intPort[0] = '\0'; GetPortMappingArgs = calloc(2, sizeof(struct UPNParg)); GetPortMappingArgs[0].elt = "NewPortMappingIndex"; GetPortMappingArgs[0].val = index; simpleUPnPcommand(-1, controlURL, servicetype, "GetGenericPortMappingEntry", GetPortMappingArgs, buffer, &bufsize); ParseNameValue(buffer, bufsize, &pdata); p = GetValueFromNameValueList(&pdata, "NewRemoteHost"); if(p && rHost) { strncpy(rHost, p, 64); rHost[63] = '\0'; } p = GetValueFromNameValueList(&pdata, "NewExternalPort"); if(p && extPort) { strncpy(extPort, p, 6); extPort[5] = '\0'; r = UPNPCOMMAND_SUCCESS; } p = GetValueFromNameValueList(&pdata, "NewProtocol"); if(p && protocol) { strncpy(protocol, p, 4); protocol[3] = '\0'; } p = GetValueFromNameValueList(&pdata, "NewInternalClient"); if(p && intClient) { strncpy(intClient, p, 16); intClient[15] = '\0'; r = 0; } p = GetValueFromNameValueList(&pdata, "NewInternalPort"); if(p && intPort) { strncpy(intPort, p, 6); intPort[5] = '\0'; } p = GetValueFromNameValueList(&pdata, "NewEnabled"); if(p && enabled) { strncpy(enabled, p, 4); enabled[3] = '\0'; } p = GetValueFromNameValueList(&pdata, "NewPortMappingDescription"); if(p && desc) { strncpy(desc, p, 80); desc[79] = '\0'; } p = GetValueFromNameValueList(&pdata, "NewLeaseDuration"); if(p && duration) { strncpy(duration, p, 16); duration[15] = '\0'; } p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { r = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &r); } ClearNameValueList(&pdata); free(GetPortMappingArgs); return r; } int UPNP_GetPortMappingNumberOfEntries(const char * controlURL, const char * servicetype, unsigned int * numEntries) { struct NameValueParserData pdata; char buffer[4096]; int bufsize = 4096; char* p; int ret = UPNPCOMMAND_UNKNOWN_ERROR; simpleUPnPcommand(-1, controlURL, servicetype, "GetPortMappingNumberOfEntries", 0, buffer, &bufsize); #ifdef DEBUG DisplayNameValueList(buffer, bufsize); #endif ParseNameValue(buffer, bufsize, &pdata); p = GetValueFromNameValueList(&pdata, "NewPortMappingNumberOfEntries"); if(numEntries && p) { *numEntries = 0; sscanf(p, "%u", numEntries); ret = UPNPCOMMAND_SUCCESS; } p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); return ret; } /* UPNP_GetSpecificPortMappingEntry retrieves an existing port mapping * the result is returned in the intClient and intPort strings * please provide 16 and 6 bytes of data */ int UPNP_GetSpecificPortMappingEntry(const char * controlURL, const char * servicetype, const char * extPort, const char * proto, char * intClient, char * intPort) { struct NameValueParserData pdata; struct UPNParg * GetPortMappingArgs; char buffer[4096]; int bufsize = 4096; char * p; int ret = UPNPCOMMAND_UNKNOWN_ERROR; if(!intPort || !intClient || !extPort || !proto) return UPNPCOMMAND_INVALID_ARGS; GetPortMappingArgs = calloc(4, sizeof(struct UPNParg)); GetPortMappingArgs[0].elt = "NewRemoteHost"; GetPortMappingArgs[1].elt = "NewExternalPort"; GetPortMappingArgs[1].val = extPort; GetPortMappingArgs[2].elt = "NewProtocol"; GetPortMappingArgs[2].val = proto; simpleUPnPcommand(-1, controlURL, servicetype, "GetSpecificPortMappingEntry", GetPortMappingArgs, buffer, &bufsize); /*fd = simpleUPnPcommand(fd, controlURL, data.servicetype, "GetSpecificPortMappingEntry", AddPortMappingArgs, buffer, &bufsize); */ /*DisplayNameValueList(buffer, bufsize);*/ ParseNameValue(buffer, bufsize, &pdata); p = GetValueFromNameValueList(&pdata, "NewInternalClient"); if(p) { strncpy(intClient, p, 16); intClient[15] = '\0'; ret = UPNPCOMMAND_SUCCESS; } else intClient[0] = '\0'; p = GetValueFromNameValueList(&pdata, "NewInternalPort"); if(p) { strncpy(intPort, p, 6); intPort[5] = '\0'; } else intPort[0] = '\0'; p = GetValueFromNameValueList(&pdata, "errorCode"); if(p) { ret = UPNPCOMMAND_UNKNOWN_ERROR; sscanf(p, "%d", &ret); } ClearNameValueList(&pdata); free(GetPortMappingArgs); return ret; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnpcommands.c
C
mit
16,257
/* $Id: igd_desc_parse.h,v 1.6 2008/04/23 11:51:07 nanard Exp $ */ /* Project : miniupnp * http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2005-2008 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #ifndef __IGD_DESC_PARSE_H__ #define __IGD_DESC_PARSE_H__ /* Structure to store the result of the parsing of UPnP * descriptions of Internet Gateway Devices */ #define MINIUPNPC_URL_MAXSIZE (128) struct IGDdatas { char cureltname[MINIUPNPC_URL_MAXSIZE]; char urlbase[MINIUPNPC_URL_MAXSIZE]; int level; /*int state;*/ /* "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */ char controlurl_CIF[MINIUPNPC_URL_MAXSIZE]; char eventsuburl_CIF[MINIUPNPC_URL_MAXSIZE]; char scpdurl_CIF[MINIUPNPC_URL_MAXSIZE]; char servicetype_CIF[MINIUPNPC_URL_MAXSIZE]; /*char devicetype_CIF[MINIUPNPC_URL_MAXSIZE];*/ /* "urn:schemas-upnp-org:service:WANIPConnection:1" * "urn:schemas-upnp-org:service:WANPPPConnection:1" */ char modeldescription[MINIUPNPC_URL_MAXSIZE]; char controlurl[MINIUPNPC_URL_MAXSIZE]; char eventsuburl[MINIUPNPC_URL_MAXSIZE]; char scpdurl[MINIUPNPC_URL_MAXSIZE]; char servicetype[MINIUPNPC_URL_MAXSIZE]; /*char devicetype[MINIUPNPC_URL_MAXSIZE];*/ /* tmp */ char controlurl_tmp[MINIUPNPC_URL_MAXSIZE]; char eventsuburl_tmp[MINIUPNPC_URL_MAXSIZE]; char scpdurl_tmp[MINIUPNPC_URL_MAXSIZE]; char servicetype_tmp[MINIUPNPC_URL_MAXSIZE]; /*char devicetype_tmp[MINIUPNPC_URL_MAXSIZE];*/ }; void IGDstartelt(void *, const char *, int); void IGDendelt(void *, const char *, int); void IGDdata(void *, const char *, int); void printIGD(struct IGDdatas *); #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/igd_desc_parse.h
C
mit
1,697
/* $Id: minisoap.h,v 1.3 2006/11/19 22:32:34 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. */ #ifndef __MINISOAP_H__ #define __MINISOAP_H__ /*int httpWrite(int, const char *, int, const char *);*/ int soapPostSubmit(int, const char *, const char *, unsigned short, const char *, const char *); #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minisoap.h
C
mit
476
/* $Id: miniupnpcstrings.h,v 1.3 2009/06/04 09:05:56 nanard Exp $ */ /* Project: miniupnp * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * Author: Thomas Bernard * Copyright (c) 2005-2009 Thomas Bernard * This software is subjects to the conditions detailed * in the LICENCE file provided within this distribution */ #ifndef __MINIUPNPCSTRINGS_H__ #define __MINIUPNPCSTRINGS_H__ #define OS_STRING "OpenBSD/4.3" #define MINIUPNPC_VERSION_STRING "1.3" #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniupnpcstrings.h
C
mit
479
/* $Id: miniupnpc.h,v 1.18 2008/09/25 18:02:50 nanard Exp $ */ /* Project: miniupnp * http://miniupnp.free.fr/ * Author: Thomas Bernard * Copyright (c) 2005-2006 Thomas Bernard * This software is subjects to the conditions detailed * in the LICENCE file provided within this distribution */ #ifndef __MINIUPNPC_H__ #define __MINIUPNPC_H__ #include "declspec.h" #include "igd_desc_parse.h" #ifdef __cplusplus extern "C" { #endif /* Structures definitions : */ struct UPNParg { const char * elt; const char * val; }; int simpleUPnPcommand(int, const char *, const char *, const char *, struct UPNParg *, char *, int *); struct UPNPDev { struct UPNPDev * pNext; char * descURL; char * st; char buffer[2]; }; /* upnpDiscover() * discover UPnP devices on the network. * The discovered devices are returned as a chained list. * It is up to the caller to free the list with freeUPNPDevlist(). * delay (in millisecond) is the maximum time for waiting any device * response. * If available, device list will be obtained from MiniSSDPd. * Default path for minissdpd socket will be used if minissdpdsock argument * is NULL. * If multicastif is not NULL, it will be used instead of the default * multicast interface for sending SSDP discover packets. * If sameport is not null, SSDP packets will be sent from the source port * 1900 (same as destination port) otherwise system assign a source port. */ LIBSPEC struct UPNPDev * upnpDiscover(int delay, const char * multicastif, const char * minissdpdsock, int sameport); /* freeUPNPDevlist() * free list returned by upnpDiscover() */ LIBSPEC void freeUPNPDevlist(struct UPNPDev * devlist); /* parserootdesc() : * parse root XML description of a UPnP device and fill the IGDdatas * structure. */ LIBSPEC void parserootdesc(const char *, int, struct IGDdatas *); /* structure used to get fast access to urls * controlURL: controlURL of the WANIPConnection * ipcondescURL: url of the description of the WANIPConnection * controlURL_CIF: controlURL of the WANCommonInterfaceConfig */ struct UPNPUrls { char * controlURL; char * ipcondescURL; char * controlURL_CIF; }; /* UPNP_GetValidIGD() : * return values : * 0 = NO IGD found * 1 = A valid connected IGD has been found * 2 = A valid IGD has been found but it reported as * not connected * 3 = an UPnP device has been found but was not recognized as an IGD * * In any non zero return case, the urls and data structures * passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to * free allocated memory. */ LIBSPEC int UPNP_GetValidIGD(struct UPNPDev * devlist, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen); /* UPNP_GetIGDFromUrl() * Used when skipping the discovery process. * return value : * 0 - Not ok * 1 - OK */ LIBSPEC int UPNP_GetIGDFromUrl(const char * rootdescurl, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen); LIBSPEC void GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *, const char *); LIBSPEC void FreeUPNPUrls(struct UPNPUrls *); /* Reads data from the specified socket. * Returns the number of bytes read if successful, zero if no bytes were * read or if we timed out. Returns negative if there was an error. */ int ReceiveData(int socket, char * data, int length, int timeout); #ifdef __cplusplus } #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniupnpc.h
C
mit
3,558
/* $Id: minixml.h,v 1.6 2006/11/30 11:47:21 nanard Exp $ */ /* minimal xml parser * * Project : miniupnp * Website : http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2005 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #ifndef __MINIXML_H__ #define __MINIXML_H__ #define IS_WHITE_SPACE(c) ((c==' ') || (c=='\t') || (c=='\r') || (c=='\n')) /* if a callback function pointer is set to NULL, * the function is not called */ struct xmlparser { const char *xmlstart; const char *xmlend; const char *xml; /* pointer to current character */ int xmlsize; void * data; void (*starteltfunc) (void *, const char *, int); void (*endeltfunc) (void *, const char *, int); void (*datafunc) (void *, const char *, int); void (*attfunc) (void *, const char *, int, const char *, int); }; /* parsexml() * the xmlparser structure must be initialized before the call * the following structure members have to be initialized : * xmlstart, xmlsize, data, *func * xml is for internal usage, xmlend is computed automatically */ void parsexml(struct xmlparser *); #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minixml.h
C
mit
1,169
/* $Id: testigddescparse.c,v 1.1 2008/04/23 11:53:45 nanard Exp $ */ /* Project : miniupnp * http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2008 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "igd_desc_parse.h" #include "minixml.h" int test_igd_desc_parse(char * buffer, int len) { struct IGDdatas igd; struct xmlparser parser; memset(&igd, 0, sizeof(struct IGDdatas)); memset(&parser, 0, sizeof(struct xmlparser)); parser.xmlstart = buffer; parser.xmlsize = len; parser.data = &igd; parser.starteltfunc = IGDstartelt; parser.endeltfunc = IGDendelt; parser.datafunc = IGDdata; parsexml(&parser); printIGD(&igd); return 0; } int main(int argc, char * * argv) { FILE * f; char * buffer; int len; int r = 0; if(argc<2) { fprintf(stderr, "Usage: %s file.xml\n", argv[0]); return 1; } f = fopen(argv[1], "r"); if(!f) { fprintf(stderr, "Cannot open %s for reading.\n", argv[1]); return 1; } fseek(f, 0, SEEK_END); len = ftell(f); fseek(f, 0, SEEK_SET); buffer = malloc(len); fread(buffer, 1, len, f); fclose(f); r = test_igd_desc_parse(buffer, len); free(buffer); return r; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/testigddescparse.c
C
mit
1,287
/* $Id: upnpreplyparse.c,v 1.10 2008/02/21 13:05:27 nanard Exp $ */ /* MiniUPnP project * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * (c) 2006 Thomas Bernard * This software is subject to the conditions detailed * in the LICENCE file provided within the distribution */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "upnpreplyparse.h" #include "minixml.h" static void NameValueParserStartElt(void * d, const char * name, int l) { struct NameValueParserData * data = (struct NameValueParserData *)d; if(l>63) l = 63; memcpy(data->curelt, name, l); data->curelt[l] = '\0'; } static void NameValueParserGetData(void * d, const char * datas, int l) { struct NameValueParserData * data = (struct NameValueParserData *)d; struct NameValue * nv; nv = malloc(sizeof(struct NameValue)); if(l>63) l = 63; strncpy(nv->name, data->curelt, 64); nv->name[63] = '\0'; memcpy(nv->value, datas, l); nv->value[l] = '\0'; LIST_INSERT_HEAD( &(data->head), nv, entries); } void ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data) { struct xmlparser parser; LIST_INIT(&(data->head)); /* init xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = NameValueParserStartElt; parser.endeltfunc = 0; parser.datafunc = NameValueParserGetData; parser.attfunc = 0; parsexml(&parser); } void ClearNameValueList(struct NameValueParserData * pdata) { struct NameValue * nv; while((nv = pdata->head.lh_first) != NULL) { LIST_REMOVE(nv, entries); free(nv); } } char * GetValueFromNameValueList(struct NameValueParserData * pdata, const char * Name) { struct NameValue * nv; char * p = NULL; for(nv = pdata->head.lh_first; (nv != NULL) && (p == NULL); nv = nv->entries.le_next) { if(strcmp(nv->name, Name) == 0) p = nv->value; } return p; } #if 0 /* useless now that minixml ignores namespaces by itself */ char * GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata, const char * Name) { struct NameValue * nv; char * p = NULL; char * pname; for(nv = pdata->head.lh_first; (nv != NULL) && (p == NULL); nv = nv->entries.le_next) { pname = strrchr(nv->name, ':'); if(pname) pname++; else pname = nv->name; if(strcmp(pname, Name)==0) p = nv->value; } return p; } #endif /* debug all-in-one function * do parsing then display to stdout */ #ifdef DEBUG void DisplayNameValueList(char * buffer, int bufsize) { struct NameValueParserData pdata; struct NameValue * nv; ParseNameValue(buffer, bufsize, &pdata); for(nv = pdata.head.lh_first; nv != NULL; nv = nv->entries.le_next) { printf("%s = %s\n", nv->name, nv->value); } ClearNameValueList(&pdata); } #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnpreplyparse.c
C
mit
3,043
/* $Id: minissdpc.h,v 1.1 2007/08/31 15:15:33 nanard Exp $ */ /* Project: miniupnp * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * Author: Thomas Bernard * Copyright (c) 2005-2007 Thomas Bernard * This software is subjects to the conditions detailed * in the LICENCE file provided within this distribution */ #ifndef __MINISSDPC_H__ #define __MINISSDPC_H__ struct UPNPDev * getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath); #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minissdpc.h
C
mit
476
/* $Id: miniupnpcmodule.c,v 1.13 2009/04/17 20:59:42 nanard Exp $*/ /* Project : miniupnp * Author : Thomas BERNARD * website : http://miniupnp.tuxfamily.org/ * copyright (c) 2007 Thomas Bernard * This software is subjet to the conditions detailed in the * provided LICENCE file. */ #include <Python.h> #define STATICLIB #include "structmember.h" #include "miniupnpc.h" #include "upnpcommands.h" #include "upnperrors.h" /* for compatibility with Python < 2.4 */ #ifndef Py_RETURN_NONE #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None #endif #ifndef Py_RETURN_TRUE #define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True #endif #ifndef Py_RETURN_FALSE #define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False #endif typedef struct { PyObject_HEAD /* Type-specific fields go here. */ struct UPNPDev * devlist; struct UPNPUrls urls; struct IGDdatas data; unsigned int discoverdelay; /* value passed to upnpDiscover() */ char lanaddr[16]; /* our ip address on the LAN */ char * multicastif; char * minissdpdsocket; } UPnPObject; static PyMemberDef UPnP_members[] = { {"lanaddr", T_STRING_INPLACE, offsetof(UPnPObject, lanaddr), READONLY, "ip address on the LAN" }, {"discoverdelay", T_UINT, offsetof(UPnPObject, discoverdelay), 0/*READWRITE*/, "value in ms used to wait for SSDP responses" }, /* T_STRING is allways readonly :( */ {"multicastif", T_STRING, offsetof(UPnPObject, multicastif), 0, "IP of the network interface to be used for multicast operations" }, {"minissdpdsocket", T_STRING, offsetof(UPnPObject, multicastif), 0, "path of the MiniSSDPd unix socket" }, {NULL} }; static void UPnPObject_dealloc(UPnPObject *self) { freeUPNPDevlist(self->devlist); FreeUPNPUrls(&self->urls); self->ob_type->tp_free((PyObject*)self); } static PyObject * UPnP_discover(UPnPObject *self) { struct UPNPDev * dev; int i; PyObject *res = NULL; if(self->devlist) { freeUPNPDevlist(self->devlist); self->devlist = 0; } self->devlist = upnpDiscover((int)self->discoverdelay/*timeout in ms*/, 0/* multicast if*/, 0/*minissdpd socket*/, 0/*sameport flag*/); /* Py_RETURN_NONE ??? */ for(dev = self->devlist, i = 0; dev; dev = dev->pNext) i++; res = Py_BuildValue("i", i); return res; } static PyObject * UPnP_selectigd(UPnPObject *self) { if(UPNP_GetValidIGD(self->devlist, &self->urls, &self->data, self->lanaddr, sizeof(self->lanaddr))) { return Py_BuildValue("s", self->urls.controlURL); } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, "No UPnP device discovered"); return NULL; } } static PyObject * UPnP_totalbytesent(UPnPObject *self) { return Py_BuildValue("I", UPNP_GetTotalBytesSent(self->urls.controlURL_CIF, self->data.servicetype_CIF)); } static PyObject * UPnP_totalbytereceived(UPnPObject *self) { return Py_BuildValue("I", UPNP_GetTotalBytesReceived(self->urls.controlURL_CIF, self->data.servicetype_CIF)); } static PyObject * UPnP_totalpacketsent(UPnPObject *self) { return Py_BuildValue("I", UPNP_GetTotalPacketsSent(self->urls.controlURL_CIF, self->data.servicetype_CIF)); } static PyObject * UPnP_totalpacketreceived(UPnPObject *self) { return Py_BuildValue("I", UPNP_GetTotalPacketsReceived(self->urls.controlURL_CIF, self->data.servicetype_CIF)); } static PyObject * UPnP_statusinfo(UPnPObject *self) { char status[64]; char lastconnerror[64]; unsigned int uptime = 0; int r; status[0] = '\0'; lastconnerror[0] = '\0'; r = UPNP_GetStatusInfo(self->urls.controlURL, self->data.servicetype, status, &uptime, lastconnerror); if(r==UPNPCOMMAND_SUCCESS) { return Py_BuildValue("(s,I,s)", status, uptime, lastconnerror); } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } static PyObject * UPnP_connectiontype(UPnPObject *self) { char connectionType[64]; int r; connectionType[0] = '\0'; r = UPNP_GetConnectionTypeInfo(self->urls.controlURL, self->data.servicetype, connectionType); if(r==UPNPCOMMAND_SUCCESS) { return Py_BuildValue("s", connectionType); } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } static PyObject * UPnP_externalipaddress(UPnPObject *self) { char externalIPAddress[16]; int r; externalIPAddress[0] = '\0'; r = UPNP_GetExternalIPAddress(self->urls.controlURL, self->data.servicetype, externalIPAddress); if(r==UPNPCOMMAND_SUCCESS) { return Py_BuildValue("s", externalIPAddress); } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } /* AddPortMapping(externalPort, protocol, internalHost, internalPort, desc, * remoteHost) * protocol is 'UDP' or 'TCP' */ static PyObject * UPnP_addportmapping(UPnPObject *self, PyObject *args) { char extPort[6]; unsigned short ePort; char inPort[6]; unsigned short iPort; const char * proto; const char * host; const char * desc; const char * remoteHost; int r; if (!PyArg_ParseTuple(args, "HssHss", &ePort, &proto, &host, &iPort, &desc, &remoteHost)) return NULL; sprintf(extPort, "%hu", ePort); sprintf(inPort, "%hu", iPort); r = UPNP_AddPortMapping(self->urls.controlURL, self->data.servicetype, extPort, inPort, host, desc, proto, remoteHost); if(r==UPNPCOMMAND_SUCCESS) { Py_RETURN_TRUE; } else { // TODO: RAISE an Exception. See upnpcommands.h for errors codes. // upnperrors.c //Py_RETURN_FALSE; /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } /* DeletePortMapping(extPort, proto, removeHost='') * proto = 'UDP', 'TCP' */ static PyObject * UPnP_deleteportmapping(UPnPObject *self, PyObject *args) { char extPort[6]; unsigned short ePort; const char * proto; const char * remoteHost = ""; int r; if(!PyArg_ParseTuple(args, "Hs|z", &ePort, &proto, &remoteHost)) return NULL; sprintf(extPort, "%hu", ePort); r = UPNP_DeletePortMapping(self->urls.controlURL, self->data.servicetype, extPort, proto, remoteHost); if(r==UPNPCOMMAND_SUCCESS) { Py_RETURN_TRUE; } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } static PyObject * UPnP_getportmappingnumberofentries(UPnPObject *self) { unsigned int n = 0; int r; r = UPNP_GetPortMappingNumberOfEntries(self->urls.controlURL, self->data.servicetype, &n); if(r==UPNPCOMMAND_SUCCESS) { return Py_BuildValue("I", n); } else { /* TODO: have our own exception type ! */ PyErr_SetString(PyExc_Exception, strupnperror(r)); return NULL; } } /* GetSpecificPortMapping(ePort, proto) * proto = 'UDP' or 'TCP' */ static PyObject * UPnP_getspecificportmapping(UPnPObject *self, PyObject *args) { char extPort[6]; unsigned short ePort; const char * proto; char intClient[16]; char intPort[6]; unsigned short iPort; if(!PyArg_ParseTuple(args, "Hs", &ePort, &proto)) return NULL; sprintf(extPort, "%hu", ePort); UPNP_GetSpecificPortMappingEntry(self->urls.controlURL, self->data.servicetype, extPort, proto, intClient, intPort); if(intClient[0]) { iPort = (unsigned short)atoi(intPort); return Py_BuildValue("(s,H)", intClient, iPort); } else { Py_RETURN_NONE; } } /* GetGenericPortMapping(index) */ static PyObject * UPnP_getgenericportmapping(UPnPObject *self, PyObject *args) { int i, r; char index[8]; char intClient[16]; char intPort[6]; unsigned short iPort; char extPort[6]; unsigned short ePort; char protocol[4]; char desc[80]; char enabled[6]; char rHost[64]; char duration[16]; /* lease duration */ unsigned int dur; if(!PyArg_ParseTuple(args, "i", &i)) return NULL; snprintf(index, sizeof(index), "%d", i); rHost[0] = '\0'; enabled[0] = '\0'; duration[0] = '\0'; desc[0] = '\0'; extPort[0] = '\0'; intPort[0] = '\0'; intClient[0] = '\0'; r = UPNP_GetGenericPortMappingEntry(self->urls.controlURL, self->data.servicetype, index, extPort, intClient, intPort, protocol, desc, enabled, rHost, duration); if(r==UPNPCOMMAND_SUCCESS) { ePort = (unsigned short)atoi(extPort); iPort = (unsigned short)atoi(intPort); dur = (unsigned int)strtoul(duration, 0, 0); return Py_BuildValue("(H,s,(s,H),s,s,s,I)", ePort, protocol, intClient, iPort, desc, enabled, rHost, dur); } else { Py_RETURN_NONE; } } /* miniupnpc.UPnP object Method Table */ static PyMethodDef UPnP_methods[] = { {"discover", (PyCFunction)UPnP_discover, METH_NOARGS, "discover UPnP IGD devices on the network" }, {"selectigd", (PyCFunction)UPnP_selectigd, METH_NOARGS, "select a valid UPnP IGD among discovered devices" }, {"totalbytesent", (PyCFunction)UPnP_totalbytesent, METH_NOARGS, "return the total number of bytes sent by UPnP IGD" }, {"totalbytereceived", (PyCFunction)UPnP_totalbytereceived, METH_NOARGS, "return the total number of bytes received by UPnP IGD" }, {"totalpacketsent", (PyCFunction)UPnP_totalpacketsent, METH_NOARGS, "return the total number of packets sent by UPnP IGD" }, {"totalpacketreceived", (PyCFunction)UPnP_totalpacketreceived, METH_NOARGS, "return the total number of packets received by UPnP IGD" }, {"statusinfo", (PyCFunction)UPnP_statusinfo, METH_NOARGS, "return status and uptime" }, {"connectiontype", (PyCFunction)UPnP_connectiontype, METH_NOARGS, "return IGD WAN connection type" }, {"externalipaddress", (PyCFunction)UPnP_externalipaddress, METH_NOARGS, "return external IP address" }, {"addportmapping", (PyCFunction)UPnP_addportmapping, METH_VARARGS, "add a port mapping" }, {"deleteportmapping", (PyCFunction)UPnP_deleteportmapping, METH_VARARGS, "delete a port mapping" }, {"getportmappingnumberofentries", (PyCFunction)UPnP_getportmappingnumberofentries, METH_NOARGS, "-- non standard --" }, {"getspecificportmapping", (PyCFunction)UPnP_getspecificportmapping, METH_VARARGS, "get details about a specific port mapping entry" }, {"getgenericportmapping", (PyCFunction)UPnP_getgenericportmapping, METH_VARARGS, "get all details about the port mapping at index" }, {NULL} /* Sentinel */ }; static PyTypeObject UPnPType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "miniupnpc.UPnP", /*tp_name*/ sizeof(UPnPObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)UPnPObject_dealloc,/*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "UPnP objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ UPnP_methods, /* tp_methods */ UPnP_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0,/*(initproc)UPnP_init,*/ /* tp_init */ 0, /* tp_alloc */ #ifndef WIN32 PyType_GenericNew,/*UPnP_new,*/ /* tp_new */ #else 0, #endif }; /* module methods */ static PyMethodDef miniupnpc_methods[] = { {NULL} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initminiupnpc(void) { PyObject* m; #ifdef WIN32 UPnPType.tp_new = PyType_GenericNew; #endif if (PyType_Ready(&UPnPType) < 0) return; m = Py_InitModule3("miniupnpc", miniupnpc_methods, "miniupnpc module."); Py_INCREF(&UPnPType); PyModule_AddObject(m, "UPnP", (PyObject *)&UPnPType); }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniupnpcmodule.c
C
mit
13,281
/* $Id: upnperrors.c,v 1.3 2008/04/27 17:21:51 nanard Exp $ */ /* Project : miniupnp * Author : Thomas BERNARD * copyright (c) 2007 Thomas Bernard * All Right reserved. * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * This software is subjet to the conditions detailed in the * provided LICENCE file. */ #include <string.h> #include "upnperrors.h" #include "upnpcommands.h" const char * strupnperror(int err) { const char * s = NULL; switch(err) { case UPNPCOMMAND_SUCCESS: s = "Success"; break; case UPNPCOMMAND_UNKNOWN_ERROR: s = "Miniupnpc Unknown Error"; break; case UPNPCOMMAND_INVALID_ARGS: s = "Miniupnpc Invalid Arguments"; break; case 401: s = "Invalid Action"; break; case 402: s = "Invalid Args"; break; case 501: s = "Action Failed"; break; case 713: s = "SpecifiedArrayIndexInvalid"; break; case 714: s = "NoSuchEntryInArray"; break; case 715: s = "WildCardNotPermittedInSrcIP"; break; case 716: s = "WildCardNotPermittedInExtPort"; break; case 718: s = "ConflictInMappingEntry"; break; case 724: s = "SamePortValuesRequired"; break; case 725: s = "OnlyPermanentLeasesSupported"; break; case 726: s = "RemoteHostOnlySupportsWildcard"; break; case 727: s = "ExternalPortOnlySupportsWildcard"; break; default: s = NULL; } return s; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnperrors.c
C
mit
1,348
@mingw32-make -f Makefile.mingw %1 @if errorlevel 1 goto end @strip upnpc-static.exe @upx --best upnpc-static.exe @strip upnpc-shared.exe @upx --best upnpc-shared.exe :end
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/mingw32make.bat
Batchfile
mit
172
/* $Id: upnpcommands.h,v 1.17 2009/04/17 21:21:19 nanard Exp $ */ /* Miniupnp project : http://miniupnp.free.fr/ * Author : Thomas Bernard * Copyright (c) 2005-2008 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided within this distribution */ #ifndef __UPNPCOMMANDS_H__ #define __UPNPCOMMANDS_H__ #include "upnpreplyparse.h" #include "declspec.h" /* MiniUPnPc return codes : */ #define UPNPCOMMAND_SUCCESS (0) #define UPNPCOMMAND_UNKNOWN_ERROR (-1) #define UPNPCOMMAND_INVALID_ARGS (-2) #ifdef __cplusplus extern "C" { #endif #if (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) #define UNSIGNED_INTEGER unsigned long long #define STRTOUI strtoull #else #define UNSIGNED_INTEGER unsigned int #define STRTOUI strtoul #endif LIBSPEC UNSIGNED_INTEGER UPNP_GetTotalBytesSent(const char * controlURL, const char * servicetype); LIBSPEC UNSIGNED_INTEGER UPNP_GetTotalBytesReceived(const char * controlURL, const char * servicetype); LIBSPEC UNSIGNED_INTEGER UPNP_GetTotalPacketsSent(const char * controlURL, const char * servicetype); LIBSPEC UNSIGNED_INTEGER UPNP_GetTotalPacketsReceived(const char * controlURL, const char * servicetype); /* UPNP_GetStatusInfo() * status and lastconnerror are 64 byte buffers * Return values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error code */ LIBSPEC int UPNP_GetStatusInfo(const char * controlURL, const char * servicetype, char * status, unsigned int * uptime, char * lastconnerror); /* UPNP_GetConnectionTypeInfo() * argument connectionType is a 64 character buffer * Return Values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error code */ LIBSPEC int UPNP_GetConnectionTypeInfo(const char * controlURL, const char * servicetype, char * connectionType); /* UPNP_GetExternalIPAddress() call the corresponding UPNP method. * if the third arg is not null the value is copied to it. * at least 16 bytes must be available * * Return values : * 0 : SUCCESS * NON ZERO : ERROR Either an UPnP error code or an unknown error. * * possible UPnP Errors : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 501 Action Failed - See UPnP Device Architecture section on Control. */ LIBSPEC int UPNP_GetExternalIPAddress(const char * controlURL, const char * servicetype, char * extIpAdd); /* UPNP_GetLinkLayerMaxBitRates() * call WANCommonInterfaceConfig:1#GetCommonLinkProperties * * return values : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code. */ LIBSPEC int UPNP_GetLinkLayerMaxBitRates(const char* controlURL, const char* servicetype, unsigned int * bitrateDown, unsigned int * bitrateUp); /* UPNP_AddPortMapping() * if desc is NULL, it will be defaulted to "libminiupnpc" * remoteHost is usually NULL because IGD don't support it. * * Return values : * 0 : SUCCESS * NON ZERO : ERROR. Either an UPnP error code or an unknown error. * * List of possible UPnP errors for AddPortMapping : * errorCode errorDescription (short) - Description (long) * 402 Invalid Args - See UPnP Device Architecture section on Control. * 501 Action Failed - See UPnP Device Architecture section on Control. * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be * wild-carded * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded * 718 ConflictInMappingEntry - The port mapping entry specified conflicts * with a mapping assigned previously to another client * 724 SamePortValuesRequired - Internal and External port values * must be the same * 725 OnlyPermanentLeasesSupported - The NAT implementation only supports * permanent lease times on port mappings * 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard * and cannot be a specific IP address or DNS name * 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and * cannot be a specific port value */ LIBSPEC int UPNP_AddPortMapping(const char * controlURL, const char * servicetype, const char * extPort, const char * inPort, const char * inClient, const char * desc, const char * proto, const char * remoteHost); /* UPNP_DeletePortMapping() * Use same argument values as what was used for AddPortMapping(). * remoteHost is usually NULL because IGD don't support it. * Return Values : * 0 : SUCCESS * NON ZERO : error. Either an UPnP error code or an undefined error. * * List of possible UPnP errors for DeletePortMapping : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 714 NoSuchEntryInArray - The specified value does not exist in the array */ LIBSPEC int UPNP_DeletePortMapping(const char * controlURL, const char * servicetype, const char * extPort, const char * proto, const char * remoteHost); /* UPNP_GetPortMappingNumberOfEntries() * not supported by all routers */ LIBSPEC int UPNP_GetPortMappingNumberOfEntries(const char* controlURL, const char* servicetype, unsigned int * num); /* UPNP_GetSpecificPortMappingEntry retrieves an existing port mapping * the result is returned in the intClient and intPort strings * please provide 16 and 6 bytes of data * * return value : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code. */ LIBSPEC int UPNP_GetSpecificPortMappingEntry(const char * controlURL, const char * servicetype, const char * extPort, const char * proto, char * intClient, char * intPort); /* UPNP_GetGenericPortMappingEntry() * * return value : * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR * or a UPnP Error Code. * * Possible UPNP Error codes : * 402 Invalid Args - See UPnP Device Architecture section on Control. * 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds */ LIBSPEC int UPNP_GetGenericPortMappingEntry(const char * controlURL, const char * servicetype, const char * index, char * extPort, char * intClient, char * intPort, char * protocol, char * desc, char * enabled, char * rHost, char * duration); #ifdef __cplusplus } #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnpcommands.h
C
mit
6,894
/* $Id: upnpc.c,v 1.65 2008/10/14 18:05:27 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005-2008 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef WIN32 #include <winsock2.h> #define snprintf _snprintf #endif #include "miniwget.h" #include "miniupnpc.h" #include "upnpcommands.h" #include "upnperrors.h" /* protofix() checks if protocol is "UDP" or "TCP" * returns NULL if not */ const char * protofix(const char * proto) { static const char proto_tcp[4] = { 'T', 'C', 'P', 0}; static const char proto_udp[4] = { 'U', 'D', 'P', 0}; int i, b; for(i=0, b=1; i<4; i++) b = b && ( (proto[i] == proto_tcp[i]) || (proto[i] == (proto_tcp[i] | 32)) ); if(b) return proto_tcp; for(i=0, b=1; i<4; i++) b = b && ( (proto[i] == proto_udp[i]) || (proto[i] == (proto_udp[i] | 32)) ); if(b) return proto_udp; return 0; } static void DisplayInfos(struct UPNPUrls * urls, struct IGDdatas * data) { char externalIPAddress[16]; char connectionType[64]; char status[64]; char lastconnerr[64]; unsigned int uptime; unsigned int brUp, brDown; int r; UPNP_GetConnectionTypeInfo(urls->controlURL, data->servicetype, connectionType); if(connectionType[0]) printf("Connection Type : %s\n", connectionType); else printf("GetConnectionTypeInfo failed.\n"); UPNP_GetStatusInfo(urls->controlURL, data->servicetype, status, &uptime, lastconnerr); printf("Status : %s, uptime=%u, LastConnectionError : %s\n", status, uptime, lastconnerr); UPNP_GetLinkLayerMaxBitRates(urls->controlURL_CIF, data->servicetype_CIF, &brDown, &brUp); printf("MaxBitRateDown : %u bps MaxBitRateUp %u bps\n", brDown, brUp); r = UPNP_GetExternalIPAddress(urls->controlURL, data->servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("GetExternalIPAddress() returned %d\n", r); if(externalIPAddress[0]) printf("ExternalIPAddress = %s\n", externalIPAddress); else printf("GetExternalIPAddress failed.\n"); } static void GetConnectionStatus(struct UPNPUrls * urls, struct IGDdatas * data) { unsigned int bytessent, bytesreceived, packetsreceived, packetssent; DisplayInfos(urls, data); bytessent = UPNP_GetTotalBytesSent(urls->controlURL_CIF, data->servicetype_CIF); bytesreceived = UPNP_GetTotalBytesReceived(urls->controlURL_CIF, data->servicetype_CIF); packetssent = UPNP_GetTotalPacketsSent(urls->controlURL_CIF, data->servicetype_CIF); packetsreceived = UPNP_GetTotalPacketsReceived(urls->controlURL_CIF, data->servicetype_CIF); printf("Bytes: Sent: %8u\tRecv: %8u\n", bytessent, bytesreceived); printf("Packets: Sent: %8u\tRecv: %8u\n", packetssent, packetsreceived); } static void ListRedirections(struct UPNPUrls * urls, struct IGDdatas * data) { int r; int i = 0; char index[6]; char intClient[16]; char intPort[6]; char extPort[6]; char protocol[4]; char desc[80]; char enabled[6]; char rHost[64]; char duration[16]; /*unsigned int num=0; UPNP_GetPortMappingNumberOfEntries(urls->controlURL, data->servicetype, &num); printf("PortMappingNumberOfEntries : %u\n", num);*/ do { snprintf(index, 6, "%d", i); rHost[0] = '\0'; enabled[0] = '\0'; duration[0] = '\0'; desc[0] = '\0'; extPort[0] = '\0'; intPort[0] = '\0'; intClient[0] = '\0'; r = UPNP_GetGenericPortMappingEntry(urls->controlURL, data->servicetype, index, extPort, intClient, intPort, protocol, desc, enabled, rHost, duration); if(r==0) /* printf("%02d - %s %s->%s:%s\tenabled=%s leaseDuration=%s\n" " desc='%s' rHost='%s'\n", i, protocol, extPort, intClient, intPort, enabled, duration, desc, rHost); */ printf("%2d %s %5s->%s:%-5s '%s' '%s'\n", i, protocol, extPort, intClient, intPort, desc, rHost); else printf("GetGenericPortMappingEntry() returned %d (%s)\n", r, strupnperror(r)); i++; } while(r==0); } /* Test function * 1 - get connection type * 2 - get extenal ip address * 3 - Add port mapping * 4 - get this port mapping from the IGD */ static void SetRedirectAndTest(struct UPNPUrls * urls, struct IGDdatas * data, const char * iaddr, const char * iport, const char * eport, const char * proto) { char externalIPAddress[16]; char intClient[16]; char intPort[6]; int r; if(!iaddr || !iport || !eport || !proto) { fprintf(stderr, "Wrong arguments\n"); return; } proto = protofix(proto); if(!proto) { fprintf(stderr, "invalid protocol\n"); return; } UPNP_GetExternalIPAddress(urls->controlURL, data->servicetype, externalIPAddress); if(externalIPAddress[0]) printf("ExternalIPAddress = %s\n", externalIPAddress); else printf("GetExternalIPAddress failed.\n"); r = UPNP_AddPortMapping(urls->controlURL, data->servicetype, eport, iport, iaddr, 0, proto, 0); if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d\n", eport, iport, iaddr, r); r = UPNP_GetSpecificPortMappingEntry(urls->controlURL, data->servicetype, eport, proto, intClient, intPort); if(r!=UPNPCOMMAND_SUCCESS) printf("GetSpecificPortMappingEntry() failed with code %d\n", r); if(intClient[0]) { printf("InternalIP:Port = %s:%s\n", intClient, intPort); printf("external %s:%s %s is redirected to internal %s:%s\n", externalIPAddress, eport, proto, intClient, intPort); } } static void RemoveRedirect(struct UPNPUrls * urls, struct IGDdatas * data, const char * eport, const char * proto) { int r; if(!proto || !eport) { fprintf(stderr, "invalid arguments\n"); return; } proto = protofix(proto); if(!proto) { fprintf(stderr, "protocol invalid\n"); return; } r = UPNP_DeletePortMapping(urls->controlURL, data->servicetype, eport, proto, 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); } /* sample upnp client program */ int main(int argc, char ** argv) { char command = 0; char ** commandargv = 0; int commandargc = 0; struct UPNPDev * devlist = 0; char lanaddr[16]; /* my ip address on the LAN */ int i; const char * rootdescurl = 0; const char * multicastif = 0; const char * minissdpdpath = 0; #ifdef WIN32 WSADATA wsaData; int nResult = WSAStartup(MAKEWORD(2,2), &wsaData); if(nResult != NO_ERROR) { fprintf(stderr, "WSAStartup() failed.\n"); return -1; } #endif printf("upnpc : miniupnpc library test client. (c) 2006-2008 Thomas Bernard\n"); printf("Go to http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/\n" "for more information.\n"); /* command line processing */ for(i=1; i<argc; i++) { if(argv[i][0] == '-') { if(argv[i][1] == 'u') rootdescurl = argv[++i]; else if(argv[i][1] == 'm') multicastif = argv[++i]; else if(argv[i][1] == 'p') minissdpdpath = argv[++i]; else { command = argv[i][1]; i++; commandargv = argv + i; commandargc = argc - i; break; } } else { fprintf(stderr, "option '%s' invalid\n", argv[i]); } } if(!command || (command == 'a' && commandargc<4) || (command == 'd' && argc<2) || (command == 'r' && argc<2)) { fprintf(stderr, "Usage :\t%s [options] -a ip port external_port protocol\n\t\tAdd port redirection\n", argv[0]); fprintf(stderr, " \t%s [options] -d external_port protocol\n\t\tDelete port redirection\n", argv[0]); fprintf(stderr, " \t%s [options] -s\n\t\tGet Connection status\n", argv[0]); fprintf(stderr, " \t%s [options] -l\n\t\tList redirections\n", argv[0]); fprintf(stderr, " \t%s [options] -r port1 protocol1 [port2 protocol2] [...]\n\t\tAdd all redirections to the current host\n", argv[0]); fprintf(stderr, "\nprotocol is UDP or TCP\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, " -u url : bypass discovery process by providing the XML root description url.\n"); fprintf(stderr, " -m address : provide ip address of the interface to use for sending SSDP multicast packets.\n"); fprintf(stderr, " -p path : use this path for MiniSSDPd socket.\n"); return 1; } if( rootdescurl || (devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0))) { struct UPNPDev * device; struct UPNPUrls urls; struct IGDdatas data; if(devlist) { printf("List of UPNP devices found on the network :\n"); for(device = devlist; device; device = device->pNext) { printf(" desc: %s\n st: %s\n\n", device->descURL, device->st); } } i = 1; if( (rootdescurl && UPNP_GetIGDFromUrl(rootdescurl, &urls, &data, lanaddr, sizeof(lanaddr))) || (i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)))) { switch(i) { case 1: printf("Found valid IGD : %s\n", urls.controlURL); break; case 2: printf("Found a (not connected?) IGD : %s\n", urls.controlURL); printf("Trying to continue anyway\n"); break; case 3: printf("UPnP device found. Is it an IGD ? : %s\n", urls.controlURL); printf("Trying to continue anyway\n"); break; default: printf("Found device (igd ?) : %s\n", urls.controlURL); printf("Trying to continue anyway\n"); } printf("Local LAN ip address : %s\n", lanaddr); #if 0 printf("getting \"%s\"\n", urls.ipcondescURL); descXML = miniwget(urls.ipcondescURL, &descXMLsize); if(descXML) { /*fwrite(descXML, 1, descXMLsize, stdout);*/ free(descXML); descXML = NULL; } #endif switch(command) { case 'l': DisplayInfos(&urls, &data); ListRedirections(&urls, &data); break; case 'a': SetRedirectAndTest(&urls, &data, commandargv[0], commandargv[1], commandargv[2], commandargv[3]); break; case 'd': RemoveRedirect(&urls, &data, commandargv[0], commandargv[1]); break; case 's': GetConnectionStatus(&urls, &data); break; case 'r': for(i=0; i<commandargc; i+=2) { /*printf("port %s protocol %s\n", argv[i], argv[i+1]);*/ SetRedirectAndTest(&urls, &data, lanaddr, commandargv[i], commandargv[i], commandargv[i+1]); } break; default: fprintf(stderr, "Unknown switch -%c\n", command); } FreeUPNPUrls(&urls); } else { fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n"); } freeUPNPDevlist(devlist); devlist = 0; } else { fprintf(stderr, "No IGD UPnP Device found on the network !\n"); } /*puts("************* HOP ***************");*/ return 0; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnpc.c
C
mit
11,073
#! /usr/bin/python # $Id: setupmingw32.py,v 1.1 2007/06/12 23:04:13 nanard Exp $ # the MiniUPnP Project (c) 2007 Thomas Bernard # http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ # # python script to build the miniupnpc module under unix # from distutils.core import setup, Extension setup(name="miniupnpc", version="1.0-RC6", ext_modules=[ Extension(name="miniupnpc", sources=["miniupnpcmodule.c"], libraries=["ws2_32"], extra_objects=["libminiupnpc.a"]) ])
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/setupmingw32.py
Python
mit
524
/* $Id: testupnpreplyparse.c,v 1.2 2008/02/21 13:05:27 nanard Exp $ */ /* MiniUPnP project * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * (c) 2006-2007 Thomas Bernard * This software is subject to the conditions detailed * in the LICENCE file provided within the distribution */ #include <stdio.h> #include <stdlib.h> #include "upnpreplyparse.h" void test_parsing(const char * buf, int len) { struct NameValueParserData pdata; ParseNameValue(buf, len, &pdata); ClearNameValueList(&pdata); } int main(int argc, char * * argv) { FILE * f; char buffer[4096]; int l; if(argc<2) { fprintf(stderr, "Usage: %s file.xml\n", argv[0]); return 1; } f = fopen(argv[1], "r"); if(!f) { fprintf(stderr, "Error : can not open file %s\n", argv[1]); return 2; } l = fread(buffer, 1, sizeof(buffer)-1, f); fclose(f); buffer[l] = '\0'; #ifdef DEBUG DisplayNameValueList(buffer, l); #endif test_parsing(buffer, l); return 0; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/testupnpreplyparse.c
C
mit
956
/* $OpenBSD: queue.h,v 1.31 2005/11/25 08:06:25 otto Exp $ */ /* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ /* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ /* * This file defines five types of data structures: singly-linked lists, * lists, simple queues, tail queues, and circular queues. * * * A singly-linked list is headed by a single forward pointer. The elements * are singly linked for minimum space and pointer manipulation overhead at * the expense of O(n) removal for arbitrary elements. New elements can be * added to the list after an existing element or at the head of the list. * Elements being removed from the head of the list should use the explicit * macro for this purpose for optimum efficiency. A singly-linked list may * only be traversed in the forward direction. Singly-linked lists are ideal * for applications with large datasets and few or no removals or for * implementing a LIFO queue. * * A list is headed by a single forward pointer (or an array of forward * pointers for a hash table header). The elements are doubly linked * so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before * or after an existing element or at the head of the list. A list * may only be traversed in the forward direction. * * A simple queue is headed by a pair of pointers, one the head of the * list and the other to the tail of the list. The elements are singly * linked to save space, so elements can only be removed from the * head of the list. New elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the * list. A simple queue may only be traversed in the forward direction. * * A tail queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or * after an existing element, at the head of the list, or at the end of * the list. A tail queue may be traversed in either direction. * * A circle queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the list. * A circle queue may be traversed in either direction, but has a more * complex end of list detection. * * For details on the use of these macros, see the queue(3) manual page. */ #ifdef QUEUE_MACRO_DEBUG #define _Q_INVALIDATE(a) (a) = ((void *)-1) #else #define _Q_INVALIDATE(a) #endif /* * Singly-linked List definitions. */ #define SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ } #define SLIST_HEAD_INITIALIZER(head) \ { NULL } #ifdef SLIST_ENTRY #undef SLIST_ENTRY #endif #define SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } /* * Singly-linked List access methods. */ #define SLIST_FIRST(head) ((head)->slh_first) #define SLIST_END(head) NULL #define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) #define SLIST_FOREACH(var, head, field) \ for((var) = SLIST_FIRST(head); \ (var) != SLIST_END(head); \ (var) = SLIST_NEXT(var, field)) #define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ for ((varp) = &SLIST_FIRST((head)); \ ((var) = *(varp)) != SLIST_END(head); \ (varp) = &SLIST_NEXT((var), field)) /* * Singly-linked List functions. */ #define SLIST_INIT(head) { \ SLIST_FIRST(head) = SLIST_END(head); \ } #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ (elm)->field.sle_next = (slistelm)->field.sle_next; \ (slistelm)->field.sle_next = (elm); \ } while (0) #define SLIST_INSERT_HEAD(head, elm, field) do { \ (elm)->field.sle_next = (head)->slh_first; \ (head)->slh_first = (elm); \ } while (0) #define SLIST_REMOVE_NEXT(head, elm, field) do { \ (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ } while (0) #define SLIST_REMOVE_HEAD(head, field) do { \ (head)->slh_first = (head)->slh_first->field.sle_next; \ } while (0) #define SLIST_REMOVE(head, elm, type, field) do { \ if ((head)->slh_first == (elm)) { \ SLIST_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->slh_first; \ \ while (curelm->field.sle_next != (elm)) \ curelm = curelm->field.sle_next; \ curelm->field.sle_next = \ curelm->field.sle_next->field.sle_next; \ _Q_INVALIDATE((elm)->field.sle_next); \ } \ } while (0) /* * List definitions. */ #define LIST_HEAD(name, type) \ struct name { \ struct type *lh_first; /* first element */ \ } #define LIST_HEAD_INITIALIZER(head) \ { NULL } #define LIST_ENTRY(type) \ struct { \ struct type *le_next; /* next element */ \ struct type **le_prev; /* address of previous next element */ \ } /* * List access methods */ #define LIST_FIRST(head) ((head)->lh_first) #define LIST_END(head) NULL #define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head)) #define LIST_NEXT(elm, field) ((elm)->field.le_next) #define LIST_FOREACH(var, head, field) \ for((var) = LIST_FIRST(head); \ (var)!= LIST_END(head); \ (var) = LIST_NEXT(var, field)) /* * List functions. */ #define LIST_INIT(head) do { \ LIST_FIRST(head) = LIST_END(head); \ } while (0) #define LIST_INSERT_AFTER(listelm, elm, field) do { \ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ (listelm)->field.le_next->field.le_prev = \ &(elm)->field.le_next; \ (listelm)->field.le_next = (elm); \ (elm)->field.le_prev = &(listelm)->field.le_next; \ } while (0) #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.le_prev = (listelm)->field.le_prev; \ (elm)->field.le_next = (listelm); \ *(listelm)->field.le_prev = (elm); \ (listelm)->field.le_prev = &(elm)->field.le_next; \ } while (0) #define LIST_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.le_next = (head)->lh_first) != NULL) \ (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ (head)->lh_first = (elm); \ (elm)->field.le_prev = &(head)->lh_first; \ } while (0) #define LIST_REMOVE(elm, field) do { \ if ((elm)->field.le_next != NULL) \ (elm)->field.le_next->field.le_prev = \ (elm)->field.le_prev; \ *(elm)->field.le_prev = (elm)->field.le_next; \ _Q_INVALIDATE((elm)->field.le_prev); \ _Q_INVALIDATE((elm)->field.le_next); \ } while (0) #define LIST_REPLACE(elm, elm2, field) do { \ if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \ (elm2)->field.le_next->field.le_prev = \ &(elm2)->field.le_next; \ (elm2)->field.le_prev = (elm)->field.le_prev; \ *(elm2)->field.le_prev = (elm2); \ _Q_INVALIDATE((elm)->field.le_prev); \ _Q_INVALIDATE((elm)->field.le_next); \ } while (0) /* * Simple queue definitions. */ #define SIMPLEQ_HEAD(name, type) \ struct name { \ struct type *sqh_first; /* first element */ \ struct type **sqh_last; /* addr of last next element */ \ } #define SIMPLEQ_HEAD_INITIALIZER(head) \ { NULL, &(head).sqh_first } #define SIMPLEQ_ENTRY(type) \ struct { \ struct type *sqe_next; /* next element */ \ } /* * Simple queue access methods. */ #define SIMPLEQ_FIRST(head) ((head)->sqh_first) #define SIMPLEQ_END(head) NULL #define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head)) #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) #define SIMPLEQ_FOREACH(var, head, field) \ for((var) = SIMPLEQ_FIRST(head); \ (var) != SIMPLEQ_END(head); \ (var) = SIMPLEQ_NEXT(var, field)) /* * Simple queue functions. */ #define SIMPLEQ_INIT(head) do { \ (head)->sqh_first = NULL; \ (head)->sqh_last = &(head)->sqh_first; \ } while (0) #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ (head)->sqh_last = &(elm)->field.sqe_next; \ (head)->sqh_first = (elm); \ } while (0) #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.sqe_next = NULL; \ *(head)->sqh_last = (elm); \ (head)->sqh_last = &(elm)->field.sqe_next; \ } while (0) #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ (head)->sqh_last = &(elm)->field.sqe_next; \ (listelm)->field.sqe_next = (elm); \ } while (0) #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ (head)->sqh_last = &(head)->sqh_first; \ } while (0) /* * Tail queue definitions. */ #define TAILQ_HEAD(name, type) \ struct name { \ struct type *tqh_first; /* first element */ \ struct type **tqh_last; /* addr of last next element */ \ } #define TAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).tqh_first } #define TAILQ_ENTRY(type) \ struct { \ struct type *tqe_next; /* next element */ \ struct type **tqe_prev; /* address of previous next element */ \ } /* * tail queue access methods */ #define TAILQ_FIRST(head) ((head)->tqh_first) #define TAILQ_END(head) NULL #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) #define TAILQ_LAST(head, headname) \ (*(((struct headname *)((head)->tqh_last))->tqh_last)) /* XXX */ #define TAILQ_PREV(elm, headname, field) \ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) #define TAILQ_EMPTY(head) \ (TAILQ_FIRST(head) == TAILQ_END(head)) #define TAILQ_FOREACH(var, head, field) \ for((var) = TAILQ_FIRST(head); \ (var) != TAILQ_END(head); \ (var) = TAILQ_NEXT(var, field)) #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ for((var) = TAILQ_LAST(head, headname); \ (var) != TAILQ_END(head); \ (var) = TAILQ_PREV(var, headname, field)) /* * Tail queue functions. */ #define TAILQ_INIT(head) do { \ (head)->tqh_first = NULL; \ (head)->tqh_last = &(head)->tqh_first; \ } while (0) #define TAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ (head)->tqh_first->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (head)->tqh_first = (elm); \ (elm)->field.tqe_prev = &(head)->tqh_first; \ } while (0) #define TAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.tqe_next = NULL; \ (elm)->field.tqe_prev = (head)->tqh_last; \ *(head)->tqh_last = (elm); \ (head)->tqh_last = &(elm)->field.tqe_next; \ } while (0) #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ (elm)->field.tqe_next->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (listelm)->field.tqe_next = (elm); \ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ } while (0) #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ (elm)->field.tqe_next = (listelm); \ *(listelm)->field.tqe_prev = (elm); \ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ } while (0) #define TAILQ_REMOVE(head, elm, field) do { \ if (((elm)->field.tqe_next) != NULL) \ (elm)->field.tqe_next->field.tqe_prev = \ (elm)->field.tqe_prev; \ else \ (head)->tqh_last = (elm)->field.tqe_prev; \ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ _Q_INVALIDATE((elm)->field.tqe_prev); \ _Q_INVALIDATE((elm)->field.tqe_next); \ } while (0) #define TAILQ_REPLACE(head, elm, elm2, field) do { \ if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \ (elm2)->field.tqe_next->field.tqe_prev = \ &(elm2)->field.tqe_next; \ else \ (head)->tqh_last = &(elm2)->field.tqe_next; \ (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \ *(elm2)->field.tqe_prev = (elm2); \ _Q_INVALIDATE((elm)->field.tqe_prev); \ _Q_INVALIDATE((elm)->field.tqe_next); \ } while (0) /* * Circular queue definitions. */ #define CIRCLEQ_HEAD(name, type) \ struct name { \ struct type *cqh_first; /* first element */ \ struct type *cqh_last; /* last element */ \ } #define CIRCLEQ_HEAD_INITIALIZER(head) \ { CIRCLEQ_END(&head), CIRCLEQ_END(&head) } #define CIRCLEQ_ENTRY(type) \ struct { \ struct type *cqe_next; /* next element */ \ struct type *cqe_prev; /* previous element */ \ } /* * Circular queue access methods */ #define CIRCLEQ_FIRST(head) ((head)->cqh_first) #define CIRCLEQ_LAST(head) ((head)->cqh_last) #define CIRCLEQ_END(head) ((void *)(head)) #define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) #define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) #define CIRCLEQ_EMPTY(head) \ (CIRCLEQ_FIRST(head) == CIRCLEQ_END(head)) #define CIRCLEQ_FOREACH(var, head, field) \ for((var) = CIRCLEQ_FIRST(head); \ (var) != CIRCLEQ_END(head); \ (var) = CIRCLEQ_NEXT(var, field)) #define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ for((var) = CIRCLEQ_LAST(head); \ (var) != CIRCLEQ_END(head); \ (var) = CIRCLEQ_PREV(var, field)) /* * Circular queue functions. */ #define CIRCLEQ_INIT(head) do { \ (head)->cqh_first = CIRCLEQ_END(head); \ (head)->cqh_last = CIRCLEQ_END(head); \ } while (0) #define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm)->field.cqe_next; \ (elm)->field.cqe_prev = (listelm); \ if ((listelm)->field.cqe_next == CIRCLEQ_END(head)) \ (head)->cqh_last = (elm); \ else \ (listelm)->field.cqe_next->field.cqe_prev = (elm); \ (listelm)->field.cqe_next = (elm); \ } while (0) #define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm); \ (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ if ((listelm)->field.cqe_prev == CIRCLEQ_END(head)) \ (head)->cqh_first = (elm); \ else \ (listelm)->field.cqe_prev->field.cqe_next = (elm); \ (listelm)->field.cqe_prev = (elm); \ } while (0) #define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \ (elm)->field.cqe_next = (head)->cqh_first; \ (elm)->field.cqe_prev = CIRCLEQ_END(head); \ if ((head)->cqh_last == CIRCLEQ_END(head)) \ (head)->cqh_last = (elm); \ else \ (head)->cqh_first->field.cqe_prev = (elm); \ (head)->cqh_first = (elm); \ } while (0) #define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.cqe_next = CIRCLEQ_END(head); \ (elm)->field.cqe_prev = (head)->cqh_last; \ if ((head)->cqh_first == CIRCLEQ_END(head)) \ (head)->cqh_first = (elm); \ else \ (head)->cqh_last->field.cqe_next = (elm); \ (head)->cqh_last = (elm); \ } while (0) #define CIRCLEQ_REMOVE(head, elm, field) do { \ if ((elm)->field.cqe_next == CIRCLEQ_END(head)) \ (head)->cqh_last = (elm)->field.cqe_prev; \ else \ (elm)->field.cqe_next->field.cqe_prev = \ (elm)->field.cqe_prev; \ if ((elm)->field.cqe_prev == CIRCLEQ_END(head)) \ (head)->cqh_first = (elm)->field.cqe_next; \ else \ (elm)->field.cqe_prev->field.cqe_next = \ (elm)->field.cqe_next; \ _Q_INVALIDATE((elm)->field.cqe_prev); \ _Q_INVALIDATE((elm)->field.cqe_next); \ } while (0) #define CIRCLEQ_REPLACE(head, elm, elm2, field) do { \ if (((elm2)->field.cqe_next = (elm)->field.cqe_next) == \ CIRCLEQ_END(head)) \ (head).cqh_last = (elm2); \ else \ (elm2)->field.cqe_next->field.cqe_prev = (elm2); \ if (((elm2)->field.cqe_prev = (elm)->field.cqe_prev) == \ CIRCLEQ_END(head)) \ (head).cqh_first = (elm2); \ else \ (elm2)->field.cqe_prev->field.cqe_next = (elm2); \ _Q_INVALIDATE((elm)->field.cqe_prev); \ _Q_INVALIDATE((elm)->field.cqe_next); \ } while (0) #endif /* !_SYS_QUEUE_H_ */
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/bsdqueue.h
C
mit
18,109
\" $Id: miniupnpc.3,v 1.2 2008/10/07 13:51:55 nanard Exp $ .TH miniupnpc 3 .SH NAME miniupnpc \- UPnP client library .SH SYNOPSIS .SH DESCRIPTION The miniupnpc library implement the UPnP protocol defined to dialog with Internet Gateway Devices. It also has the ability to use data gathered by minissdpd(1) about UPnP devices up on the network in order to skip the long UPnP device discovery process. .PP At first, upnpDiscover(3) has to be used to discover UPnP IGD present on the network. Then UPNP_GetValidIGD(3) to select the right one. Alternatively, UPNP_GetIGDFromUrl(3) could be used to bypass discovery process if the root description url of the device to use is known. Then all the UPNP_* functions can be used, such as UPNP_GetConnectionTypeInfo(3), UPNP_AddPortMapping(3), etc... .SH "HEADER FILES" .IP miniupnpc.h That's the main header file for the miniupnpc library API. It contains all the functions and structures related to device discovery. .IP upnpcommands.h This header file contain the UPnP IGD methods that are accessible through the miniupnpc API. The name of the C functions are matching the UPnP methods names. ie: GetGenericPortMappingEntry is UPNP_GetGenericPortMappingEntry. .SH "API FUNCTIONS" .IP "struct UPNPDev * upnpDiscover(int delay, const char * multicastif, const char * minissdpdsock, int sameport);" execute the discovery process. delay (in millisecond) is the maximum time for waiting any device response. If available, device list will be obtained from MiniSSDPd. Default path for minissdpd socket will be used if minissdpdsock argument is NULL. If multicastif is not NULL, it will be used instead of the default multicast interface for sending SSDP discover packets. If sameport is not null, SSDP packets will be sent from the source port 1900 (same as destination port) otherwise system assign a source port. .IP "void freeUPNPDevlist(struct UPNPDev * devlist);" free the list returned by upnpDiscover(). .IP "int UPNP_GetValidIGD(struct UPNPDev * devlist, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen);" browse the list of device returned by upnpDiscover(), find a live UPnP internet gateway device and fill structures passed as arguments with data used for UPNP methods invokation. .IP "int UPNP_GetIGDFromUrl(const char * rootdescurl, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen);" permit to bypass the upnpDiscover() call if the xml root description URL of the UPnP IGD is known. Fill structures passed as arguments with data used for UPNP methods invokation. .IP "void GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *, const char *);" .IP "void FreeUPNPUrls(struct UPNPUrls *);" .SH "SEE ALSO" minissdpd(1) .SH BUGS
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/man3/miniupnpc.3
Roff Manpage
mit
2,734
#ifndef __DECLSPEC_H__ #define __DECLSPEC_H__ #if defined(WIN32) && !defined(STATICLIB) #ifdef MINIUPNP_EXPORTS #define LIBSPEC __declspec(dllexport) #else #define LIBSPEC __declspec(dllimport) #endif #else #define LIBSPEC #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/declspec.h
C
mit
248
/* $Id: miniwget.c,v 1.22 2009/02/28 10:36:35 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "miniupnpc.h" #ifdef WIN32 #include <winsock2.h> #include <io.h> #define MAXHOSTNAMELEN 64 #define MIN(x,y) (((x)<(y))?(x):(y)) #define snprintf _snprintf #define herror #define socklen_t int #else #include <unistd.h> #include <sys/param.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #define closesocket close #endif #if defined(__sun) || defined(sun) #define MIN(x,y) (((x)<(y))?(x):(y)) #endif #include "miniupnpcstrings.h" /* miniwget2() : * */ static void * miniwget2(const char * url, const char * host, unsigned short port, const char * path, int * size, char * addr_str, int addr_str_len) { char buf[2048]; int s; struct sockaddr_in dest; struct hostent *hp; *size = 0; hp = gethostbyname(host); if(hp==NULL) { herror(host); return NULL; } /* memcpy((char *)&dest.sin_addr, hp->h_addr, hp->h_length); */ memcpy(&dest.sin_addr, hp->h_addr, sizeof(dest.sin_addr)); memset(dest.sin_zero, 0, sizeof(dest.sin_zero)); s = socket(PF_INET, SOCK_STREAM, 0); if(s < 0) { perror("socket"); return NULL; } dest.sin_family = AF_INET; dest.sin_port = htons(port); if(connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr_in))<0) { perror("connect"); closesocket(s); return NULL; } /* get address for caller ! */ if(addr_str) { struct sockaddr_in saddr; socklen_t len; len = sizeof(saddr); getsockname(s, (struct sockaddr *)&saddr, &len); #ifndef WIN32 inet_ntop(AF_INET, &saddr.sin_addr, addr_str, addr_str_len); #else /* using INT WINAPI WSAAddressToStringA(LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFOA, LPSTR, LPDWORD); * But his function make a string with the port : nn.nn.nn.nn:port */ /* if(WSAAddressToStringA((SOCKADDR *)&saddr, sizeof(saddr), NULL, addr_str, (DWORD *)&addr_str_len)) { printf("WSAAddressToStringA() failed : %d\n", WSAGetLastError()); }*/ strncpy(addr_str, inet_ntoa(saddr.sin_addr), addr_str_len); #endif #ifdef DEBUG printf("address miniwget : %s\n", addr_str); #endif } snprintf(buf, sizeof(buf), "GET %s HTTP/1.1\r\n" "Host: %s:%d\r\n" "Connection: Close\r\n" "User-Agent: " OS_STRING ", UPnP/1.0, MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n" "\r\n", path, host, port); /*write(s, buf, strlen(buf));*/ send(s, buf, strlen(buf), 0); { int n, headers=1; char * respbuffer = NULL; int allreadyread = 0; /*while((n = recv(s, buf, 2048, 0)) > 0)*/ while((n = ReceiveData(s, buf, 2048, 5000)) > 0) { if(headers) { int i=0; while(i<n-3) { if(buf[i]=='\r' && buf[i+1]=='\n' && buf[i+2]=='\r' && buf[i+3]=='\n') { headers = 0; /* end */ if(i<n-4) { respbuffer = (char *)realloc((void *)respbuffer, allreadyread+(n-i-4)); memcpy(respbuffer+allreadyread, buf + i + 4, n-i-4); allreadyread += (n-i-4); } break; } i++; } } else { respbuffer = (char *)realloc((void *)respbuffer, allreadyread+n); memcpy(respbuffer+allreadyread, buf, n); allreadyread += n; } } *size = allreadyread; #ifdef DEBUG printf("%d bytes read\n", *size); #endif closesocket(s); return respbuffer; } } /* parseURL() * arguments : * url : source string not modified * hostname : hostname destination string (size of MAXHOSTNAMELEN+1) * port : port (destination) * path : pointer to the path part of the URL * * Return values : * 0 - Failure * 1 - Success */ int parseURL(const char * url, char * hostname, unsigned short * port, char * * path) { if ( url==0 ) { printf("%s: url was empty zero\n",__PRETTY_FUNCTION__); return 0; } char * p1, *p2, *p3; p1 = strstr(url, "://"); if(!p1) return 0; p1 += 3; if( (url[0]!='h') || (url[1]!='t') ||(url[2]!='t') || (url[3]!='p')) return 0; p2 = strchr(p1, ':'); p3 = strchr(p1, '/'); if(!p3) return 0; memset(hostname, 0, MAXHOSTNAMELEN + 1); if(!p2 || (p2>p3)) { strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p3-p1))); *port = 80; } else { strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1))); *port = 0; p2++; while( (*p2 >= '0') && (*p2 <= '9')) { *port *= 10; *port += (unsigned short)(*p2 - '0'); p2++; } } *path = p3; return 1; } void * miniwget(const char * url, int * size) { unsigned short port; char * path; /* protocol://host:port/chemin */ char hostname[MAXHOSTNAMELEN+1]; *size = 0; if(!parseURL(url, hostname, &port, &path)) return NULL; return miniwget2(url, hostname, port, path, size, 0, 0); } void * miniwget_getaddr(const char * url, int * size, char * addr, int addrlen) { unsigned short port; char * path; /* protocol://host:port/chemin */ char hostname[MAXHOSTNAMELEN+1]; *size = 0; if(addr) addr[0] = '\0'; if(!parseURL(url, hostname, &port, &path)) return NULL; return miniwget2(url, hostname, port, path, size, addr, addrlen); }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniwget.c
C
mit
5,323
/* $Id: minixml.c,v 1.6 2007/05/15 18:14:08 nanard Exp $ */ /* minixml.c : the minimum size a xml parser can be ! */ /* Project : miniupnp * webpage: http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * Author : Thomas Bernard Copyright (c) 2005-2007, Thomas BERNARD All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "minixml.h" /* parseatt : used to parse the argument list * return 0 (false) in case of success and -1 (true) if the end * of the xmlbuffer is reached. */ int parseatt(struct xmlparser * p) { const char * attname; int attnamelen; const char * attvalue; int attvaluelen; while(p->xml < p->xmlend) { if(*p->xml=='/' || *p->xml=='>') return 0; if( !IS_WHITE_SPACE(*p->xml) ) { char sep; attname = p->xml; attnamelen = 0; while(*p->xml!='=' && !IS_WHITE_SPACE(*p->xml) ) { attnamelen++; p->xml++; if(p->xml >= p->xmlend) return -1; } while(*(p->xml++) != '=') { if(p->xml >= p->xmlend) return -1; } while(IS_WHITE_SPACE(*p->xml)) { p->xml++; if(p->xml >= p->xmlend) return -1; } sep = *p->xml; if(sep=='\'' || sep=='\"') { p->xml++; if(p->xml >= p->xmlend) return -1; attvalue = p->xml; attvaluelen = 0; while(*p->xml != sep) { attvaluelen++; p->xml++; if(p->xml >= p->xmlend) return -1; } } else { attvalue = p->xml; attvaluelen = 0; while( !IS_WHITE_SPACE(*p->xml) && *p->xml != '>' && *p->xml != '/') { attvaluelen++; p->xml++; if(p->xml >= p->xmlend) return -1; } } /*printf("%.*s='%.*s'\n", attnamelen, attname, attvaluelen, attvalue);*/ if(p->attfunc) p->attfunc(p->data, attname, attnamelen, attvalue, attvaluelen); } p->xml++; } return -1; } /* parseelt parse the xml stream and * call the callback functions when needed... */ void parseelt(struct xmlparser * p) { int i; const char * elementname; while(p->xml < (p->xmlend - 1)) { if((p->xml)[0]=='<' && (p->xml)[1]!='?') { i = 0; elementname = ++p->xml; while( !IS_WHITE_SPACE(*p->xml) && (*p->xml!='>') && (*p->xml!='/') ) { i++; p->xml++; if (p->xml >= p->xmlend) return; /* to ignore namespace : */ if(*p->xml==':') { i = 0; elementname = ++p->xml; } } if(i>0) { if(p->starteltfunc) p->starteltfunc(p->data, elementname, i); if(parseatt(p)) return; if(*p->xml!='/') { const char * data; i = 0; data = ++p->xml; if (p->xml >= p->xmlend) return; while( IS_WHITE_SPACE(*p->xml) ) { p->xml++; if (p->xml >= p->xmlend) return; } while(*p->xml!='<') { i++; p->xml++; if (p->xml >= p->xmlend) return; } if(i>0 && p->datafunc) p->datafunc(p->data, data, i); } } else if(*p->xml == '/') { i = 0; elementname = ++p->xml; if (p->xml >= p->xmlend) return; while((*p->xml != '>')) { i++; p->xml++; if (p->xml >= p->xmlend) return; } if(p->endeltfunc) p->endeltfunc(p->data, elementname, i); p->xml++; } } else { p->xml++; } } } /* the parser must be initialized before calling this function */ void parsexml(struct xmlparser * parser) { parser->xml = parser->xmlstart; parser->xmlend = parser->xmlstart + parser->xmlsize; parseelt(parser); }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minixml.c
C
mit
4,830
/* $Id: upnpreplyparse.h,v 1.8 2008/02/21 13:05:27 nanard Exp $ */ /* MiniUPnP project * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * (c) 2006 Thomas Bernard * This software is subject to the conditions detailed * in the LICENCE file provided within the distribution */ #ifndef __UPNPREPLYPARSE_H__ #define __UPNPREPLYPARSE_H__ #if defined(NO_SYS_QUEUE_H) || defined(WIN32) #include "bsdqueue.h" #else #include <sys/queue.h> #endif #ifdef __cplusplus extern "C" { #endif struct NameValue { LIST_ENTRY(NameValue) entries; char name[64]; char value[64]; }; struct NameValueParserData { LIST_HEAD(listhead, NameValue) head; char curelt[64]; }; /* ParseNameValue() */ void ParseNameValue(const char * buffer, int bufsize, struct NameValueParserData * data); /* ClearNameValueList() */ void ClearNameValueList(struct NameValueParserData * pdata); /* GetValueFromNameValueList() */ char * GetValueFromNameValueList(struct NameValueParserData * pdata, const char * Name); /* GetValueFromNameValueListIgnoreNS() */ char * GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata, const char * Name); /* DisplayNameValueList() */ #ifdef DEBUG void DisplayNameValueList(char * buffer, int bufsize); #endif #ifdef __cplusplus } #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/upnpreplyparse.h
C
mit
1,372
#! /usr/bin/python # MiniUPnP project # Author : Thomas Bernard # This Sample code is public domain. # website : http://miniupnp.tuxfamily.org/ # import the python miniupnpc module import miniupnpc import sys # create the object u = miniupnpc.UPnP() print 'inital(default) values :' print ' discoverdelay', u.discoverdelay print ' lanaddr', u.lanaddr print ' multicastif', u.multicastif print ' minissdpdsocket', u.minissdpdsocket u.discoverdelay = 200; #u.minissdpdsocket = '../minissdpd/minissdpd.sock' # discovery process, it usualy takes several seconds (2 seconds or more) print 'Discovering... delay=%ums' % u.discoverdelay print u.discover(), 'device(s) detected' # select an igd try: u.selectigd() except Exception, e: print 'Exception :', e sys.exit(1) # display information about the IGD and the internet connection print 'local ip address :', u.lanaddr print 'external ip address :', u.externalipaddress() print u.statusinfo(), u.connectiontype() #print u.addportmapping(64000, 'TCP', # '192.168.1.166', 63000, 'port mapping test', '') #print u.deleteportmapping(64000, 'TCP') port = 0 proto = 'UDP' # list the redirections : i = 0 while True: p = u.getgenericportmapping(i) if p==None: break print i, p (port, proto, (ihost,iport), desc, c, d, e) = p #print port, desc i = i + 1 print u.getspecificportmapping(port, proto)
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/pymoduletest.py
Python
mit
1,377
/* $Id: minissdpc.c,v 1.7 2008/12/18 17:45:48 nanard Exp $ */ /* Project : miniupnp * Author : Thomas BERNARD * copyright (c) 2005-2008 Thomas Bernard * This software is subjet to the conditions detailed in the * provided LICENCE file. */ /*#include <syslog.h>*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #ifdef WIN32 #include <winsock2.h> #include <Ws2tcpip.h> #include <io.h> #else #include <sys/socket.h> #include <sys/un.h> #endif #include "minissdpc.h" #include "miniupnpc.h" #include "codelength.h" struct UPNPDev * getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath) { struct UPNPDev * tmp; struct UPNPDev * devlist = NULL; unsigned char buffer[2048]; ssize_t n; unsigned char * p; unsigned char * url; unsigned int i; unsigned int urlsize, stsize, usnsize, l; int s; struct sockaddr_un addr; s = socket(AF_UNIX, SOCK_STREAM, 0); if(s < 0) { /*syslog(LOG_ERR, "socket(unix): %m");*/ perror("socket(unix)"); return NULL; } addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socketpath, sizeof(addr.sun_path)); if(connect(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) { /*syslog(LOG_WARNING, "connect(\"%s\"): %m", socketpath);*/ close(s); return NULL; } stsize = strlen(devtype); buffer[0] = 1; /* request type 1 : request devices/services by type */ p = buffer + 1; l = stsize; CODELENGTH(l, p); memcpy(p, devtype, stsize); p += stsize; if(write(s, buffer, p - buffer) < 0) { /*syslog(LOG_ERR, "write(): %m");*/ perror("minissdpc.c: write()"); close(s); return NULL; } n = read(s, buffer, sizeof(buffer)); if(n<=0) { perror("minissdpc.c: read()"); close(s); return NULL; } p = buffer + 1; for(i = 0; i < buffer[0]; i++) { if(p+2>=buffer+sizeof(buffer)) break; DECODELENGTH(urlsize, p); if(p+urlsize+2>=buffer+sizeof(buffer)) break; url = p; p += urlsize; DECODELENGTH(stsize, p); if(p+stsize+2>=buffer+sizeof(buffer)) break; tmp = (struct UPNPDev *)malloc(sizeof(struct UPNPDev)+urlsize+stsize); tmp->pNext = devlist; tmp->descURL = tmp->buffer; tmp->st = tmp->buffer + 1 + urlsize; memcpy(tmp->buffer, url, urlsize); tmp->buffer[urlsize] = '\0'; memcpy(tmp->buffer + urlsize + 1, p, stsize); p += stsize; tmp->buffer[urlsize+1+stsize] = '\0'; devlist = tmp; /* added for compatibility with recent versions of MiniSSDPd * >= 2007/12/19 */ DECODELENGTH(usnsize, p); p += usnsize; if(p>buffer + sizeof(buffer)) break; } close(s); return devlist; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minissdpc.c
C
mit
2,578
/* $Id: minisoap.c,v 1.16 2008/10/11 16:39:29 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * * Minimal SOAP implementation for UPnP protocol. */ #include <stdio.h> #include <string.h> #ifdef WIN32 #include <io.h> #include <winsock2.h> #define snprintf _snprintf #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #endif #include "minisoap.h" #include "miniupnpcstrings.h" /* only for malloc */ #include <stdlib.h> #ifdef WIN32 #define PRINT_SOCKET_ERROR(x) printf("Socket error: %s, %d\n", x, WSAGetLastError()); #else #define PRINT_SOCKET_ERROR(x) perror(x) #endif /* httpWrite sends the headers and the body to the socket * and returns the number of bytes sent */ static int httpWrite(int fd, const char * body, int bodysize, const char * headers, int headerssize) { int n = 0; /*n = write(fd, headers, headerssize);*/ /*if(bodysize>0) n += write(fd, body, bodysize);*/ /* Note : my old linksys router only took into account * soap request that are sent into only one packet */ char * p; /* TODO: AVOID MALLOC */ p = malloc(headerssize+bodysize); if(!p) return 0; memcpy(p, headers, headerssize); memcpy(p+headerssize, body, bodysize); /*n = write(fd, p, headerssize+bodysize);*/ n = send(fd, p, headerssize+bodysize, 0); if(n<0) { PRINT_SOCKET_ERROR("send"); } /* disable send on the socket */ /* draytek routers dont seems to like that... */ #if 0 #ifdef WIN32 if(shutdown(fd, SD_SEND)<0) { #else if(shutdown(fd, SHUT_WR)<0) { /*SD_SEND*/ #endif PRINT_SOCKET_ERROR("shutdown"); } #endif free(p); return n; } /* self explanatory */ int soapPostSubmit(int fd, const char * url, const char * host, unsigned short port, const char * action, const char * body) { int bodysize; char headerbuf[512]; int headerssize; char portstr[8]; bodysize = (int)strlen(body); /* We are not using keep-alive HTTP connections. * HTTP/1.1 needs the header Connection: close to do that. * This is the default with HTTP/1.0 */ /* Connection: Close is normally there only in HTTP/1.1 but who knows */ portstr[0] = '\0'; if(port != 80) snprintf(portstr, sizeof(portstr), ":%hu", port); headerssize = snprintf(headerbuf, sizeof(headerbuf), "POST %s HTTP/1.1\r\n" /* "POST %s HTTP/1.0\r\n"*/ "Host: %s%s\r\n" "User-Agent: " OS_STRING ", UPnP/1.0, MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n" "Content-Length: %d\r\n" "Content-Type: text/xml\r\n" "SOAPAction: \"%s\"\r\n" "Connection: Close\r\n" "Cache-Control: no-cache\r\n" /* ??? */ "Pragma: no-cache\r\n" "\r\n", url, host, portstr, bodysize, action); #ifdef DEBUG printf("SOAP request : headersize=%d bodysize=%d\n", headerssize, bodysize); /*printf("%s", headerbuf);*/ #endif return httpWrite(fd, body, bodysize, headerbuf, headerssize); }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minisoap.c
C
mit
3,141
/* $Id: miniupnpc.c,v 1.57 2008/12/18 17:46:36 nanard Exp $ */ /* Project : miniupnp * Author : Thomas BERNARD * copyright (c) 2005-2007 Thomas Bernard * This software is subjet to the conditions detailed in the * provided LICENCE file. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef WIN32 /* Win32 Specific includes and defines */ #include <winsock2.h> #include <Ws2tcpip.h> #include <io.h> #define snprintf _snprintf #if defined(_MSC_VER) && (_MSC_VER >= 1400) #define strncasecmp _memicmp #else #define strncasecmp memicmp #endif #define MAXHOSTNAMELEN 64 #else /* Standard POSIX includes */ #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/param.h> #include <netinet/in.h> #include <arpa/inet.h> #include <poll.h> #include <netdb.h> #define closesocket close #endif #include "miniupnpc.h" #include "minissdpc.h" #include "miniwget.h" #include "minisoap.h" #include "minixml.h" #include "upnpcommands.h" #ifdef WIN32 #define PRINT_SOCKET_ERROR(x) printf("Socket error: %s, %d\n", x, WSAGetLastError()); #else #define PRINT_SOCKET_ERROR(x) perror(x) #endif #define SOAPPREFIX "s" #define SERVICEPREFIX "u" #define SERVICEPREFIX2 'u' /* root description parsing */ void parserootdesc(const char * buffer, int bufsize, struct IGDdatas * data) { struct xmlparser parser; /* xmlparser object */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = data; parser.starteltfunc = IGDstartelt; parser.endeltfunc = IGDendelt; parser.datafunc = IGDdata; parser.attfunc = 0; parsexml(&parser); #ifdef DEBUG printIGD(data); #endif } /* Content-length: nnn */ static int getcontentlenfromline(const char * p, int n) { static const char contlenstr[] = "content-length"; const char * p2 = contlenstr; int a = 0; while(*p2) { if(n==0) return -1; if(*p2 != *p && *p2 != (*p + 32)) return -1; p++; p2++; n--; } if(n==0) return -1; if(*p != ':') return -1; p++; n--; while(*p == ' ') { if(n==0) return -1; p++; n--; } while(*p >= '0' && *p <= '9') { if(n==0) return -1; a = (a * 10) + (*p - '0'); p++; n--; } return a; } static void getContentLengthAndHeaderLength(char * p, int n, int * contentlen, int * headerlen) { char * line; int linelen; int r; line = p; while(line < p + n) { linelen = 0; while(line[linelen] != '\r' && line[linelen] != '\r') { if(line+linelen >= p+n) return; linelen++; } r = getcontentlenfromline(line, linelen); if(r>0) *contentlen = r; line = line + linelen + 2; if(line[0] == '\r' && line[1] == '\n') { *headerlen = (line - p) + 2; return; } } } /* simpleUPnPcommand : * not so simple ! * return values : * 0 - OK * -1 - error */ int simpleUPnPcommand(int s, const char * url, const char * service, const char * action, struct UPNParg * args, char * buffer, int * bufsize) { struct sockaddr_in dest; char hostname[MAXHOSTNAMELEN+1]; unsigned short port = 0; char * path; char soapact[128]; char soapbody[2048]; char * buf; int buffree; int n; int contentlen, headerlen; /* for the response */ snprintf(soapact, sizeof(soapact), "%s#%s", service, action); if(args==NULL) { /*soapbodylen = */snprintf(soapbody, sizeof(soapbody), "<?xml version=\"1.0\"?>\r\n" "<" SOAPPREFIX ":Envelope " "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" " SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" "<" SOAPPREFIX ":Body>" "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">" "</" SERVICEPREFIX ":%s>" "</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>" "\r\n", action, service, action); } else { char * p; const char * pe, * pv; int soapbodylen; soapbodylen = snprintf(soapbody, sizeof(soapbody), "<?xml version=\"1.0\"?>\r\n" "<" SOAPPREFIX ":Envelope " "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" " SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" "<" SOAPPREFIX ":Body>" "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">", action, service); p = soapbody + soapbodylen; while(args->elt) { /* check that we are never overflowing the string... */ if(soapbody + sizeof(soapbody) <= p + 100) { /* we keep a margin of at least 100 bytes */ *bufsize = 0; return -1; } *(p++) = '<'; pe = args->elt; while(*pe) *(p++) = *(pe++); *(p++) = '>'; if((pv = args->val)) { while(*pv) *(p++) = *(pv++); } *(p++) = '<'; *(p++) = '/'; pe = args->elt; while(*pe) *(p++) = *(pe++); *(p++) = '>'; args++; } *(p++) = '<'; *(p++) = '/'; *(p++) = SERVICEPREFIX2; *(p++) = ':'; pe = action; while(*pe) *(p++) = *(pe++); strncpy(p, "></" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>\r\n", soapbody + sizeof(soapbody) - p); } if(!parseURL(url, hostname, &port, &path)) return -1; if(s<0) { s = socket(PF_INET, SOCK_STREAM, 0); if(s<0) { PRINT_SOCKET_ERROR("socket"); *bufsize = 0; return -1; } dest.sin_family = AF_INET; dest.sin_port = htons(port); dest.sin_addr.s_addr = inet_addr(hostname); if(connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr))<0) { PRINT_SOCKET_ERROR("connect"); closesocket(s); *bufsize = 0; return -1; } } n = soapPostSubmit(s, path, hostname, port, soapact, soapbody); if(n<=0) { #ifdef DEBUG printf("Error sending SOAP request\n"); #endif closesocket(s); return -1; } contentlen = -1; headerlen = -1; buf = buffer; buffree = *bufsize; *bufsize = 0; while ((n = ReceiveData(s, buf, buffree, 5000)) > 0) { buffree -= n; buf += n; *bufsize += n; getContentLengthAndHeaderLength(buffer, *bufsize, &contentlen, &headerlen); #ifdef DEBUG printf("received n=%dbytes bufsize=%d ContLen=%d HeadLen=%d\n", n, *bufsize, contentlen, headerlen); #endif /* break if we received everything */ if(contentlen > 0 && headerlen > 0 && *bufsize >= contentlen+headerlen) break; } closesocket(s); return 0; } /* parseMSEARCHReply() * the last 4 arguments are filled during the parsing : * - location/locationsize : "location:" field of the SSDP reply packet * - st/stsize : "st:" field of the SSDP reply packet. * The strings are NOT null terminated */ static void parseMSEARCHReply(const char * reply, int size, const char * * location, int * locationsize, const char * * st, int * stsize) { int a, b, i; i = 0; a = i; /* start of the line */ b = 0; while(i<size) { switch(reply[i]) { case ':': if(b==0) { b = i; /* end of the "header" */ /*for(j=a; j<b; j++) { putchar(reply[j]); } */ } break; case '\x0a': case '\x0d': if(b!=0) { /*for(j=b+1; j<i; j++) { putchar(reply[j]); } putchar('\n');*/ do { b++; } while(reply[b]==' '); if(0==strncasecmp(reply+a, "location", 8)) { *location = reply+b; *locationsize = i-b; } else if(0==strncasecmp(reply+a, "st", 2)) { *st = reply+b; *stsize = i-b; } b = 0; } a = i+1; break; default: break; } i++; } } /* port upnp discover : SSDP protocol */ #define PORT 1900 #define XSTR(s) STR(s) #define STR(s) #s #define UPNP_MCAST_ADDR "239.255.255.250" /* upnpDiscover() : * return a chained list of all devices found or NULL if * no devices was found. * It is up to the caller to free the chained list * delay is in millisecond (poll) */ struct UPNPDev * upnpDiscover(int delay, const char * multicastif, const char * minissdpdsock, int sameport) { struct UPNPDev * tmp; struct UPNPDev * devlist = 0; int opt = 1; static const char MSearchMsgFmt[] = "M-SEARCH * HTTP/1.1\r\n" "HOST: " UPNP_MCAST_ADDR ":" XSTR(PORT) "\r\n" "ST: %s\r\n" "MAN: \"ssdp:discover\"\r\n" "MX: 3\r\n" "\r\n"; static const char * const deviceList[] = { "urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1", "upnp:rootdevice", 0 }; int deviceIndex = 0; char bufr[1536]; /* reception and emission buffer */ int sudp; int n; struct sockaddr_in sockudp_r, sockudp_w; #ifndef WIN32 /* first try to get infos from minissdpd ! */ if(!minissdpdsock) minissdpdsock = "/var/run/minissdpd.sock"; while(!devlist && deviceList[deviceIndex]) { devlist = getDevicesFromMiniSSDPD(deviceList[deviceIndex], minissdpdsock); /* We return what we have found if it was not only a rootdevice */ if(devlist && !strstr(deviceList[deviceIndex], "rootdevice")) return devlist; deviceIndex++; } deviceIndex = 0; #endif /* fallback to direct discovery */ #ifdef WIN32 sudp = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); #else sudp = socket(PF_INET, SOCK_DGRAM, 0); #endif if(sudp < 0) { PRINT_SOCKET_ERROR("socket"); return NULL; } /* reception */ memset(&sockudp_r, 0, sizeof(struct sockaddr_in)); sockudp_r.sin_family = AF_INET; if(sameport) sockudp_r.sin_port = htons(PORT); sockudp_r.sin_addr.s_addr = INADDR_ANY; /* emission */ memset(&sockudp_w, 0, sizeof(struct sockaddr_in)); sockudp_w.sin_family = AF_INET; sockudp_w.sin_port = htons(PORT); sockudp_w.sin_addr.s_addr = inet_addr(UPNP_MCAST_ADDR); #ifdef WIN32 if (setsockopt(sudp, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof (opt)) < 0) #else if (setsockopt(sudp, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0) #endif { PRINT_SOCKET_ERROR("setsockopt"); return NULL; } if(multicastif) { struct in_addr mc_if; mc_if.s_addr = inet_addr(multicastif); sockudp_r.sin_addr.s_addr = mc_if.s_addr; if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&mc_if, sizeof(mc_if)) < 0) { PRINT_SOCKET_ERROR("setsockopt"); } } /* Avant d'envoyer le paquet on bind pour recevoir la reponse */ if (bind(sudp, (struct sockaddr *)&sockudp_r, sizeof(struct sockaddr_in)) != 0) { PRINT_SOCKET_ERROR("bind"); closesocket(sudp); return NULL; } /* receiving SSDP response packet */ for(n = 0;;) { if(n == 0) { /* sending the SSDP M-SEARCH packet */ n = snprintf(bufr, sizeof(bufr), MSearchMsgFmt, deviceList[deviceIndex++]); /*printf("Sending %s", bufr);*/ n = sendto(sudp, bufr, n, 0, (struct sockaddr *)&sockudp_w, sizeof(struct sockaddr_in)); if (n < 0) { PRINT_SOCKET_ERROR("sendto"); closesocket(sudp); return devlist; } } /* Waiting for SSDP REPLY packet to M-SEARCH */ n = ReceiveData(sudp, bufr, sizeof(bufr), delay); if (n < 0) { /* error */ closesocket(sudp); return devlist; } else if (n == 0) { /* no data or Time Out */ if (devlist || (deviceList[deviceIndex] == 0)) { /* no more device type to look for... */ closesocket(sudp); return devlist; } } else { const char * descURL=NULL; int urlsize=0; const char * st=NULL; int stsize=0; /*printf("%d byte(s) :\n%s\n", n, bufr);*/ /* affichage du message */ parseMSEARCHReply(bufr, n, &descURL, &urlsize, &st, &stsize); if(st&&descURL) { /*printf("M-SEARCH Reply:\nST: %.*s\nLocation: %.*s\n", stsize, st, urlsize, descURL); */ tmp = (struct UPNPDev *)malloc(sizeof(struct UPNPDev)+urlsize+stsize); tmp->pNext = devlist; tmp->descURL = tmp->buffer; tmp->st = tmp->buffer + 1 + urlsize; memcpy(tmp->buffer, descURL, urlsize); tmp->buffer[urlsize] = '\0'; memcpy(tmp->buffer + urlsize + 1, st, stsize); tmp->buffer[urlsize+1+stsize] = '\0'; devlist = tmp; } } } } /* freeUPNPDevlist() should be used to * free the chained list returned by upnpDiscover() */ void freeUPNPDevlist(struct UPNPDev * devlist) { struct UPNPDev * next; while(devlist) { next = devlist->pNext; free(devlist); devlist = next; } } static void url_cpy_or_cat(char * dst, const char * src, int n) { if( (src[0] == 'h') &&(src[1] == 't') &&(src[2] == 't') &&(src[3] == 'p') &&(src[4] == ':') &&(src[5] == '/') &&(src[6] == '/')) { strncpy(dst, src, n); } else { int l = strlen(dst); if(src[0] != '/') dst[l++] = '/'; if(l<=n) strncpy(dst + l, src, n - l); } } /* Prepare the Urls for usage... */ void GetUPNPUrls(struct UPNPUrls * urls, struct IGDdatas * data, const char * descURL) { char * p; int n1, n2, n3; n1 = strlen(data->urlbase); if(n1==0) n1 = strlen(descURL); n1 += 2; /* 1 byte more for Null terminator, 1 byte for '/' if needed */ n2 = n1; n3 = n1; n1 += strlen(data->scpdurl); n2 += strlen(data->controlurl); n3 += strlen(data->controlurl_CIF); urls->ipcondescURL = (char *)malloc(n1); urls->controlURL = (char *)malloc(n2); urls->controlURL_CIF = (char *)malloc(n3); /* maintenant on chope la desc du WANIPConnection */ if(data->urlbase[0] != '\0') strncpy(urls->ipcondescURL, data->urlbase, n1); else strncpy(urls->ipcondescURL, descURL, n1); p = strchr(urls->ipcondescURL+7, '/'); if(p) p[0] = '\0'; strncpy(urls->controlURL, urls->ipcondescURL, n2); strncpy(urls->controlURL_CIF, urls->ipcondescURL, n3); url_cpy_or_cat(urls->ipcondescURL, data->scpdurl, n1); url_cpy_or_cat(urls->controlURL, data->controlurl, n2); url_cpy_or_cat(urls->controlURL_CIF, data->controlurl_CIF, n3); #ifdef DEBUG printf("urls->ipcondescURL='%s' %d n1=%d\n", urls->ipcondescURL, strlen(urls->ipcondescURL), n1); printf("urls->controlURL='%s' %d n2=%d\n", urls->controlURL, strlen(urls->controlURL), n2); printf("urls->controlURL_CIF='%s' %d n3=%d\n", urls->controlURL_CIF, strlen(urls->controlURL_CIF), n3); #endif } void FreeUPNPUrls(struct UPNPUrls * urls) { if(!urls) return; free(urls->controlURL); urls->controlURL = 0; free(urls->ipcondescURL); urls->ipcondescURL = 0; free(urls->controlURL_CIF); urls->controlURL_CIF = 0; } int ReceiveData(int socket, char * data, int length, int timeout) { int n; #ifndef WIN32 struct pollfd fds[1]; /* for the poll */ fds[0].fd = socket; fds[0].events = POLLIN; n = poll(fds, 1, timeout); if(n < 0) { PRINT_SOCKET_ERROR("poll"); return -1; } else if(n == 0) { return 0; } #else fd_set socketSet; TIMEVAL timeval; FD_ZERO(&socketSet); FD_SET(socket, &socketSet); timeval.tv_sec = timeout / 1000; timeval.tv_usec = (timeout % 1000) * 1000; /*n = select(0, &socketSet, NULL, NULL, &timeval);*/ n = select(FD_SETSIZE, &socketSet, NULL, NULL, &timeval); if(n < 0) { PRINT_SOCKET_ERROR("select"); return -1; } else if(n == 0) { return 0; } #endif n = recv(socket, data, length, 0); if(n<0) { PRINT_SOCKET_ERROR("recv"); } return n; } int UPNPIGD_IsConnected(struct UPNPUrls * urls, struct IGDdatas * data) { char status[64]; unsigned int uptime; status[0] = '\0'; UPNP_GetStatusInfo(urls->controlURL, data->servicetype, status, &uptime, NULL); if(0 == strcmp("Connected", status)) { return 1; } else return 0; } /* UPNP_GetValidIGD() : * return values : * 0 = NO IGD found * 1 = A valid connected IGD has been found * 2 = A valid IGD has been found but it reported as * not connected * 3 = an UPnP device has been found but was not recognized as an IGD * * In any non zero return case, the urls and data structures * passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to * free allocated memory. */ int UPNP_GetValidIGD(struct UPNPDev * devlist, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen) { char * descXML; int descXMLsize = 0; struct UPNPDev * dev; int ndev = 0; int state; /* state 1 : IGD connected. State 2 : IGD. State 3 : anything */ if(!devlist) { #ifdef DEBUG printf("Empty devlist\n"); #endif return 0; } for(state = 1; state <= 3; state++) { for(dev = devlist; dev; dev = dev->pNext) { /* we should choose an internet gateway device. * with st == urn:schemas-upnp-org:device:InternetGatewayDevice:1 */ descXML = miniwget_getaddr(dev->descURL, &descXMLsize, lanaddr, lanaddrlen); if(descXML) { ndev++; memset(data, 0, sizeof(struct IGDdatas)); memset(urls, 0, sizeof(struct UPNPUrls)); parserootdesc(descXML, descXMLsize, data); free(descXML); descXML = NULL; if(0==strcmp(data->servicetype_CIF, "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1") || state >= 3 ) { GetUPNPUrls(urls, data, dev->descURL); #ifdef DEBUG printf("UPNPIGD_IsConnected(%s) = %d\n", urls->controlURL, UPNPIGD_IsConnected(urls, data)); #endif if((state >= 2) || UPNPIGD_IsConnected(urls, data)) return state; FreeUPNPUrls(urls); } memset(data, 0, sizeof(struct IGDdatas)); } #ifdef DEBUG else { printf("error getting XML description %s\n", dev->descURL); } #endif } } return 0; } /* UPNP_GetIGDFromUrl() * Used when skipping the discovery process. * return value : * 0 - Not ok * 1 - OK */ int UPNP_GetIGDFromUrl(const char * rootdescurl, struct UPNPUrls * urls, struct IGDdatas * data, char * lanaddr, int lanaddrlen) { char * descXML; int descXMLsize = 0; descXML = miniwget_getaddr(rootdescurl, &descXMLsize, lanaddr, lanaddrlen); if(descXML) { memset(data, 0, sizeof(struct IGDdatas)); memset(urls, 0, sizeof(struct UPNPUrls)); parserootdesc(descXML, descXMLsize, data); free(descXML); descXML = NULL; GetUPNPUrls(urls, data, rootdescurl); return 1; } else { return 0; } }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniupnpc.c
C
mit
18,098
/* $Id: minixmlvalid.c,v 1.2 2006/11/30 11:31:55 nanard Exp $ */ /* MiniUPnP Project * http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ * minixmlvalid.c : * validation program for the minixml parser * * (c) 2006 Thomas Bernard */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "minixml.h" /* xml event structure */ struct event { enum { ELTSTART, ELTEND, ATT, CHARDATA } type; const char * data; int len; }; struct eventlist { int n; struct event * events; }; /* compare 2 xml event lists * return 0 if the two lists are equals */ int evtlistcmp(struct eventlist * a, struct eventlist * b) { int i; struct event * ae, * be; if(a->n != b->n) return 1; for(i=0; i<a->n; i++) { ae = a->events + i; be = b->events + i; if( (ae->type != be->type) ||(ae->len != be->len) ||memcmp(ae->data, be->data, ae->len)) { printf("Found a difference : %d '%.*s' != %d '%.*s'\n", ae->type, ae->len, ae->data, be->type, be->len, be->data); return 1; } } return 0; } /* Test data */ static const char xmldata[] = "<xmlroot>\n" " <elt1 att1=\"attvalue1\" att2=\"attvalue2\">" "character data" "</elt1> \n \t" "<elt1b/>" "<elt2a> \t<elt2b>chardata1</elt2b><elt2b>chardata2</elt2b></elt2a>" "</xmlroot>"; static const struct event evtref[] = { {ELTSTART, "xmlroot", 7}, {ELTSTART, "elt1", 4}, /* attributes */ {CHARDATA, "character data", 14}, {ELTEND, "elt1", 4}, {ELTSTART, "elt1b", 5}, {ELTSTART, "elt2a", 5}, {ELTSTART, "elt2b", 5}, {CHARDATA, "chardata1", 9}, {ELTEND, "elt2b", 5}, {ELTSTART, "elt2b", 5}, {CHARDATA, "chardata2", 9}, {ELTEND, "elt2b", 5}, {ELTEND, "elt2a", 5}, {ELTEND, "xmlroot", 7} }; void startelt(void * data, const char * p, int l) { struct eventlist * evtlist = data; struct event * evt; evt = evtlist->events + evtlist->n; /*printf("startelt : %.*s\n", l, p);*/ evt->type = ELTSTART; evt->data = p; evt->len = l; evtlist->n++; } void endelt(void * data, const char * p, int l) { struct eventlist * evtlist = data; struct event * evt; evt = evtlist->events + evtlist->n; /*printf("endelt : %.*s\n", l, p);*/ evt->type = ELTEND; evt->data = p; evt->len = l; evtlist->n++; } void chardata(void * data, const char * p, int l) { struct eventlist * evtlist = data; struct event * evt; evt = evtlist->events + evtlist->n; /*printf("chardata : '%.*s'\n", l, p);*/ evt->type = CHARDATA; evt->data = p; evt->len = l; evtlist->n++; } int testxmlparser(const char * xml, int size) { int r; struct eventlist evtlist; struct eventlist evtlistref; struct xmlparser parser; evtlist.n = 0; evtlist.events = malloc(sizeof(struct event)*100); memset(&parser, 0, sizeof(parser)); parser.xmlstart = xml; parser.xmlsize = size; parser.data = &evtlist; parser.starteltfunc = startelt; parser.endeltfunc = endelt; parser.datafunc = chardata; parsexml(&parser); printf("%d events\n", evtlist.n); /* compare */ evtlistref.n = sizeof(evtref)/sizeof(struct event); evtlistref.events = (struct event *)evtref; r = evtlistcmp(&evtlistref, &evtlist); free(evtlist.events); return r; } int main(int argc, char * * argv) { int r; r = testxmlparser(xmldata, sizeof(xmldata)-1); if(r) printf("minixml validation test failed\n"); return r; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/minixmlvalid.c
C
mit
3,289
/* $Id: miniwget.h,v 1.5 2007/01/29 20:27:23 nanard Exp $ */ /* Project : miniupnp * Author : Thomas Bernard * Copyright (c) 2005 Thomas Bernard * This software is subject to the conditions detailed in the * LICENCE file provided in this distribution. * */ #ifndef __MINIWGET_H__ #define __MINIWGET_H__ #include "declspec.h" #ifdef __cplusplus extern "C" { #endif LIBSPEC void * miniwget(const char *, int *); LIBSPEC void * miniwget_getaddr(const char *, int *, char *, int); int parseURL(const char *, char *, unsigned short *, char * *); #ifdef __cplusplus } #endif #endif
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/miniwget.h
C
mit
589
/* $Id: testminixml.c,v 1.6 2006/11/19 22:32:35 nanard Exp $ * testminixml.c * test program for the "minixml" functions. * Author : Thomas Bernard. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "minixml.h" #include "igd_desc_parse.h" #ifdef WIN32 #define NO_BZERO #endif #ifdef NO_BZERO #define bzero(p, n) memset(p, 0, n) #endif /* ---------------------------------------------------------------------- */ void printeltname1(void * d, const char * name, int l) { int i; printf("element "); for(i=0;i<l;i++) putchar(name[i]); } void printeltname2(void * d, const char * name, int l) { int i; putchar('/'); for(i=0;i<l;i++) putchar(name[i]); putchar('\n'); } void printdata(void *d, const char * data, int l) { int i; printf("data : "); for(i=0;i<l;i++) putchar(data[i]); putchar('\n'); } void burptest(const char * buffer, int bufsize) { struct IGDdatas data; struct xmlparser parser; /*objet IGDdatas */ bzero(&data, sizeof(struct IGDdatas)); /* objet xmlparser */ parser.xmlstart = buffer; parser.xmlsize = bufsize; parser.data = &data; /*parser.starteltfunc = printeltname1; parser.endeltfunc = printeltname2; parser.datafunc = printdata; */ parser.starteltfunc = IGDstartelt; parser.endeltfunc = IGDendelt; parser.datafunc = IGDdata; parsexml(&parser); printIGD(&data); } /* ----- main ---- */ #define XML_MAX_SIZE (8192) int main(int argc, char * * argv) { FILE * f; char buffer[XML_MAX_SIZE]; int bufsize; if(argc<2) { printf("usage:\t%s file.xml\n", argv[0]); return 1; } f = fopen(argv[1], "r"); if(!f) { printf("cannot open file %s\n", argv[1]); return 1; } bufsize = (int)fread(buffer, 1, XML_MAX_SIZE, f); fclose(f); burptest(buffer, bufsize); return 0; }
118controlsman-testtest
TCMPortMapper/framework/miniupnpc/testminixml.c
C
mit
1,758
// // NSNotificationCenterThreadingAdditions // Enable NSNotification being sent from threads // // Copyright (c) 2007-2008 TheCodingMonkeys: // Martin Pittenauer, Dominik Wagner, <http://codingmonkeys.de> // Some rights reserved: <http://opensource.org/licenses/mit-license.php> // @interface NSNotificationCenter (NSNotificationCenterThreadingAdditions) - (void)postNotificationOnMainThread:(NSNotification *)aNotification; - (void)postNotificationOnMainThreadWithName:(NSString *)aName object:(id)anObject; @end
118controlsman-testtest
TCMPortMapper/framework/NSNotificationCenterThreadingAdditions.h
Objective-C
mit
523
#import "TCMPortMapper.h" #import "TCMNATPMPPortMapper.h" #import "TCMUPNPPortMapper.h" #import "IXSCNotificationManager.h" #import "NSNotificationCenterThreadingAdditions.h" #import <SystemConfiguration/SystemConfiguration.h> #import <SystemConfiguration/SCSchemaDefinitions.h> #import <sys/sysctl.h> #import <netinet/in.h> #import <arpa/inet.h> #import <net/route.h> #import <netinet/if_ether.h> #import <net/if_dl.h> #import <openssl/md5.h> // update port mappings all 30 minutes as a default #define UPNP_REFRESH_INTERVAL (30.*60.) NSString * const TCMPortMapperExternalIPAddressDidChange = @"TCMPortMapperExternalIPAddressDidChange"; NSString * const TCMPortMapperWillStartSearchForRouterNotification = @"TCMPortMapperWillStartSearchForRouterNotification"; NSString * const TCMPortMapperDidFinishSearchForRouterNotification = @"TCMPortMapperDidFinishSearchForRouterNotification"; NSString * const TCMPortMappingDidChangeMappingStatusNotification = @"TCMPortMappingDidChangeMappingStatusNotification"; NSString * const TCMPortMapperDidStartWorkNotification = @"TCMPortMapperDidStartWorkNotification"; NSString * const TCMPortMapperDidFinishWorkNotification = @"TCMPortMapperDidFinishWorkNotification"; NSString * const TCMPortMapperDidReceiveUPNPMappingTableNotification = @"TCMPortMapperDidReceiveUPNPMappingTableNotification"; NSString * const TCMNATPMPPortMapProtocol = @"NAT-PMP"; NSString * const TCMUPNPPortMapProtocol = @"UPnP"; NSString * const TCMNoPortMapProtocol = @"None"; static TCMPortMapper *S_sharedInstance; enum { TCMPortMapProtocolFailed = 0, TCMPortMapProtocolTrying = 1, TCMPortMapProtocolWorks = 2 }; @interface NSString (IPAdditions) - (BOOL)IPv4AddressInPrivateSubnet; @end @implementation NSString (IPAdditions) - (BOOL)IPv4AddressInPrivateSubnet { in_addr_t myaddr = inet_addr([self UTF8String]); // private subnets as defined in http://tools.ietf.org/html/rfc1918 // loopback addresses 127.0.0.1/8 http://tools.ietf.org/html/rfc3330 // zeroconf/bonjour self assigned addresses 169.254.0.0/16 http://tools.ietf.org/html/rfc3927 char *ipAddresses[] = {"192.168.0.0", "10.0.0.0", "172.16.0.0","127.0.0.1","169.254.0.0"}; char *networkMasks[] = {"255.255.0.0","255.0.0.0","255.240.0.0","255.0.0.0","255.255.0.0"}; int countOfAddresses=5; int i = 0; for (i=0;i<countOfAddresses;i++) { in_addr_t subnetmask = inet_addr(networkMasks[i]); in_addr_t networkaddress = inet_addr(ipAddresses[i]); if ((myaddr & subnetmask) == (networkaddress & subnetmask)) { return YES; } } return NO; } @end @implementation TCMPortMapping + (id)portMappingWithLocalPort:(int)aPrivatePort desiredExternalPort:(int)aPublicPort transportProtocol:(int)aTransportProtocol userInfo:(id)aUserInfo { NSAssert(aPrivatePort<65536 && aPublicPort<65536 && aPrivatePort>0 && aPublicPort>0, @"Port number has to be between 1 and 65535"); return [[[self alloc] initWithLocalPort:aPrivatePort desiredExternalPort:aPublicPort transportProtocol:aTransportProtocol userInfo:aUserInfo] autorelease]; } - (id)initWithLocalPort:(int)aPrivatePort desiredExternalPort:(int)aPublicPort transportProtocol:(int)aTransportProtocol userInfo:(id)aUserInfo { if ((self=[super init])) { _desiredExternalPort = aPublicPort; _localPort = aPrivatePort; _userInfo = [aUserInfo retain]; _transportProtocol = aTransportProtocol; } return self; } - (void)dealloc { [_userInfo release]; [super dealloc]; } - (int)desiredExternalPort { return _desiredExternalPort; } - (id)userInfo { return _userInfo; } - (TCMPortMappingStatus)mappingStatus { return _mappingStatus; } - (void)setMappingStatus:(TCMPortMappingStatus)aStatus { if (_mappingStatus != aStatus) { _mappingStatus = aStatus; if (_mappingStatus == TCMPortMappingStatusUnmapped) { [self setExternalPort:0]; } [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadWithName:TCMPortMappingDidChangeMappingStatusNotification object:self]; } } - (TCMPortMappingTransportProtocol)transportProtocol { return _transportProtocol; } - (void)setTransportProtocol:(TCMPortMappingTransportProtocol)aProtocol { if (_transportProtocol != aProtocol) { _transportProtocol = aProtocol; } } - (int)externalPort { return _externalPort; } - (void)setExternalPort:(int)aPublicPort { _externalPort=aPublicPort; } - (int)localPort { return _localPort; } - (NSString *)description { return [NSString stringWithFormat:@"%@ privatePort:%u desiredPublicPort:%u publicPort:%u mappingStatus:%@ transportProtocol:%d",[super description], _localPort, _desiredExternalPort, _externalPort, _mappingStatus == TCMPortMappingStatusUnmapped ? @"unmapped" : (_mappingStatus == TCMPortMappingStatusMapped ? @"mapped" : @"trying"),_transportProtocol]; } @end @interface TCMPortMapper (Private) - (void)cleanupUPNPPortMapperTimer; - (void)setExternalIPAddress:(NSString *)anAddress; - (void)setLocalIPAddress:(NSString *)anAddress; - (void)increaseWorkCount:(NSNotification *)aNotification; - (void)decreaseWorkCount:(NSNotification *)aNotification; - (void)scheduleRefresh; @end @implementation TCMPortMapper + (TCMPortMapper *)sharedInstance { if (!S_sharedInstance) { S_sharedInstance = [self new]; } return S_sharedInstance; } - (id)init { if (S_sharedInstance) { [self dealloc]; return S_sharedInstance; } if ((self=[super init])) { _systemConfigNotificationManager = [IXSCNotificationManager new]; // since we are only interested in this specific key, let us configure it so. [_systemConfigNotificationManager setObservedKeys:[NSArray arrayWithObject:@"State:/Network/Global/IPv4"] regExes:nil]; _isRunning = NO; _ignoreNetworkChanges = NO; _refreshIsScheduled = NO; _NATPMPPortMapper = [[TCMNATPMPPortMapper alloc] init]; _UPNPPortMapper = [[TCMUPNPPortMapper alloc] init]; _portMappings = [NSMutableSet new]; _removeMappingQueue = [NSMutableSet new]; _upnpPortMappingsToRemove = [NSMutableSet new]; [self hashUserID:NSUserName()]; S_sharedInstance = self; NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(increaseWorkCount:) name: TCMUPNPPortMapperDidBeginWorkingNotification object:_UPNPPortMapper]; [center addObserver:self selector:@selector(increaseWorkCount:) name:TCMNATPMPPortMapperDidBeginWorkingNotification object:_NATPMPPortMapper]; [center addObserver:self selector:@selector(decreaseWorkCount:) name: TCMUPNPPortMapperDidEndWorkingNotification object:_UPNPPortMapper]; [center addObserver:self selector:@selector(decreaseWorkCount:) name:TCMNATPMPPortMapperDidEndWorkingNotification object:_NATPMPPortMapper]; [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(didWake:) name:NSWorkspaceDidWakeNotification object:nil]; [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(willSleep:) name:NSWorkspaceWillSleepNotification object:nil]; } return self; } - (void)dealloc { [self cleanupUPNPPortMapperTimer]; [_systemConfigNotificationManager release]; [_NATPMPPortMapper release]; [_UPNPPortMapper release]; [_portMappings release]; [_removeMappingQueue release]; [_userID release]; [super dealloc]; } - (BOOL)networkReachable { Boolean success; BOOL okay; SCNetworkConnectionFlags status; success = SCNetworkCheckReachabilityByName("www.apple.com", &status); okay = success && (status & kSCNetworkFlagsReachable) && !(status & kSCNetworkFlagsConnectionRequired); return okay; } - (void)networkDidChange:(NSNotification *)aNotification { #ifndef NDEBUG NSLog(@"%s %@",__FUNCTION__,aNotification); #endif if (!_ignoreNetworkChanges) { [self scheduleRefresh]; } } - (NSString *)externalIPAddress { return [[_externalIPAddress retain] autorelease]; } - (NSString *)localBonjourHostName { SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"TCMPortMapper", NULL, NULL); NSString *hostname = [(NSString *)SCDynamicStoreCopyLocalHostName(dynRef) autorelease]; CFRelease(dynRef); return [hostname stringByAppendingString:@".local"]; } - (void)updateLocalIPAddress { NSString *routerAddress = [self routerIPAddress]; SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"TCMPortMapper", NULL, NULL); NSDictionary *scobjects = (NSDictionary *)SCDynamicStoreCopyValue(dynRef,(CFStringRef)@"State:/Network/Global/IPv4" ); NSString *ipv4Key = [NSString stringWithFormat:@"State:/Network/Interface/%@/IPv4", [scobjects objectForKey:(NSString *)kSCDynamicStorePropNetPrimaryInterface]]; CFRelease(dynRef); [scobjects release]; dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"TCMPortMapper", NULL, NULL); scobjects = (NSDictionary *)SCDynamicStoreCopyValue(dynRef,(CFStringRef)ipv4Key); // NSLog(@"%s scobjects:%@",__FUNCTION__,scobjects); NSArray *IPAddresses = (NSArray *)[scobjects objectForKey:(NSString *)kSCPropNetIPv4Addresses]; NSArray *subNetMasks = (NSArray *)[scobjects objectForKey:(NSString *)kSCPropNetIPv4SubnetMasks]; // NSLog(@"%s addresses:%@ masks:%@",__FUNCTION__,IPAddresses, subNetMasks); if (routerAddress) { NSString *ipAddress = nil; int i; for (i=0;i<[IPAddresses count];i++) { ipAddress = (NSString *) [IPAddresses objectAtIndex:i]; NSString *subNetMask = (NSString *) [subNetMasks objectAtIndex:i]; // NSLog(@"%s ipAddress:%@ subNetMask:%@",__FUNCTION__, ipAddress, subNetMask); // Check if local to Host if (ipAddress && subNetMask) { in_addr_t myaddr = inet_addr([ipAddress UTF8String]); in_addr_t subnetmask = inet_addr([subNetMask UTF8String]); in_addr_t routeraddr = inet_addr([routerAddress UTF8String]); // NSLog(@"%s ipNative:%X maskNative:%X",__FUNCTION__,routeraddr,subnetmask); if ((myaddr & subnetmask) == (routeraddr & subnetmask)) { [self setLocalIPAddress:ipAddress]; _localIPOnRouterSubnet = YES; break; } } } // this should never happen - if we have a router then we need to have an IP address on the same subnet to know this... if (i==[IPAddresses count]) { // we haven't found an IP address that matches - so set the last one _localIPOnRouterSubnet = NO; [self setLocalIPAddress:ipAddress]; } } else { [self setLocalIPAddress:[IPAddresses lastObject]]; _localIPOnRouterSubnet = NO; } CFRelease(dynRef); [scobjects release]; } - (NSString *)localIPAddress { // make sure it is up to date [self updateLocalIPAddress]; return [[_localIPAddress retain] autorelease]; } - (NSString *)userID { return [[_userID retain] autorelease]; } + (NSString *)sizereducableHashOfString:(NSString *)inString { unsigned char digest[16]; char hashstring[16*2+1]; int i; NSData *dataToHash = [inString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]; MD5([dataToHash bytes],[dataToHash length],digest); for(i=0;i<16;i++) sprintf(hashstring+i*2,"%02x",digest[i]); hashstring[i*2]=0; return [NSString stringWithUTF8String:hashstring]; } - (void)hashUserID:(NSString *)aUserIDToHash { NSString *hashString = [TCMPortMapper sizereducableHashOfString:aUserIDToHash]; if ([hashString length] > 16) hashString = [hashString substringToIndex:16]; [self setUserID:hashString]; } - (void)setUserID:(NSString *)aUserID { if (_userID != aUserID) { NSString *tmp = _userID; _userID = [aUserID copy]; [tmp release]; } } - (NSSet *)portMappings{ return _portMappings; } - (NSMutableSet *)removeMappingQueue { return _removeMappingQueue; } - (NSMutableSet *)_upnpPortMappingsToRemove { return _upnpPortMappingsToRemove; } - (void)updatePortMappings { NSString *protocol = [self mappingProtocol]; if ([protocol isEqualToString:TCMNATPMPPortMapProtocol]) { [_NATPMPPortMapper updatePortMappings]; } else if ([protocol isEqualToString:TCMUPNPPortMapProtocol]) { [_UPNPPortMapper updatePortMappings]; } } - (void)addPortMapping:(TCMPortMapping *)aMapping { @synchronized(_portMappings) { [_portMappings addObject:aMapping]; } [self updatePortMappings]; } - (void)removePortMapping:(TCMPortMapping *)aMapping { if (aMapping) { @synchronized(_portMappings) { [[aMapping retain] autorelease]; [_portMappings removeObject:aMapping]; } @synchronized(_removeMappingQueue) { if ([aMapping mappingStatus] != TCMPortMappingStatusUnmapped) { [_removeMappingQueue addObject:aMapping]; } } if (_isRunning) [self updatePortMappings]; } } // add some delay to the refresh caused by network changes so mDNSResponer has a little time to grab its port before us - (void)scheduleRefresh { if (!_refreshIsScheduled) { [self performSelector:@selector(refresh) withObject:nil afterDelay:0.5]; } } - (void)refresh { [self increaseWorkCount:nil]; [self setRouterName:@"Unknown"]; [self setMappingProtocol:TCMNoPortMapProtocol]; [self setExternalIPAddress:nil]; @synchronized(_portMappings) { NSEnumerator *portMappings = [_portMappings objectEnumerator]; TCMPortMapping *portMapping = nil; while ((portMapping = [portMappings nextObject])) { if ([portMapping mappingStatus]==TCMPortMappingStatusMapped) [portMapping setMappingStatus:TCMPortMappingStatusUnmapped]; } } [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperWillStartSearchForRouterNotification object:self]; NSString *routerAddress = [self routerIPAddress]; if (routerAddress) { NSString *manufacturer = [TCMPortMapper manufacturerForHardwareAddress:[self routerHardwareAddress]]; if (manufacturer) { [self setRouterName:manufacturer]; } else { [self setRouterName:@"Unknown"]; } NSString *localIPAddress = [self localIPAddress]; // will always be updated when accessed if (localIPAddress && _localIPOnRouterSubnet) { [self setExternalIPAddress:nil]; if ([routerAddress IPv4AddressInPrivateSubnet]) { _NATPMPStatus = TCMPortMapProtocolTrying; _UPNPStatus = TCMPortMapProtocolTrying; [_NATPMPPortMapper refresh]; [_UPNPPortMapper refresh]; } else { _NATPMPStatus = TCMPortMapProtocolFailed; _UPNPStatus = TCMPortMapProtocolFailed; [self setExternalIPAddress:localIPAddress]; [self setMappingProtocol:TCMNoPortMapProtocol]; // set all mappings to be mapped with their local port number being the external one @synchronized(_portMappings) { NSEnumerator *portMappings = [_portMappings objectEnumerator]; TCMPortMapping *portMapping = nil; while ((portMapping = [portMappings nextObject])) { [portMapping setExternalPort:[portMapping localPort]]; [portMapping setMappingStatus:TCMPortMappingStatusMapped]; } } [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; // we know we have a public address so we are finished - but maybe we should set all mappings to mapped } } else { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } } else { [_NATPMPPortMapper stopListeningToExternalIPAddressChanges]; [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } // add the delay to bridge the gap between the thread starting and this method returning [self performSelector:@selector(decreaseWorkCount:) withObject:nil afterDelay:1.0]; // make way for further refresh schedulings _refreshIsScheduled = NO; } - (void)setExternalIPAddress:(NSString *)anIPAddress { if (_externalIPAddress != anIPAddress) { NSString *tmp=_externalIPAddress; _externalIPAddress = [anIPAddress retain]; [tmp release]; } // notify always even if the external IP Address is unchanged so that we get the notification anytime when new information is here [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperExternalIPAddressDidChange object:self]; } - (void)setLocalIPAddress:(NSString *)anIPAddress { if (_localIPAddress != anIPAddress) { NSString *tmp=_localIPAddress; _localIPAddress = [anIPAddress retain]; [tmp release]; } } - (NSString *)hardwareAddressForIPAddress: (NSString *) address { if (!address) return nil; int mib[6]; size_t needed; char *lim, *buf, *next; struct sockaddr_inarp blank_sin = {sizeof(blank_sin), AF_INET }; struct rt_msghdr *rtm; struct sockaddr_inarp *sin; struct sockaddr_dl *sdl; struct sockaddr_inarp sin_m; struct sockaddr_inarp *sin2 = &sin_m; sin_m = blank_sin; sin2->sin_addr.s_addr = inet_addr([address UTF8String]); u_long addr = sin2->sin_addr.s_addr; mib[0] = CTL_NET; mib[1] = PF_ROUTE; mib[2] = 0; mib[3] = AF_INET; mib[4] = NET_RT_FLAGS; mib[5] = RTF_LLINFO; if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) err(1, "route-sysctl-estimate"); if ((buf = malloc(needed)) == NULL) err(1, "malloc"); if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) err(1, "actual retrieval of routing table"); lim = buf + needed; for (next = buf; next < lim; next += rtm->rtm_msglen) { rtm = (struct rt_msghdr *)next; sin = (struct sockaddr_inarp *)(rtm + 1); sdl = (struct sockaddr_dl *)(sin + 1); if (addr) { if (addr != sin->sin_addr.s_addr) continue; } if (sdl->sdl_alen) { u_char *cp = (u_char *)LLADDR(sdl); NSString* result = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]]; free(buf); return result; } else { free(buf); return nil; } } return nil; } + (NSString *)manufacturerForHardwareAddress:(NSString *)aMACAddress { static NSDictionary *hardwareManufacturerDictionary = nil; if (hardwareManufacturerDictionary==nil) { NSString *plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"OUItoCompany" ofType:@"plist"]; if (plistPath) { hardwareManufacturerDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath]; } else { hardwareManufacturerDictionary = [NSDictionary new]; } } if ([aMACAddress length]<8) return nil; NSString *result = [hardwareManufacturerDictionary objectForKey:[[aMACAddress substringToIndex:8] uppercaseString]]; return result; } - (void)start { if (!_isRunning) { NSNotificationCenter *center=[NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(networkDidChange:) name:@"State:/Network/Global/IPv4" object:_systemConfigNotificationManager]; [center addObserver:self selector:@selector(NATPMPPortMapperDidGetExternalIPAddress:) name:TCMNATPMPPortMapperDidGetExternalIPAddressNotification object:_NATPMPPortMapper]; [center addObserver:self selector:@selector(NATPMPPortMapperDidFail:) name:TCMNATPMPPortMapperDidFailNotification object:_NATPMPPortMapper]; [center addObserver:self selector:@selector(NATPMPPortMapperDidReceiveBroadcastedExternalIPChange:) name:TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification object:_NATPMPPortMapper]; [center addObserver:self selector:@selector(UPNPPortMapperDidGetExternalIPAddress:) name:TCMUPNPPortMapperDidGetExternalIPAddressNotification object:_UPNPPortMapper]; [center addObserver:self selector:@selector(UPNPPortMapperDidFail:) name:TCMUPNPPortMapperDidFailNotification object:_UPNPPortMapper]; _isRunning = YES; } [self refresh]; } - (void)NATPMPPortMapperDidGetExternalIPAddress:(NSNotification *)aNotification { BOOL shouldNotify = NO; if (_NATPMPStatus==TCMPortMapProtocolTrying) { _NATPMPStatus =TCMPortMapProtocolWorks; [self setMappingProtocol:TCMNATPMPPortMapProtocol]; shouldNotify = YES; } [self setExternalIPAddress:[[aNotification userInfo] objectForKey:@"externalIPAddress"]]; if (shouldNotify) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } } - (void)NATPMPPortMapperDidFail:(NSNotification *)aNotification { if (_NATPMPStatus==TCMPortMapProtocolTrying) { _NATPMPStatus =TCMPortMapProtocolFailed; } else if (_NATPMPStatus==TCMPortMapProtocolWorks) { [self setExternalIPAddress:nil]; } // also mark all port mappings as unmapped if UPNP failed too if (_UPNPStatus == TCMPortMapProtocolFailed) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } } - (void)UPNPPortMapperDidGetExternalIPAddress:(NSNotification *)aNotification { BOOL shouldNotify = NO; if (_UPNPStatus==TCMPortMapProtocolTrying) { _UPNPStatus =TCMPortMapProtocolWorks; [self setMappingProtocol:TCMUPNPPortMapProtocol]; shouldNotify = YES; if (_NATPMPStatus==TCMPortMapProtocolTrying) { [_NATPMPPortMapper stop]; _NATPMPStatus =TCMPortMapProtocolFailed; } } NSString *routerName = [[aNotification userInfo] objectForKey:@"routerName"]; if (routerName) { [self setRouterName:routerName]; } [self setExternalIPAddress:[[aNotification userInfo] objectForKey:@"externalIPAddress"]]; if (shouldNotify) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } if (!_upnpPortMapperTimer) { _upnpPortMapperTimer = [[NSTimer scheduledTimerWithTimeInterval:UPNP_REFRESH_INTERVAL target:self selector:@selector(refresh) userInfo:nil repeats:YES] retain]; } } - (void)UPNPPortMapperDidFail:(NSNotification *)aNotification { if (_UPNPStatus==TCMPortMapProtocolTrying) { _UPNPStatus =TCMPortMapProtocolFailed; } else if (_UPNPStatus==TCMPortMapProtocolWorks) { [self setExternalIPAddress:nil]; } [self cleanupUPNPPortMapperTimer]; // also mark all port mappings as unmapped if NATPMP failed too if (_NATPMPStatus == TCMPortMapProtocolFailed) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishSearchForRouterNotification object:self]; } } - (void)printNotification:(NSNotification *)aNotification { NSLog(@"TCMPortMapper received notification: %@", aNotification); } - (void)cleanupUPNPPortMapperTimer { if (_upnpPortMapperTimer) { [_upnpPortMapperTimer invalidate]; [_upnpPortMapperTimer release]; _upnpPortMapperTimer = nil; } } - (void)internalStop { NSNotificationCenter *center=[NSNotificationCenter defaultCenter]; [center removeObserver:self name:@"State:/Network/Global/IPv4" object:_systemConfigNotificationManager]; [center removeObserver:self name:TCMNATPMPPortMapperDidGetExternalIPAddressNotification object:_NATPMPPortMapper]; [center removeObserver:self name:TCMNATPMPPortMapperDidFailNotification object:_NATPMPPortMapper]; [center removeObserver:self name:TCMNATPMPPortMapperDidReceiveBroadcastedExternalIPChangeNotification object:_NATPMPPortMapper]; [center removeObserver:self name:TCMUPNPPortMapperDidGetExternalIPAddressNotification object:_UPNPPortMapper]; [center removeObserver:self name:TCMUPNPPortMapperDidFailNotification object:_UPNPPortMapper]; [self cleanupUPNPPortMapperTimer]; } - (void)stop { if (_isRunning) { [self internalStop]; _isRunning = NO; if (_NATPMPStatus != TCMPortMapProtocolFailed) { [_NATPMPPortMapper stop]; } if (_UPNPStatus != TCMPortMapProtocolFailed) { [_UPNPPortMapper stop]; } } } - (void)stopBlocking { if (_isRunning) { [self internalStop]; if (_NATPMPStatus == TCMPortMapProtocolWorks) { [_NATPMPPortMapper stopBlocking]; } if (_UPNPStatus == TCMPortMapProtocolWorks) { [_UPNPPortMapper stopBlocking]; } _isRunning = NO; } } - (void)removeUPNPMappings:(NSArray *)aMappingList { if (_UPNPStatus == TCMPortMapProtocolWorks) { @synchronized (_upnpPortMappingsToRemove) { [_upnpPortMappingsToRemove addObjectsFromArray:aMappingList]; } [_UPNPPortMapper updatePortMappings]; } } - (void)requestUPNPMappingTable { if (_UPNPStatus == TCMPortMapProtocolWorks) { _sendUPNPMappingTableNotification = YES; [_UPNPPortMapper updatePortMappings]; } } - (void)setMappingProtocol:(NSString *)aProtocol { [_mappingProtocol autorelease]; _mappingProtocol = [aProtocol copy]; } - (NSString *)mappingProtocol { return _mappingProtocol; } - (void)setRouterName:(NSString *)aRouterName { // NSLog(@"%s %@->%@",__FUNCTION__,_routerName,aRouterName); [_routerName autorelease]; _routerName = [aRouterName copy]; } - (NSString *)routerName { return _routerName; } - (BOOL)isRunning { return _isRunning; } - (BOOL)isAtWork { return (_workCount > 0); } - (NSString *)routerIPAddress { SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"TCMPortMapper", NULL, NULL); NSDictionary *scobjects = (NSDictionary *)SCDynamicStoreCopyValue(dynRef,(CFStringRef)@"State:/Network/Global/IPv4" ); NSString *routerIPAddress = (NSString *)[scobjects objectForKey:(NSString *)kSCPropNetIPv4Router]; routerIPAddress = [[routerIPAddress copy] autorelease]; CFRelease(dynRef); [scobjects release]; return routerIPAddress; } - (NSString *)routerHardwareAddress { NSString *result = nil; NSString *routerAddress = [self routerIPAddress]; if (routerAddress) { result = [self hardwareAddressForIPAddress:routerAddress]; } return result; } - (void)increaseWorkCount:(NSNotification *)aNotification { #ifdef DEBUG NSLog(@"%s %d %@",__FUNCTION__,_workCount,aNotification); #endif if (_workCount == 0) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidStartWorkNotification object:self]; } _workCount++; } - (void)decreaseWorkCount:(NSNotification *)aNotification { #ifdef DEBUG NSLog(@"%s %d %@",__FUNCTION__,_workCount,aNotification); #endif _workCount--; if (_workCount == 0) { if (_UPNPStatus == TCMPortMapProtocolWorks && _sendUPNPMappingTableNotification) { [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidReceiveUPNPMappingTableNotification object:self userInfo:[NSDictionary dictionaryWithObject:[_UPNPPortMapper latestUPNPPortMappingsList] forKey:@"mappingTable"]]; _sendUPNPMappingTableNotification = NO; } [[NSNotificationCenter defaultCenter] postNotificationName:TCMPortMapperDidFinishWorkNotification object:self]; } } - (void)postWakeAction { _ignoreNetworkChanges = NO; if (_isRunning) { // take some time because on the moment of awakening e.g. airport isn't yet connected [self refresh]; } } - (void)didWake:(NSNotification *)aNotification { // postpone the action because we need to wait for some delay until stuff is up. moreover we need to give the buggy mdnsresponder a chance to grab his nat-pmp port so we can do so later [self performSelector:@selector(postWakeAction) withObject:nil afterDelay:2.]; } - (void)willSleep:(NSNotification *)aNotification { #ifdef DEBUG NSLog(@"%s, pmp:%d, upnp:%d",__FUNCTION__,_NATPMPStatus,_UPNPStatus); #endif _ignoreNetworkChanges = YES; if (_isRunning) { if (_NATPMPStatus == TCMPortMapProtocolWorks) { [_NATPMPPortMapper stopBlocking]; } if (_UPNPStatus == TCMPortMapProtocolWorks) { [_UPNPPortMapper stopBlocking]; } } } - (void)NATPMPPortMapperDidReceiveBroadcastedExternalIPChange:(NSNotification *)aNotification { if (_isRunning) { NSDictionary *userInfo = [aNotification userInfo]; // senderAddress is of the format <ipv4address>:<port> NSString *senderIPAddress = [userInfo objectForKey:@"senderAddress"]; // we have to check if the sender is actually our router - if not disregard if ([senderIPAddress isEqualToString:[self routerIPAddress]]) { if (![[self externalIPAddress] isEqualToString:[userInfo objectForKey:@"externalIPAddress"]]) { // NSLog(@"Refreshing because of NAT-PMP-Device external IP broadcast:%@",userInfo); [self refresh]; } } else { NSLog(@"Got Information from rogue NAT-PMP-Device:%@",userInfo); } } } @end
118controlsman-testtest
TCMPortMapper/framework/TCMPortMapper.m
Objective-C
mit
30,721
// // TCMUPNPPortMapper.h // Encapsulates miniupnp framework // // Copyright (c) 2007-2008 TheCodingMonkeys: // Martin Pittenauer, Dominik Wagner, <http://codingmonkeys.de> // Some rights reserved: <http://opensource.org/licenses/mit-license.php> // #import "TCMPortMapper.h" #import "TCMNATPMPPortMapper.h" #include "miniwget.h" #include "miniupnpc.h" #include "upnpcommands.h" #include "upnperrors.h" extern NSString * const TCMUPNPPortMapperDidFailNotification; extern NSString * const TCMUPNPPortMapperDidGetExternalIPAddressNotification; extern NSString * const TCMUPNPPortMapperDidBeginWorkingNotification; extern NSString * const TCMUPNPPortMapperDidEndWorkingNotification; @interface TCMUPNPPortMapper : NSObject { NSLock *_threadIsRunningLock; BOOL refreshThreadShouldQuit; BOOL UpdatePortMappingsThreadShouldQuit; BOOL UpdatePortMappingsThreadShouldRestart; TCMPortMappingThreadID runningThreadID; NSArray *_latestUPNPPortMappingsList; struct UPNPUrls _urls; struct IGDdatas _igddata; } - (void)refresh; - (void)updatePortMappings; - (void)stop; - (void)stopBlocking; - (NSArray *)latestUPNPPortMappingsList; @end
118controlsman-testtest
TCMPortMapper/framework/TCMUPNPPortMapper.h
Objective-C
mit
1,168
-- cabal install WAVE -- runghc proof.hs -- -- The input file has to be called sound.wav in the current dir. -- -- Haskell proof-of-concept of stages 1/2/3 (see ALGORITHM). module Main where import Control.Monad import Data.WAVE import Data.Int import Data.List (group, sort) -- Take a flat stream and break it into chunks of at most N elements. chunkBy :: Int -> [a] -> [[a]] chunkBy _ [] = [] chunkBy n xs = let (as,bs) = splitAt n xs in as : chunkBy n bs -- The first analysis step analyzes small chunks of raw sound samples -- (tens of milliseconds at a time) and quantizes each chunk to either -- "tone" or "no tone". analysisStep1 :: [Integer] -> Int -> [Bool] analysisStep1 samples sampleRate = let -- -- 1.1: compute the number of samples per chunk for the -- desired quantization window. quantizationWindowMs :: Int quantizationWindowMs = 5 samplesInWindow :: Int samplesInWindow = (fromIntegral quantizationWindowMs) * sampleRate `quot` 1000 -- 1.2: chunk up the stream into ~10ms chunks. sampleChunks :: [[Integer]] sampleChunks = chunkBy samplesInWindow samples -- 1.3: for each chunk, compute the maximum amplitude of the -- sound wave in that chunk. This collapses each chunk back -- into a single value, which is the very crude approximation -- of the amount of sound energy in that ~10ms window. amplitudes :: [Integer] amplitudes = map (\x -> maximum x - minimum x) sampleChunks -- 1.4: bundle up these amplitudes into groups such that each -- group represents ~1s of sound. quantizationAnalysisWindow :: Int quantizationAnalysisWindow = 1000 `quot` quantizationWindowMs amplitudeChunks :: [[Integer]] amplitudeChunks = chunkBy quantizationAnalysisWindow amplitudes -- 1.5: within each chunk of amplitudes, compute the middle -- amplitude, and use that middle to quantize all amplitudes -- to either 0 or 1. quantize :: [Integer] -> [Bool] quantize amplitudes = map (> discriminator) amplitudes where discriminator :: Integer discriminator = smallest + middle middle :: Integer middle = (biggest - smallest) `quot` 2 biggest = maximum amplitudes smallest = minimum amplitudes -- step 1 complete: quantizedStream tells us whether each of -- the 10ms blocks of the input sound contains a tone or -- silence. quantizedStream :: [Bool] quantizedStream = concatMap quantize amplitudeChunks in quantizedStream -- The second analysis step converts a stream of quantized 10ms states -- into a stream of state lengths. That is, if the input stream is -- 0001100111100 (with 1 = tone and 0 = silence), we want to output -- the list [3, 2, 2, 4, 2], which can be seen as the "rhythm" of the -- coded message. -- -- The operation to do this is a trivial run-length encoding of the -- input stream. And delightfully, run-length encoding is trivial to -- accomplish in Haskell. type Duration = Int analysisStep2 :: [Bool] -> [Duration] analysisStep2 = map length . group -- The third analysis step determines the unit length of the coded -- phrase (the length of one inter-symbol silence), and from there -- translates each duration into its standardized value (in Morse, all -- symbols, both tones and silences, are 1, 3 and 7 units long) analysisStep3 :: [Duration] -> [Duration] analysisStep3 durations = let -- Again, we need to consider elements within their context. Here, -- we chunk up into groups of 20 symbols (10 tones and 10 -- silences). analysisGroup :: Int analysisGroup = 20 durationChunks :: [[Duration]] durationChunks = chunkBy analysisGroup durations -- Within each chunk, we sort the durations, and select the 25th -- percentile duration as our 1-unit duration. This magical 25% -- number derives from the observation that 1-unit silences are -- the most common symbol in a normal Morse phrase, so they should -- compose the majority of the bottom of the sorted pile of -- durations. In theory we could simply pick the smallest, but by -- going with the 25th percentile, the hope is to avoid picking -- the extreme, ridiculously small sample that results from a -- quantization error. unit :: [Duration] -> Duration unit durations = (sort durations) !! (length durations `quot` 4) chunkUnits = map unit durationChunks -- Now that we have a unit duration for each duration chunk, use -- it to normalize each duration chunk, and output them all as a -- single stream again. Note that we do the normalization in -- floating point, so that the normalization is more precise than -- brutal truncating integer division. normalize :: Duration -> [Duration] -> [Double] normalize unit durations = map (\x -> fromIntegral x / fromIntegral unit) durations normalizedApproximateStream :: [Double] normalizedApproximateStream = concatMap (uncurry normalize) (zip chunkUnits durationChunks) -- Finally, we try to clamp each value in the stream to one of 1, -- 3 or 7, by rounding each double to the nearest of these -- values. We do know however that there can be silences much -- longer than 7 units as operators pause between sentences, so -- anything greater than 8 units long gets rounded up to 10, which -- we'll consider our "break" value. clamp :: Double -> Duration clamp x | x > 8 = 10 | x > 5 = 7 | x > 2 = 3 | otherwise = 1 in map clamp normalizedApproximateStream data Token = Dit | Dah | EndLetter | EndWord | Pause | Error deriving (Show) analysisStep4 :: [Duration] -> [Token] analysisStep4 ds = tone (tail ds) where tone [] = [] tone (1:ds) = Dit : silence ds tone (3:ds) = Dah : silence ds tone (_:ds) = Error : tone ds silence [] = [] silence (1:ds) = tone ds silence (3:ds) = EndLetter : tone ds silence (7:ds) = EndWord : tone ds silence (10:ds) = Pause : tone ds silence (_:ds) = Error : tone ds analyze :: [Integer] -> Int -> [Token] analyze samples sampleRate = let toneStream :: [Bool] toneStream = analysisStep1 samples sampleRate durationStream :: [Duration] durationStream = analysisStep2 toneStream normalizedDurationStream :: [Duration] normalizedDurationStream = analysisStep3 durationStream tokenStream :: [Token] tokenStream = analysisStep4 normalizedDurationStream in tokenStream nice :: Token -> String nice Dit = "." nice Dah = "-" nice EndLetter = " " nice EndWord = "\n" nice Pause = "\n\n" main = do wav <- getWAVEFile "sound.wav" -- Before analysis, we convert the sound samples from Int32 to -- Integer. This allows us to ignore integer overflow issues, at -- the cost of performance. let samples :: [Integer] samples = map (fromIntegral . head) (waveSamples wav) -- Fire off the analysis and print the result. result = analyze samples (fromIntegral $ waveFrameRate $ waveHeader wav) mapM_ (putStr . nice) result putStrLn ""
05eugene-cw0102030405060708090
proof.hs
Haskell
bsd
7,195
// A basic package to decode Wave files. package audio import ( "rog-go.googlecode.com/hg/exp/abc" "os" "fmt" "io" "encoding/binary" "reflect" "strings" ) func init() { Register("readwav", wInput, map[string]abc.Socket { "out": abc.Socket{SamplesT, abc.Male}, "1": abc.Socket{abc.StringT, abc.Female}, }, makeWavReader) Register("writewav", wOutput, map[string]abc.Socket { "1": abc.Socket{SamplesT, abc.Female}, "2": abc.Socket{abc.StringT, abc.Female}, }, makeWavWriter) } type Rerror string type fileOffset int64 // help prevent mixing of file offsets and sample counts type WavReader struct { fd *os.File end fileOffset offset fileOffset bytesPerSample int Format bytesPerFrame int eof bool buf []byte cvt func([]float32, []byte) } type dataChunk chunkHeader type WavWriter struct { Format fd *os.File } func makeWavReader(status *abc.Status, args map[string]interface{}) Widget { defer un(log("makeWavReader")) w, err := OpenWavReader(args["1"].(string)) if w == nil { panic(err.String()) } return w } func (w *WavReader) Init(_ map[string]Widget) { } // 0 4 ChunkID Contains the letters "RIFF" in ASCII form // (0x52494646 big-endian form). // 4 4 ChunkSize 36 + SubChunk2Size, or more precisely: // 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size) // This is the size of the rest of the chunk // following this number. This is the size of the // entire file in bytes minus 8 bytes for the // two fields not included in this count: // ChunkID and ChunkSize. // 8 4 Format Contains the letters "WAVE" // (0x57415645 big-endian form). // // // The "WAVE" format consists of two subchunks: "fmt " and "data": // The "fmt " subchunk describes the sound data's format: // // 12 4 Subchunk1ID Contains the letters "fmt " // (0x666d7420 big-endian form). // 16 4 Subchunk1Size 16 for PCM. This is the size of the // rest of the Subchunk which follows this number. // 20 2 AudioFormat PCM = 1 (i.e. Linear quantization) // Values other than 1 indicate some // form of compression. // 22 2 NumChannels Mono = 1, Stereo = 2, etc. // 24 4 SampleRate 8000, 44100, etc. // 28 4 ByteRate == SampleRate * NumChannels * BitsPerSample/8 // 32 2 BlockAlign == NumChannels * BitsPerSample/8 // The number of bytes for one sample including // all channels. I wonder what happens when // this number isn't an integer? // 34 2 BitsPerSample 8 bits = 8, 16 bits = 16, etc. // 2 ExtraParamSize if PCM, then doesn't exist // X ExtraParams space for extra parameters // // The "data" subchunk contains the size of the data and the actual sound: // // 36 4 Subchunk2ID Contains the letters "data" // (0x64617461 big-endian form). // 40 4 Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8 // This is the number of bytes in the data. // You can also think of this as the size // of the read of the subchunk following this // number. // 44 * Data The actual sound data. type chunkHeader struct { ChunkID uint32 ChunkSize uint32 } type riffChunk struct { ChunkSize uint32 Format uint32 } type fmtChunk struct { chunkHeader AudioFormat int16 NumChannels int16 SampleRate int32 ByteRate int32 BlockAlign int16 BitsPerSample int16 } func sizeof(x interface{}) int { return binary.TotalSize(reflect.NewValue(x)) } func OpenWavReader(filename string) (r *WavReader, err os.Error) { defer func() { switch s := recover().(type) { case nil: case Rerror: err = os.NewError(string(s)) default: panic(s) } }() fd, err := os.Open(filename, os.O_RDONLY, 0) if fd == nil { return nil, err } var hd uint32 binread(fd, binary.BigEndian, &hd) var endian binary.ByteOrder = binary.LittleEndian switch hd { case str4("RIFF", binary.BigEndian): endian = binary.LittleEndian case str4("RIFX", binary.BigEndian): endian = binary.BigEndian default: panic(Rerror("unknown wav header")) } var c0 riffChunk binread(fd, endian, &c0) if c0.Format != str4("WAVE", endian) { panic(Rerror(fmt.Sprintf("bad format %x", c0.Format))) } var c1 fmtChunk binread(fd, endian, &c1) if c1.ChunkID != str4("fmt ", endian) { panic(Rerror("unexpected chunk header id")) } if c1.AudioFormat != 1 { panic(Rerror("unknown audio format")) } var c2 dataChunk binread(fd, endian, &c2) if c2.ChunkID != str4("data", endian) { panic(Rerror("no data chunk found")) } r = &WavReader{fd: fd} r.cvt = cvtFns[endian][int(c1.BitsPerSample)] if r.cvt == nil { panic(Rerror("unsupported bits per sample")) } r.NumChans = int(c1.NumChannels) r.Rate = int(c1.SampleRate) r.Type = Float32Type r.Layout = Interleaved r.bytesPerSample = int(c1.BitsPerSample) / 8 r.bytesPerFrame = r.bytesPerSample * r.NumChans r.end = fileOffset(c2.ChunkSize) return r, nil } var cvtFns = map[binary.ByteOrder]map[int]func([]float32, []byte){ binary.LittleEndian: map[int]func([]float32, []byte){ 16: int16tofloat32le, }, binary.BigEndian: map[int]func([]float32, []byte){ 16: int16tofloat32be, }, } func (r *WavReader) ReadSamples(b Buffer, p int64) bool { if r.eof { return false } defer un(log("wav read %v [%d]", p, b.Len())) o0 := fileOffset(p * int64(r.bytesPerFrame)) if o0 != r.offset { r.fd.Seek(int64(o0 - r.offset), 1) r.offset = o0 } if r.offset >= r.end { return false } samples := b.(ContiguousFloat32Buffer).AsFloat32Buf() n := len(samples) o1 := o0 + fileOffset(n * r.bytesPerSample) leftover := 0 if o1 > r.end { leftover = (int(o1 - r.end) + r.bytesPerSample - 1) / r.bytesPerSample samples = samples[0: n - leftover] o1 = r.end } nb := len(samples) * r.bytesPerSample if nb > len(r.buf) { r.buf = make([]byte, nb) } nr, err := io.ReadFull(r.fd, r.buf[0:nb]) if err != nil { fmt.Fprintf(os.Stderr, "sample read error: %v\n", err) r.offset = r.end // ensure we don't try again leftover += (nb - nr + r.bytesPerFrame - 1) / r.bytesPerFrame samples = samples[0:n - leftover] nb = nr } r.offset += fileOffset(nb) r.cvt(samples, r.buf) if leftover > 0 { samples = samples[len(samples) : n] samples.Zero(0, len(samples)) r.eof = true } return nb > 0 } func makeWavWriter(status *abc.Status, args map[string]interface{}) Widget { defer un(log("makeWavWriter")) filename := args["2"].(string) fd, err := os.Open(filename, os.O_WRONLY|os.O_CREATE, 0666) if fd == nil { panic("cannot open " + filename + ": " + err.String()) } w := &WavWriter{} w.fd = fd w.Layout = Interleaved w.Type = Float32Type return w } func (w *WavWriter) Init(inputs map[string]Widget) { w.init(inputs["1"]) } func (w *WavWriter) ReadSamples(_ Buffer, _ int64) bool { panic("readsamples called on output widget") } func WriteWav(filename string, input Widget) os.Error { fd, err := os.Open(filename, os.O_WRONLY|os.O_CREATE, 0666) if fd == nil { return err } w := new(WavWriter) w.fd = fd w.init(input) return nil } func (w *WavWriter) init(input Widget) { endian := binary.LittleEndian const ( bitsPerSample = 16 ) c0 := riffChunk{ ChunkSize: 4 + // Format uint32(sizeof(fmtChunk{})) + uint32(sizeof(dataChunk{})), // excluding data length Format: str4("WAVE", endian), } format := input.GetFormat("out") c1 := fmtChunk{ chunkHeader: chunkHeader{ ChunkID: str4("fmt ", endian), ChunkSize: uint32(sizeof(fmtChunk{})) - 8, }, AudioFormat: 1, NumChannels: int16(format.NumChans), SampleRate: int32(format.Rate), ByteRate: int32(format.Rate* format.NumChans) * (bitsPerSample / 8), BlockAlign: int16(format.NumChans) * (bitsPerSample / 8), BitsPerSample: bitsPerSample, } c2 := dataChunk{ ChunkID: str4("data", endian), ChunkSize: 0, // excluding data length } w.fd.Write([]byte("RIFF")) binary.Write(w.fd, endian, c0) binary.Write(w.fd, endian, c1) binary.Write(w.fd, endian, c2) samples := AllocNFloat32Buf(int(c1.NumChannels), 8192) buf := make([]byte, samples.Size * int(c1.BlockAlign)) p := int64(0) for input.ReadSamples(samples, p) { float32toint16le(buf, samples.Buf) w.fd.Write(buf) p += int64(samples.Size) } size := fileOffset(p) * fileOffset(c1.BlockAlign) if size > 0x7fffffff - fileOffset(c0.ChunkSize) { fmt.Fprintf(os.Stderr, "wav file limit exceeded") size = 0x7fffffff - fileOffset(c0.ChunkSize) } // rewrite header with correct size information c0.ChunkSize += uint32(size) c2.ChunkSize = uint32(size) w.fd.Seek(0, 0) w.fd.Write([]byte("RIFF")) binary.Write(w.fd, endian, c0) binary.Write(w.fd, endian, c1) binary.Write(w.fd, endian, c2) } func int16tofloat32le(samples []float32, data []byte) { j := 0 for i := range samples { n := int16(data[j]) + int16(data[j+1]) << 8 samples[i] = float32(n) / 0x7fff j += 2 } } func int16tofloat32be(samples []float32, data []byte) { j := 0 for i := range samples { n := int16(data[j+1]) + int16(data[j]) << 8 samples[i] = float32(n) / 0x7fff j += 2 } } func float32toint16le(data[]byte, samples []float32) { j := 0 for _, s := range samples { s *= 0x7fff switch { case s > 0x7fff: s = 0x7fff case s < -0x8000: s = -0x8000 case s > 0: s += 0.5 case s < 0: s -= 0.5 } n := int(s) data[j] = byte(n) data[j + 1] = byte(n >> 8) j += 2 } } func str4(s string, e binary.ByteOrder) (x uint32) { binary.Read(strings.NewReader(s), e, &x) return } func binread(r io.Reader, e binary.ByteOrder, x interface{}) { err := binary.Read(r, e, x) if err != nil { panic(Rerror(fmt.Sprintf("error reading binary: %v", err))) } }
05eugene-cw0102030405060708090
wave-decoder.go
Go
bsd
10,331
/* Go program to decode an audio stream of Morse code into a stream of ASCII. See the ALGORITHM file for a description of what's going on, and 'proof.hs' as the original proof-of-concept implementation of this algorithm in Haskell. */ package main import ( "fmt" "math" "rand" "sort" ) type token int const ( dit = iota dah = iota endLetter = iota endWord = iota pause = iota noOp = iota cwError = iota ) // ------- Stage 1: Detect tones in the stream. ------------------ // Use Root Mean Square (RMS) method to return 'average' value of an // array of audio samples. func rms(audiovals []int) int { sum := 0 squaresum := 0 for i := 0; i < len(audiovals); i++ { v := audiovals[i] sum = sum + v squaresum = squaresum + (v*v) } mean := sum / len(audiovals) meanOfSquares := squaresum / len(audiovals) return int(math.Sqrt(float64(meanOfSquares - (mean * mean)))) } // Read audiosample chunks from 'chunks' channel, and push simple RMS // amplitudes into the 'amplitudes' channel. func amplituder(chunks chan []int, amplitudes chan int) { for chunk := range chunks { amplitudes <- rms(chunk) } close(amplitudes) } // Read amplitudes from 'amplitudes' channel, and push quantized // on/off values to 'quants' channel. func quantizer(amplitudes chan int, quants chan bool) { var group [100]int seen := 0 max := 0 min := 0 for amp := range amplitudes { // Suck 100 amplitudes at a time from input channel, // figure out 'middle' amplitude for the group, and // use that value to quantize each amplitude. group[seen] = amp seen += 1 if amp > max { max = amp } if amp < min { min = amp } if seen == 100 { middle := (max - min) / 2 for i := 0; i < 100; i++ { quants <- (group[i] >= middle) } max = 0 min = 0 seen = 0 } } close(quants) } // Main stage 1 pipeline: reads audiochunks from input channel; // returns a boolean channel to which it pushes quantized on/off // values. func getQuantizePipe(audiochunks chan []int) chan bool { amplitudes := make(chan int) quants := make(chan bool) go amplituder(audiochunks, amplitudes) go quantizer(amplitudes, quants) return quants } // ------- Stage 2: Run-length encode the on/off states. ---------- // // That is, if the input stream is 0001100111100, we want to output // the list [3, 2, 2, 4, 2], which can be seen as the "rhythm" of the // coded message. func getRlePipe(quants chan bool) chan int { lengths := make(chan int) go func() { currentState := false tally := 0 // TODO(sussman): need to "debounce" this stream for quant := range quants { if quant == currentState { tally += 1 } else { lengths <- tally currentState = quant tally = 1 } } close(lengths) }() return lengths } // ------- Stage 3: Figure out length of morse 'unit' & output logic tokens // // Take a list of on/off duration events, sort them, return the 25th // percentile value as the "1 unit" duration within the time window. // // This magical 25% number derives from the observation that 1-unit // silences are the most common symbol in a normal Morse phrase, so // they should compose the majority of the bottom of the sorted pile // of durations. In theory we could simply pick the smallest, but by // going with the 25th percentile, the hope is to avoid picking the // ridiculously small sample that results from a quantization error. func calculateUnitDuration(group sort.IntArray) int { group.Sort() // fmt.Printf("(%d) ", group) return group[(len(group) / 4)] } // Take a normalized duration value, 'clamp' it to the magic numbers // 1, 3, 7 (which are the faundational time durations in Morse code), // and return a sensible semantic token. func clamp(x float32, silence bool) token { if (silence) { switch { case x > 8: return pause case x > 5: return endWord case x > 2: return endLetter default: return noOp } } else { switch { case x > 8: return cwError case x > 5: return cwError case x > 2: return dah default: return dit } } return cwError } func getTokenPipe(durations chan int) chan token { tokens := make(chan token) seen := 0 go func() { // As a contextual window, look at sets of 20 on/off // duration events when calculating the unitDuration. // // TODO(sussman): make this windowsize a constant we // can fiddle. group := make([]int, 20) for duration := range durations { group[seen] = duration seen += 1 if seen == 20 { seen = 0 // figure out the length of a 'dit' (1 unit) unitDuration := calculateUnitDuration(group[:]) // normalize & clamp each duration by this silence := false for i := range group { norm := float32(group[i] / unitDuration) tokens <- clamp(norm, silence) silence = !silence } } } close(durations) }() return tokens } // ------ Put all the pipes together. -------------- func main () { // main input pipe: chunks := make(chan []int) // construct main output pipe... whee! output := getTokenPipe(getRlePipe(getQuantizePipe(chunks))) // Start pushing random data into the pipeline in the background go func() { for i :=0 ; i < 5000; i++ { chunk := make([]int, 10) for j := 0; j < 10; j++ { chunk[j] = rand.Int() } chunks <- chunk } close(chunks) }() // Print logical tokens from the pipeline's output for val := range output { out := "" switch val { case dit: out = "dit " case dah: out = "dah " case endLetter: out = "endLetter " case endWord: out = "endWord " case pause: out = "pause " case noOp: out = "" default: out = "ERROR " } fmt.Printf("%s ", out) } close(output) }
05eugene-cw0102030405060708090
cw-decode.go
Go
bsd
5,695
all: 8g cw-decode.go 8l -o cw-decode cw-decode.8 clean: rm -f *.8 cw-decode
05eugene-cw0102030405060708090
Makefile
Makefile
bsd
83
/* * Theme Name: 017leena * Description: 梨衣名 * Author: Stock Style **/ @charset "utf-8"; /*------------------------------トップページ */ #main.top_main { width:520px; height:490px; margin:0; padding:0; position:relative; background:url(./images/front/img_top.jpg) no-repeat 0 0 #000; } .top_img { width:152px; height:80px; } .top_img h1 { padding:20px 0 0 20px; } .top_msg { width:200px; position:absolute; top:130px; left:20px; text-align:center; } .top_msg em { font-size:123.1%; font-style: normal; font-weight:bold; color:#fff; } .top_msg p { margin-top:10px; line-height:1.5em; text-align:left; font-size:93%; color:#fff; } /*------------------------------プロフィール */ .prof_img { width:240px; float:left; display:inline; margin:0 0 0 20px; } .prof_msg { width:206px; float:left; display:inline; color:#666; } .prof_msg h3 { font-size:138.5%; font-weight:bold; margin:10px 0 5px; color:#333; } .prof_msg p.bd { margin-top:5px; font-size:93%; color:#333; } .prof_msg p.p_data { margin-top:10px; line-height:1.5em; font-size:93%; } /*------------------------------Favorite */ .fav_main { background:url(./images/front/bg_main.png) left repeat-y; } .fav_box { width:460px; padding:0 0 18px 0; margin:0 auto 18px auto; background:url(images/front/bg_fav.png) bottom repeat-x; } .fav_img { width:148px; float:left; } .fav_item { width:300px; padding:0 0 0 12px; float:right; } h3.fav_title { padding:0 0 3px 0; color:#000; } h3.fav_title a { color:#000; } .fav_price { padding:0 0 5px 0; color:#000; } .fav_price span { padding:0 0 0 1em; font-size:12px; } .fav_detail { padding:0 0 10px 0; color:#595959; } .fav_item label { padding:0 0 5px 0; display:block; color:#595959; } .fav_item label select { width:100px; margin:0 0 0 10px; } .fav_model { padding:0 30px 0 0; margin:0 0 10px 0; text-align:right; } .fav_model a { width:142px; height:0; padding:23px 0 0 0; background:url(images/front/btn_model.jpg) 0 0 no-repeat; display:block; overflow:hidden; float:right; } .fav_model a:hover { opacity:0.8; } .fav_button { text-align:center; } #fav_buy { width:203px; height:38px; margin:0; background:url(images/front/btn_buy.jpg) 0 0 no-repeat; border:none; cursor:pointer; } #fav_buy:hover { opacity:0.8; } /*------------------------------インフォメーション/イベント */ #search_box { width:460px; margin:20px auto 30px; } #search_box select{ margin-top:10px; font-size:11px; width:200px; background-color:#ffffff; border:#cccccc 2px solid; } #search_box .category { width:220px; float:left; display:inline; margin-right:40px; } #search_box .month { width:230px; float:left; } #info_box { width:460px; margin:10px auto 20px; } .info_top { width:460px; height:56px; margin:0; background:url(./images/front/line_top.jpg) no-repeat center top; } .info_top p.date { color:#ae841d; font-weight:bold; margin-left:25px; padding-top:35px; } .info_body { width:460px; } .info_body h3 { margin:0 0 20px 25px; } .info_body p { margin:10px 20px 0 25px; line-height:1.5em; } .info_bottom { width:440px; height:53px; margin:10px auto 0; padding-right:20px; text-align:right; } /*------------------------------ギャラリー/GOODS */ #gallery_box { width:460px; margin:0 auto 25px; } #gallery_box .photobox { font-size:1.2em; width:120px; float:left; display:inline-block; margin:16px; text-align:center; } #gallery_box .photobox p { margin-bottom:10px; } #gallery_box .photobox p.item { font-size:0.9em; text-align:left; margin-bottom:5px; } #gallery_box .photobox p.like { text-align:left; } /*------------------------------ブログ */ #blog_box { width:460px; margin:10px auto 20px; background:url(./images/front/bg_blog.jpg) no-repeat center bottom; } .blog_top { width:440px; height:50px; margin:0; padding-right:20px; text-align:right; } .blog_top p.date { padding-top:30px; } .blog_body { width:460px; } .blog_body h3 { margin:0 0 20px 25px; } .blog_body p { margin:10px 20px 0 25px; line-height:1.5em; } .blog_bottom { width:440px; height:53px; margin:10px auto 0; padding-right:20px; text-align:right; } /*------------------------------twitter */ #twitter_box { width:460px; margin:20px auto 20px; color:#555; } #followme img { vertical-align:middle; margin-left:15px; } #twitter_box a{ color:#AE841D; } ol { margin: 0; padding: 0; list-style: none outside none; } ol#tweets.loading { padding: 6em 0; } ol#tweets li { font-size:1.2em; padding: 1.25em 0; border-bottom: 1px dashed #ccc; } ol#tweets li.error { margin: 50px 0 30px 0; font-family: Georgia, "Times New Roman", serif; text-align: center; font-size: 1.0em; } ol#tweets p span.time { font-size: 0.9em; color: #999; } .user img { float: left; padding: 5px; border: 1px solid #e9e9e9; margin-right: 20px; } .user h3 { float: left; margin: 0 15px 0 0; line-height: 60px; } ol#tweets p { font-size: 1.0em; clear:left; } /*------------------------------ショップ */ .shop_img { width:315px; float:left; display:inline; margin:0 10px 20px; } .shop_msg { width:150px; float:left; display:inline; } .shop_msg h3 { font-size:1.6em; font-weight:bold; color:#ae841d; margin:0; } .shop_msg p.p_data { margin-top:10px; font-size:1.2em; line-height:1.5em; } .tablenav { color: #2583ad; margin: 1em auto; line-height:2em; text-align:center; } a.page-numbers, .tablenav .current { color: #00019b; padding: 2px .4em; border:solid 1px #ccc; text-decoration:none; font-size:smaller; } a.page-numbers:hover { color:white; background: #328ab2; } .tablenav .current { color: white; background: #328ab2; border-color: #328ab2; font-weight:bold: } .tablenav .next, .tablenav .prev { border:0 none; background:transparent; text-decoration:underline; font-size:smaller; font-weight:bold; }
017leena
style.css
CSS
oos
5,938
<?php get_header(); ?> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- コンテンツ START --> <div id="main" class="top_main clearfix"> <!-- コンテンツ START --> <div class="top_img"> <h1><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="梨衣名" width="152" height="80" title="梨衣名" /></h1> </div> <div class="top_msg"> <?php if(have_posts()): the_post(); the_content(); endif; ?> </div> </div> <!-- //コンテンツ END// --> <!-- グローバルナビ START --> <?php echo get_navi(); ?> <!-- //グローバルナビ END// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#pagetop">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> <?php get_footer(); ?>
017leena
custom_topic.php
PHP
oos
913
<?php define("PACKAGE_ROOT", dirname(__FILE__)); include_once PACKAGE_ROOT.'/conf/facebook_const.php'; include_once PACKAGE_ROOT.'/lib/mastercontrol.php'; //+++++++++++++++++++++++++++++++++++++++++ //カスタムヘッダー include_once 'lib/func_header.php'; include_once 'lib/func_footer.php'; include_once 'lib/layout/func.php'; include_once 'lib/design/func.php'; include_once 'lib/social.php'; add_shortcode('ogp_single_blog', 'ogp_single_base_content'); add_shortcode('blog_like', 'get_base_like'); /* add_custom_image_header('','admin_header_style'); function admin_header_style() {} //標準のヘッダー画像を指定 define('HEADER_IMAGE','%s/images/header.jpg'); //ヘッダー画像の横幅と高さを指定 define('HEADER_IMAGE_WIDTH','256'); define('HEADER_IMAGE_HEIGHT','88'); //ヘッダーの文字を隠す define('NO_HEADER_TEXT',true); //背景画像を指定 add_custom_background(); //記事のpタグを削除 remove_filter('the_content', 'wpautop'); */ //+++++++++++++++++++++++++++++++++++++++++ //カスタムメニュー include_once 'lib/func_gnavi.php'; /* register_nav_menus(array( 'navbar' => 'ナビゲーションバー', 'sidebar' => 'サイドバー' )); */ //+++++++++++++++++++++++++++++++++++++++++ //エディタ・スタイルシート add_editor_style(); //+++++++++++++++++++++++++++++++++++++++++ //ウィジェット登録 register_sidebar(array( 'description' => '', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '' ) ); register_sidebar(array( 'description' => '', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '' ) ); //ウィジェットタイトル非表示 function my_widget_title( $title ) { return ''; } add_filter( 'widget_title', 'my_widget_title' ); //+++++++++++++++++++++++++++++++++++++++++ // アイキャチ画像 add_theme_support('post-thumbnails'); set_post_thumbnail_size(120, 90, true); //set_post_thumbnail_size(120, 90); //+++++++++++++++++++++++++++++++++++++++++ // アイキャチ画像のURLを取得 function get_featured_image_url() { $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id, 'thumbnail', true); echo $image_url[0]; } //+++++++++++++++++++++++++++++++++++++++++ // 管理バーを消す add_filter( 'show_admin_bar', '__return_false' ); //+++++++++++++++++++++++++++++++++++++++++ // ログイン画面ロゴ function custom_login_logo() { echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'/images/tool/master_control_image.png) 50% 50% no-repeat !important; }</style>'; } add_action('login_head', 'custom_login_logo'); //+++++++++++++++++++++++++++++++++++++++++ // 管理画面左上のロゴ add_action('admin_head', 'my_custom_logo'); function my_custom_logo() { echo '<style type="text/css">#header-logo { background-image:url('.get_bloginfo('template_directory').'/images/tool/master_control_logo.png) !important; }</style>'; } //+++++++++++++++++++++++++++++++++++++++++ // 管理画面フッターのテキスト function custom_admin_footer() { echo '© CYBIRD Co., Ltd All Rights Reserved.'; } add_filter('admin_footer_text', 'custom_admin_footer'); //+++++++++++++++++++++++++++++++++++++++++ // HTML エディタのフォントを変更 function change_editor_font(){ echo "<style type='text/css'> #editorcontainer textarea#content { font-family: \"ヒラギノ角ゴ Pro W3\", \"Hiragino Kaku Gothic Pro\", Osaka, \"MS Pゴシック\", sans-serif; font-size:14px; color:#333; } </style>"; } add_action("admin_print_styles", "change_editor_font"); //+++++++++++++++++++++++++++++++++++++++++ // アドミンバーを消す add_filter('show_admin_bar','__return_false'); //+++++++++++++++++++++++++++++++++++++++++ // 管理者以外にアップデートのお知らせ非表示 if (!current_user_can('edit_users')) { function wphidenag() { remove_action( 'admin_notices', 'update_nag'); } add_action('admin_menu','wphidenag'); } //+++++++++++++++++++++++++++++++++++++++++ // 管理者以外にダッシュボードの内容非表示 if (!current_user_can('edit_users')) { remove_all_actions('wp_dashboard_setup'); function example_remove_dashboard_widgets() { global $wp_meta_boxes; //Main column unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']); //Side Column unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']); } add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' ); } //+++++++++++++++++++++++++++++++++++++++++ // 管理者以外は[表示オプション][ヘルプ]のタブを非表示にする if (!current_user_can('edit_users')) { function my_admin_print_styles(){ echo ' <style type="text/css"> #screen-options-link-wrap, #contextual-help-link-wrap{display:none;} </style>'; } add_action('admin_print_styles', 'my_admin_print_styles', 21); } //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Event情報 include_once 'lib/module/info/func.php'; /* register_post_type( 'event', array( 'label' => 'イベント情報', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/event.png', 'supports' => array( 'title', 'editor' ) ) ); */ //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト photogallery register_post_type( 'photogallery', array( 'label' => 'フォトギャラリー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト DISCOGRAPHY register_post_type( 'discography', array( 'label' => 'ディスコグラフィー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/discography.png', 'supports' => array( 'title', ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MEDIA register_post_type( 'media', array( 'label' => 'メディア/出演情報', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト BLOG include_once 'lib/module/blog/func.php'; /* register_post_type( 'blog', array( 'label' => 'ブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); */ //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MULTI-BLOG register_post_type( 'multiblog', array( 'label' => 'マルチブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト ITUNES register_post_type( 'itunes', array( 'label' => 'iTunes', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/itune.png', 'supports' => array( 'title', 'editor' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト GOODS register_post_type( 'goods', array( 'label' => 'グッズ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/goods.png', 'supports' => array( 'title', 'thumbnail' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Twitter include_once 'lib/module/twitter/func.php'; /* register_post_type( 'twitter', array( 'label' => 'Twitter', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/twitter.png', 'supports' => array( 'title' ) ) ); */ //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト YouTube register_post_type( 'youtube', array( 'label' => 'YouTube', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/youtube.png', 'supports' => array( 'title' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Profile register_post_type( 'profile', array( 'label' => 'プロフィール', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/profile.png', 'supports' => array( 'title', 'editor' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MasterControl Setting register_post_type( 'mastercontrol', array( 'label' => 'MasterControl', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/master_control_logo.png', 'supports' => array( 'title' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト おすすめコーデ register_post_type( 'osusume', array( 'label' => 'おすすめコーデ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/stockstyle.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ //パンくずリスト用(未使用) function get_breadcrumbs(){ global $wp_query; if ( !is_home() ){ // Add the Home link echo '<a href="'. get_settings('home') .'">TOP</a>'; if ( is_category() ) { $catTitle = single_cat_title( "", false ); $cat = get_cat_ID( $catTitle ); echo '&gt;<span class="now">'. get_category_parents( $cat, TRUE, "" ) .'</span>'; } elseif ( is_archive() && !is_category() ) { echo '&gt;&nbsp;<span class="now">Archives</span>'; } elseif ( is_search() ) { echo '&gt;&nbsp;<span class="now">Search Results</span>'; } elseif ( is_404() ) { echo '&gt;&nbsp;<span class="now">404 Not Found</span>'; } elseif ( is_single() ) { $category = get_the_category(); $category_id = get_cat_ID( $category[0]->cat_name ); echo '&gt;<span class="now">'. get_category_parents( $category_id, TRUE, "&gt;" ); echo '&nbsp;&nbsp;' . the_title('','', FALSE) ."</span>"; } elseif ( is_page() ) { $post = $wp_query->get_queried_object(); if ( $post->post_parent == 0 ){ echo '&nbsp;&gt;&nbsp;<span class="now">'.the_title('','', FALSE).'</span>'; } else { $title = the_title('','', FALSE); $ancestors = array_reverse( get_post_ancestors( $post->ID ) ); array_push($ancestors, $post->ID); foreach ( $ancestors as $ancestor ){ if( $ancestor != end($ancestors) ){ echo '&nbsp;&gt;&nbsp; <a href="'. get_permalink($ancestor) .'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a>'; } else { echo '&nbsp;&gt;&nbsp; <span class="now">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</span>'; } } } } } } function get_breadcrumb(){ if(function_exists('bcn_display')){ return bcn_display(true); } return; } add_shortcode('bcn_display', 'get_breadcrumb'); //+++++++++++++++++++++++++++++++++++++++++ // ギャラリー用facebookいいねボタン追加 /* デフォルトのショートコードを削除 */ remove_shortcode('gallery', 'gallery_shortcode'); /* 新しい関数を定義 */ add_shortcode('gallery', 'my_gallery_shortcode'); function my_gallery_shortcode($attr) { global $post, $wp_locale; static $instpe = 0; $instpe++; // Allow plugins/themes to override the default gallery template. $output = apply_filters('post_gallery', '', $attr); if ( $output != '' ) return $output; // We're trusting author input, so let's at least make sure it looks like a valid orderby statement if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( !$attr['orderby'] ) unset( $attr['orderby'] ); } extract(shortcode_atts(array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post->ID, 'itemtag' => 'dl', 'icontag' => 'dt', 'captiontag' => 'dd', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'exclude' => '' ), $attr)); $id = intval($id); if ( 'RAND' == $order ) $orderby = 'none'; if ( !empty($include) ) { $include = preg_replace( '/[^0-9,]+/', '', $include ); $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( !empty($exclude) ) { $exclude = preg_replace( '/[^0-9,]+/', '', $exclude ); $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } else { $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } if ( empty($attachments) ) return ''; if ( is_feed() ) { $output = "¥n"; foreach ( $attachments as $att_id => $attachment ) $output .= wp_get_attachment_link($att_id, $size, true) . "¥n"; return $output; } $itemtag = tag_escape($itemtag); $captiontag = tag_escape($captiontag); $columns = intval($columns); $itemwidth = $columns > 0 ? floor(100/$columns) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = "gallery-{$instpe}"; $output = apply_filters('gallery_style', " <style type='text/css'> #{$selector} { margin: auto; } #{$selector} .gallery-item { float: {$float}; margin-top: 10px; text-align: center; width: {$itemwidth}%; } #{$selector} img { border: 2px solid #cfcfcf; } #{$selector} .gallery-caption { margin-left: 0; } </style> <!-- see gallery_shortcode() in wp-includes/media.php --> <div id='$selector' class='gallery galleryid-{$id}'>"); $i = 0; foreach ( $attachments as $id => $attachment ) { $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false); $output .= "<{$itemtag} class='gallery-item'>"; $output .= " <{$icontag} class='gallery-icon'> $link </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <{$captiontag} class='gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>"; } $url_thumbnail = wp_get_attachment_image_src($id, $size='thumbnail'); $url = urlencode(get_bloginfo('home') . '/?attachment_id=' . $id); $url .= urlencode('&app_data=' . get_bloginfo('home') . '/?attachment_id=' . $id); $output .= '<p><div class="btn_like"><iframe src="http://www.facebook.com/plugins/like.php?href='; $output .= $url; $output .= '&amp;id=fb&amp;send=false&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=like&amp;colorscheme=light$amp;locale=ja_JA&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:21px;" allowTransparency="true"></iframe></div></p>'; $output .= "</{$itemtag}>"; if ( $columns > 0 && ++$i % $columns == 0 ) $output .= '<br style="clear: both" />'; } $output .= "</div>"; return $output; } function remove_gallery_css() { return "<div id='gallery_box'>"; } add_filter('gallery_style', 'remove_gallery_css'); function fix_gallery_output( $output ){ $output = preg_replace("%<br style=.*clear: both.* />%", "", $output); $output = preg_replace("%<dl class='gallery-item'>%", "<div class='photobox'>", $output); $output = preg_replace("%<dt class='gallery-icon'>%", "", $output); $output = preg_replace("%</dl>%", "</div>", $output); $output = preg_replace("%</dt>%", "", $output); return $output; } add_filter('the_content', 'fix_gallery_output',11, 1); //+++++++++++++++++++++++++++++++++++++++++ ?>
017leena
functions.php
PHP
oos
17,660
jQuery(document).ready(function(){ var navTag = '#gnav_' + jQuery('h2.menu_image').html() + ' a'; jQuery(navTag).attr("class", "current"); });
017leena
js/navi_current.js
JavaScript
oos
145
// ----------------------------------------------------------------------------------- // // Lightbox v2.04 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 2/9/08 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.rel == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if (this.imageArray[this.activeImage][1] != ""){ this.caption.update(this.imageArray[this.activeImage][1]).show(); } // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
017leena
js/lightbox-web.js
JavaScript
oos
18,389
// script.aculo.us scriptaculous.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.9.0', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); } catch(e) { // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); } }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
017leena
js/scriptaculous.js
JavaScript
oos
2,931
// script.aculo.us builder.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010 // Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return $(element); }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e); else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); }; }); } };
017leena
js/builder.js
JavaScript
oos
4,744
// ----------------------------------------------------------------------------------- // // Lightbox v2.05 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 3/18/11 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: '/wp-content/themes/999mastercontrol-dev/images/loading.gif', fileBottomNavCloseImage: '/wp-content/themes/999mastercontrol-dev/images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.getAttribute("rel") == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; /*Bug Fixed by Andy Scott*/ this.lightboxImage.width = imgPreloader.width; this.lightboxImage.height = imgPreloader.height; /*End of Bug Fix*/ this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { this.caption.update(this.imageArray[this.activeImage][1]).show(); // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
017leena
js/lightbox.js
JavaScript
oos
18,593
<?php $template_type = get_post_type(get_the_ID()); include 'custom_' . $template_type . '.php'; ?>
017leena
single.php
PHP
oos
107
<?php /* Template Name: Event */ ?> <?php get_header(); ?> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> <div id="google_translate_element" style="float:right"></div> <!-- ヘッダー START --> <div id="header"> <h1><a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="<?php bloginfo('name'); ?>" title="<?php bloginfo('name'); ?>" /></a></h1> </div> <!-- //ヘッダー END// --> <!-- コンテンツ START --> <div id="main_top">&nbsp;</div> <div id="main" class="clearfix"> <h2 class="menu_image info">Information</h2> <!-- 検索条件START --> <?php if(!is_single()): ?> <div id="search_box"> <hr class="search"> <div class="category"> <p><img src="<?php bloginfo('template_url'); ?>/images/front/stitle_cat.png"></p> <?php echo get_selectbox_category(); ?> </div> <div class="monthly"> <p><img src="<?php bloginfo('template_url'); ?>/images/front/stitle_month.png"></p> <?php echo get_selectbox_monthly(); ?> </div> <hr class="search"> </div> <?php endif; ?> <!-- //検索条件END// --> <!-- ブログSTART --> <!-- ##シングルページへのアクセスだった場合(single.phpからのincludeの場合)は表示させるPostIDを取得 --> <?php if(is_single()){ $displayablePostID = get_the_ID();}else{$displayablePostID = "";} ?> <!-- ##Eventポスト取得のループ開始 --> <?php wp_reset_query();query_posts('post_type=event&meta_key=eventstart&orderby=meta_value&order=DSC'); ?> <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <?php $event = get_event_meta(); ?> <!-- ##イベントの非表示条件を判定 --> <?php if(is_event_disable($event)){continue;} ?> <!-- ##シングルページの場合は、指定されたPostID以外は表示させない --> <?php if($displayablePostID !== "" && $displayablePostID !== get_the_ID()){ continue; } ?> <div id="info_box"> <div class="info_top"> <p class="date"><?php echo $event["startdate"]; ?></p> </div> <div class="info_body"> <h3> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <img src="<?php bloginfo('template_url'); ?>/images/front/ico_<?php echo $event["category"]; ?>.png"> </h3> <p class="detail"><?php the_content(); ?></p> </div> <div class="info_bottom"> <?php echo getLikeBottun(); ?> </div> </div> <!-- //インフォ詳細END// --> <?php endwhile; ?> <?php endif; ?> <!-- //ブログEND// --> </div> <!-- //コンテンツ END// --> <!-- グローバルナビ START --> <?php echo get_navi(); ?> <!-- //グローバルナビ END// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> <?php function get_event_meta(){ $c = get_post_custom_values('eventstart', get_the_ID()); $event["startdate"] = $c[0]; $c = get_post_custom_values('eventend' , get_the_ID()); $event["enddate"] = $c[0]; $c = get_post_custom_values('opendate' , get_the_ID()); $event["opendate"] = $c[0]; $c = get_post_custom_values('closedate' , get_the_ID()); $event["closedate"] = $c[0]; $c = get_post_custom_values('category' , get_the_ID()); $event["category"] = $c[0]; if($event["enddate"] == "" || $event["enddate"] === $event["startdate"]){$event["datelabel"] = $event["startdate"];} if($event["enddate"] != "" && $event["enddate"] != $event["startdate"]){$event["datelabel"] = $event["startdate"] . " - " . $event["enddate"];} return $event; } function is_event_disable($event){ $filtered = false; // ##opendate <- -> closedate 以外であれば非表示 if( $event["opendate"] != ""){ if(strtotime( $event["opendate"] ) > time() ){ $filtered = true; }} if( $event["closedate"] != ""){ if(strtotime( $event["closedate"] ) < time() ){ $filtered = true; }} //##月指定があれば絞り込み if(isset($_REQUEST["mon"])){ $filter = date("Y", $_REQUEST["mon"]) . date("m", $_REQUEST["mon"]); $current = date("Y", strtotime($event["startdate"])) . date("m", strtotime($event["startdate"])); if($filter != $current){$filtered = true;} } //##カテゴリ指定があれば絞り込み if(isset($_REQUEST["cat"])){ if($_REQUEST["cat"] != $event["category"]){$filtered = true;} } return $filtered; } function get_selectbox_category(){ wp_reset_query(); query_posts('post_type=event'); if(have_posts()){ while(have_posts()){ the_post(); $e = get_event_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $cat = get_post_custom_values('category', get_the_ID()); $catList[$e["category"]] = ""; } } $catListKeys = array_keys($catList); $selectbox_html = "<select name='cat' id='cat' class='postform' >"; $selectbox_html .= "<option value=''>カテゴリーを選択</option>"; foreach($catListKeys as $k=>$v){ if($_REQUEST["cat"] === $v){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . $v . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var catdropdown = document.getElementById('cat');"; $selectbox_html .= " function onCatChange() {"; $selectbox_html .= " location.href = './?cat='+catdropdown.options[catdropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "catdropdown.onchange = onCatChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } function get_selectbox_monthly(){ wp_reset_query(); query_posts('post_type=event'); if(have_posts()){ while(have_posts()){ the_post(); $e = get_event_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $monthList[date("Y", strtotime($e["startdate"])) . "/" . date("n", strtotime($e["startdate"]))] = ""; } } $monthListKeys = array_keys($monthList); $selectbox_html = "<select name='mon' id='mon' class='postform' >"; $selectbox_html .= "<option value=''>月を選択</option>"; foreach($monthListKeys as $k=>$v){ if($_REQUEST["mon"] === strtotime($v."/1")){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . strtotime($v."/1") . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var mondropdown = document.getElementById('mon');"; $selectbox_html .= "function onMonChange() {"; $selectbox_html .= " location.href = './?mon='+mondropdown.options[mondropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "mondropdown.onchange = onMonChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } ?> <?php get_footer(); ?>
017leena
custom_event.php
PHP
oos
7,410
<?php /* Template Name: Blog */ get_header(); ?> <div id="wrapper"> <a name="pagetop" id="pagetop"></a> <?php run_layout(); ?> <?php get_footer(); ?>
017leena
custom_blog.php
PHP
oos
155
@charset "utf-8"; /*------------------------------Base Setting */ h1, h2, h3, h4, h5, h6, p, ul, ol, dl, dt, dd, li, table, th, td, form, select, option, address, pre, strong, em, p { padding: 0; margin: 0; } body{ padding: 0; margin: 0; width:100%; font-size:13px; font-family:Verdana,Arial,sans-serif; line-height:1; } * html body { font-family: 'MS Pゴシック',sans-serif; } *:first-child+html body { font-family: 'メイリオ','MS Pゴシック',sans-serif; } select,input,button,textarea,button { font:99% arial,helvetica,clean,sans-serif; } #wrapper { width:520px; margin:0 auto; background-color:#000; color:#666; } a img { border:none; } .floatClear { clear: both; } .clearfix { overflow: visible; } .clearfix:after { content:"."; display:block; height:1px; clear:both; visibility:hidden; } table { font-size:inherit; font:100%; border-collapse:collapse; border-spacing:0; } ol, ul { list-style: none; } /*------------------------------FONT-SIZE */ /* 10px = 77% 11px = 85% 12px = 93% 13px = 100% 14px = 108% 15px = 116% 16px = 123.1% 17px = 131% 18px = 138.5% 19px = 146.5% 20px = 153.9% 21px = 161.6% 22px = 167% 23px = 174% 24px = 182% 25px = 189% 26px = 197% */ .txt_bold { font-weight:bold; } .txt_11 { font-size:85%; } .txt_12 { font-size:93%; } .txt_13 { font-size:100%; } .txt_14 { font-size:108%; } .txt_15 { font-size:116%; } .txt_16 { font-size:123.1%; }
017leena
base.css
CSS
oos
1,445
<?php /* Template Name: osusume */ get_header(); $template_url = get_bloginfo('template_url'); $site_name = get_bloginfo('name'); $is_single = false; print <<<META_HEADER <script type="text/javascript" src="$template_url/js/prototype.js"></script> <script type="text/javascript" src="$template_url/js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="$template_url/js/lightbox.js"></script> <link rel="stylesheet" href="$template_url/css/lightbox.css" type="text/css" media="screen" /> <script type="text/javascript">//<![CDATA[ // セレクトボックスに項目を割り当てる。 function lnSetSelect(form, name1, name2, val, lists, vals) { //sele11 = document[form][name1]; sele11 = document.getElementById(name1); sele12 = document.getElementById(name2); if(sele11 && sele12) { index = sele11.selectedIndex; // セレクトボックスのクリア count = sele12.options.length; for(i = count; i >= 0; i--) { sele12.options[i] = null; } // セレクトボックスに値を割り当てる len = lists[index].length; for(i = 0; i < len; i++) { sele12.options[i] = new Option(lists[index][i], vals[index][i]); if(val != "" && vals[index][i] == val) { sele12.options[i].selected = true; } } } } //]]> </script> <script type="text/javascript">//<![CDATA[ jQuery(document).ready( function(){ jQuery(".fav_button").live('click', function() { var reqcnt = 0; var reqparams = ""; jQuery("input:checked").each( function(){ if ( jQuery(this)[0] ) { var formid = '#' + jQuery(this).attr('formid'); var prodid = formid + " input[name=product_id]"; var catid1 = formid + " select[name=classcategory_id1] option:selected"; var catid2 = formid + " select[name=classcategory_id2] option:selected"; var sizid = formid + ' #size'; var colid = formid + ' #color'; var req_url = "/products/facebook.php"; var req_mode = 'cart'; var req_product_id = jQuery(prodid).val(); var mesag = formid + ' #messege' + req_product_id; var req_cry_id1 = jQuery(catid1).val(); var req_cry_id2 = jQuery(catid2).val(); reqparams += "ary_product_id[" + reqcnt + "]=" + req_product_id + '&ary_classcategory_id1[' + reqcnt + ']=' + req_cry_id1 + '&ary_classcategory_id2[' + reqcnt + ']=' + req_cry_id2 + '&'; reqcnt++; } }); var reqobj; reqparams += "multimode=cart&quantity=1"; reqobj = jQuery.ajax({type: 'POST', url: '/products/facebook.php', data: reqparams, success: function(html) { var w = window.open('about:blank', '_blank'); w.location.href = '/cart/index.php'; }}); }); }); //]]> </script> </head> META_HEADER; // Google翻訳 $google_trans = '<div id="google_translate_element" style="float:right"></div>'; // グローバルナビ $global_navi = get_navi(); $bloginfo_url = get_bloginfo('url'); print <<<CUSTOM_HEADER <body> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> $google_trans <!-- ヘッダーSTART --> <div id="header"> <h1><a href="$bloginfo_url"><img src="$template_url/images/front/img_h1.png" alt="$site_name" title="$site_name" /></a></h1> </div> <!-- //ヘッダーEND// --> <!-- コンテンツ START --> <div class="info_main clearfix"> <div id="main" class="clearfix"> <h2 class="menu_image favorites">Favorites</h2> CUSTOM_HEADER; echo '<!-- おすすめコーデSTART -->'; // ##シングルページへのアクセスだった場合(single.phpからのincludeの場合)は表示させるPostIDを取得 if(is_single()){ $is_single = true; $displayablePostID = get_the_ID(); }else{ $is_single = false; $displayablePostID = ""; } // <!-- ##blogポスト取得のループ開始 --> query_posts('post_type=osusume'); if(have_posts()): $listcount = 0; while(have_posts()): the_post(); $title = $content = $post_meta = $permalink = $likebutton = 0; $listcount++; $title = get_the_title(); $content = get_the_content(); $post_meta = get_post_meta($post->ID, sprintf("products", $c), true); $permalink = get_permalink(); $url = parse_url($permalink); $stockstyle = "stockstyle.net"; if ( $url['host'] === "dev.mastercontrol.jp" ){ $stockstyle = "stage.stockstyle.net"; } $url_path = $url['path']; $likebutton = getLikeBottun(); // <!-- ##シングルページの場合は、指定されたPostID以外は表示させない --> if($is_single && $displayablePostID !== get_the_ID()){ continue; } if( $is_single || $listcount == 1): // モデル着用ボタン $model_photo_url = get_post_meta($post->ID, sprintf("モデルPhoto", $c), true); $model_photo_style = $model_photo_url !== "" ? ' style="display:none;"' : ''; // -------------- シングル コンテンツ 開始 --------------- print <<<SINGLE_CONTENT <!-- コメントSTART --> $content <!-- コメントEND --> <!-- inline:osusume_code --> $post_meta <!-- inline:osusume_code --> <p class="fav_model clearfix" $model_photo_style> <a href="$model_photo_url" rel="lightbox">モデル着用PHOTO</a> </p> <!-- //購入ボタンSTART --> <div class="fav_button"> <input type="submit" value="" id="fav_buy" /> </div> <!-- //購入ボタンEND// --> SINGLE_CONTENT; // -------------- シングル コンテンツ 終了 --------------- else: // -------------- 一覧 コンテンツ 開始 --------------- print <<<LIST_CONTENT <div id="info_box"> <div class="info_body"> <h3><a href="http://$stockstyle/products/facebook.php?osusume_url=$url_path">$title</a></h3> </div> </div> LIST_CONTENT; // -------------- 一覧 コンテンツ 終了 --------------- endif; endwhile; endif; echo '<!-- //おすすめコーデEND// -->'; print <<<CUSTOM_FOOTER </div> </div> <!-- コンテンツ END --> <!-- グローバルナビ START --> $global_navi <!-- //グローバルナビ END// --> <!-- Pagetop START --> <div class="pagetop"> <p><a href="#pagetop">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> CUSTOM_FOOTER; get_footer(); ?>
017leena
custom_osusume.php
PHP
oos
6,608
<?php get_header(); ?> <?php get_footer(); ?>
017leena
index.php
PHP
oos
46
<?php get_header(); ?> <?php get_footer(); ?>
017leena
page.php
PHP
oos
47
<?php /* Template Name: Info */ get_header(); ?> <div id="wrapper"> <a name="pagetop" id="pagetop"></a> <?php run_layout(); ?> <?php get_footer(); ?>
017leena
custom_info.php
PHP
oos
155
<!-- Pagetop START --> <div class="pagetop"> <p><a href="#pagetop">▲Page Topに戻る</a></p> </div> <!-- //Pagetop END// --> <!-- フッター START --> <div id="footer"> <p>Copyright&copy; LesPros Entertainment Co., Ltd. All rights reserved.</p> </div> <!-- //フッター END// --> <div> <?php wp_footer(); ?> </body> </html>
017leena
footer.php
PHP
oos
383
<?php $q = get_posts('post_type=mastercontrol&posts_per_page=1'); $qq = get_post_custom_values('appid', $q[0]->ID); if($qq[0] == ""){$APP_ID = "";}else{$APP_ID = $qq[0];} define("APP_ID", $APP_ID); $qq = get_post_custom_values('appsecret', $q[0]->ID); if($qq[0] == ""){$SECRET_KEY = "";}else{$SECRET_KEY = $qq[0];} define("SECRET_KEY", $SECRET_KEY); $qq = get_post_custom_values('facebookurl', $q[0]->ID); if($qq[0] == ""){$FB_URL = "";}else{$FB_URL = $qq[0];} define("FB_URL", $FB_URL); $qq = get_post_custom_values('page_id', $q[0]->ID); if($qq[0] == ""){$PAGE_ID = "";}else{$PAGE_ID = $qq[0];} define("PAGE_ID", $PAGE_ID); $qq = get_post_custom_values('access_token', $q[0]->ID); if($qq[0] == ""){$ACCESS_TOKEN = "";}else{$ACCESS_TOKEN = $qq[0];} define("ACCESS_TOKEN", $ACCESS_TOKEN); $qq = get_post_custom_values('enable_site', $q[0]->ID); if($qq[0] == ""){$ENABLE_SITE = "";}else{$ENABLE_SITE = $qq[0];} define("ENABLE_SITE", $ENABLE_SITE); $qq = get_post_custom_values('fbpage_only', $q[0]->ID); if($qq[0] == ""){$FBPAGE_ONLY = false;}else{$FBPAGE_ONLY = true;} define("FBPAGE_ONLY", $FBPAGE_ONLY); ?>
017leena
conf/facebook_const.php
PHP
oos
1,146
<?php loadIframeFB(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xml:lang="ja" lang="ja"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <meta http-equiv="content-script-type" content="text/javascript"> <title><?php bloginfo('name'); ?> facebook page</title> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" /> <link rel="stylesheet" href="<?php echo get_custom_templateurl(); ?>/base.css" type="text/css" /> <link rel="stylesheet" href="<?php echo get_custom_templateurl(); ?>/rayout.css" type="text/css" /> <?php echo do_shortcode('[ogp_meta]'); redirectFB(); wp_head(); ?> </head> <body>
017leena
header.php
PHP
oos
870
<?php /* Template Name: Profile */ ?> <?php get_header(); ?> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> <div id="google_translate_element" style="float:right"></div> <!-- ヘッダー START --> <div id="header"> <h1><a href="<?php bloginfo('url'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="<?php bloginfo('name'); ?>" title="<?php bloginfo('name'); ?>" /></a></h1> </div> <!-- //ヘッダー END// --> <!-- コンテンツ START --> <div id="main" class="prof_main clearfix"> <h2 class="menu_image prof">Profile</h2> <?php query_posts('post_type=profile'); if(have_posts()): the_post(); the_content(); endif; ?> </div> <!-- //コンテンツ END// --> <!-- グローバルナビ START --> <?php echo get_navi(); ?> <!-- //グローバルナビ END// --> <?php get_footer(); ?>
017leena
custom_profile.php
PHP
oos
883
<?php get_header(); ?> <a name="pagetop" id="pagetop"></a> <div id="wrapper"> <!-- コンテンツ START --> <div id="main" class="top_main clearfix"> <!-- コンテンツ START --> <div class="top_img"> <h1><img src="<?php bloginfo('template_url'); ?>/images/front/img_h1.png" alt="梨衣名" width="152" height="80" title="梨衣名" /></h1> </div> <div class="top_msg"> <?php if(have_posts()): the_post(); the_content(); endif; ?> </div> </div> <!-- //コンテンツ END// --> <!-- グローバルナビ START --> <?php echo do_shortcode("[gnavi]"); ?> <!-- //グローバルナビ END// --> <?php get_footer(); ?>
017leena
home.php
PHP
oos
740
#lightbox{ position: absolute; left: 0; width: 100%; z-index: 100; text-align: center; line-height: 0;} #lightbox img{ width: auto; height: auto;} #lightbox a img{ border: none; } #outerImageContainer{ position: relative; background-color: #fff; width: 250px; height: 250px; margin: 0 auto; } #imageContainer{ padding: 10px; } #loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; text-align: center; line-height: 0; } #hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; } #imageContainer>#hoverNav{ left: 0;} #hoverNav a{ outline: none;} #prevLink, #nextLink{ width: 49%; height: 100%; background-image: url(data:image/gif;base64,AAAA); /* Trick IE into showing hover */ display: block; } #prevLink { left: 0; float: left;} #nextLink { right: 0; float: right;} #prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; } #nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; } #imageDataContainer{ font: 10px Verdana, Helvetica, sans-serif; background-color: #fff; margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100% ; } #imageData{ padding:0 10px; color: #666; } #imageData #imageDetails{ width: 70%; float: left; text-align: left; } #imageData #caption{ font-weight: bold; } #imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em; } #imageData #bottomNavClose{ width: 66px; float: right; padding-bottom: 0.7em; outline: none;} #overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; height: 500px; background-color: #000; }
017leena
css/lightbox.css
CSS
oos
1,648
/*------------------------------Gloval Navi */ #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; background-color:#000; margin: 0; padding: 0; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .menu_Profile { width: 90px; background:url("../images/front/gnav_prof.png") 0 0 no-repeat;} .menu_Info { width: 125px; background:url("../images/front/gnav_info.png") 0 0 no-repeat;} .menu_Favorites { width: 125px; background:url("../images/front/gnav_favorites.png") 0 0 no-repeat;} .menu_Blog { width: 90px; background:url("../images/front/gnav_blog.png") 0 0 no-repeat;} .menu_Twitter { width: 90px; background:url("../images/front/gnav_twitter.png") 0 0 no-repeat;} .menu_Profile a:hover, .menu_Profile a.current { background:url("../images/front/gnav_prof.png") 0px -35px no-repeat; } .menu_Info a:hover, .menu_Info a.current { background:url("../images/front/gnav_info.png") 0px -35px no-repeat; } .menu_Favorites a:hover, .menu_Favorites a.current { background:url("../images/front/gnav_favorites.png") 0px -35px no-repeat; } .menu_Blog a:hover, .menu_Blog a.current { background:url("../images/front/gnav_blog.png") 0px -35px no-repeat; } .menu_Twitter a:hover, .menu_Twitter a.current { background:url("../images/front/gnav_twitter.png") 0px -35px no-repeat; }
017leena
css/gnavi.css
CSS
oos
1,495
<div id="gnav" class="floatClear"> <ul class="navi"> <li id="gnav_Profile" class="gnav_01"><a href="http://dev.mastercontrol.jp/017leena/profile/" title="Profile" >Profile</a></li> <li id="gnav_Information" class="gnav_02"><a href="http://dev.mastercontrol.jp/017leena/event/" title="Information">Information</a></li> <li id="gnav_Favorites" class="gnav_03"><a href="http://stage.stockstyle.net/products/facebook.php?osusume_url=/017leena/single/osusume/274/" title="Favorites!" >Favorites!</a></li> <li id="gnav_Blog" class="gnav_04"><a href="http://dev.mastercontrol.jp/017leena/blog/" title="Blog" >Blog</a></li> </ul> </div> <!-- <SELECT onChange="document.body.style.zoom=this.options[this.selectedIndex].value"> <OPTION value="30%">30% <OPTION value="50%">50% <OPTION value="80%">80% <OPTION value="100%" selected>100% <OPTION value="125%">125% <OPTION value="150%">150% <OPTION value="200%">200% <OPTION value="300%">300% </SELECT> -->
017leena
css/navi.tpl
Smarty
oos
993
@charset "utf-8"; /*------------------------------Link */ a:link,a:visited { color:#AE841D; text-decoration:none; } a:hover { color:#AE841D; text-decoration:underline; } /*------------------------------Header */ #header { width:520px; height:115px; margin:0; background:url(./images/front/bg_header.jpg) no-repeat 0 0; } #header h1 { width:360px; height:80px; margin:0px; position:relative; top:15px; left:361px; } /*------------------------------Gloval Navi #gnav { width:520px; height:35px; } .navi { width:520px; height:35px; margin: 0; padding: 0; } .navi li, .navi a { height: 35px; display: block; } .navi li { float: left; list-style: none; display: inline; text-indent: -9999em; } .gnav_01 { width: 90px; background:url("images/front/gnav_prof.png") 0 0 no-repeat; } .gnav_02 { width: 125px; background:url("images/front/gnav_info.png") 0 0 no-repeat;} .gnav_03 { width: 125px; background:url("images/front/gnav_favorites.png") 0 0 no-repeat;} .gnav_04 { width: 90px; background:url("images/front/gnav_blog.png") 0 0 no-repeat;} .gnav_05 { width: 90px; background:url("images/front/gnav_twitter.png") 0 0 no-repeat;} .gnav_01 a:hover { background:url("images/front/gnav_prof.png") 0px -35px no-repeat; } .gnav_02 a:hover { background:url("images/front/gnav_info.png") 0px -35px no-repeat; } .gnav_03 a:hover { background:url("images/front/gnav_favorites.png") 0px -35px no-repeat; } .gnav_04 a:hover { background:url("images/front/gnav_blog.png") 0px -35px no-repeat; } .gnav_05 a:hover { background:url("images/front/gnav_twitter.png") 0px -35px no-repeat; } .gnav_01 a.current { background:url("images/front/gnav_prof.png") 0px -35px no-repeat; } .gnav_02 a.current { background:url("images/front/gnav_info.png") 0px -35px no-repeat; } .gnav_03 a.current { background:url("images/front/gnav_favorites.png") 0px -35px no-repeat; } .gnav_04 a.current { background:url("images/front/gnav_blog.png") 0px -35px no-repeat; } .gnav_05 a.current { background:url("images/front/gnav_twitter.png") 0px -35px no-repeat; } */ /*------------------------------Main Content */ #main { width:486px; margin:0 auto 21px; padding:0 0 20px 0; background:url(./images/front/bg_main.jpg) repeat-y center top; } #main_top { width:486px; height:8px; margin:0 auto; background:url(./images/front/bg_maintop.jpg) no-repeat center bottom; } /*------------------------------Content H2 */ h2.prof { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_prof.png") 10px 20px no-repeat; text-indent:-9999px; } h2.info { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_info.png") 10px 20px no-repeat; text-indent:-9999px; } h2.favorites { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_fav.png") 10px 20px no-repeat; text-indent:-9999px; } h2.event { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_event.png") 10px 20px no-repeat; text-indent:-9999px; } h2.goods { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_goods.png") 10px 20px no-repeat; text-indent:-9999px; } h2.shop { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_shop.png") 10px 20px no-repeat; text-indent:-9999px; } h2.gallery { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_gallery.png") 10px 20px no-repeat; text-indent:-9999px; } h2.blog { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_blog.png") 10px 20px no-repeat; text-indent:-9999px; } h2.twitter { width:160px; height:51px; margin-bottom:20px; background:url("./images/front/h2_twitter.png") 10px 20px no-repeat; text-indent:-9999px; } /*------------------------------Page Nation */ .pager { width:500px; margin:0 auto 20px; text-align:center; } .pager ul { width:410px; height:20px; float:right; } .pager ul li { margin:0 5px; display:inline-block; } .pager .now { font-weight:bold; color:#595959; text-decoration:underline; } /*------------------------------Page Top */ .pagetop { width:510px; text-align:right; margin-top:20px; padding-right:10px; } /*------------------------------Powerd */ #powerd { width:520px; height:25px; margin:5px auto 0; text-align:right; font-size:10px; color:#ffffff; } #powerd a { color:#ffffcc; text-decoration:none; } #powerd a:hover { color:#ffffcc; text-decoration:underline; } .likeCountArrow { background:url("./images/front/ico_likethum.png") left center no-repeat; padding-left:15px; margin-left:10px; } /*------------------------------Footer */ #footer { width:520px; height:25px; margin:0; text-align:center; background:url(./images/front/bg_footer.jpg) no-repeat 0 0; } #footer p { color:#efefef; padding-top:10px; }
017leena
rayout.css
CSS
oos
4,870
<?php function footer_html(){ $likeCount = facebook_likeCount("http://www.facebook.com/stockstyle"); print <<<FOOTER_STYLE <div id="powerd"> Powerd by&nbsp;<a href="https://www.facebook.com/stockstyle">STOCK STYLE</a> <span class="likeCountArrow"><span>$likeCount</span></span> </div> FOOTER_STYLE; } add_action( 'wp_footer', 'footer_html' ); ?>
017leena
lib/func_footer.php
PHP
oos
356
<?php // プラグイン //remove_action( 'wp_head', 'wordbooker_header' ); remove_action( 'wp_head', 'wpogp_auto_include' ); remove_action( 'wp_head', 'wp_page_numbers_stylesheet' ); remove_action( 'wp_head', 'widget_akismet_style' ); remove_action( 'wp_head', 'feed_links' ); // システム remove_action( 'wp_head', 'feed_links'); remove_action( 'wp_head', 'feed_links_extra'); remove_action( 'wp_head', 'rsd_link'); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'index_rel_link'); remove_action( 'wp_head', 'parent_post_rel_link'); remove_action( 'wp_head', 'start_post_rel_link'); remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head'); remove_action( 'wp_head', 'wp_generator' ); remove_action( 'wp_head', 'rel_canonical' ); remove_action( 'wp_head', 'wp_enqueue_scripts' ); remove_action( 'wp_head', 'locale_stylesheet' ); remove_action( 'wp_head', 'noindex' ); remove_action( 'wp_head', 'wp_print_styles' ); remove_action( 'wp_head', 'wp_print_head_scripts' ); remove_action( 'wp_head', '_custom_background_cb' ); // ヘッダースタイル add_action( 'wp_head', 'header_style' ); //+++++++++++++++++++++++++++++++++++++++++ //カスタムヘッダー add_custom_image_header('','admin_header_style'); function admin_header_style() {} //標準のヘッダー画像を指定 define('HEADER_IMAGE','%s/images/front/bg_header.jpg'); register_default_headers( array( 'default' => array( 'url' => '%s/images/front/bg_header.jpg', 'thumbnail_url' => '%s/images/front/bg_header.jpg', 'description' => __( 'default', 'default_header' ) ) ) ); //ヘッダー画像の横幅と高さを指定 define('HEADER_IMAGE_WIDTH','520'); define('HEADER_IMAGE_HEIGHT','115'); //ヘッダーの文字を隠す define('NO_HEADER_TEXT',true); function get_custom_css($design_type){ list($conf_designs) = get_posts( array('post_type'=>'design', 'meta_query' => array( array( 'key'=>'design_type', 'value'=>"$design_type", ), ), 'order'=>'ASC' ) ); $style_sheet = ""; if( isset($conf_designs) ): list($get_style) = get_post_meta($conf_designs->ID, 'stylesheet'); $style_sheet = $get_style; endif; return $style_sheet; } function get_ogp_meta(){ $template_type = get_template_type(); $app_ogp = "ogp_" . PAGE_TYPE . "_" . $template_type; if(function_exists($app_ogp)) { return do_shortcode("[" . $app_ogp ."]"); } else { return ""; } } add_shortcode('ogp_meta', 'get_ogp_meta'); function get_template_type(){ global $posts; $app_type = "home"; if ( $posts[0]->{"post_type"} === 'page' ){ $app_type = $posts[0]->{"post_name"}; define( 'PAGE_TYPE', 'page' ); } else { $app_type = $posts[0]->{"post_type"}; $single_id = $posts[0]->{"ID"}; define( 'PAGE_TYPE', 'single' ); define( 'POST_ID', $single_id ); } return $app_type; } function header_style(){ $header_image = get_header_image(); $background_style = get_custom_background(); $custom_style = get_custom_css(get_template_type()); print <<<HEADER_STYLE <style> #header { background: url($header_image); } #wrapper { $background_style } body { overflow-x : hidden ;} $custom_style </style> <script> function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'ja', includedLanguages: 'en,ko,ja', layout: google.translate.TranslateElement.InlineLayout.SIMPLE }, 'google_translate_element'); } </script> <script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> jQuery.event.add(window, "load", function(){ var footer_height = jQuery("#footer").position().top + 200; FB.Canvas.setSize({ height: footer_height }); }); </script> HEADER_STYLE; } if ( is_admin() ){ require_once( ABSPATH . 'wp-admin/custom-background.php' ); $GLOBALS['custom_background'] =& new Custom_Background( $admin_header_callback, $admin_image_div_callback ); add_action( 'admin_menu', array( &$GLOBALS['custom_background'], 'init' ) ); } /** * Default custom background callback. * * @since 3.0.0 * @see add_custom_background() * @access protected */ function get_custom_background() { $background = get_background_image(); $color = get_background_color(); if ( ! $background && ! $color ) return; $style = $color ? "background-color: #$color;" : ''; if ( $background ) { $image = " background-image: url('$background');"; $repeat = get_theme_mod( 'background_repeat', 'repeat' ); if ( ! in_array( $repeat, array( 'no-repeat', 'repeat-x', 'repeat-y', 'repeat' ) ) ) $repeat = 'repeat'; $repeat = " background-repeat: $repeat;"; $position = get_theme_mod( 'background_position_x', 'left' ); if ( ! in_array( $position, array( 'center', 'right', 'left' ) ) ) $position = 'left'; $position = " background-position: top $position;"; $attachment = get_theme_mod( 'background_attachment', 'scroll' ); if ( ! in_array( $attachment, array( 'fixed', 'scroll' ) ) ) $attachment = 'scroll'; $attachment = " background-attachment: $attachment;"; $style .= $image . $repeat . $position . $attachment; } return trim( $style ); } ?>
017leena
lib/func_header.php
PHP
oos
5,663
<?php // FacebookPageにリダイレクト function redirectFB() { if($_GET["app_data"] != "" && !ereg("facebook",$_SERVER['HTTP_USER_AGENT'])){ echo '<meta http-equiv="refresh" CONTENT="0;URL=' . FB_URL . "&app_data=" . $_GET["app_data"] . '" />'; exit; } } function loadIframeFB(){ if ( isset($_REQUEST["signed_request"]) ){ $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); } // Fan Gate if ( isset($data["page"]["liked"]) ){ if ( $data["page"]["liked"] === true ){ } else { echo '<html><head><style>body{overflow-x : hidden ;overflow-y : hidden ;}</style></head><body><img src="'. get_bloginfo('template_url'). '/images/front/fangate.jpg" alt="' . get_bloginfo('name') . '" title="' . get_bloginfo('name') . '" /></body></html>'; exit; } } // like page if ( isset($data["app_data"]) ){ echo '<meta http-equiv="refresh" CONTENT="0;URL=' . get_bloginfo("siteurl") . base64_decode($data["app_data"]) . '" />'; exit; } } // FacebookLikeボタンを取得 function getLikeBottun() { $permalink = get_permalink(); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $like_link = $permalink . '?app_data=' . base64_encode( $appdata ); $like_bottun = '<iframe src="https://www.facebook.com/plugins/like.php?app_id=' . APP_ID . '&href='; $like_bottun .= urlencode($like_link); $like_bottun .= '&amp;send=false&amp;layout=button_count&amp;width=150&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:20px" allowTransparency="true"></iframe>'; return '<!--' . $like_link . '-->' . $like_bottun; //return $like_bottun; } add_shortcode('facebook_like', 'getLikeBottun'); // OGPタグを取得 function getOGPMeta() { global $post, $id; setup_postdata($post); if (is_page_template('custom_photogallary.php')) { $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="Photo Gallary' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_the_post_thumbnail($id) . '" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else if (is_single()) { $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_bloginfo('template_url') . '/images/front/img_head.jpg" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else if (is_attachment()) { $url_large = wp_get_attachment_image_src($id, $size='large'); $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_bloginfo('home') . '/?attachment_id=' . $id . '&app_data=' . base64_encode(get_bloginfo('home')) . '/?attachment_id=' . $id . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . $url_large[0] . '" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; }else{ $OGP_meta = '<meta property="og:type" content="article" />'; $OGP_meta .= '<meta property="og:title" content="「' . get_the_title() . '」" />'; $OGP_meta .= '<meta property="og:url" content="' . get_permalink() . '?app_data=' . base64_encode(get_permalink()) . '" />'; $OGP_meta .= '<meta property="og:description" content="' . get_the_title() . '" />'; $OGP_meta .= '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />'; $OGP_meta .= '<meta property="og:image" content="' . get_bloginfo('template_url') . '/images/front/img_head.jpg" />'; $OGP_meta .= '<meta property="fb:app_id" content="' . APP_ID . '" />'; } return $OGP_meta; } ?>
017leena
lib/mastercontrol.php
PHP
oos
4,997
<?php function header_googleplus(){ print <<<GOOGLE_PLUS <script type="text/javascript"> window.___gcfg = {lang: 'ja'}; (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> GOOGLE_PLUS; } add_action( 'wp_head', 'header_googleplus' ); function header_facebook(){ $appId = APP_ID; print <<<HEADER_FACEBOOK <script type="text/javascript" src="https://connect.facebook.net/ja_JP/all.js"></script> <div id="fb-root"></div> <script type="text/javascript"> FB.init({ appId : '$appId', status : true, // check login status cookie : true, // enable cookies xfbml : true, // parse XFBML logging : true }); </script> HEADER_FACEBOOK; } add_action( 'wp_head', 'header_facebook' ); /* * いいね用 デフォルト */ function get_base_like(){ global $custom_post; if ( isset($custom_post) ){ $ID = $custom_post->ID; $like_title = $custom_post->post_title; } else { $ID = get_the_ID(); $like_title = get_the_title(); } $single_page = '/single/' . get_template_type() . '/' . $ID . '/'; $permalink = get_bloginfo('siteurl') . $single_page; $like_link = $permalink . '?app_data=' . base64_encode( $single_page ); $like_bottun = '<iframe src="https://www.facebook.com/plugins/like.php?app_id=' . APP_ID . '&href='; $like_bottun .= urlencode($like_link); $like_bottun .= '&amp;send=false&amp;layout=button_count&amp;width=68&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:68px; height:20px" allowTransparency="true"></iframe>'; $google_plus = '<div class="g-plusone" data-size="medium" data-annotation="none"></div>'; //$google_plus = ''; $twitter = <<<TWITTER_BUTTON <a href="https://twitter.com/share" class="twitter-share-button" data-url="$like_link" data-text="$like_title" data-lang="ja" data-count="none">ツイート</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> TWITTER_BUTTON; //$twitter = ''; return "\n" . $google_plus . "\n" . $twitter . "\n" . $like_bottun . "\n" . '<!-- facebook_like: ' . $like_link . ' // -->'; } add_shortcode('base_like', 'get_base_like'); add_shortcode('facebook_like', 'get_base_like'); /* * OpenGraphProtocol デフォルト * * Usage: * */ function ogp_single_base_content(){ $ogp_meta = ""; global $wp_query; $og_site = get_bloginfo('name'); $permalink = get_permalink(); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $text_excerpt = strip_tags(htmlspecialchars_decode(get_the_excerpt())); $text_content = $wp_query->{"queried_object"}->{"post_content"}; $default_img = get_bloginfo("template_url") . "/screenshot.png"; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $text_content, $matches)) ? array_unique($matches[1]) : array($default_img); $og_title = get_the_title(); $og_content = $text_excerpt; $refresh = FB_URL . "&app_data=" . urlencode(base64_encode( get_permalink() )); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && ('https' === $_SERVER['HTTP_X_FORWARDED_PROTO']) ){ $og_url = str_replace( "http:", "https:", $og_url ); } $ogp_meta = <<<META_OGP <meta property="og:title" content="$og_title" /> <meta property="og:type" content="article" /> <meta property="og:url" content="$og_url" /> <meta property="og:image" content="$og_image" /> <meta property="og:site_name" content="$og_site" /> <meta property="fb:app_id" content="$og_appId" /> <meta property="og:description" content="$og_content"> <meta property="og:locale" content="ja_JP" /> <meta itemprop="name" content="$og_title"> <meta itemprop="description" content="$og_content"> <meta itemprop="image" content="$og_image"> META_OGP; return $ogp_meta; } add_shortcode('ogp_single_content', 'ogp_single_base_content'); /* * WallPost用 * * @prams og_image 画像 (無くてもよい) * @prams og_url いいね用 URL * @prams title タイトル * @prams message メッセージ * */ function wall_post( $og_image, $og_url, $og_title, $message ){ $fanpage = PAGE_ID; $page_token = ACCESS_TOKEN; if ( $page_token !== "" ): $ch = curl_init(); $params = 'access_token=' . urlencode($page_token); if ( !empty($og_image) ) $params .= '&picture=' . urlencode($og_image); $params .= '&link=' . urlencode($og_url); $params .= '&name=' . urlencode($og_title); $params .= '&message=' . $message; curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'.$fanpage.'/feed'); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $resp = curl_exec($ch); curl_close($ch); endif; } $wppostfix = new WpPostFix(); // 記事が保存されたときに起動する add_action('save_post', array($wppostfix, 'postfix'), 99); //add_action('edit_post', array($wppostfix, 'postfix'), 99); //add_action('publish_post', array($wppostfix, 'postfix'), 99); class WpPostFix { function postfix($postID) { // ウォール投稿多重チェック $wall_posted = get_option( 'wall_posted' ); if ( empty($wall_posted) ){ // 未投稿 add_option( 'wall_posted', $postID, '', 'yes' ); } else { if ( $wall_posted < $postID ){ // 投稿許可 } else { // 投稿済みの為 ここで終了 return $postID; } } global $wpdb; list($result) = $wpdb->get_results("SELECT post_status,post_title,post_type,post_content FROM {$wpdb->posts} WHERE ID = '{$postID}' LIMIT 1"); $post_status = $result->post_status; $content = $result->post_content; $post_type = $result->post_type; $og_title = $result->post_title; $message = br2nl( strip_tags(htmlspecialchars_decode( $content ), '<br>') ); // 誤動作防止 if ( get_bloginfo("siteurl") !== ENABLE_SITE ) { return $postID; } $single_page_url = '/single/' . $post_type . '/' . $postID; $og_url = get_bloginfo("siteurl") . $single_page_url . '?app_data=' . urlencode(base64_encode($single_page_url)); //$og_url = htmlspecialchars_decode(get_post_meta($postID ,'syndication_permalink',true)); // 画像 content 内 // デフォルト画像が必要な時 $default_img = get_bloginfo("template_url") . "/screenshot.png"; // $default_img = null; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $content, $matches)) ? array_unique($matches[1]) : array($default_img); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } // 画像 ここまで // ウォール投稿を許可するカスタムポストタイプ $enable_type = array( 'blog' ); if ( in_array( $post_type , $enable_type ) ): /* * 動作チェック用 * // コンテンツ書き換え */ // $content = $this->blogcontent($post_status, $content); // * // DB をなおした内容でアップデートする // $wpdb->query("UPDATE {$wpdb->posts} SET post_content = '{$content}' WHERE ID = '{$postID}'"); // */ // 公開の投稿をウォールへポスト if ( $post_status === 'publish' ){ // ウォールへポスト wall_post( $og_image, $og_url, $og_title, $message ); update_option( 'wall_posted', $postID ); } endif; // 次の人のために post_id 戻しておく return $postID; } function blogcontent($post_type, $content) { // 書き換えたい内容を記載 $before = 'hogehoge'; $after = 'mogemoge'; $after = $post_type; $content = preg_replace("/$before/i", $after, $content); // 戻す return $content; } } function br2nl($string){ //改行コードのリスト $aBreakTags = array( '/&lt;br&gt;/', '/&lt;br \/&gt;/', '/&lt;BR&gt;/', '/<br>/', '/<BR>/', '/<br \/>/', '/<BR \/>/' ); return preg_replace($aBreakTags ,"\n" , $string ); } function facebook_likeCount($str = null) { if($str) $url = $str; else $url = ((!empty($_SERVER['HTTPS']))? "https://" : "http://").$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $json = file_get_contents('http://graph.facebook.com/' . $url ,true); $data = json_decode($json, true); return ($data['shares'])? $data['shares'] : 0; } ?>
017leena
lib/social.php
PHP
oos
9,425
<?php //+++++++++++++++++++++++++++++++++++++++++ //カスタムメニュー register_nav_menus(array( 'navbar' => 'ナビゲーションバー', 'sidebar' => 'サイドバー' )); function facebook_js(){ print <<<FACEBOOK_HEADER <script type="text/javascript" src="https://connect.facebook.net/en_US/all.js"></script> <script type="text/javascript"> FB.Canvas.setSize({ width: 520, height: 800 }); </script> FACEBOOK_HEADER; } //add_action( 'wp_head', 'facebook_js' ); function header_gnav_script(){ $template_url = get_custom_templateurl(); $local_time = time(); define( CUSTOM_TYPE , get_template_type() ); print <<<HEADER_GNAV <link rel="stylesheet" href="$template_url/css/gnavi.css?$local_time" type="text/css" /> HEADER_GNAV; } add_action( 'wp_head', 'header_gnav_script' ); function get_navi(){ $nav_opt = array( 'menu' => 'gnav', // menu '' カスタムメニューのIDを指定 'container' => 'div', // container 'div' ナビゲーションメニューを囲むタグ名を指定 'container_class' => 'floatClear', // container_class '' ナビゲーションメニューを囲むタグのクラス名を指定 'container_id' => 'gnav', // container_id '' ナビゲーションメニューを囲むタグのIDを指定 'menu_class' => 'navi', // menu_class 'menu' ナビゲーションメニューを囲むタグのクラス名を指定 'echo' => false, // echo true ナビゲーションメニューを表示する場合はtrue、文字列として取得する場合はfalseを指定 'depth' => 0, // depth 0 階層数を指定(0はすべてを表示、1ならばメニューバーのみ)。 'walker' => new MasterControl_Global_Navi(), // walker '' コールバック関数名を指定 'theme_location' => 'navbar', // theme_location '' テーマ内のロケーションIDを指定。 ); return wp_nav_menu($nav_opt); } function print_navi(){ $nav_opt = array( 'menu' => 'gnav', // menu '' カスタムメニューのIDを指定 'container' => 'div', // container 'div' ナビゲーションメニューを囲むタグ名を指定 'container_class' => 'floatClear', // container_class '' ナビゲーションメニューを囲むタグのクラス名を指定 'container_id' => 'gnav', // container_id '' ナビゲーションメニューを囲むタグのIDを指定 'menu_class' => 'navi', // menu_class 'menu' ナビゲーションメニューを囲むタグのクラス名を指定 'echo' => false, // echo true ナビゲーションメニューを表示する場合はtrue、文字列として取得する場合はfalseを指定 'depth' => 0, // depth 0 階層数を指定(0はすべてを表示、1ならばメニューバーのみ)。 'walker' => new MasterControl_Global_Navi(), // walker '' コールバック関数名を指定 'theme_location' => 'navbar', // theme_location '' テーマ内のロケーションIDを指定。 ); print wp_nav_menu($nav_opt); } add_shortcode('gnavi', 'get_navi'); /** * Navigation Menu template functions * * @package WordPress * @subpackage Nav_Menus * @since 3.0.0 */ /** * Create HTML list of nav menu items. * * @package WordPress * @since 3.0.0 * @uses Walker */ class MasterControl_Global_Navi extends Walker_Nav_Menu { /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ function start_el(&$output, $item, $depth, $args) { global $gnavi_Class; global $wp_query; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $LF = "\n"; $class_names = $value = ''; $gnavi_Class = 'menu_' . $item->title; $class_names = ' class="' . esc_attr( 'menu_' . $item->title ) . '" '; $id = ' id="' . esc_attr( 'gnav_' . $item->title ) . '"'; $output .= $indent . '<li' . $id . $value . $class_names .'>' . $LF; $attributes = ' title="' . esc_attr( $item->title ) . '"'; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= strtolower(CUSTOM_TYPE) === strtolower($item->title) ? ' class="current"' : ''; if ( preg_match("/favorites/", $item->url)) { $url = parse_url($item->url); $stockstyle = $url['host'] === "dev.mastercontrol.jp" ? "stage.stockstyle.net" : "stockstyle.net"; $attributes .= 'href="//' . $stockstyle . '/products/facebook.php?osusume_url=' . $url['path'] . '"'; } else { $lang_url = ( isset($_GET["lang"]) ) ? '?lang=' . $_GET["lang"] : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) . $lang_url . '"' : ''; } $item_output = $args->before; $item_output .= '<a'. str_replace( "http:", "", $attributes ) .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ?>
017leena
lib/func_gnavi.php
PHP
oos
5,774
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Info 情報 register_post_type( 'Info', array( 'label' => 'Infomation', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/event.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); function get_info_meta(){ $c = get_post_custom_values('infostart', get_the_ID()); $info["startdate"] = $c[0]; $c = get_post_custom_values('infoend' , get_the_ID()); $info["enddate"] = $c[0]; $c = get_post_custom_values('opendate' , get_the_ID()); $info["opendate"] = $c[0]; $c = get_post_custom_values('closedate' , get_the_ID()); $info["closedate"] = $c[0]; $c = get_post_custom_values('category' , get_the_ID()); $info["category"] = $c[0]; if($info["enddate"] == "" || $info["enddate"] === $info["startdate"]){$info["datelabel"] = $info["startdate"];} if($info["enddate"] != "" && $info["enddate"] != $info["startdate"]){$info["datelabel"] = $info["startdate"] . " - " . $info["enddate"];} return $info; } /* function is_info_disable($info){ $filtered = false; // ##opendate <- -> closedate 以外であれば非表示 if( $info["opendate"] != ""){ if(strtotime( $info["opendate"] ) > time() ){ $filtered = true; }} if( $info["closedate"] != ""){ if(strtotime( $info["closedate"] ) < time() ){ $filtered = true; }} //##月指定があれば絞り込み if(isset($_REQUEST["mon"])){ $filter = date("Y", $_REQUEST["mon"]) . date("m", $_REQUEST["mon"]); $current = date("Y", strtotime($info["startdate"])) . date("m", strtotime($info["startdate"])); if($filter != $current){$filtered = true;} } //##カテゴリ指定があれば絞り込み if(isset($_REQUEST["cat"])){ if($_REQUEST["cat"] != $info["category"]){$filtered = true;} } return $filtered; } */ function get_selectbox_category(){ wp_reset_query(); query_posts('post_type=info'); $catList = array(); if(have_posts()){ while(have_posts()){ the_post(); $e = get_info_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $cat = get_post_custom_values('category', get_the_ID()); $catList[$e["category"]] = ""; } } $catListKeys = array_keys($catList); $selectbox_html = "<select name='cat' id='cat' class='postform' >"; $selectbox_html .= "<option value=''>カテゴリーを選択</option>"; foreach($catListKeys as $k=>$v){ if($_REQUEST["cat"] === $v){$selected = "selected";}else{$selected = "";} $selectbox_html .= '<option class="level-0" value="' . $v . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var catdropdown = document.getElementById('cat');"; $selectbox_html .= " function onCatChange() {"; $selectbox_html .= " location.href = './?cat='+catdropdown.options[catdropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "catdropdown.onchange = onCatChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } add_shortcode('select_category', 'get_selectbox_category'); function get_selectbox_monthly(){ wp_reset_query(); query_posts('post_type=info'); $monthList = array(); if(have_posts()){ while(have_posts()){ the_post(); $e = get_info_meta(); if( $e["opendate"] != ""){ if(strtotime( $e["opendate"] ) > time() ){ continue; }} if( $e["closedate"] != ""){ if(strtotime( $e["closedate"] ) < time() ){ continue; }} $monthList[date("Y", strtotime($e["startdate"])) . "/" . date("n", strtotime($e["startdate"]))] = ""; } } $monthListKeys = array_keys($monthList); $selectbox_html = "<select name='mon' id='mon' class='postform' >"; $selectbox_html .= "<option value=''>月を選択</option>"; foreach($monthListKeys as $k=>$v){ if(intval( $_REQUEST["mon"] ) === strtotime($v."/1")){ $selected = "selected"; }else{ $selected = ""; } $selectbox_html .= '<option class="level-0" value="' . strtotime($v."/1") . '" ' . $selected . '>' . $v . '</option>'; } $selectbox_html .= "</select>"; $selectbox_html .= "<script type='text/javascript'>"; $selectbox_html .= "/* <![CDATA[ */"; $selectbox_html .= "var mondropdown = document.getElementById('mon');"; $selectbox_html .= "function onMonChange() {"; $selectbox_html .= " location.href = './?mon='+mondropdown.options[mondropdown.selectedIndex].value;"; $selectbox_html .= "}"; $selectbox_html .= "mondropdown.onchange = onMonChange;"; $selectbox_html .= "/* ]]> */"; $selectbox_html .= "</script>"; return $selectbox_html; } add_shortcode('select_monthly', 'get_selectbox_monthly'); function get_info_the_title(){ return get_custom_the_title(); } add_shortcode('info_title', 'get_info_the_title'); function get_info_the_content(){ return get_custom_the_content(); } add_shortcode('info_content', 'get_info_the_content'); function get_info_category(){ return get_custom_category(); } add_shortcode('info_category', 'get_info_category'); function get_page_info(){ if ( PAGE_TYPE === 'page' ) { global $custom_post; global $custom_query_posts; $item_content = ""; $items = get_posts($custom_query_posts); if( isset($items) ): for( $i = 0; $i < count( $items ) && $custom_post = $items[$i]; $i++ ) : $item_content .= apply_filters('the_content', constant('INFO_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('info_page' , 'get_page_info'); function get_single_info(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); $item_content = apply_filters('the_content', constant('INFO_HTML_PAGE')); } return $item_content; } add_shortcode('info_single' , 'get_single_info'); function exec_info(){ //echo $_GET["cat"] . "<BR>\n"; global $custom_query_posts; $custom_query_posts = ""; if ( isset($_GET["cat"]) ){ $category = $_GET["cat"]; $custom_query_posts = array( 'post_type'=>'info', 'meta_query' => array( array( 'key'=>'category', 'value'=>"$category", ), array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'posts_per_page'=>10, 'meta_key'=>'infostart', 'orderby'=>'meta_value', 'order'=>'ASC' ); } elseif ( isset($_GET["mon"]) ){ $select_mon = $_GET["mon"]; $startDay = date("Y-m-d", $select_mon); $lastDay = date("Y-m-d", mktime(0, 0, 0, date("m",$select_mon)+1, 0, date("Y",$select_mon))); $custom_query_posts = array( 'meta_query' => array( array( 'key' => 'infostart', 'value' => $startDay, 'compare'=> '>=', 'type' => 'DATE' ), array( 'key' => 'infostart', 'value' => $lastDay, 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'meta_key' => 'infostart', 'orderby' => 'meta_value', 'post_type' => 'info', 'posts_per_page' => 20, 'order' => 'DSC' ); } else { $custom_query_posts = array( 'meta_query' => array( array( 'key' => 'opendate', 'value' => date("Y-m-d"), 'compare'=> '<=', 'type' => 'DATE' ), array( 'key' => 'closedate', 'value' => date("Y-m-d"), 'compare'=> '>=', 'type' => 'DATE' ), 'relation'=>'AND' ), 'meta_key' => 'infostart', 'orderby' => 'meta_value', 'post_type' => 'info', 'posts_per_page' => 20, 'order' => 'DSC' ); } get_import_design("info"); return apply_filters('the_content', INFO_HTML_FRAME); } add_shortcode('run_info', 'exec_info'); ?>
017leena
lib/module/info/func.php
PHP
oos
8,779
<script> var menu_Tag = "Info"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/infomation.css" type="text/css" />
017leena
lib/module/info/header.php
Hack
oos
154
<?php /* //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト photogallery register_post_type( 'photogallery', array( 'label' => 'フォトギャラリー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト DISCOGRAPHY register_post_type( 'discography', array( 'label' => 'ディスコグラフィー', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/discography.png', 'supports' => array( 'title', ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MEDIA register_post_type( 'media', array( 'label' => 'メディア/出演情報', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト MULTI-BLOG register_post_type( 'multiblog', array( 'label' => 'マルチブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); */ ?>
017leena
lib/module/other/func.php
PHP
oos
1,842
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Profile register_post_type( 'profile', array( 'label' => 'Profile', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/profile.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_prof_detail(){ return get_custom_textarea(PROF_ID, 'prof_detail'); } add_shortcode('prof_detail', 'get_prof_detail'); function get_prof_comment(){ return get_custom_textarea(PROF_ID, 'prof_comment'); } add_shortcode('prof_comment', 'get_prof_comment'); function get_prof_image(){ return get_custom_image(PROF_ID, ('prof_image')); } add_shortcode('prof_image', 'get_prof_image'); function exec_profile(){ get_import_design("profile"); list($conf_profile) = get_posts('post_type=profile&order=DSC'); if ( isset( $conf_profile ) ): define('PROF_ID' , $conf_profile->ID); endif; return apply_filters('the_content', PROFILE_HTML_FRAME); } add_shortcode('run_profile', 'exec_profile'); ?>
017leena
lib/module/profile/func.php
PHP
oos
1,135
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト ITUNES register_post_type( 'itunes', array( 'label' => 'iTunes', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/itune.png', 'supports' => array( 'title', 'editor' ) ) ); function exec_itunes(){ print <<<START_ITUNES <div id="main" class="clearfix"> <h2 class="itunes">itunes</h2> START_ITUNES; $itunes_url = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?term=%E7%A7%8B%E8%B5%A4%E9%9F%B3&country=JP&limit=10&entity=album&offset=0"; $itunes_res = json_decode(file_get_contents($itunes_url)); foreach ( $itunes_res->{"results"} as $album ) : $collectionId = $album->{"collectionId"}; echo <<<VIEW_ITUNE_IFRAME <iframe src="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewAlbumSocialPreview?id=$collectionId&s=143462&uo=4&wdId=32800" frameborder="0" scrolling="no" width="500px" height="280px"></iframe> VIEW_ITUNE_IFRAME; endforeach; print <<<END_ITUNES </div> END_ITUNES; } add_shortcode('run_itunes', 'exec_itunes'); ?>
017leena
lib/module/itunes/func.php
PHP
oos
1,227
<script> var menu_Tag = "iTunes"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/itunes.css" type="text/css" />
017leena
lib/module/itunes/header.php
Hack
oos
153
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト BLOG register_post_type( 'blog', array( 'label' => 'ブログ', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/blog.png', 'supports' => array( 'title', 'editor', 'custom-fields' ) ) ); function ogp_single_blog(){ $ogp_meta = ""; global $wp_query; $og_site = get_bloginfo('name'); $permalink = get_permalink(); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $text_excerpt = strip_tags(htmlspecialchars_decode(get_the_excerpt())); $text_content = $wp_query->{"queried_object"}->{"post_content"}; $default_img = get_bloginfo("template_url") . "/screenshot.png"; $all_images = (preg_match_all('~img.+?src="([^"]+?)"~', $text_content, $matches)) ? array_unique($matches[1]) : array($default_img); $og_title = get_the_title(); $og_content = $text_excerpt; $refresh = FB_URL . "&app_data=" . urlencode(base64_encode( get_permalink() )); $maxwidth = 0; foreach ( $all_images as $image ) : $buf_image = @getimagesize($image); if ( $buf_image[0] > $maxwidth ){ $maxwidth = $buf_image[0]; $og_image = $image; } endforeach; if ( empty($og_image) ) { $og_image = $default_img; } if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && ('https' === $_SERVER['HTTP_X_FORWARDED_PROTO']) ){ $og_url = str_replace( "http:", "https:", $og_url ); } $ogp_meta = <<<META_OGP <meta property="og:title" content="$og_title" /> <meta property="og:type" content="article" /> <meta property="og:url" content="$og_url" /> <meta property="og:image" content="$og_image" /> <meta property="og:site_name" content="$og_site" /> <meta property="fb:app_id" content="$og_appId" /> <meta property="og:description" content="$og_content"> <meta property="og:locale" content="ja_JP" /> META_OGP; return $ogp_meta; } // add_shortcode('ogp_single_blog', 'ogp_single_blog'); function get_blog_the_title(){ return get_custom_the_title(); } add_shortcode('blog_title', 'get_blog_the_title'); function get_blog_the_content(){ $content = str_replace('img src="', 'img src="/img.php?imgurl=', get_custom_the_content()); $content = str_replace('a href="', 'a target="_blank" href="', $content); $content = strip_tags( $content , '<img><br>'); return $content; } add_shortcode('blog_content', 'get_blog_the_content'); function get_blog_date(){ return date('Y年m月d日', SimplePie_Parse_Date::get()->parse(get_custom_date())); } add_shortcode('blog_date', 'get_blog_date'); function get_blog_url(){ global $custom_post; return get_post_meta($custom_post->ID ,'syndication_permalink',true); } add_shortcode('blog_url', 'get_blog_url'); function get_blog_like(){ global $custom_post; $single_page = '/single/blog/' . $custom_post->ID . '/'; $permalink = get_bloginfo('siteurl') . $single_page; $like_link = $permalink . '?app_data=' . base64_encode( $single_page ); $like_bottun = '<iframe src="https://www.facebook.com/plugins/like.php?app_id=' . APP_ID . '&href='; $like_bottun .= urlencode($like_link); $like_bottun .= '&amp;send=false&amp;layout=button_count&amp;width=150&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:20px" allowTransparency="true"></iframe>'; return "\n" . $like_bottun . "\n" . '<!-- facebook_like: ' . $like_link . ' // -->'; } //add_shortcode('blog_like', 'get_blog_like'); function get_pagenavi(){ $navi_html = ""; $navi_html = '<div class="tablenav">'; $paged = get_query_var('paged'); $paginate_base = get_pagenum_link(1); global $wp_rewrite; global $max_pages; if (strpos($paginate_base, '?') || ! $wp_rewrite->using_permalinks()) { $paginate_format = ''; $paginate_base = add_query_arg('paged', '%#%'); } else { $paginate_format = (substr($paginate_base, -1 ,1) == '/' ? '' : '/') . user_trailingslashit('page/%#%/', 'paged');; $paginate_base .= '%_%'; } $navi_html .= paginate_links( array( 'base' => $paginate_base, 'format' => $paginate_format, 'total' => $max_pages, 'mid_size' => 3, 'current' => ($paged ? $paged : 1), 'prev_text' => '&laquo;', 'next_text' => '&raquo;', )); $navi_html .= '</div>'; return str_replace('http:', '', $navi_html); } add_shortcode('pagenavi', 'get_pagenavi'); function get_page_blog(){ if ( PAGE_TYPE === 'page' ) { global $custom_post; global $custom_query_posts; $item_content = ""; wp_reset_query(); query_posts($custom_query_posts); global $wp_query; global $max_pages; $max_pages = $wp_query->{"max_num_pages"}; $item_content .= do_shortcode('[pagenavi]'); if( isset($wp_query) ): $items = $wp_query->{"posts"}; for( $i = 0; $i < count( $items ) && $custom_post = $items[$i]; $i++ ) : $item_content .= do_shortcode( constant('BLOG_HTML_PAGE') ); endfor; endif; return $item_content; } return; } add_shortcode('blog_page' , 'get_page_blog'); function get_single_blog(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); if(have_posts()): while(have_posts()): the_post(); $item_content = do_shortcode( constant('BLOG_HTML_SINGLE') ); endwhile; endif; } return $item_content; } add_shortcode('blog_single' , 'get_single_blog'); function exec_blog(){ global $custom_query_posts; $blog_content = ""; $paged = get_query_var('paged'); $custom_query_posts = "post_type=blog&posts_per_page=2&paged=$paged&order=DSC"; get_import_design("blog"); //return apply_filters('the_content', BLOG_HTML_FRAME); return do_shortcode( constant('BLOG_HTML_FRAME') ); } add_shortcode('run_blog', 'exec_blog');
017leena
lib/module/blog/func.php
PHP
oos
6,402
<?php register_post_type( 'gallery', array( 'label' => 'Gallery', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/media.png', 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail' ) ) ); function exec_gallery(){ $gallery_content = ""; wp_reset_query();query_posts('post_type=gallery&order=ASC'); if(have_posts()): while(have_posts()): the_post(); echo the_title() . "<br>\n"; echo the_content(); echo the_permalink() . "<br>\n"; endwhile; endif; //get_import_design("gallery"); //return apply_filters('the_content', GALLERY_HTML_FRAME); } add_shortcode('run_gallery', 'exec_gallery'); //+++++++++++++++++++++++++++++++++++++++++ // ギャラリー用facebookいいねボタン追加 /* デフォルトのショートコードを削除 */ remove_shortcode('gallery', 'gallery_shortcode'); /* 新しい関数を定義 */ add_shortcode('gallery', 'my_gallery_shortcode'); function my_gallery_shortcode($attr) { global $post, $wp_locale; static $instpe = 0; $instpe++; // Allow plugins/themes to override the default gallery template. $output = apply_filters('post_gallery', '', $attr); if ( $output != '' ) return $output; // We're trusting author input, so let's at least make sure it looks like a valid orderby statement if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( !$attr['orderby'] ) unset( $attr['orderby'] ); } extract(shortcode_atts(array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post->ID, 'itemtag' => 'dl', 'icontag' => 'dt', 'captiontag' => 'dd', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'exclude' => '' ), $attr)); $id = intval($id); if ( 'RAND' == $order ) $orderby = 'none'; if ( !empty($include) ) { $include = preg_replace( '/[^0-9,]+/', '', $include ); $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( !empty($exclude) ) { $exclude = preg_replace( '/[^0-9,]+/', '', $exclude ); $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } else { $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } if ( empty($attachments) ) return ''; if ( is_feed() ) { $output = "¥n"; foreach ( $attachments as $att_id => $attachment ) $output .= wp_get_attachment_link($att_id, $size, true) . "¥n"; return $output; } $itemtag = tag_escape($itemtag); $captiontag = tag_escape($captiontag); $columns = intval($columns); $itemwidth = $columns > 0 ? floor(100/$columns) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = "gallery-{$instpe}"; $output = apply_filters('gallery_style', " <style type='text/css'> #{$selector} { margin: auto; } #{$selector} .gallery-item { float: {$float}; margin-top: 10px; text-align: center; width: {$itemwidth}%; } #{$selector} img { border: 2px solid #cfcfcf; } #{$selector} .gallery-caption { margin-left: 0; } </style> <!-- see gallery_shortcode() in wp-includes/media.php --> <div id='$selector' class='gallery galleryid-{$id}'>"); $i = 0; foreach ( $attachments as $id => $attachment ) { echo "<!--" . var_dump($attachment) . "-->\n"; $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false); echo "\n<!-- link: " . $link . " /link -->"; $output .= "<{$itemtag} class='gallery-item'>"; $output .= " <{$icontag} class='gallery-icon'> $link </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <{$captiontag} class='gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>"; } $url_thumbnail = wp_get_attachment_image_src($id, $size='thumbnail'); $url = urlencode(get_bloginfo('home') . '/?attachment_id=' . $id); $url .= urlencode('&app_data=' . get_bloginfo('home') . '/?attachment_id=' . $id); $output .= '<p><div class="btn_like"><iframe src="http://www.facebook.com/plugins/like.php?href='; $output .= $url; $output .= '&amp;id=fb&amp;send=false&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=like&amp;colorscheme=light$amp;locale=ja_JA&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:21px;" allowTransparency="true"></iframe></div></p>'; $output .= "</{$itemtag}>"; if ( $columns > 0 && ++$i % $columns == 0 ) $output .= '<br style="clear: both" />'; } $output .= "</div>"; return $output; } function remove_gallery_css() { return "<div id='gallery_box'>"; } add_filter('gallery_style', 'remove_gallery_css'); function fix_gallery_output( $output ){ /* $output = preg_replace("%<br style=.*clear: both.* />%", "", $output); $output = preg_replace("%<dl class='gallery-item'>%", "<div class='photobox'>", $output); $output = preg_replace("%<dt class='gallery-icon'>%", "", $output); $output = preg_replace("%</dl>%", "</div>", $output); $output = preg_replace("%</dt>%", "", $output); */ return $output; } add_filter('the_content', 'fix_gallery_output',11, 1); //+++++++++++++++++++++++++++++++++++++++++ ?>
017leena
lib/module/gallery/func.php
PHP
oos
6,174
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト PV (YouTube) register_post_type( 'pv', array( 'label' => 'PV', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/youtube.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function ogp_page_pv(){ $ogp_meta = ""; list($ogp_post) = get_posts("post_type=pv&order=DSC"); if(have_posts()): the_post(); //$ogp_meta = ogp_single_pv(); setup_postdata($ogp_post); $og_site = get_bloginfo('name'); $permalink = get_permalink(); $youtube_url = get_post_meta($ogp_post->ID, 'URL', true); $contents = file_get_contents("https://youtu.be/" . $youtube_url); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $htmls = split ( "\n" , $contents ); foreach ( $htmls as $linehtml ){ if ( preg_match('/"og:([^"]+)"/', $linehtml, $matchline) ){ if ( $matchline[1] === "url" ) { $ogp_meta .= '<meta property="og:url" content="'.$og_url.'" />' . "\n"; } elseif ( $matchline[1] === "site_name" ){ $ogp_meta .= '<meta property="og:site_name" content="'.$og_site.'" />' . "\n"; } else { $ogp_meta .= $linehtml . "\n"; } } } endif; $ogp_meta .= '<meta property="og:locale" content="ja_JP" />' . "\n"; return $ogp_meta; } add_shortcode('ogp_page_pv', 'ogp_page_pv'); function ogp_single_pv(){ $ogp_meta = ""; $og_site = get_bloginfo('name'); $permalink = get_permalink(); $youtube_url = get_post_meta(get_the_ID(), 'URL', true); $contents = file_get_contents("https://youtu.be/" . $youtube_url); $appdata = str_replace(get_bloginfo("siteurl"), "", $permalink); $og_url = $permalink . '?app_data=' . urlencode(base64_encode( $appdata )); $og_appId = APP_ID; $htmls = split ( "\n" , $contents ); foreach ( $htmls as $linehtml ){ if ( preg_match('/"og:([^"]+)"/', $linehtml, $matchline) ){ if ( $matchline[1] === "url" ) { $ogp_meta .= '<meta property="og:url" content="'.$og_url.'" />' . "\n"; } elseif ( $matchline[1] === "site_name" ){ $ogp_meta .= '<meta property="og:site_name" content="'.$og_site.'" />' . "\n"; } else { $ogp_meta .= $linehtml . "\n"; } } } $ogp_meta .= '<meta property="og:locale" content="ja_JP" />'; return $ogp_meta; } add_shortcode('ogp_single_pv', 'ogp_single_pv'); function get_custom_title(){ return get_custom_text(get_the_ID(), 'タイトル'); } add_shortcode('pv_title', 'get_custom_title'); function get_custom_url(){ return get_custom_text(get_the_ID(), 'URL'); } add_shortcode('youtubeID', 'get_custom_url'); function get_custom_detail(){ return get_custom_text(get_the_ID(), '説明文'); } add_shortcode('pv_detail', 'get_custom_detail'); function get_page_pv(){ if ( PAGE_TYPE === 'page' ) { global $custom_query_posts; $item_content = ""; query_posts($custom_query_posts); if(have_posts()): while(have_posts()): the_post(); $item_content .= apply_filters('the_content', constant('PV_HTML_PAGE')); endwhile; endif; return $item_content; } return; } add_shortcode('pv_page' , 'get_page_pv'); function get_single_pv(){ $item_content = ""; if ( PAGE_TYPE === 'single' ) { global $custom_post; $custom_post = wp_get_single_post( POST_ID, 'OBJECT' ); if(have_posts()): while(have_posts()): the_post(); $item_content = apply_filters('the_content', constant('PV_HTML_SINGLE')); endwhile; endif; } return $item_content; } add_shortcode('pv_single' , 'get_single_pv'); function exec_pv(){ global $custom_query_posts; $custom_query_posts = "post_type=pv&order=DSC"; get_import_design("pv"); return apply_filters('the_content', PV_HTML_FRAME); } add_shortcode('run_pv', 'exec_pv'); ?>
017leena
lib/module/pv/func.php
PHP
oos
4,045
<?php register_post_type( 'goods_book', array( 'label' => 'Goods_BOOK', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/goods.png', 'supports' => array( 'title', 'custom-fields' ) ) ); register_post_type( 'goods_cd', array( 'label' => 'Goods_CD', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/goods.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_item_detail(){ global $goods_id; return get_custom_textarea($goods_id, 'item_detail'); } add_shortcode('item_detail', 'get_item_detail'); function get_item_title(){ global $goods_id; return get_custom_textarea($goods_id, 'item_title'); } add_shortcode('item_title', 'get_item_title'); function get_item_image(){ global $goods_id; return get_custom_image($goods_id, 'item_image'); } add_shortcode('item_image', 'get_item_image'); function get_page_book(){ if ( PAGE_TYPE === 'page' ) { global $goods_id; get_import_design("goods_book"); $item_content = ""; $items = get_posts("post_type=goods_book&order=DSC"); if( isset($items) ): for( $i = 0; $i < count( $items ) && $item = $items[$i]; $i++ ) : $goods_id = $item->ID; $item_content .= apply_filters('the_content', constant('GOODS_BOOK_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('book_page' , 'get_page_book'); function get_page_cd(){ if ( PAGE_TYPE === 'page' ) { global $goods_id; get_import_design("goods_cd"); $item_content = ""; $items = get_posts('post_type=goods_cd&order=DSC'); if( isset($items) ): for( $i = 0; $i < count( $items ) && $item = $items[$i]; $i++ ) : $goods_id = $item->ID; $item_content .= apply_filters('the_content', constant('GOODS_CD_HTML_PAGE')); endfor; endif; return $item_content; } return; } add_shortcode('cd_page' , 'get_page_cd'); function get_single_cd(){ if ( PAGE_TYPE === 'single' ) { global $goods_id; get_import_design("goods_cd"); $goods_id = POST_ID; $item_content .= apply_filters('the_content', constant('GOODS_CD_HTML_SINGLE')); return $item_content; } return; } add_shortcode('cd_single' , 'get_single_cd'); function get_single_book(){ if ( PAGE_TYPE === 'single' ) { global $goods_id; get_import_design("goods_book"); //$items = wp_get_single_post(POST_ID, 'ARRAY_A'); $goods_id = POST_ID; $item_content .= apply_filters('the_content', constant('GOODS_BOOK_HTML_SINGLE')); return $item_content; } return; } add_shortcode('book_single' , 'get_single_book'); function exec_goods_book(){ get_import_design('goods_book'); return apply_filters('the_content', constant('GOODS_BOOK_HTML_FRAME')); } add_shortcode('run_goods_book', 'exec_goods_book'); function exec_goods_cd(){ get_import_design('goods_cd'); return apply_filters('the_content', constant('GOODS_CD_HTML_FRAME')); } add_shortcode('run_goods_cd', 'exec_goods_cd'); function exec_goods(){ get_import_design("goods"); return apply_filters('the_content', GOODS_HTML_FRAME); } add_shortcode('run_goods', 'exec_goods'); ?>
017leena
lib/module/goods/func.php
PHP
oos
3,400
<script> var menu_Tag = "Goods"; </script> <link rel="stylesheet" href="/008akiakane/wp-content/themes/008akiakane/css/goods.css" type="text/css" />
017leena
lib/module/goods/header.php
Hack
oos
151
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト Twitter register_post_type( 'twitter', array( 'label' => 'Twitter', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/twitter.png', 'supports' => array( 'title' ) ) ); function get_twitter_account(){ return get_custom_text(TWITTER_ID, ('Twitter')); } add_shortcode('twitter_account', 'get_twitter_account'); function exec_twitter(){ get_import_design("twitter"); list($conf_twitter) = get_posts('post_type=twitter&order=DSC'); if ( isset( $conf_twitter ) ): define('TWITTER_ID' , $conf_twitter->ID); endif; return apply_filters('the_content', TWITTER_HTML_FRAME); } add_shortcode('run_twitter', 'exec_twitter'); ?>
017leena
lib/module/twitter/func.php
PHP
oos
884
<?php //+++++++++++++++++++++++++++++++++++++++++ // カスタムポスト デザイン register_post_type( 'design', array( 'label' => 'デザイン', 'hierarchical' => false, 'public' => true, 'query_var' => false, 'menu_icon' => get_bloginfo('template_url').'/images/tool/master_control_logo.png', 'supports' => array( 'title', 'custom-fields' ) ) ); function get_css_design($design_type){ list($conf_designs) = get_posts( array('post_type'=>'design', 'meta_query' => array( array( 'key'=>'design_type', 'value'=>"$design_type", ), ), 'order'=>'ASC' ) ); $style_sheet = ""; if( isset($conf_designs) ): list($get_style) = get_post_meta($conf_designs->ID, 'stylesheet'); $style_sheet = $get_style; endif; return $style_sheet; } function get_import_design($design_type){ // Design Template OUTPUT  $design = array(); list($conf_designs) = get_posts(array('post_type'=>'design','meta_key'=>'design_type','meta_value'=>"$design_type",'order'=>'ASC')); if( isset($conf_designs) ): // $title = $conf_designs->post_title; list($conf_design_type) = get_post_meta($conf_designs->ID, 'design_type'); list($design["html_frame"]) = get_post_meta($conf_designs->ID, 'html_frame'); list($design["html_page"]) = get_post_meta($conf_designs->ID, 'html_page'); list($design["html_single"]) = get_post_meta($conf_designs->ID, 'html_single'); $frame_name = strtoupper($design_type) . '_HTML_FRAME'; define($frame_name, $design["html_frame"] ); $frame_name = strtoupper($design_type) . '_HTML_SINGLE'; define($frame_name, $design["html_single"] ); $frame_name = strtoupper($design_type) . '_HTML_PAGE'; define($frame_name, $design["html_page"] ); endif; return $design; } ?>
017leena
lib/design/func.php
PHP
oos
1,892
goog.provide('bentlyschemistrylab.GamePlayer'); goog.require("lime.Sprite"); goog.require("lime.Label"); goog.require("lime.RoundedRect"); goog.require("lime.fill.Frame"); goog.require("lime.audio.Audio"); var objMap = { easy : [ {answer: "Hydrogen", x: 0, y: 0, width: 128, height: 128}, {answer: "Helium", x: 128, y: 0, width: 128, height: 128}, {answer: "Boron", x: 256, y: 0, width: 128, height: 128}, {answer: "Carbon", x: 384, y: 0, width: 128, height: 128}, {answer: "Nitrogen", x: 512, y: 0, width: 128, height: 128}, {answer: "Oxygen", x: 640, y: 0, width: 128, height: 128}, {answer: "Fluorine", x: 768, y: 0, width: 128, height: 128}, {answer: "Neon", x: 896, y: 0, width: 128, height: 128}, {answer: "Sodium", x: 1024, y: 0, width: 128, height: 128}, {answer: "Magnesium", x: 1152, y: 0, width: 128, height: 128}, {answer: "Aluminium", x: 1280, y: 0, width: 128, height: 128}, {answer: "Silicon", x: 1408, y: 0, width: 128, height: 128}, {answer: "Phosphorus", x: 1536, y: 0, width: 128, height: 128}, {answer: "Sulfur", x: 1664, y: 0, width: 128, height: 128}, {answer: "Chlorine", x: 1792, y: 0, width: 128, height: 128}, {answer: "Calcium", x: 0, y: 128, width: 128, height: 128}, {answer: "Titanium", x: 128, y: 128, width: 128, height: 128}, {answer: "Vanadium", x: 256, y: 128, width: 128, height: 128}, {answer: "Cobalt", x: 384, y: 128, width: 128, height: 128}, {answer: "Nickel", x: 512, y: 128, width: 128, height: 128}, {answer: "Copper", x: 640, y: 128, width: 128, height: 128}, {answer: "Zinc", x: 768, y: 128, width: 128, height: 128}, {answer: "Krypton", x: 896, y: 128, width: 128, height: 128}, {answer: "Iodine", x: 1024, y: 128, width: 128, height: 128}, {answer: "Xenon", x: 1152, y: 128, width: 128, height: 128}, {answer: "Platinum", x: 1280, y: 128, width: 128, height: 128}, {answer: "Radon", x: 1408, y: 128, width: 128, height: 128}, {answer: "Francium", x: 1536, y: 128, width: 128, height: 128}, {answer: "Radium", x: 1664, y: 128, width: 128, height: 128} ], medium: [ {answer: "Lithium", x: 0, y: 256, width: 128, height: 128}, {answer: "Beryllium", x: 128, y: 256, width: 128, height: 128}, {answer: "Potassium", x: 256, y: 256, width: 128, height: 128}, {answer: "Argon", x: 384, y: 256, width: 128, height: 128}, {answer: "Scandium", x: 512, y: 256, width: 128, height: 128}, {answer: "Iron", x: 640, y: 256, width: 128, height: 128}, {answer: "Chromium", x: 768, y: 256, width: 128, height: 128}, {answer: "Manganese", x: 896, y: 256, width: 128, height: 128}, {answer: "Gallium", x: 1024, y: 256, width: 128, height: 128}, {answer: "Germanium", x: 1152, y: 256, width: 128, height: 128}, {answer: "Arsenic", x: 1280, y: 256, width: 128, height: 128}, {answer: "Selenium", x: 1408, y: 256, width: 128, height: 128}, {answer: "Bromine", x: 1536, y: 256, width: 128, height: 128}, {answer: "Rubidium", x: 1664, y: 256, width: 128, height: 128}, {answer: "Strontium", x: 1792, y: 256, width: 128, height: 128}, {answer: "Yttrium", x: 0, y: 384, width: 128, height: 128}, {answer: "Silver", x: 128, y: 384, width: 128, height: 128}, {answer: "Tin", x: 256, y: 384, width: 128, height: 128}, {answer: "Zirconium", x: 384, y: 384, width: 128, height: 128}, {answer: "Ruthenium", x: 512, y: 384, width: 128, height: 128}, {answer: "Barium", x: 640, y: 384, width: 128, height: 128}, {answer: "Tungsten", x: 768, y: 384, width: 128, height: 128}, {answer: "Gold", x: 896, y: 384, width: 128, height: 128}, {answer: "Mercury", x: 1024, y: 384, width: 128, height: 128}, {answer: "Lead", x: 1152, y: 384, width: 128, height: 128}, {answer: "Bismuth", x: 1280, y: 384, width: 128, height: 128}, {answer: "Polonium", x: 1408, y: 384, width: 128, height: 128} ], hard: [ {answer: "Niobium", x: 0, y: 512, width: 128, height: 128}, {answer: "Molybdenum", x: 128, y: 512, width: 128, height: 128}, {answer: "Technetium", x: 256, y: 512, width: 128, height: 128}, {answer: "Rhodium", x: 384, y: 512, width: 128, height: 128}, {answer: "Palladium", x: 512, y: 512, width: 128, height: 128}, {answer: "Cadmium", x: 640, y: 512, width: 128, height: 128}, {answer: "Indium", x: 768, y: 512, width: 128, height: 128}, {answer: "Antimony", x: 896, y: 512, width: 128, height: 128}, {answer: "Tellurium", x: 1024, y: 512, width: 128, height: 128}, {answer: "Caesium", x: 1152, y: 512, width: 128, height: 128}, {answer: "Lanthanum", x: 1280, y: 512, width: 128, height: 128}, {answer: "Cerium", x: 1408, y: 512, width: 128, height: 128}, {answer: "Praseodymium", x: 1536, y: 512, width: 128, height: 128}, {answer: "Neodymium", x: 1664, y: 512, width: 128, height: 128}, {answer: "Promethium", x: 1792, y: 512, width: 128, height: 128}, {answer: "Samarium", x: 0, y: 640, width: 128, height: 128}, {answer: "Europium", x: 128, y: 640, width: 128, height: 128}, {answer: "Gadolinium", x: 256, y: 640, width: 128, height: 128}, {answer: "Terbium", x: 384, y: 640, width: 128, height: 128}, {answer: "Dysprosium", x: 512, y: 640, width: 128, height: 128}, {answer: "Holmium", x: 640, y: 640, width: 128, height: 128}, {answer: "Erbium", x: 768, y: 640, width: 128, height: 128}, {answer: "Thulium", x: 896, y: 640, width: 128, height: 128}, {answer: "Ytterbium", x: 1024, y: 640, width: 128, height: 128}, {answer: "Lutetium", x: 1152, y: 640, width: 128, height: 128}, {answer: "Hafnium", x: 1280, y: 640, width: 128, height: 128}, {answer: "Tantalum", x: 1408, y: 640, width: 128, height: 128} ], imageFile: "asset/graphic/game/Chemistry.png" }; var maxTimer = 10000; bentlyschemistrylab.GamePlayer = function(gameObj, gameLayer, gameOverCallback) { goog.base(this); this.gameObj = gameObj; this.gameLayer = gameLayer; this.gameOverCallback = gameOverCallback; this.setPosition(0, 0); this.setAnchorPoint(0, 0); this.setSize(gameObj.width, gameObj.height); this.setFill("asset/graphic/screen/GameScreen.png"); this.curTime = 0; this.timeIncrement = 5000; this.active = false; this.correctSound = new lime.audio.Audio("asset/sound/RightAnswer.wav"); this.wrongSound = new lime.audio.Audio("asset/sound/WrongAnswer.wav"); this.correctAnswer = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.otherAnswer1 = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.otherAnswer2 = new lime.Sprite().setAnchorPoint(0.5, 0.5); this.answerLabel = new lime.Label() .setAnchorPoint(0.5, 0.5) .setFontColor("#0000FF") .setFontSize(58); this.timeBar = new lime.RoundedRect() .setAnchorPoint(0, 0) .setRadius(0) .setPosition(0, 508) .setSize(gameObj.width, 5) .setFill("#00FF00"); goog.events.listen(this.correctAnswer, ["touchstart", "mousedown"], function(e) { this.getParent().correctSound.play(); this.getParent().increaseTimer(); this.getParent().nextQuestion(); }); goog.events.listen(this.otherAnswer1, ["touchstart", "mousedown"], function(e) { this.getParent().wrongSound.play(); this.getParent().decreaseTimer(); this.getParent().nextQuestion(); }); goog.events.listen(this.otherAnswer2, ["touchstart", "mousedown"], function(e) { this.getParent().wrongSound.play(); this.getParent().decreaseTimer(); this.getParent().nextQuestion(); }); this.appendChild(this.correctAnswer); this.appendChild(this.otherAnswer1); this.appendChild(this.otherAnswer2); this.appendChild(this.answerLabel); this.appendChild(this.timeBar); this.initialize(gameObj); lime.scheduleManager.schedule(function(dt) { this.update(dt); }, this); this.nextQuestion(); }; goog.inherits(bentlyschemistrylab.GamePlayer, lime.Sprite); bentlyschemistrylab.GamePlayer.prototype.initialize = function(gameObj) { this.curDifficulty = gameObj.curDifficulty; this.curTime = maxTimer; this.active = true; }; bentlyschemistrylab.GamePlayer.prototype.nextQuestion = function() { var choices = objMap; var imageFile = choices.imageFile; switch(this.curDifficulty){ case 1: choices = choices.easy; break; case 2: choices = choices.medium; break; case 3: choices = choices.hard; break; } var numChoices = choices.length; var cBtn = choices[Math.floor(Math.random() * numChoices)]; var iBtn1 = choices[Math.floor(Math.random() * numChoices)]; var iBtn2 = choices[Math.floor(Math.random() * numChoices)]; var cFrame = new lime.fill.Frame(imageFile, cBtn.x, cBtn.y, cBtn.width, cBtn.height); var iFrame1 = new lime.fill.Frame(imageFile, iBtn1.x, iBtn1.y, iBtn1.width, iBtn1.height); var iFrame2 = new lime.fill.Frame(imageFile, iBtn2.x, iBtn2.y, iBtn2.width, iBtn2.height); this.answerLabel.setText(cBtn.answer).setPosition(this.gameObj.width / 2, 585); var pos = [ {x: 240, y: 120}, {x: 100, y: 350}, {x: 380, y: 350}, {x: 240, y: 120}, {x: 100, y: 350} ]; var startPos = Math.floor(Math.random() * 3); this.correctAnswer .setSize(cBtn.width, cBtn.height) .setFill(cFrame).setPosition(pos[startPos].x, pos[startPos].y); this.otherAnswer1 .setSize(iBtn1.width, iBtn1.height) .setFill(iFrame1).setPosition(pos[startPos + 1].x, pos[startPos + 1].y); this.otherAnswer2 .setSize(iBtn2.width, iBtn2.height) .setFill(iFrame2).setPosition(pos[startPos + 2].x, pos[startPos + 2].y); }; bentlyschemistrylab.GamePlayer.prototype.update = function(dt) { if(this.active) { if(this.curTime > 0) { this.curTime -= dt; this.timeBar.setSize((this.curTime / maxTimer) * this.gameObj.width, 5); } else { this.active = false; this.gameOverCallback(); } } }; bentlyschemistrylab.GamePlayer.prototype.increaseTimer = function() { this.curTime += this.timeIncrement; if(this.curTime > maxTimer) { this.curTime = maxTimer; } }; bentlyschemistrylab.GamePlayer.prototype.decreaseTimer = function() { this.curTime -= 10; if(this.timeIncrement > 250) { this.timeIncrement -= 50; } };
06-june-1gam-bently-lab
trunk/gamePlayer.js
JavaScript
gpl3
10,192
//set main namespace goog.provide('bentlyschemistrylab'); //get requirements goog.require("lime.Director"); goog.require("lime.Scene"); goog.require("lime.Layer"); goog.require("lime.transitions.Dissolve"); goog.require("lime.audio.Audio"); goog.require('bentlyschemistrylab.GamePlayer'); // entrypoint bentlyschemistrylab.start = function() { var gameObj = { width: 480, height: 640, renderer: lime.Renderer.CANVAS, curMode: 1, curDifficulty: 1 }; var director = new lime.Director(document.getElementById("gameContainer"), gameObj.width, gameObj.height); var titleScene = new lime.Scene(); var difficultyScene = new lime.Scene(); var gameScene = new lime.Scene(); var creditScene = new lime.Scene(); var titleLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var difficultyLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var gameLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); var creditLayer = new lime.Layer().setAnchorPoint(0, 0).setRenderer(gameObj.renderer).setPosition(0, 0); titleScene.appendChild(titleLayer); difficultyScene.appendChild(difficultyLayer); gameScene.appendChild(gameLayer); creditScene.appendChild(creditLayer); var menuSound = new lime.audio.Audio("asset/sound/MenuSelect.wav"); // Title Screen Objects var titleImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/TitleScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); titleLayer.appendChild(titleImage); var startButton = new lime.Sprite() .setSize(320, 230) .setFill("asset/graphic/button/StartButton.png") .setAnchorPoint(0, 0) .setPosition(75, 330); titleLayer.appendChild(startButton); goog.events.listen(startButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); director.replaceScene(difficultyScene, lime.transitions.Dissolve, 0.5); difficultyLayer.setDirty(255); }); // Difficult Select Screen Objects var difficultySelectImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/DifficultySelectScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); difficultyLayer.appendChild(difficultySelectImage); var easyButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/EasyButton.png") .setAnchorPoint(0, 0) .setPosition(80, 250); difficultyLayer.appendChild(easyButton); goog.events.listen(easyButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 1; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); var mediumButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/MediumButton.png") .setAnchorPoint(0, 0) .setPosition(80, 350); difficultyLayer.appendChild(mediumButton); goog.events.listen(mediumButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 2; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); var hardButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/HardButton.png") .setAnchorPoint(0, 0) .setPosition(80, 450); difficultyLayer.appendChild(hardButton); goog.events.listen(hardButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); gameObj.curDifficulty = 3; gamePlayer.initialize(gameObj); director.replaceScene(gameScene, lime.transitions.Dissolve, 0.5); gameLayer.setDirty(255); }); // Game Screen Objects var gamePlayer = new bentlyschemistrylab.GamePlayer(gameObj, gameLayer, function() { director.replaceScene(creditScene, lime.transitions.Dissolve, 0.5); creditLayer.setDirty(255); }); gameLayer.appendChild(gamePlayer); // Credit Screen Objects var creditImage = new lime.Sprite() .setSize(gameObj.width, gameObj.height) .setFill("asset/graphic/screen/CreditScreen.png") .setAnchorPoint(0, 0) .setPosition(0, 0); creditLayer.appendChild(creditImage); var continueButton = new lime.Sprite() .setSize(320, 70) .setFill("asset/graphic/button/ContinueButton.png") .setAnchorPoint(0, 0) .setPosition(80, 400); creditLayer.appendChild(continueButton); goog.events.listen(continueButton, ["touchstart", "mousedown"], function(e) { menuSound.play(); director.replaceScene(titleScene, lime.transitions.Dissolve, 0.5); titleLayer.setDirty(255); }); director.makeMobileWebAppCapable(); director.replaceScene(titleScene); } //this is required for outside access after code is compiled in ADVANCED_COMPILATIONS mode goog.exportSymbol('bentlyschemistrylab.start', bentlyschemistrylab.start);
06-june-1gam-bently-lab
trunk/bentlyschemistrylab.js
JavaScript
gpl3
4,985
<!DOCTYPE HTML> <html> <head> <title>bentlyschemistrylab</title> <script type="text/javascript" src="../closure/closure/goog/base.js"></script> <script type="text/javascript" src="bentlyschemistrylab.js"></script> </head> <body onload="bentlyschemistrylab.start()"> <div id="gameContainer" style="width: 480px; height: 640px; margin: auto;"></div> </body> </html>
06-june-1gam-bently-lab
trunk/bentlyschemistrylab.html
HTML
gpl3
383