Compare commits

..

2 Commits

Author SHA1 Message Date
Marcelo Roberto Jimenez
84692a6e84 Creating a tag for release 1.6.0.
git-svn-id: https://pupnp.svn.sourceforge.net/svnroot/pupnp/tags/release-1.6.0@211 119443c7-1b9e-41f8-b6fc-b9c35fce742c
2007-06-23 14:24:54 +00:00
Marcelo Roberto Jimenez
2a76749682 Creating branch 1.6.x.
git-svn-id: https://pupnp.svn.sourceforge.net/svnroot/pupnp/branches/branch-1.6.x@210 119443c7-1b9e-41f8-b6fc-b9c35fce742c
2007-06-23 14:23:29 +00:00
32 changed files with 2800 additions and 3057 deletions

View File

@@ -1,88 +1,3 @@
*******************************************************************************
Version 1.6.2
*******************************************************************************
2007-12-10 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Fixed a compilation error due to a missing #ifdef in
upnp/src/genlib/miniserver/miniserver.c. Thanks to Eugene Christensen.
2007-11-12 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* "make check" was failing because ixml/test/test_document.sh did not
have the executable flag set. Thanks to Steve Bresson.
2007-11-12 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Fixed a memory leak in upnpapi.c to delete gMiniServerThreadPool in
the call to UpnpFinish(). Thanks to Fabrice Fontaine.
2007-11-09 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Added a isleep() call to the error handler of select() in
RunMiniServer(), so that it does not take 100% cpu in case select()
fails repeatedly.
*******************************************************************************
Version 1.6.1
*******************************************************************************
2007-11-07 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* SF Bug Tracker [ 1825278 ] AdvertiseAndReply sleeps with handle lock out
Applied patch from Alex (afaucher) to change some write locks to read
locks.
2007-11-06 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Adjusting libtool library numbers to reflect the last changes.
2007-11-06 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* SF Bug Tracker [ 1825278 ] AdvertiseAndReply sleeps with handle lock out
GlobalHndMutex, which was a mutex is now GlobalHndRWLock, which is a
rwlock. HandleLock() is mapped to HandleWriteLock() while all other
instances have not been checked. One instance in AdvertiseAndReply()
has been changed to HandleReadLock(). Thanks to Alex (afaucher) for the
bug report and suggestions.
2007-11-06 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Added support for rwlocks.
2007-11-05 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* SF Bug Tracker [ 1825929 ] woker thread still alive after UpnpFinish()
Submitted By: Luke Kim - nereusuj
Worker thread still alive after calling UpnpFinish() because
ThreadPoolShutdown() is in the #ifdef DEBUG block.
421
422 #ifdef DEBUG
423 ThreadPoolShutdown( &gSendThreadPool );
424 ThreadPoolShutdown( &gRecvThreadPool );
2007-08-28 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Changed the calls to virtualDirCallback.open(filename, UPNP_WRITE)
to (virtualDirCallback.open)(filename, UPNP_WRITE) (notice the
parenthesis) due to a change in glibc that produces compilation
errors.
2007-08-28 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Initialization of the "randomness" struct so that valgrind does not
complain.
2007-08-06 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Merge of patch submitted By Keith Brindley - brindlk
SF Bug Tracker [ 1762758 ] Seek not working for large files
Problem:
Requests from the uPnP client to seek to a position beyond 2GB in a large
file are handled as a request to see from the 2GB point.
Impact:
Varies depending on client. The Xbox 360 kills the connection when it
realises.
Solution:
GetNextRange function (webserver.c) is updated to handle large file sizes.
Fix should also recognise when built on a 32bit platform rather than 64 and
handle accordingly.
2007-08-05 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Merge of Mac OS X patch from St<53>phane Corth<74>sy (davelopper),
SF Bug Tracker [ 1686420 ] Modifications for MacOSX.
Some of the proposed changes were already done by Rene Hexel's patch.
*******************************************************************************
Version 1.6.0
*******************************************************************************
@@ -137,10 +52,6 @@ Version 1.6.0
an interface change in the library and the minor library version was
bumped. Also, the libtool library numbers were changed accordingly.
*******************************************************************************
Version 1.4.7
*******************************************************************************
2007-05-26 Marcelo Jimenez <mroberto(at)users.sourceforge.net>
* Added support for the Basic Device
(http://www.upnp.org/standardizeddcps/basic.asp) as suggested by

8
THANKS
View File

@@ -6,7 +6,6 @@ suggesting various improvements or submitting actual code.
Here is a list of these people. Help us keep it complete and
exempt of errors.
- Alex (afaucher)
- Arno Willig
- Bob Ciora
- Chaos
@@ -16,18 +15,15 @@ exempt of errors.
- Erik Johansson
- Eric Tanguy
- Erwan Velu
- Eugene Christensen
- Fabrice Fontaine
- Fredrik Svensson
- Glen Masgai
- Jiri Zouhar
- John Dennis
- Jonathan (no_dice)
- Keith Brindley
- Leuk_He
- Loigu
- Luke Kim
- Marcelo Roberto Jimenez (mroberto)
- Marcelo Roberto Jimenez
- Markus Strobl
- Nektarios K. Papadopoulos
- Oskar Liljeblad
@@ -35,8 +31,6 @@ exempt of errors.
- Paul Vixie
- Rene Hexel
- Siva Chandran
- Stéphane Corthésy
- Steve Bresson
- Timothy Redaelli
- Titus Winters

View File

@@ -261,7 +261,7 @@
/** @name Other debugging features
The UPnP SDK contains other features to aid in debugging:
see <upnp/inc/upnpdebug.h>
see <upnp/upnpdebug.h>
*/
#define DEBUG_ALL 1

View File

@@ -4,13 +4,12 @@
#
# Process this file with autoconf to produce a configure script.
#
# (C) Copyright 2005-2007 R<>mi Turboult <r3mi@users.sourceforge.net>
# (C) Copyright 2005-2006 R<>mi Turboult <r3mi@users.sourceforge.net>
#
AC_PREREQ(2.60)
AC_INIT([libupnp], [1.6.2], [mroberto@users.sourceforge.net])
###############################################################################
AC_INIT([libupnp], [1.6.0], [mroberto@users.sourceforge.net])
# *Independently* of the above libupnp package version, the libtool version
# of the 3 libraries need to be updated whenever there is a change released :
# "current:revision:age" (this is NOT the same as the package version), where:
@@ -20,14 +19,11 @@ AC_INIT([libupnp], [1.6.2], [mroberto@users.sourceforge.net])
# - interfaces removed: age=0
# *please update only once, before a formal release, not for each change*
#
###############################################################################
# Release 1.4.1:
# For release 1.4.1, we had:
#AC_SUBST([LT_VERSION_IXML], [2:2:0])
#AC_SUBST([LT_VERSION_THREADUTIL], [2:2:0])
#AC_SUBST([LT_VERSION_UPNP], [2:2:0])
#
###############################################################################
# Release 1.4.6:
# "current:revision:age"
#
# - Code has changed in ixml
@@ -41,12 +37,11 @@ AC_INIT([libupnp], [1.6.2], [mroberto@users.sourceforge.net])
# - Code has changed in upnp
# revision: 2 -> 3
#
# For release 1.4.6, we had:
#AC_SUBST([LT_VERSION_IXML], [2:3:0])
#AC_SUBST([LT_VERSION_THREADUTIL], [3:0:1])
#AC_SUBST([LT_VERSION_UPNP], [2:3:0])
#
###############################################################################
# Release 1.6.0:
# "current:revision:age"
#
# - Code has changed in ixml
@@ -61,61 +56,21 @@ AC_INIT([libupnp], [1.6.2], [mroberto@users.sourceforge.net])
# - Interface removed in upnp
# age: 0 -> 0
#
# For release 1.6.0, we had:
#AC_SUBST([LT_VERSION_IXML], [2:4:0])
#AC_SUBST([LT_VERSION_THREADUTIL], [3:1:1])
#AC_SUBST([LT_VERSION_UPNP], [3:0:0])
#
###############################################################################
# Release 1.6.1:
# "current:revision:age"
#
# - Code has changed in threadutil
# revision: 1 -> 2
# - Interface added in threadutil
# current: 3 -> 4
# revision: 2 -> 0
# - Interface added in threadutil
# age: 1 -> 2
# - Code has changed in upnp
# revision: 0 -> 1
#
#AC_SUBST([LT_VERSION_IXML], [2:4:0])
#AC_SUBST([LT_VERSION_THREADUTIL], [4:0:2])
#AC_SUBST([LT_VERSION_UPNP], [3:1:0])
#
###############################################################################
# Release 1.6.2:
# "current:revision:age"
#
# - Code has changed in upnp
# revision: 1 -> 2
#
#AC_SUBST([LT_VERSION_IXML], [2:4:0])
#AC_SUBST([LT_VERSION_THREADUTIL], [4:0:2])
#AC_SUBST([LT_VERSION_UPNP], [3:2:0])
#
###############################################################################
AC_SUBST([LT_VERSION_IXML], [2:4:0])
AC_SUBST([LT_VERSION_THREADUTIL], [4:0:2])
AC_SUBST([LT_VERSION_UPNP], [3:2:0])
###############################################################################
# Repeating the algorithm so that it is closer to the modificatin place:
# - library code modified: revision++
# - interfaces changed/added/removed: current++ and revision=0
# - interfaces added: age++
# - interfaces removed: age=0
# *please update only once, before a formal release, not for each change*
###############################################################################
AC_SUBST([LT_VERSION_THREADUTIL], [3:1:1])
AC_SUBST([LT_VERSION_UPNP], [3:0:0])
AC_CONFIG_AUX_DIR(config.aux)
AC_CONFIG_MACRO_DIR(m4)
AC_CONFIG_SRCDIR(upnp/inc/upnp.h)
AM_INIT_AUTOMAKE([1.8 -Wall foreign subdir-objects dist-bzip2])
#
# Get canonical host names in host and host_os
#

0
ixml/test/test_document.sh Executable file → Normal file
View File

View File

@@ -1,4 +1,4 @@
Version: 1.6.2
Version: 1.4.2
Summary: Universal Plug and Play (UPnP) SDK
Name: libupnp
Release: 1%{?dist}
@@ -77,12 +77,6 @@ make install DESTDIR=$RPM_BUILD_ROOT
rm -rf %{buildroot}
%changelog
* Mon Nov 19 2007 Marcelo Jimenez <mroberto@users.sourceforge.net> - 1.6.2-1
- Update to version 1.6.2
* Mon Nov 19 2007 Marcelo Jimenez <mroberto@users.sourceforge.net> - 1.4.7-1
- Update to version 1.4.7
* Fri Feb 02 2007 Eric Tanguy <eric.tanguy@univ-nantes.fr> - 1.4.2-1
- Update to version 1.4.2

View File

@@ -547,10 +547,6 @@ int TPAttrSetMaxJobsTotal(ThreadPoolAttr *attr, int maxJobsTotal);
EXPORT int ThreadPoolGetStats(ThreadPool *tp, ThreadPoolStats *stats);
EXPORT void ThreadPoolPrintStats(ThreadPoolStats *stats);
#else
static UPNP_INLINE int ThreadPoolGetStats(ThreadPool *tp, ThreadPoolStats *stats) {}
static UPNP_INLINE void ThreadPoolPrintStats(ThreadPoolStats *stats) {}
#endif
#ifdef __cplusplus

View File

@@ -52,16 +52,11 @@ extern "C" {
#define ITHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL
#define ITHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE
#define ITHREAD_MUTEX_ERRORCHECK_NP PTHREAD_MUTEX_ERRORCHECK
#else /* PTHREAD_MUTEX_RECURSIVE */
#else
#define ITHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_FAST_NP
#define ITHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE_NP
#define ITHREAD_MUTEX_ERRORCHECK_NP PTHREAD_MUTEX_ERRORCHECK_NP
#endif /* PTHREAD_MUTEX_RECURSIVE */
#define ITHREAD_PROCESS_PRIVATE PTHREAD_PROCESS_PRIVATE
#define ITHREAD_PROCESS_SHARED PTHREAD_PROCESS_SHARED
#endif
#define ITHREAD_CANCELED PTHREAD_CANCELED
@@ -141,28 +136,6 @@ typedef pthread_mutex_t ithread_mutex_t;
***************************************************************************/
typedef pthread_condattr_t ithread_condattr_t;
/****************************************************************************
* Name: ithread_rwlockattr_t
*
* Description:
* Mutex attribute.
* typedef to pthread_rwlockattr_t
* Internal Use Only
***************************************************************************/
typedef pthread_rwlockattr_t ithread_rwlockattr_t;
/****************************************************************************
* Name: ithread_rwlock_t
*
* Description:
* Condition attribute.
* typedef to pthread_rwlock_t
* Internal Use Only
***************************************************************************/
typedef pthread_rwlock_t ithread_rwlock_t;
/****************************************************************************
* Function: ithread_mutexattr_init
*
@@ -177,8 +150,8 @@ typedef pthread_rwlock_t ithread_rwlock_t;
* Always returns 0.
* See man page for pthread_mutexattr_init
***************************************************************************/
#define ithread_mutexattr_init pthread_mutexattr_init
#define ithread_mutexattr_init pthread_mutexattr_init
/****************************************************************************
* Function: ithread_mutexattr_destroy
@@ -207,7 +180,7 @@ typedef pthread_rwlock_t ithread_rwlock_t;
* ITHREAD_MUTEX_ERRORCHECK_NP
*
* Parameters:
* ithread_mutexattr_t * attr (must be valid non NULL pointer to
* ithread_mutexattr_t * mutex (must be valid non NULL pointer to
* ithread_mutexattr_t)
* int kind (one of ITHREAD_MUTEX_FAST_NP or ITHREAD_MUTEX_RECURSIVE_NP
* or ITHREAD_MUTEX_ERRORCHECK_NP)
@@ -232,7 +205,7 @@ typedef pthread_rwlock_t ithread_rwlock_t;
* ITHREAD_MUTEX_ERRORCHECK_NP
*
* Parameters:
* ithread_mutexattr_t * attr (must be valid non NULL pointer to
* ithread_mutexattr_t * mutex (must be valid non NULL pointer to
* pthread_mutexattr_t)
* int *kind (one of ITHREAD_MUTEX_FAST_NP or ITHREAD_MUTEX_RECURSIVE_NP
* or ITHREAD_MUTEX_ERRORCHECK_NP)
@@ -265,7 +238,6 @@ typedef pthread_rwlock_t ithread_rwlock_t;
*****************************************************************************/
#define ithread_mutex_init pthread_mutex_init
/****************************************************************************
* Function: ithread_mutex_lock
*
@@ -320,169 +292,6 @@ typedef pthread_rwlock_t ithread_rwlock_t;
#define ithread_mutex_destroy pthread_mutex_destroy
/****************************************************************************
* Function: ithread_rwlockattr_init
*
* Description:
* Initializes a rwlock attribute variable to default values.
* Parameters:
* const ithread_rwlockattr_init *attr (must be valid non NULL pointer to
* pthread_rwlockattr_t)
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlockattr_init
***************************************************************************/
#define ithread_rwlockattr_init pthread_rwlockattr_init
/****************************************************************************
* Function: ithread_rwlockattr_destroy
*
* Description:
* Releases any resources held by the rwlock attribute.
* Parameters:
* ithread_rwlockattr_t *attr (must be valid non NULL pointer to
* pthread_rwlockattr_t)
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlockattr_destroy
***************************************************************************/
#define ithread_rwlockattr_destroy pthread_rwlockattr_destroy
/****************************************************************************
* Function: ithread_rwlockatttr_setpshared
*
* Description:
* Sets the rwlock type in the attribute.
* Valid types are: ITHREAD_PROCESS_PRIVATE
* ITHREAD_PROCESS_SHARED
*
* Parameters:
* ithread_rwlockattr_t * attr (must be valid non NULL pointer to
* ithread_rwlockattr_t)
* int kind (one of ITHREAD_PROCESS_PRIVATE or ITHREAD_PROCESS_SHARED)
*
* Returns:
* 0 on success. Nonzero on failure.
* Returns EINVAL if the kind is not supported.
* See man page for pthread_rwlockattr_setkind_np
*****************************************************************************/
#define ithread_rwlockatttr_setpshared pthread_rwlockatttr_setpshared
/****************************************************************************
* Function: ithread_rwlockatttr_getpshared
*
* Description:
* Gets the rwlock type in the attribute.
* Valid types are: ITHREAD_PROCESS_PRIVATE
* ITHREAD_PROCESS_SHARED
*
* Parameters:
* ithread_rwlockattr_t * attr (must be valid non NULL pointer to
* pthread_rwlockattr_t)
* int *kind (one of ITHREAD_PROCESS_PRIVATE or ITHREAD_PROCESS_SHARED)
*
* Returns:
* 0 on success. Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlockatttr_getpshared
*****************************************************************************/
#define ithread_rwlockatttr_getpshared pthread_rwlockatttr_getpshared
/****************************************************************************
* Function: ithread_rwlock_init
*
* Description:
* Initializes rwlock.
* Must be called before use.
*
* Parameters:
* ithread_rwlock_t * rwlock (must be valid non NULL pointer to pthread_rwlock_t)
* const ithread_rwlockattr_t * rwlock_attr
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlock_init
*****************************************************************************/
#define ithread_rwlock_init pthread_rwlock_init
/****************************************************************************
* Function: ithread_rwlock_rdlock
*
* Description:
* Locks rwlock for reading.
* Parameters:
* ithread_rwlock_t * rwlock (must be valid non NULL pointer to pthread_rwlock_t)
* rwlock must be initialized.
*
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlock_rdlock
*****************************************************************************/
#define ithread_rwlock_rdlock pthread_rwlock_rdlock
/****************************************************************************
* Function: ithread_rwlock_wrlock
*
* Description:
* Locks rwlock for writting.
* Parameters:
* ithread_rwlock_t * rwlock (must be valid non NULL pointer to pthread_rwlock_t)
* rwlock must be initialized.
*
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlock_wrlock
*****************************************************************************/
#define ithread_rwlock_wrlock pthread_rwlock_wrlock
/****************************************************************************
* Function: ithread_rwlock_unlock
*
* Description:
* Unlocks rwlock.
*
* Parameters:
* ithread_rwlock_t * rwlock (must be valid non NULL pointer to pthread_rwlock_t)
* rwlock must be initialized.
*
* Returns:
* 0 on success, Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlock_unlock
*****************************************************************************/
#define ithread_rwlock_unlock pthread_rwlock_unlock
/****************************************************************************
* Function: ithread_rwlock_destroy
*
* Description:
* Releases any resources held by the rwlock.
* rwlock can no longer be used after this call.
* rwlock is only destroyed when there are no longer any threads waiting on it.
* rwlock cannot be destroyed if it is locked.
* Parameters:
* ithread_rwlock_t * rwlock (must be valid non NULL pointer to pthread_rwlock_t)
* rwlock must be initialized.
* Returns:
* 0 on success. Nonzero on failure.
* Always returns 0.
* See man page for pthread_rwlock_destroy
*****************************************************************************/
#define ithread_rwlock_destroy pthread_rwlock_destroy
/****************************************************************************
* Function: ithread_cond_init
*

View File

@@ -31,7 +31,7 @@
#include "LinkedList.h"
#include <sys/param.h>
#if (defined(BSD) && BSD >= 199306) || defined(__OSX__)
#if (defined(BSD) && BSD >= 199306)
#include <stdlib.h>
#else
#include <malloc.h>

View File

@@ -93,10 +93,8 @@ SetPolicyType( PolicyType in )
#ifdef __CYGWIN__
/* TODO not currently working... */
return 0;
#elif defined(__OSX__)
setpriority(PRIO_PROCESS, 0, 0);
return 0;
#elif defined(WIN32)
#else
#ifdef WIN32
return sched_setscheduler( 0, in);
#elif defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
struct sched_param current;
@@ -107,6 +105,7 @@ SetPolicyType( PolicyType in )
#else
return 0;
#endif
#endif
}
/****************************************************************************
@@ -365,7 +364,7 @@ static void SetSeed() {
ftime( &t );
#if defined(WIN32)
srand( ( unsigned int )t.millitm + (unsigned int)ithread_get_current_thread_id().p );
#elif defined(__FreeBSD__) || defined(__OSX__)
#elif defined(__FreeBSD__)
srand( ( unsigned int )t.millitm + (unsigned int)ithread_get_current_thread_id() );
#elif defined(__linux__)
srand( ( unsigned int )t.millitm + ithread_get_current_thread_id() );
@@ -1511,33 +1510,36 @@ static void SetSeed() {
}
#ifdef STATS
void ThreadPoolPrintStats(ThreadPoolStats * stats)
{
assert( stats != NULL );
if (stats == NULL) {
return;
}
void ThreadPoolPrintStats( ThreadPoolStats * stats ) {
assert( stats != NULL ); if( stats == NULL ) {
return;}
#ifdef __FreeBSD__
printf( "ThreadPoolStats at Time: %d\n", time( NULL ) );
#else /* __FreeBSD__ */
#else
printf( "ThreadPoolStats at Time: %ld\n", time( NULL ) );
#endif /* __FreeBSD__ */
printf("High Jobs pending: %d\n", stats->currentJobsHQ);
printf("Med Jobs Pending: %d\n", stats->currentJobsMQ);
printf("Low Jobs Pending: %d\n", stats->currentJobsLQ);
printf("Average Wait in High Priority Q in milliseconds: %f\n", stats->avgWaitHQ);
printf("Average Wait in Med Priority Q in milliseconds: %f\n", stats->avgWaitMQ);
printf("Averate Wait in Low Priority Q in milliseconds: %f\n", stats->avgWaitLQ);
#endif
printf
( "Average Wait in High Priority Q in milliseconds: %f\n",
stats->avgWaitHQ );
printf
( "Average Wait in Med Priority Q in milliseconds: %f\n",
stats->avgWaitMQ );
printf
( "Averate Wait in Low Priority Q in milliseconds: %f\n",
stats->avgWaitLQ );
printf( "Max Threads Active: %d\n", stats->maxThreads );
printf("Current Worker Threads: %d\n", stats->workerThreads);
printf("Current Persistent Threads: %d\n", stats->persistentThreads);
printf( "Current Worker Threads: %d\n",
stats->workerThreads );
printf( "Current Persistent Threads: %d\n",
stats->persistentThreads );
printf( "Current Idle Threads: %d\n", stats->idleThreads );
printf( "Total Threads : %d\n", stats->totalThreads );
printf("Total Time spent Working in seconds: %f\n", stats->totalWorkTime);
printf("Total Time spent Idle in seconds : %f\n", stats->totalIdleTime);
}
#endif /* STATS */
printf( "Total Time spent Working in seconds: %f\n",
stats->totalWorkTime );
printf( "Total Time spent Idle in seconds : %f\n",
stats->totalIdleTime );}
#endif
/****************************************************************************
* Function: TPAttrSetMaxJobsTotal
@@ -1550,10 +1552,8 @@ void ThreadPoolPrintStats(ThreadPoolStats * stats)
* Returns:
* Always returns 0.
*****************************************************************************/
int TPAttrSetMaxJobsTotal(
ThreadPoolAttr * attr,
int maxJobsTotal )
{
int TPAttrSetMaxJobsTotal( ThreadPoolAttr * attr,
int maxJobsTotal ) {
assert( attr != NULL );
if( attr == NULL ) {
@@ -1579,54 +1579,40 @@ int TPAttrSetMaxJobsTotal(
*****************************************************************************/
#ifdef STATS
int
ThreadPoolGetStats(
ThreadPool *tp,
ThreadPoolStats *stats)
{
ThreadPoolGetStats( ThreadPool * tp,
ThreadPoolStats * stats ) {
assert( tp != NULL );
assert( stats != NULL );
if (tp == NULL || stats == NULL) {
return EINVAL;
}
if( ( tp == NULL ) || ( stats == NULL ) ) {
return EINVAL;}
//if not shutdown then acquire mutex
if( !tp->shutdown ) {
ithread_mutex_lock(&tp->mutex);
}
ithread_mutex_lock( &tp->mutex );}
*stats = tp->stats;
if (stats->totalJobsHQ > 0) {
stats->avgWaitHQ = stats->totalTimeHQ / stats->totalJobsHQ;
} else {
stats->avgWaitHQ = 0;
}
if( stats->totalJobsMQ > 0 ) {
stats->avgWaitMQ = stats->totalTimeMQ / stats->totalJobsMQ;
} else {
stats->avgWaitMQ = 0;
}
if( stats->totalJobsLQ > 0 ) {
stats->avgWaitLQ = stats->totalTimeLQ / stats->totalJobsLQ;
} else {
( *stats ) = tp->stats; if( stats->totalJobsHQ > 0 )
stats->avgWaitHQ =
stats->totalTimeHQ / stats->totalJobsHQ;
else
stats->avgWaitHQ = 0; if( stats->totalJobsMQ > 0 )
stats->avgWaitMQ =
stats->totalTimeMQ / stats->totalJobsMQ;
else
stats->avgWaitMQ = 0; if( stats->totalJobsLQ > 0 )
stats->avgWaitLQ =
stats->totalTimeLQ / stats->totalJobsLQ;
else
stats->avgWaitLQ = 0;
}
stats->totalThreads = tp->totalThreads;
stats->persistentThreads = tp->persistentThreads;
stats->currentJobsHQ = ListSize( &tp->highJobQ );
stats->currentJobsLQ = ListSize( &tp->lowJobQ );
stats->currentJobsMQ = ListSize( &tp->medJobQ );
//if not shutdown then release mutex
if( !tp->shutdown ) {
ithread_mutex_unlock( &tp->mutex );
}
ithread_mutex_unlock( &tp->mutex );}
return 0;
}
#endif /* STATS */
return 0;}
#endif

View File

@@ -32,7 +32,7 @@
#include <stdarg.h>
#include <assert.h>
#include <sys/param.h>
#if (defined(BSD) && BSD >= 199306) || defined(__OSX__)
#if (defined(BSD) && BSD >= 199306)
#include <stdlib.h>
#else
#include <malloc.h>

View File

@@ -258,7 +258,7 @@ void UpnpPrintf(
__attribute__((format (__printf__, 5, 6)))
#endif
;
#else /* DEBUG */
#else
static UPNP_INLINE void UpnpPrintf(
Upnp_LogLevel DLevel,
Dbg_Module Module,
@@ -266,7 +266,7 @@ static UPNP_INLINE void UpnpPrintf(
int DbgLineNo,
const char* FmtStr,
...) {}
#endif /* DEBUG */
#endif
/***************************************************************************

View File

@@ -1362,7 +1362,7 @@ TvCtrlPointStart( print_string printFunctionPtr,
ithread_mutex_init( &DeviceListMutex, 0 );
SampleUtil_Print( "Initializing UPnP with ipaddress=%s port=%d",
SampleUtil_Print( "Intializing UPnP with ipaddress=%s port=%d",
ip_address, port );
rc = UpnpInit( ip_address, port );
if( UPNP_E_SUCCESS != rc ) {

View File

@@ -84,16 +84,18 @@ virtualDirList *pVirtualDirList;
// Mutex to synchronize the subscription handling at the client side
CLIENTONLY( ithread_mutex_t GlobalClientSubscribeMutex; )
// rwlock to synchronize handles (root device or control point handle)
ithread_rwlock_t GlobalHndRWLock;
//Mutex to synchronize handles ( root device or control point handle)
ithread_mutex_t GlobalHndMutex;
// Mutex to synchronize the uuid creation process
ithread_mutex_t gUUIDMutex;
TimerThread gTimerThread;
ThreadPool gSendThreadPool;
ThreadPool gRecvThreadPool;
ThreadPool gSendThreadPool;
ThreadPool gMiniServerThreadPool;
//Flag to indicate the state of web server
@@ -211,9 +213,9 @@ int UpnpInit( IN const char *HostIP,
#ifdef __CYGWIN__
/* On Cygwin, pthread_mutex_init() fails without this memset. */
/* TODO: Fix Cygwin so we don't need this memset(). */
memset(&GlobalHndRWLock, 0, sizeof(GlobalHndRWLock));
memset(&GlobalHndMutex, 0, sizeof(GlobalHndMutex));
#endif
if (ithread_rwlock_init(&GlobalHndRWLock, NULL) != 0) {
if( ithread_mutex_init( &GlobalHndMutex, NULL ) != 0 ) {
return UPNP_E_INIT_FAILED;
}
@@ -228,9 +230,9 @@ int UpnpInit( IN const char *HostIP,
#endif
HandleLock();
if( HostIP != NULL ) {
if( HostIP != NULL )
strcpy( LOCAL_HOST, HostIP );
} else {
else {
if( getlocalhostname( LOCAL_HOST ) != UPNP_E_SUCCESS ) {
HandleUnlock();
return UPNP_E_INIT_FAILED;
@@ -321,54 +323,27 @@ int UpnpInit( IN const char *HostIP,
#ifdef DEBUG
static void
PrintThreadPoolStats(
ThreadPool *tp,
const char *DbgFileName,
int DbgLineNo,
const char *msg)
PrintThreadPoolStats (const char* DbgFileName, int DbgLineNo,
const char* msg, const ThreadPoolStats* const stats)
{
ThreadPoolStats stats;
ThreadPoolGetStats(tp, &stats);
UpnpPrintf (UPNP_INFO, API, DbgFileName, DbgLineNo,
"%s \n"
"High Jobs pending: %d\n"
"Med Jobs Pending: %d\n"
"Low Jobs Pending: %d\n"
"Average wait in High Q in milliseconds: %lf\n"
"Average wait in Med Q in milliseconds: %lf\n"
"Average wait in Low Q in milliseconds: %lf\n"
"Max Threads Used: %d\n"
"Worker Threads: %d\n"
"Persistent Threads: %d\n"
"Idle Threads: %d\n"
"Total Threads: %d\n"
"Total Work Time: %lf\n"
"Total Idle Time: %lf\n",
"%s \n High Jobs pending = %d \nMed Jobs Pending = %d\n"
" Low Jobs Pending = %d \nWorker Threads = %d\n"
"Idle Threads = %d\nPersistent Threads = %d\n"
"Average Time spent in High Q = %lf\n"
"Average Time spent in Med Q = %lf\n"
"Average Time spent in Low Q = %lf\n"
"Max Threads Used: %d\nTotal Work Time= %lf\n"
"Total Idle Time = %lf\n",
msg,
stats.currentJobsHQ,
stats.currentJobsMQ,
stats.currentJobsLQ,
stats.avgWaitHQ,
stats.avgWaitMQ,
stats.avgWaitLQ,
stats.maxThreads,
stats.workerThreads,
stats.persistentThreads,
stats.idleThreads,
stats.totalThreads,
stats.totalWorkTime,
stats.totalIdleTime);
stats->currentJobsHQ, stats->currentJobsMQ,
stats->currentJobsLQ, stats->workerThreads,
stats->idleThreads, stats->persistentThreads,
stats->avgWaitHQ, stats->avgWaitMQ, stats->avgWaitLQ,
stats->maxThreads, stats->totalWorkTime,
stats->totalIdleTime );
}
#else /* DEBUG */
static UPNP_INLINE void
PrintThreadPoolStats(
ThreadPool *tp,
const char *DbgFileName,
int DbgLineNo,
const char *msg)
{
}
#endif /* DEBUG */
#endif
/****************************************************************************
@@ -399,6 +374,10 @@ UpnpFinish()
#endif
struct Handle_Info *temp;
#ifdef DEBUG
ThreadPoolStats stats;
#endif
#ifdef WIN32
// WSACleanup( );
#endif
@@ -408,15 +387,20 @@ UpnpFinish()
}
UpnpPrintf( UPNP_INFO, API, __FILE__, __LINE__,
"Inside UpnpFinish : UpnpSdkInit is :%d:\n", UpnpSdkInit );
"Inside UpnpFinish : UpnpSdkInit is :%d:\n",
UpnpSdkInit );
#ifdef DEBUG
if( UpnpSdkInit == 1 ) {
UpnpPrintf( UPNP_INFO, API, __FILE__, __LINE__,
"UpnpFinish : UpnpSdkInit is ONE\n" );
}
PrintThreadPoolStats(&gSendThreadPool, __FILE__, __LINE__, "Send Thread Pool");
PrintThreadPoolStats(&gRecvThreadPool, __FILE__, __LINE__, "Recv Thread Pool");
PrintThreadPoolStats(&gMiniServerThreadPool, __FILE__, __LINE__, "MiniServer Thread Pool");
ThreadPoolGetStats( &gRecvThreadPool, &stats );
PrintThreadPoolStats (__FILE__, __LINE__,
"Recv Thread Pool", &stats);
ThreadPoolGetStats( &gSendThreadPool, &stats );
PrintThreadPoolStats (__FILE__, __LINE__,
"Send Thread Pool", &stats);
#endif
#ifdef INCLUDE_DEVICE_APIS
if( GetDeviceHandleInfo( &device_handle, &temp ) == HND_DEVICE )
UpnpUnRegisterRootDevice( device_handle );
@@ -428,47 +412,51 @@ UpnpFinish()
#endif
TimerThreadShutdown( &gTimerThread );
StopMiniServer();
#if EXCLUDE_WEB_SERVER == 0
web_server_destroy();
#endif
ThreadPoolShutdown(&gMiniServerThreadPool);
ThreadPoolShutdown(&gRecvThreadPool);
#ifdef DEBUG
ThreadPoolShutdown( &gSendThreadPool );
PrintThreadPoolStats(&gSendThreadPool, __FILE__, __LINE__, "Send Thread Pool");
PrintThreadPoolStats(&gRecvThreadPool, __FILE__, __LINE__, "Recv Thread Pool");
PrintThreadPoolStats(&gMiniServerThreadPool, __FILE__, __LINE__, "MiniServer Thread Pool");
ThreadPoolShutdown( &gRecvThreadPool );
UpnpPrintf( UPNP_INFO, API, __FILE__, __LINE__,
"Exiting UpnpFinish : UpnpSdkInit is :%d:\n",
UpnpSdkInit );
ThreadPoolGetStats( &gRecvThreadPool, &stats );
PrintThreadPoolStats( __FILE__, __LINE__,
"Recv Thread Pool", &stats);
ThreadPoolGetStats( &gSendThreadPool, &stats );
PrintThreadPoolStats(__FILE__, __LINE__,
"Send Thread Pool", &stats);
UpnpCloseLog();
#endif
#ifdef INCLUDE_CLIENT_APIS
ithread_mutex_destroy( &GlobalClientSubscribeMutex );
#endif
ithread_rwlock_destroy(&GlobalHndRWLock);
ithread_mutex_destroy( &GlobalHndMutex );
ithread_mutex_destroy( &gUUIDMutex );
// remove all virtual dirs
UpnpRemoveAllVirtualDirs();
// allow static linking
// leuk_he allow static linking:
#ifdef WIN32
#ifdef PTW32_STATIC_LIB
pthread_win32_thread_detach_np ();
#endif
#endif
UpnpSdkInit = 0;
UpnpPrintf( UPNP_INFO, API, __FILE__, __LINE__,
"Exiting UpnpFinish : UpnpSdkInit is :%d:\n", UpnpSdkInit);
UpnpCloseLog();
return UPNP_E_SUCCESS;
}
/*************************** End of UpnpFinish *****************************/
} /********************* End of UpnpFinish *************************/
/******************************************************************************
/****************************************************************************
* Function: UpnpGetServerPort
*
* Parameters: NONE
@@ -965,7 +953,7 @@ GetDescDocumentAndURL( IN Upnp_DescType descriptionType,
char *temp_str = NULL;
FILE *fp = NULL;
off_t fileLen;
size_t num_read;
unsigned num_read;
time_t last_modified;
struct stat file_info;
struct sockaddr_in serverAddr;
@@ -1571,7 +1559,7 @@ UpnpSearchAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpSearchAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -1747,7 +1735,7 @@ UpnpSubscribeAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpSubscribeAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -1764,13 +1752,15 @@ UpnpSubscribeAsync( IN UpnpClient_Handle Hnd,
HandleUnlock();
return UPNP_E_INVALID_PARAM;
}
HandleUnlock();
Param = (struct UpnpNonblockParam *)
Param =
( struct UpnpNonblockParam * )
malloc( sizeof( struct UpnpNonblockParam ) );
if( Param == NULL ) {
HandleUnlock();
return UPNP_E_OUTOF_MEMORY;
}
HandleUnlock();
Param->FunName = SUBSCRIBE;
Param->Handle = Hnd;
@@ -1830,7 +1820,7 @@ UpnpSubscribe( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpSubscribe \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -1890,7 +1880,7 @@ UpnpUnSubscribe( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpUnSubscribe \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -1949,7 +1939,7 @@ UpnpUnSubscribeAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpUnSubscribeAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2023,7 +2013,7 @@ UpnpRenewSubscription( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpRenewSubscription \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2088,7 +2078,7 @@ UpnpRenewSubscriptionAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpRenewSubscriptionAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2183,7 +2173,7 @@ UpnpNotify( IN UpnpDevice_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpNotify \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_DEVICE ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2254,7 +2244,7 @@ UpnpNotifyExt( IN UpnpDevice_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpNotify \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_DEVICE ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2331,7 +2321,7 @@ UpnpAcceptSubscription( IN UpnpDevice_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpAcceptSubscription \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_DEVICE ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2407,7 +2397,7 @@ UpnpAcceptSubscriptionExt( IN UpnpDevice_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpAcceptSubscription \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_DEVICE ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2503,7 +2493,7 @@ UpnpSendAction( IN UpnpClient_Handle Hnd,
}
DevUDN_const = NULL;
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2587,7 +2577,7 @@ UpnpSendActionEx( IN UpnpClient_Handle Hnd,
return retVal;
}
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2663,7 +2653,7 @@ UpnpSendActionAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpSendActionAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2783,7 +2773,7 @@ UpnpSendActionExAsync( IN UpnpClient_Handle Hnd,
return retVal;
}
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2897,7 +2887,7 @@ UpnpGetServiceVarStatusAsync( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpGetServiceVarStatusAsync \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -2977,7 +2967,7 @@ UpnpGetServiceVarStatus( IN UpnpClient_Handle Hnd,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Inside UpnpGetServiceVarStatus \n" );
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_CLIENT ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
@@ -3310,9 +3300,9 @@ UpnpDownloadXmlDoc( const char *url,
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"****************** END OF Parsed XML Doc *****************\n" );
ixmlFreeDOMString( xml_buf );
#endif
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Exiting UpnpDownloadXmlDoc\n" );
#endif
return UPNP_E_SUCCESS;
}
}
@@ -3645,6 +3635,7 @@ int PrintHandleInfo( IN UpnpClient_Handle Hnd )
struct Handle_Info * HndInfo;
if (HandleTable[Hnd] != NULL) {
HndInfo = HandleTable[Hnd];
#ifdef DEBUG
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
"Printing information for Handle_%d\n", Hnd);
UpnpPrintf(UPNP_ALL, API, __FILE__, __LINE__,
@@ -3653,6 +3644,7 @@ int PrintHandleInfo( IN UpnpClient_Handle Hnd )
if(HndInfo->HType != HND_CLIENT)
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"DescURL_%s\n", HndInfo->DescURL );
#endif
#endif
} else {
return UPNP_E_INVALID_HANDLE;

View File

@@ -44,7 +44,7 @@ struct ErrorString {
};
// Initializing the array of error structures.
//Intializing the array of error structures.
struct ErrorString ErrorMessages[] = { {UPNP_E_SUCCESS, "UPNP_E_SUCCESS"},
{UPNP_E_INVALID_HANDLE, "UPNP_E_INVALID_HANDLE"},
{UPNP_E_INVALID_PARAM, "UPNP_E_INVALID_PARAM"},
@@ -581,5 +581,4 @@ UpnpCreatePropertySet( IN int NumArg,
return PropSet;
}
#endif // EXCLUDE_DOM == 0
#endif

View File

@@ -93,7 +93,7 @@ GenaAutoRenewSubscription( IN void *input )
}
}
if( send_callback ) {
HandleReadLock();
HandleLock();
if( GetHandleInfo( event->handle, &handle_info ) != HND_CLIENT ) {
HandleUnlock();
free_upnp_timeout( event );
@@ -543,10 +543,10 @@ genaSubscribe( IN UpnpClient_Handle client_handle,
UpnpPrintf( UPNP_INFO, GENA, __FILE__, __LINE__,
"GENA SUBSCRIBE BEGIN" );
HandleLock();
memset( out_sid, 0, sizeof( Upnp_SID ) );
HandleReadLock();
// validate handle
if( GetHandleInfo( client_handle, &handle_info ) != HND_CLIENT ) {
HandleUnlock();
@@ -881,4 +881,3 @@ gena_process_notification_event( IN SOCKINFO * info,
#endif // INCLUDE_CLIENT_APIS
#endif // EXCLUDE_GENA

View File

@@ -365,7 +365,7 @@ genaNotifyThread( IN void *input )
struct Handle_Info *handle_info;
ThreadPoolJob job;
HandleReadLock();
HandleLock();
//validate context
if( GetHandleInfo( in->device_handle, &handle_info ) != HND_DEVICE ) {

View File

@@ -42,12 +42,12 @@
#include <sys/wait.h>
#include <unistd.h>
#include <sys/time.h>
#else /* WIN32 */
#else
#include <winsock2.h>
typedef int socklen_t;
#define EAFNOSUPPORT 97
#endif /* WIN32 */
#endif
#include "unixutil.h"
#include "ithread.h"
@@ -91,12 +91,13 @@ static MiniServerState gMServState = MSERV_IDLE;
* Function : SetHTTPGetCallback
*
* Parameters :
* MiniServerCallback callback - HTTP Callback to be invoked
* MiniServerCallback callback ; - HTTP Callback to be invoked
*
* Description:
* Set HTTP Get Callback
* Description : Set HTTP Get Callback
*
* Return : void
*
* Note :
************************************************************************/
void
SetHTTPGetCallback( MiniServerCallback callback )
@@ -108,31 +109,31 @@ SetHTTPGetCallback( MiniServerCallback callback )
* Function : SetSoapCallback
*
* Parameters :
* MiniServerCallback callback - SOAP Callback to be invoked
* MiniServerCallback callback ; - SOAP Callback to be invoked
*
* Description:
* Set SOAP Callback
* Description : Set SOAP Callback
*
* Return : void
*
* Note :
************************************************************************/
#ifdef INCLUDE_DEVICE_APIS
void
SetSoapCallback( MiniServerCallback callback )
{
gSoapCallback = callback;
}
#endif /* INCLUDE_DEVICE_APIS */
/************************************************************************
* Function : SetGenaCallback
*
* Parameters :
* MiniServerCallback callback - GENA Callback to be invoked
* MiniServerCallback callback ; - GENA Callback to be invoked
*
* Description:
* Set GENA Callback
* Description : Set GENA Callback
*
* Return : void
*
* Note :
************************************************************************/
void
SetGenaCallback( MiniServerCallback callback )
@@ -144,15 +145,17 @@ SetGenaCallback( MiniServerCallback callback )
* Function : dispatch_request
*
* Parameters :
* IN SOCKINFO *info - Socket Information object.
* http_parser_t* hparser - HTTP parser object.
* IN SOCKINFO *info ; Socket Information object.
* http_parser_t* hparser ; HTTP parser object.
*
* Description :
* Based on the type pf message, appropriate callback is issued
* Description : Based on the type pf message, appropriate callback
* is issued
*
* Return: int
* Return : int ;
* 0 - On Success
* HTTP_INTERNAL_SERVER_ERROR - Callback is NULL
*
* Note :
************************************************************************/
static int
dispatch_request( IN SOCKINFO * info,
@@ -200,15 +203,17 @@ dispatch_request( IN SOCKINFO * info,
* Function : handle_error
*
* Parameters :
* IN SOCKINFO *info - Socket Inforamtion Object
* int http_error_code - HTTP Error Code
* int major - Major Version Number
* int minor - Minor Version Number
*
* Description:
* Send Error Message
* IN SOCKINFO *info ; Socket Inforamtion Object
* int http_error_code ; HTTP Error Code
* int major ; Major Version Number
* int minor ; Minor Version Number
*
* Return: void
* Description : Send Error Message
*
* Return : void;
*
* Note :
************************************************************************/
static UPNP_INLINE void
handle_error( IN SOCKINFO * info,
@@ -225,11 +230,12 @@ handle_error( IN SOCKINFO * info,
* Parameters :
* void *args ; Request Message to be freed
*
* Description:
* Free memory assigned for handling request and unitialize socket
* functionality
* Description : Free memory assigned for handling request and unitial-
* -ize socket functionality
*
* Return : void
*
* Note :
************************************************************************/
static void
free_handle_request_arg( void *args )
@@ -245,12 +251,13 @@ free_handle_request_arg( void *args )
* Function : handle_request
*
* Parameters :
* void *args - Request Message to be handled
* void *args ; Request Message to be handled
*
* Description:
* Receive the request and dispatch it for handling
* Description : Receive the request and dispatch it for handling
*
* Return : void
*
* Note :
************************************************************************/
static void
handle_request( void *args )
@@ -315,14 +322,16 @@ handle_request( void *args )
* Function : schedule_request_job
*
* Parameters :
* IN int connfd - Socket Descriptor on which connection is accepted
* IN struct sockaddr_in* clientAddr - Clients Address information
* IN int connfd ; Socket Descriptor on which connection is accepted
* IN struct sockaddr_in* clientAddr ; Clients Address information
*
* Description:
* Initilize the thread pool to handle a request.
* Description : Initilize the thread pool to handle a request.
* Sets priority for the job and adds the job to the thread pool
*
*
* Return : void
*
* Note :
************************************************************************/
static UPNP_INLINE void
schedule_request_job( IN int connfd,
@@ -365,28 +374,29 @@ schedule_request_job( IN int connfd,
* Function : RunMiniServer
*
* Parameters :
* MiniServerSockArray *miniSock - Socket Array
* MiniServerSockArray *miniSock ; Socket Array
*
* Description:
* Function runs the miniserver. The MiniServer accepts a
* Description : Function runs the miniserver. The MiniServer accepts a
* new request and schedules a thread to handle the new request.
* Checks for socket state and invokes appropriate read and shutdown
* actions for the Miniserver and SSDP sockets
*
* Return : void
*
* Note :
************************************************************************/
static void
RunMiniServer( MiniServerSockArray * miniSock )
{
struct sockaddr_in clientAddr;
socklen_t clientLen;
SOCKET connectHnd;
SOCKET miniServSock = miniSock->miniServerSock;
SOCKET miniServStopSock = miniSock->miniServerStopSock;
SOCKET ssdpSock = miniSock->ssdpSock;
#ifdef INCLUDE_CLIENT_APIS
SOCKET ssdpReqSock = miniSock->ssdpReqSock;
#endif
SOCKET miniServSock,
connectHnd;
SOCKET miniServStopSock;
SOCKET ssdpSock;
CLIENTONLY( SOCKET ssdpReqSock;
)
fd_set expSet;
fd_set rdSet;
@@ -394,55 +404,66 @@ RunMiniServer( MiniServerSockArray * miniSock )
int byteReceived;
char requestBuf[256];
maxMiniSock = max( miniServSock, miniServStopSock) ;
maxMiniSock = max( maxMiniSock, (SOCKET)(ssdpSock) );
#ifdef INCLUDE_CLIENT_APIS
maxMiniSock = max( maxMiniSock, (SOCKET)(ssdpReqSock) );
#endif
++maxMiniSock;
miniServSock = miniSock->miniServerSock;
miniServStopSock = miniSock->miniServerStopSock;
ssdpSock = miniSock->ssdpSock;
CLIENTONLY( ssdpReqSock = miniSock->ssdpReqSock;
);
gMServState = MSERV_RUNNING;
maxMiniSock = max( miniServSock, miniServStopSock );
maxMiniSock = max( maxMiniSock, ( SOCKET ) ( ssdpSock ) );
CLIENTONLY( maxMiniSock =
max( maxMiniSock, ( SOCKET ) ( ssdpReqSock ) ) );
++maxMiniSock;
while( TRUE ) {
FD_ZERO( &rdSet );
FD_ZERO( &expSet );
FD_SET( miniServStopSock, &expSet );
FD_SET( miniServSock, &rdSet );
FD_SET( miniServStopSock, &rdSet );
FD_SET( ssdpSock, &rdSet );
#ifdef INCLUDE_CLIENT_APIS
FD_SET( ssdpReqSock, &rdSet );
#endif
CLIENTONLY( FD_SET( ssdpReqSock, &rdSet ) );
if( select( maxMiniSock, &rdSet, NULL, &expSet, NULL ) ==
UPNP_SOCKETERROR ) {
UpnpPrintf( UPNP_CRITICAL, SSDP, __FILE__, __LINE__,
"Error in select call!\n" );
/* Avoid 100% CPU in case of repeated error in select() */
isleep( 1 );
"Error in select call !!!\n" );
continue;
} else {
if( FD_ISSET( miniServSock, &rdSet ) ) {
clientLen = sizeof( struct sockaddr_in );
connectHnd = accept( miniServSock,
( struct sockaddr * )&clientAddr, &clientLen );
( struct sockaddr * )&clientAddr,
&clientLen );
if( connectHnd == UPNP_INVALID_SOCKET ) {
UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__,
"miniserver: Error in accepting connection\n" );
"miniserver: Error"
" in accepting connection\n" );
continue;
}
schedule_request_job( connectHnd, &clientAddr );
}
#ifdef INCLUDE_CLIENT_APIS
//ssdp
if( FD_ISSET( ssdpReqSock, &rdSet ) ) {
readFromSSDPSocket( ssdpReqSock );
}
#endif
CLIENTONLY( if( FD_ISSET( ssdpReqSock, &rdSet ) ) {
readFromSSDPSocket( ssdpReqSock );}
)
if( FD_ISSET( ssdpSock, &rdSet ) ) {
readFromSSDPSocket( ssdpSock );
}
if( FD_ISSET( miniServStopSock, &rdSet ) ) {
clientLen = sizeof( struct sockaddr_in );
memset( ( char * )&clientAddr, 0,
sizeof( struct sockaddr_in ) );
@@ -458,6 +479,7 @@ RunMiniServer( MiniServerSockArray * miniSock )
UpnpPrintf( UPNP_PACKET, MSERV, __FILE__, __LINE__,
"Received multicast packet: \n %s\n",
requestBuf );
if( NULL != strstr( requestBuf, "ShutDown" ) ) {
break;
}
@@ -472,29 +494,30 @@ RunMiniServer( MiniServerSockArray * miniSock )
UpnpCloseSocket( miniServStopSock );
shutdown( ssdpSock, SD_BOTH );
UpnpCloseSocket( ssdpSock );
#ifdef INCLUDE_CLIENT_APIS
shutdown( ssdpReqSock, SD_BOTH );
UpnpCloseSocket( ssdpReqSock );
#endif
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
free( miniSock );
gMServState = MSERV_IDLE;
return;
}
/************************************************************************
* Function : get_port
*
* Parameters :
* int sockfd - Socket Descriptor
* int sockfd ; Socket Descriptor
*
* Description:
* Returns port to which socket, sockfd, is bound.
* Description : Returns port to which socket, sockfd, is bound.
*
* Return: int
* Return : int,
* -1 on error; check errno
* > 0 means port number
*
* Note :
************************************************************************/
static int
get_port( int sockfd )
@@ -521,24 +544,24 @@ get_port( int sockfd )
* Function : get_miniserver_sockets
*
* Parameters :
* MiniServerSockArray *out - Socket Array
* unsigned short listen_port - port on which the server is
* listening for incoming connections
*
* Description:
* Creates a STREAM socket, binds to INADDR_ANY and listens for
* incoming connecttions. Returns the actual port which the sockets
* sub-system returned.
* MiniServerSockArray *out ; Socket Array
* unsigned short listen_port ; port on which the server is listening
* for incoming connections
*
* Description : Creates a STREAM socket, binds to INADDR_ANY and
* listens for incoming connecttions. Returns the actual port which
* the sockets sub-system returned.
* Also creates a DGRAM socket, binds to the loop back address and
* returns the port allocated by the socket sub-system.
*
* Return: int
* Return : int :
* UPNP_E_OUTOF_SOCKET - Failed to create a socket
* UPNP_E_SOCKET_BIND - Bind() failed
* UPNP_E_LISTEN - Listen() failed
* UPNP_E_INTERNAL_ERROR - Port returned by the socket layer is < 0
* UPNP_E_SUCCESS - Success
*
* Note :
************************************************************************/
int
get_miniserver_sockets( MiniServerSockArray * out,
@@ -669,8 +692,8 @@ get_miniserver_sockets( MiniServerSockArray * out,
miniStopSockPort = get_port( miniServerStopSock );
if( miniStopSockPort <= 0 ) {
shutdown( miniServerStopSock, SD_BOTH );
UpnpCloseSocket( miniServerStopSock );
shutdown( listenfd, SD_BOTH );
UpnpCloseSocket( miniServerStopSock );
UpnpCloseSocket( listenfd );
return UPNP_E_INTERNAL_ERROR;
}
@@ -688,11 +711,10 @@ get_miniserver_sockets( MiniServerSockArray * out,
* Function : StartMiniServer
*
* Parameters :
* unsigned short listen_port - Port on which the server listens for
* unsigned short listen_port ; Port on which the server listens for
* incoming connections
*
* Description:
* Initialize the sockets functionality for the
* Description : Initialize the sockets functionality for the
* Miniserver. Initialize a thread pool job to run the MiniServer
* and the job to the thread pool. If listen port is 0, port is
* dynamically picked
@@ -700,14 +722,17 @@ get_miniserver_sockets( MiniServerSockArray * out,
* Use timer mechanism to start the MiniServer, failure to meet the
* allowed delay aborts the attempt to launch the MiniServer.
*
* Return: int
* Actual port socket is bound to - On Success
* Return : int ;
* Actual port socket is bound to - On Success:
* A negative number UPNP_E_XXX - On Error
* Note :
************************************************************************/
int
StartMiniServer( unsigned short listen_port )
{
int success;
int count;
int max_count = 10000;
@@ -730,10 +755,12 @@ StartMiniServer( unsigned short listen_port )
}
if( ( success = get_ssdp_sockets( miniSocket ) ) != UPNP_E_SUCCESS ) {
shutdown( miniSocket->miniServerSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerSock );
shutdown( miniSocket->miniServerStopSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerStopSock );
free( miniSocket );
return success;
@@ -749,15 +776,14 @@ StartMiniServer( unsigned short listen_port )
if( success < 0 ) {
shutdown( miniSocket->miniServerSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerSock );
shutdown( miniSocket->miniServerStopSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerStopSock );
shutdown( miniSocket->ssdpSock, SD_BOTH );
CLIENTONLY( shutdown( miniSocket->ssdpReqSock, SD_BOTH ) );
UpnpCloseSocket( miniSocket->miniServerSock );
UpnpCloseSocket( miniSocket->miniServerStopSock );
UpnpCloseSocket( miniSocket->ssdpSock );
#ifdef INCLUDE_CLIENT_APIS
shutdown( miniSocket->ssdpReqSock, SD_BOTH );
UpnpCloseSocket( miniSocket->ssdpReqSock );
#endif
CLIENTONLY( UpnpCloseSocket( miniSocket->ssdpReqSock ) );
return UPNP_E_OUTOF_MEMORY;
}
@@ -770,16 +796,16 @@ StartMiniServer( unsigned short listen_port )
// taking too long to start that thread
if( count >= max_count ) {
shutdown( miniSocket->miniServerSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerSock );
shutdown( miniSocket->miniServerStopSock, SD_BOTH );
UpnpCloseSocket( miniSocket->miniServerStopSock );
shutdown( miniSocket->ssdpSock, SD_BOTH );
CLIENTONLY( shutdown( miniSocket->ssdpReqSock, SD_BOTH ) );
UpnpCloseSocket( miniSocket->miniServerSock );
UpnpCloseSocket( miniSocket->miniServerStopSock );
UpnpCloseSocket( miniSocket->ssdpSock );
#ifdef INCLUDE_CLIENT_APIS
shutdown( miniSocket->ssdpReqSock, SD_BOTH );
UpnpCloseSocket( miniSocket->ssdpReqSock );
#endif
CLIENTONLY( UpnpCloseSocket( miniSocket->ssdpReqSock ) );
return UPNP_E_INTERNAL_ERROR;
}
@@ -791,30 +817,30 @@ StartMiniServer( unsigned short listen_port )
* Function : StopMiniServer
*
* Parameters :
* void
* void ;
*
* Description:
* Stop and Shutdown the MiniServer and free socket
* Description : Stop and Shutdown the MiniServer and free socket
* resources.
*
* Return: int
* Return : int ;
* Always returns 0
*
* Note :
************************************************************************/
int
StopMiniServer( void )
{
int socklen = sizeof( struct sockaddr_in );
int sock;
int socklen = sizeof( struct sockaddr_in ),
sock;
struct sockaddr_in ssdpAddr;
char buf[256] = "ShutDown";
int bufLen = strlen( buf );
if( gMServState == MSERV_RUNNING ) {
if( gMServState == MSERV_RUNNING )
gMServState = MSERV_STOPPING;
} else {
else
return 0;
}
sock = socket( AF_INET, SOCK_DGRAM, 0 );
if( sock == UPNP_INVALID_SOCKET ) {
@@ -838,4 +864,3 @@ StopMiniServer( void )
UpnpCloseSocket( sock );
return 0;
}

View File

@@ -70,10 +70,8 @@
#include "sock.h"
#include "webserver.h"
const int CHUNK_HEADER_SIZE = 10;
const int CHUNK_TAIL_SIZE = 10;
#define DOSOCKET_READ 1
#define DOSOCKET_WRITE 0
/************************************************************************
* Function: http_FixUrl
@@ -82,8 +80,7 @@ const int CHUNK_TAIL_SIZE = 10;
* IN uri_type* url ; URL to be validated and fixed
* OUT uri_type* fixed_url ; URL after being fixed.
*
* Description:
* Validates URL
* Description: Validates URL
*
* Returns:
* UPNP_E_INVALID_URL
@@ -113,7 +110,6 @@ http_FixUrl( IN uri_type * url,
return UPNP_E_SUCCESS;
}
/************************************************************************
* Function: http_FixStrUrl
*
@@ -122,8 +118,7 @@ http_FixUrl( IN uri_type * url,
* IN int urlstrlen ; Length of the character string
* OUT uri_type* fixed_url ; Fixed and corrected URL
*
* Description:
* Parses URL and then validates URL
* Description: Parses URL and then validates URL
*
* Returns:
* UPNP_E_INVALID_URL
@@ -143,7 +138,6 @@ http_FixStrUrl( IN char *urlstr,
return http_FixUrl( &url, fixed_url );
}
/************************************************************************
* Function: http_Connect
*
@@ -151,8 +145,8 @@ http_FixStrUrl( IN char *urlstr,
* IN uri_type* destination_url ; URL containing destination information
* OUT uri_type *url ; Fixed and corrected URL
*
* Description:
* Gets destination address from URL and then connects to the remote end
* Description: Gets destination address from URL and then connects to the
* remote end
*
* Returns:
* socket descriptor on sucess
@@ -186,21 +180,19 @@ http_Connect( IN uri_type * destination_url,
return connfd;
}
/************************************************************************
* Function: http_RecvMessage
*
* Parameters:
* IN SOCKINFO *info ; Socket information object
* OUT http_parser_t* parser; HTTP parser object
* OUT http_parser_t* parser, HTTP parser object
* IN http_method_t request_method ; HTTP request method
* IN OUT int* timeout_secs ; time out
* OUT int* http_error_code ; HTTP error code returned
*
* Description:
* Get the data on the socket and take actions based on the read data
* to modify the parser objects buffer. If an error is reported while
* parsing the data, the error code is passed in the http_errr_code
* Description: Get the data on the socket and take actions based on the
* read data to modify the parser objects buffer. If an error is reported
* while parsing the data, the error code is passed in the http_errr_code
* parameter
*
* Returns:
@@ -274,7 +266,6 @@ http_RecvMessage( IN SOCKINFO * info,
}
}
/************************************************************************
* Function: http_SendMessage
*
@@ -283,8 +274,7 @@ http_RecvMessage( IN SOCKINFO * info,
* IN OUT int * TimeOut ; time out value
* IN const char* fmt, ... Pattern format to take actions upon
*
* Description:
* Sends a message to the destination based on the
* Description: Sends a message to the destination based on the
* IN const char* fmt parameter
* fmt types:
* 'f': arg = const char * file name
@@ -307,19 +297,22 @@ http_SendMessage( IN SOCKINFO * info,
IN const char *fmt,
... )
{
#define CHUNK_HEADER_SIZE 10
#define CHUNK_TAIL_SIZE 10
char c;
char *buf = NULL;
size_t buf_length;
char *filename = NULL;
FILE *Fp;
int num_read;
int num_written;
int num_read,
num_written;
off_t amount_to_be_read = 0;
va_list argp;
char *file_buf = NULL;
char *ChunkBuf = NULL;
char *file_buf = NULL,
*ChunkBuf = NULL;
struct SendInstruction *Instr = NULL;
char Chunk_Header[CHUNK_HEADER_SIZE];
char Chunk_Header[10];
int RetVal = 0;
// 10 byte allocated for chunk header.
@@ -329,40 +322,44 @@ http_SendMessage( IN SOCKINFO * info,
while( ( c = *fmt++ ) != 0 ) {
if( c == 'I' ) {
Instr = va_arg(argp, struct SendInstruction *);
Instr = ( struct SendInstruction * )
va_arg( argp, struct SendInstruction * );
assert( Instr );
if( Instr->ReadSendSize >= 0 ) {
if( Instr->ReadSendSize >= 0 )
amount_to_be_read = Instr->ReadSendSize;
} else {
else
amount_to_be_read = Data_Buf_Size;
}
if( amount_to_be_read < WEB_SERVER_BUF_SIZE ) {
if( amount_to_be_read < WEB_SERVER_BUF_SIZE )
Data_Buf_Size = amount_to_be_read;
}
ChunkBuf = (char *)malloc(
Data_Buf_Size + CHUNK_HEADER_SIZE + CHUNK_TAIL_SIZE);
if( !ChunkBuf ) {
ChunkBuf = ( char * )malloc( Data_Buf_Size +
CHUNK_HEADER_SIZE +
CHUNK_TAIL_SIZE );
if( !ChunkBuf )
return UPNP_E_OUTOF_MEMORY;
file_buf = ChunkBuf + 10;
}
file_buf = ChunkBuf + CHUNK_HEADER_SIZE;
} else if( c == 'f' ) {
// file name
filename = va_arg(argp, char *);
if( Instr && Instr->IsVirtualFile ) {
Fp = (virtualDirCallback.open)( filename, UPNP_READ );
} else {
if( c == 'f' ) { // file name
filename = ( char * )va_arg( argp, char * );
if( Instr && Instr->IsVirtualFile )
Fp = virtualDirCallback.open( filename, UPNP_READ );
else
Fp = fopen( filename, "rb" );
}
if( Fp == NULL ) {
free( ChunkBuf );
return UPNP_E_FILE_READ_ERROR;
}
assert( Fp );
if( Instr && Instr->IsRangeActive && Instr->IsVirtualFile ) {
if( virtualDirCallback.seek( Fp, Instr->RangeOffset,
SEEK_CUR ) != 0 ) {
@@ -378,14 +375,26 @@ http_SendMessage( IN SOCKINFO * info,
while( amount_to_be_read ) {
if( Instr ) {
int n = (amount_to_be_read >= Data_Buf_Size) ?
Data_Buf_Size : amount_to_be_read;
if( Instr->IsVirtualFile ) {
num_read = virtualDirCallback.read( Fp, file_buf, n );
if( amount_to_be_read >= Data_Buf_Size ) {
if( Instr->IsVirtualFile )
num_read = virtualDirCallback.read( Fp,
file_buf,
Data_Buf_Size );
else
num_read = fread( file_buf, 1, Data_Buf_Size,
Fp );
} else {
num_read = fread( file_buf, 1, n, Fp );
if( Instr->IsVirtualFile )
num_read = virtualDirCallback.read( Fp,
file_buf,
amount_to_be_read );
else
num_read = fread( file_buf, 1,
amount_to_be_read, Fp );
}
amount_to_be_read = amount_to_be_read - num_read;
if( Instr->ReadSendSize < 0 ) {
//read until close
amount_to_be_read = Data_Buf_Size;
@@ -394,11 +403,12 @@ http_SendMessage( IN SOCKINFO * info,
num_read = fread( file_buf, 1, Data_Buf_Size, Fp );
}
if( num_read == 0 ) {
// EOF so no more to send.
if( num_read == 0 ) // EOF so no more to send.
{
if( Instr && Instr->IsChunkActive ) {
char *str = "0\r\n\r\n";
num_written = sock_write(info, str, strlen(str), TimeOut);
num_written = sock_write( info, "0\r\n\r\n",
strlen( "0\r\n\r\n" ),
TimeOut );
} else {
RetVal = UPNP_E_FILE_READ_ERROR;
}
@@ -422,51 +432,54 @@ http_SendMessage( IN SOCKINFO * info,
// on the top of the buffer.
//file_buf[num_read+strlen(Chunk_Header)] = NULL;
//printf("Sending %s\n",file_buf-strlen(Chunk_Header));
num_written = sock_write(
info, file_buf - strlen( Chunk_Header ),
num_read + strlen( Chunk_Header ) + 2, TimeOut );
num_written = sock_write( info,
file_buf -
strlen( Chunk_Header ),
num_read +
strlen( Chunk_Header ) + 2,
TimeOut );
if( num_written !=
num_read + ( int )strlen( Chunk_Header ) + 2 ) {
// Send error nothing we can do.
goto Cleanup_File;
num_read + ( int )strlen( Chunk_Header )
+ 2 ) {
goto Cleanup_File; //Send error nothing we can do.
}
} else {
// write data
num_written = sock_write( info, file_buf, num_read, TimeOut );
num_written = sock_write( info, file_buf, num_read,
TimeOut );
UpnpPrintf( UPNP_INFO, HTTP, __FILE__, __LINE__,
">>> (SENT) >>>\n%.*s\n------------\n",
( int )num_written, file_buf );
//Send error nothing we can do
if( num_written != num_read ) {
goto Cleanup_File;
}
}
} // while
} //While
Cleanup_File:
va_end( argp );
if( Instr && Instr->IsVirtualFile ) {
if( Instr && Instr->IsVirtualFile )
virtualDirCallback.close( Fp );
} else {
else
fclose( Fp );
}
free( ChunkBuf );
return RetVal;
} else if( c == 'b' ) {
// memory buffer
buf = va_arg(argp, char *);
buf_length = va_arg(argp, size_t);
} else if( c == 'b' ) { // memory buffer
buf = ( char * )va_arg( argp, char * );
buf_length = ( size_t ) va_arg( argp, size_t );
if( buf_length > 0 ) {
num_written = sock_write( info, buf, buf_length, TimeOut );
UpnpPrintf( UPNP_INFO, HTTP, __FILE__, __LINE__,
">>> (SENT) >>>\n"
"%.*s\nbuf_length=%d, num_written=%d\n"
"------------\n",
(int)buf_length, buf, (int)buf_length, num_written );
if( (size_t)num_written != buf_length ) {
if( ( size_t ) num_written != buf_length )
goto end;
}
UpnpPrintf( UPNP_INFO, HTTP, __FILE__, __LINE__,
">>> (SENT) >>>\n%.*s\n------------\n",
( int )buf_length, buf );
}
}
}
@@ -477,7 +490,6 @@ end:
return 0;
}
/************************************************************************
* Function: http_RequestAndResponse
*
@@ -490,8 +502,7 @@ end:
* IN int timeout_secs ; time out value
* OUT http_parser_t* response; Parser object to receive the repsonse
*
* Description:
* Initiates socket, connects to the destination, sends a
* Description: Initiates socket, connects to the destination, sends a
* request and waits for the response from the remote end
*
* Returns:
@@ -551,25 +562,25 @@ http_RequestAndResponse( IN uri_type * destination,
return ret_code;
}
/************************************************************************
* Function : http_Download
*
* Parameters :
* IN const char* url_str; String as a URL
* IN int timeout_secs; time out value
* OUT char** document; buffer to store the document extracted
* IN const char* url_str: String as a URL
* IN int timeout_secs: time out value
* OUT char** document: buffer to store the document extracted
* from the donloaded message.
* OUT int* doc_length; length of the extracted document
* OUT char* content_type; Type of content
* OUT int* doc_length: length of the extracted document
* OUT char* content_type: Type of content
*
* Description:
* Download the document message and extract the document
* Description : Download the document message and extract the document
* from the message.
*
* Return: int
* UPNP_E_SUCCESS
* UPNP_E_INVALID_URL
* Return : int;
* UPNP_E_SUCCESS;
* UPNP_E_INVALID_URL;
*
* Note :
************************************************************************/
int
http_Download( IN const char *url_str,
@@ -671,8 +682,8 @@ http_Download( IN const char *url_str,
if( ( *doc_length = ( int )response.msg.entity.length ) == 0 ) {
// 0-length msg
*document = NULL;
} else if( response.msg.status_code == HTTP_OK ) {
//LEAK_FIX_MK
} else if( response.msg.status_code == HTTP_OK ) //LEAK_FIX_MK
{
// copy entity
entity_start = response.msg.entity.buf; // what we want
msg_length = response.msg.msg.length; // save for posterity
@@ -714,13 +725,12 @@ typedef struct HTTPPOSTHANDLE {
* Parameters:
* const char *url_str ; String as a URL
* membuffer *request ; Buffer containing the request
* uri_type *url; URI object containing the scheme,
* path query token, etc.
* uri_type *url ; URI object containing the scheme, path
* query token, etc.
* int contentLength ; length of content
* const char *contentType ; Type of content
*
* Description:
* Makes the message for the HTTP POST message
* Description: Makes the message for the HTTP POST message
*
* Returns:
* UPNP_E_INVALID_URL
@@ -822,14 +832,15 @@ MakePostMessage( const char *url_str,
* IN unsigned int *size : Size of the data to be sent.
* IN int timeout : time out value
*
* Description:
* Formats data if format used is UPNP_USING_CHUNKED.
* Description : Formats data if format used is UPNP_USING_CHUNKED.
* Writes data on the socket connected to the peer.
*
* Return: int
* Return : int ;
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Parameter
* -1 - On Socket Error.
*
* Note :
************************************************************************/
int
http_WriteHttpPost( IN void *Handle,
@@ -851,18 +862,17 @@ http_WriteHttpPost( IN void *Handle,
if( handle->contentLength == UPNP_USING_CHUNKED ) {
if( ( *size ) ) {
int tempSize = 0;
tempbuf = ( char * )malloc(
*size + CHUNK_HEADER_SIZE + CHUNK_TAIL_SIZE );
if ( tempbuf == NULL) {
return UPNP_E_OUTOF_MEMORY;
}
// begin chunk
sprintf( tempbuf, "%x\r\n", ( *size ) );
tempbuf =
( char * )malloc( ( *size ) + CHUNK_HEADER_SIZE +
CHUNK_TAIL_SIZE );
if ( tempbuf == NULL) return UPNP_E_OUTOF_MEMORY;
sprintf( tempbuf, "%x\r\n", ( *size ) ); //begin chunk
tempSize = strlen( tempbuf );
memcpy( tempbuf + tempSize, buf, ( *size ) );
memcpy( tempbuf + tempSize + ( *size ), "\r\n", 2 );
// end of chunk
memcpy( tempbuf + tempSize + ( *size ), "\r\n", 2 ); //end of chunk
tempbufSize = tempSize + ( *size ) + 2;
freeTempbuf = 1;
}
@@ -891,19 +901,20 @@ http_WriteHttpPost( IN void *Handle,
* Function : http_CloseHttpPost
*
* Parameters :
* IN void *Handle; Handle to the http post object
* IN OUT int *httpStatus; HTTP status returned on receiving a
* IN void *Handle : Handle to the http post object
* IN OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout; time out value
* IN int timeout : time out value
*
* Description:
* Sends remaining data if using UPNP_USING_CHUNKED
* Description : Sends remaining data if using UPNP_USING_CHUNKED
* format. Receives any more messages. Destroys socket and any socket
* associated memory. Frees handle associated with the HTTP POST msg.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
*
* Note :
************************************************************************/
int
http_CloseHttpPost( IN void *Handle,
@@ -944,24 +955,25 @@ http_CloseHttpPost( IN void *Handle,
* Function : http_OpenHttpPost
*
* Parameters :
* IN const char *url_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN const char *contentType; Type of content
* IN int contentLength; length of content
* IN int timeout; time out value
* IN const char *contentType : Type of content
* IN int contentLength : length of content
* IN int timeout : time out value
*
* Description:
* Makes the HTTP POST message, connects to the peer,
* Description : Makes the HTTP POST message, connects to the peer,
* sends the HTTP POST request. Adds the post handle to buffer of
* such handles
*
* Return : int;
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_SOCKET_CONNECT
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Paramter ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_SOCKET_CONNECT ;
*
* Note :
************************************************************************/
int
http_OpenHttpPost( IN const char *url_str,
@@ -1049,8 +1061,7 @@ typedef struct HTTPGETHANDLE {
* uri_type *url ; URI object containing the scheme, path
* query token, etc.
*
* Description:
* Makes the message for the HTTP GET method
* Description: Makes the message for the HTTP GET method
*
* Returns:
* UPNP_E_INVALID_URL
@@ -1140,15 +1151,16 @@ MakeGetMessage( const char *url_str,
* IN OUT int *timeout_secs ; time out value
* IN OUT int *http_error_code ; HTTP errror code returned
*
* Description:
* Parses already exiting data. If not complete reads more
* Description : Parses already exiting data. If not complete reads more
* data on the connected socket. The read data is then parsed. The
* same methid is carried out for headers.
*
* Return: int
* Return : int ;
* PARSE_OK - On Success
* PARSE_FAILURE - Failure to parse data correctly
* UPNP_E_BAD_HTTPMSG - Socker read() returns an error
*
* Note :
************************************************************************/
int
ReadResponseLineAndHeaders( IN SOCKINFO * info,
@@ -1259,21 +1271,22 @@ ReadResponseLineAndHeaders( IN SOCKINFO * info,
* Function : http_ReadHttpGet
*
* Parameters :
* IN void *Handle; Handle to the HTTP get object
* IN OUT char *buf; Buffer to get the read and parsed data
* IN OUT unsigned int *size; Size of the buffer passed
* IN int timeout; time out value
* IN void *Handle : Handle to the HTTP get object
* IN OUT char *buf : Buffer to get the read and parsed data
* IN OUT unsigned int *size : Size of the buffer passed
* IN int timeout : time out value
*
* Description:
* Parses already existing data, then gets new data.
* Description : Parses already existing data, then gets new data.
* Parses and extracts information from the new data.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* UPNP_E_BAD_RESPONSE
* UPNP_E_BAD_HTTPMSG
* UPNP_E_CANCELED
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
* UPNP_E_BAD_RESPONSE ;
* UPNP_E_BAD_HTTPMSG ;
* UPNP_E_CANCELED ;
*
* Note :
************************************************************************/
int
http_ReadHttpGet( IN void *Handle,
@@ -1383,16 +1396,18 @@ http_ReadHttpGet( IN void *Handle,
* Function : http_HttpGetProgress
*
* Parameters :
* IN void *Handle; Handle to the HTTP get object
* OUT unsigned int *length; Buffer to get the read and parsed data
* OUT unsigned int *total; Size of tge buffer passed
* IN void *Handle : Handle to the HTTP get object
* OUT unsigned int *length : Buffer to get the read and parsed data
* OUT unsigned int *total : Size of tge buffer passed
*
* Description:
* Extracts information from the Handle to the HTTP get object.
* Description : Extracts information from the Handle to the HTTP get
* object.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
*
* Note :
************************************************************************/
int http_HttpGetProgress( IN void *Handle,
OUT unsigned int *length,
@@ -1414,12 +1429,13 @@ int http_HttpGetProgress( IN void *Handle,
* Parameters :
* IN void *Handle ; Handle to HTTP get object
*
* Description:
* Set the cancel flag of the HttpGet handle
* Description : Set the cancel flag of the HttpGet handle
*
* Return: int
* Return : int ;
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Parameter
*
* Note :
************************************************************************/
int
http_CancelHttpGet( IN void *Handle )
@@ -1442,13 +1458,14 @@ http_CancelHttpGet( IN void *Handle )
* Parameters :
* IN void *Handle ; Handle to HTTP get object
*
* Description:
* Clears the handle allocated for the HTTP GET operation
* Description : Clears the handle allocated for the HTTP GET operation
* Clears socket states and memory allocated for socket operations.
*
* Return: int
* Return : int ;
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Parameter
*
* Note :
************************************************************************/
int
http_CloseHttpGet( IN void *Handle )
@@ -1479,17 +1496,19 @@ http_CloseHttpGet( IN void *Handle )
* response message
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
************************************************************************/
int
http_OpenHttpGet( IN const char *url_str,
@@ -1506,27 +1525,30 @@ http_OpenHttpGet( IN const char *url_str,
* Function : http_OpenHttpGetProxy
*
* Parameters :
* IN const char *url_str; String as a URL
* IN const char *proxy_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN const char *proxy_str : String as a URL
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN OUT char **contentType; Type of content
* OUT int *contentLength; length of content
* OUT int *httpStatus; HTTP status returned on receiving a
* IN OUT char **contentType : Type of content
* OUT int *contentLength : length of content
* OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the response.
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
* If a proxy URL is defined then the connection is made there.
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
************************************************************************/
int
http_OpenHttpGetProxy( IN const char *url_str,
@@ -1661,21 +1683,22 @@ http_OpenHttpGetProxy( IN const char *url_str,
* Function : http_SendStatusResponse
*
* Parameters :
* IN SOCKINFO *info; Socket information object
* IN int http_status_code; error code returned while making
* IN SOCKINFO *info : Socket information object
* IN int http_status_code : error code returned while making
* or sending the response message
* IN int request_major_version; request major version
* IN int request_minor_version; request minor version
* IN int request_major_version : request major version
* IN int request_minor_version : request minor version
*
* Description:
* Generate a response message for the status query and send the
* status response.
* Description : Generate a response message for the status query and
* send the status response.
*
* Return: int
* Return : int;
* 0 -- success
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_WRITE
* UPNP_E_TIMEDOUT
*
* Note :
************************************************************************/
int
http_SendStatusResponse( IN SOCKINFO * info,
@@ -1711,26 +1734,23 @@ http_SendStatusResponse( IN SOCKINFO * info,
return ret;
}
/************************************************************************
* Function : http_MakeMessage
*
* Parameters :
* INOUT membuffer* buf; buffer with the contents of the
* INOUT membuffer* buf : buffer with the contents of the
* message
* IN int http_major_version; HTTP major version
* IN int http_minor_version; HTTP minor version
* IN const char* fmt; Pattern format
* ...;
* IN int http_major_version : HTTP major version
* IN int http_minor_version : HTTP minor version
* IN const char* fmt : Pattern format
* ... :
*
* Description:
* Generate an HTTP message based on the format that is specified
* in the input parameters.
* Description : Generate an HTTP message based on the format that is
* specified in the input parameters.
*
* fmt types:
* 'B': arg = int status_code
* appends content-length, content-type and HTML body
* for given code
* appends content-length, content-type and HTML body for given code
* 'b': arg1 = const char* buf;
* arg2 = size_t buf_length memory ptr
* 'C': (no args) appends a HTTP CONNECTION: close header
@@ -1756,10 +1776,12 @@ http_SendStatusResponse( IN SOCKINFO * info,
* 'U': (no args) appends HTTP USER-AGENT: header
* 'X': arg = const char useragent; "redsonic" HTTP X-User-Agent: useragent
*
* Return: int
* Return : int;
* 0 - On Success
* UPNP_E_OUTOF_MEMORY
* UPNP_E_INVALID_URL
* UPNP_E_INVALID_URL;
*
* Note :
************************************************************************/
int
http_MakeMessage( INOUT membuffer * buf,
@@ -2014,20 +2036,21 @@ error_handler:
return error_code;
}
/************************************************************************
* Function : http_CalcResponseVersion
*
* Parameters :
* IN int request_major_vers; Request major version
* IN int request_minor_vers; Request minor version
* OUT int* response_major_vers; Response mojor version
* OUT int* response_minor_vers; Response minor version
* IN int request_major_vers : Request major version
* IN int request_minor_vers : Request minor version
* OUT int* response_major_vers : Response mojor version
* OUT int* response_minor_vers : Response minor version
*
* Description:
* Calculate HTTP response versions based on the request versions.
* Description : Calculate HTTP response versions based on the request
* versions.
*
* Return : void
*
* Note :
************************************************************************/
void
http_CalcResponseVersion( IN int request_major_vers,
@@ -2055,8 +2078,7 @@ http_CalcResponseVersion( IN int request_major_vers,
* uri_type *url ; URI object containing the scheme, path
* query token, etc.
*
* Description:
* Makes the message for the HTTP GET method
* Description: Makes the message for the HTTP GET method
*
* Returns:
* UPNP_E_INVALID_URL
@@ -2143,26 +2165,28 @@ MakeGetMessageEx( const char *url_str,
* Function : http_OpenHttpGetEx
*
* Parameters :
* IN const char *url_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN OUT char **contentType; Type of content
* OUT int *contentLength; length of content
* OUT int *httpStatus; HTTP status returned on receiving a
* IN OUT char **contentType : Type of content
* OUT int *contentLength : length of content
* OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout; time out value
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
************************************************************************/
int
http_OpenHttpGetEx( IN const char *url_str,
@@ -2309,18 +2333,19 @@ http_OpenHttpGetEx( IN const char *url_str,
return errCode;
}
/************************************************************************
* Function : get_sdk_info
*
* Parameters :
* OUT char *info; buffer to store the operating system information
* OUT char *info : buffer to store the operating system
* information
*
* Description:
* Returns the server information for the operating system
* Description : Returns the server information for the operating
* system
*
* Return:
* UPNP_INLINE void
* Return : UPNP_INLINE void
*
* Note :
************************************************************************/
// 'info' should have a size of at least 100 bytes
void
@@ -2329,18 +2354,11 @@ get_sdk_info( OUT char *info )
#ifdef WIN32
OSVERSIONINFO versioninfo;
versioninfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
if (GetVersionEx(&versioninfo)!=0) {
sprintf( info,
"%d.%d.%d %d/%s, UPnP/1.0, Portable SDK for UPnP devices/"PACKAGE_VERSION"\r\n",
versioninfo.dwMajorVersion,
versioninfo.dwMinorVersion,
versioninfo.dwBuildNumber,
versioninfo.dwPlatformId,
versioninfo.szCSDVersion );
} else {
if (GetVersionEx(&versioninfo)!=0)
sprintf( info, "%d.%d.%d %d/%s, UPnP/1.0, Portable SDK for UPnP devices/"PACKAGE_VERSION"\r\n",
versioninfo.dwMajorVersion, versioninfo.dwMinorVersion, versioninfo.dwBuildNumber, versioninfo.dwPlatformId, versioninfo.szCSDVersion );
else
*info = '\0';
}
#else
int ret_code;
struct utsname sys_info;
@@ -2349,10 +2367,9 @@ get_sdk_info( OUT char *info )
if( ret_code == -1 ) {
*info = '\0';
}
sprintf( info,
"%s/%s, UPnP/1.0, Portable SDK for UPnP devices/"PACKAGE_VERSION "\r\n",
sys_info.sysname,
sys_info.release );
sprintf( info, "%s/%s, UPnP/1.0, Portable SDK for UPnP devices/"
PACKAGE_VERSION "\r\n",
sys_info.sysname, sys_info.release );
#endif
}

View File

@@ -29,10 +29,10 @@
//
///////////////////////////////////////////////////////////////////////////
/******************************************************************************
/************************************************************************
* Purpose: This file defines the Web Server and has functions to carry out
* operations of the Web Server.
******************************************************************************/
************************************************************************/
#include "config.h"
#include <assert.h>
@@ -64,11 +64,7 @@
/*
Response Types
*/
enum resp_type {
RESP_FILEDOC,
RESP_XMLDOC,
RESP_HEADERS,
RESP_WEBDOC,
enum resp_type { RESP_FILEDOC, RESP_XMLDOC, RESP_HEADERS, RESP_WEBDOC,
RESP_POST };
// mapping of file extension to content-type of document
@@ -186,9 +182,12 @@ static const char *gEncodedMediaTypes =
"zip\0" APPLICATION_STR "zip\0" "\0";
// *** end ***
/************************************************************************
/***********************************************************************/
/*
module variables - Globals, static and externs
************************************************************************/
*/
/***********************************************************************/
static struct document_type_t gMediaTypeList[NUM_MEDIA_TYPES];
membuffer gDocumentRootDir; // a local dir which serves as webserver root
static struct xml_alias_t gAliasDoc; // XML document
@@ -590,9 +589,10 @@ web_server_destroy( void )
* Parameters:
* IN const char* filename ; Filename having the description document
* OUT struct File_Info * info ; File information object having file
* attributes such as filelength, when was the file last
* modified, whether a file or a directory and whether the
* file or directory is readable.
* attributes such as filelength, when was
* the file last modified, whether a file
* or a directory and whether the file or
* directory is readable.
*
* Description: Release memory allocated for the global web server root
* directory and the global XML document
@@ -689,7 +689,8 @@ web_server_set_root_dir( IN const char *root_dir )
* OUT struct xml_alias_t* alias ; xml alias object which has a file name
* stored
* OUT struct File_Info * info ; File information object which will be
* filled up if the file comparison succeeds
* filled up if the file comparison
* succeeds
*
* Description: Compare the files names between the one on the XML alias
* the one passed in as the input parameter. If equal extract file
@@ -869,7 +870,7 @@ StrTok( char **Src,
* OUT int * FirstByte ; gets the first byte of the token
* OUT int * LastByte ; gets the last byte of the token
*
* Description: Returns a range of integers from a string
* Description: Returns a range of integers from a sring
*
* Returns: int ;
* always returns 1;
@@ -879,24 +880,22 @@ GetNextRange( char **SrcRangeStr,
off_t *FirstByte,
off_t *LastByte )
{
char *Ptr;
char *Tok;
int i;
int64_t F = -1;
int64_t L = -1;
char *Ptr,
*Tok;
int i,
F = -1,
L = -1;
int Is_Suffix_byte_Range = 1;
if( *SrcRangeStr == NULL ) {
if( *SrcRangeStr == NULL )
return -1;
}
Tok = StrTok( SrcRangeStr, "," );
if( ( Ptr = strstr( Tok, "-" ) ) == NULL ) {
if( ( Ptr = strstr( Tok, "-" ) ) == NULL )
return -1;
}
*Ptr = ' ';
sscanf( Tok, "%"SCNd64"%"SCNd64, &F, &L );
sscanf( Tok, "%d%d", &F, &L );
if( F == -1 || L == -1 ) {
*Ptr = '-';
@@ -911,15 +910,16 @@ GetNextRange( char **SrcRangeStr,
}
if( Is_Suffix_byte_Range ) {
*FirstByte = (off_t)L;
*LastByte = (off_t)F;
*FirstByte = L;
*LastByte = F;
return 1;
}
}
*FirstByte = (off_t)F;
*LastByte = (off_t)L;
*FirstByte = F;
*LastByte = L;
return 1;
}
/************************************************************************
@@ -928,8 +928,8 @@ GetNextRange( char **SrcRangeStr,
* Parameters:
* char * ByteRangeSpecifier ; String containing the range
* long FileLength ; Length of the file
* OUT struct SendInstruction * Instr ; SendInstruction object
* where the range operations will be stored
* OUT struct SendInstruction * Instr ; SendInstruction object where the
* range operations will be stored
*
* Description: Fills in the Offset, read size and contents to send out
* as an HTTP Range Response
@@ -1531,7 +1531,7 @@ http_RecvPostMessage( http_parser_t * parser,
if( Instr && Instr->IsVirtualFile ) {
Fp = (virtualDirCallback.open)( filename, UPNP_WRITE );
Fp = virtualDirCallback.open( filename, UPNP_WRITE );
if( Fp == NULL ) {
return HTTP_INTERNAL_SERVER_ERROR;
}
@@ -1763,4 +1763,3 @@ web_server_callback( IN http_parser_t * parser,
membuffer_destroy( &headers );
membuffer_destroy( &filename );
}

View File

@@ -555,7 +555,7 @@ parse_hostport( const char *in,
int begin_port;
int hostport_size = 0;
int host_size = 0;
#if !defined(WIN32) && !defined(__OSX__)
#ifndef WIN32
char temp_hostbyname_buff[BUFFER_SIZE];
struct hostent h_buf;
#endif
@@ -628,28 +628,20 @@ parse_hostport( const char *in,
#if defined(WIN32) || defined(__CYGWIN__)
h=gethostbyname(temp_host_name);
#elif defined(SPARC_SOLARIS)
errCode = gethostbyname_r(
temp_host_name,
errCode = gethostbyname_r( temp_host_name,
&h,
temp_hostbyname_buff,
BUFFER_SIZE, &errcode );
#elif defined(__FreeBSD__) && __FreeBSD_version < 601103
h = lwres_gethostbyname_r(
temp_host_name,
h = lwres_gethostbyname_r( temp_host_name,
&h_buf,
temp_hostbyname_buff,
BUFFER_SIZE, &errcode );
if ( h == NULL ) {
errCode = 1;
}
#elif defined(__OSX__)
h = gethostbyname(temp_host_name);
if ( h == NULL ) {
errCode = 1;
}
#elif defined(__linux__)
errCode = gethostbyname_r(
temp_host_name,
errCode = gethostbyname_r( temp_host_name,
&h_buf,
temp_hostbyname_buff,
BUFFER_SIZE, &h, &errcode );
@@ -681,6 +673,7 @@ parse_hostport( const char *in,
}
}
#endif
if( errCode == 0 ) {
if( h ) {
if( ( h->h_addrtype == AF_INET ) && ( h->h_length == 4 ) ) {

View File

@@ -261,7 +261,7 @@
/** @name Other debugging features
The UPnP SDK contains other features to aid in debugging:
see <upnp/inc/upnpdebug.h>
see <upnp/upnpdebug.h>
*/
#define DEBUG_ALL 1

View File

@@ -56,8 +56,7 @@ http_CancelHttpGet( IN void *Handle );
* IN uri_type* url ; URL to be validated and fixed
* OUT uri_type* fixed_url ; URL after being fixed.
*
* Description:
* Validates URL
* Description: Validates URL
*
* Returns:
* UPNP_E_INVALID_URL
@@ -65,7 +64,6 @@ http_CancelHttpGet( IN void *Handle );
************************************************************************/
int http_FixUrl( IN uri_type* url, OUT uri_type* fixed_url );
/************************************************************************
* Function: http_FixStrUrl
*
@@ -74,8 +72,7 @@ int http_FixUrl( IN uri_type* url, OUT uri_type* fixed_url );
* IN int urlstrlen ; Length of the character string
* OUT uri_type* fixed_url ; Fixed and corrected URL
*
* Description:
* Parses URL and then validates URL
* Description: Parses URL and then validates URL
*
* Returns:
* UPNP_E_INVALID_URL
@@ -91,8 +88,8 @@ int http_FixStrUrl( IN char* urlstr, IN int urlstrlen, OUT uri_type* fixed_url )
* IN uri_type* destination_url ; URL containing destination information
* OUT uri_type *url ; Fixed and corrected URL
*
* Description:
* Gets destination address from URL and then connects to the remote end
* Description: Gets destination address from URL and then connects to the
* remote end
*
* Returns:
* socket descriptor on sucess
@@ -101,21 +98,19 @@ int http_FixStrUrl( IN char* urlstr, IN int urlstrlen, OUT uri_type* fixed_url )
************************************************************************/
int http_Connect( IN uri_type* destination_url, OUT uri_type *url );
/************************************************************************
* Function: http_RecvMessage
*
* Parameters:
* IN SOCKINFO *info ; Socket information object
* OUT http_parser_t* parser; HTTP parser object
* OUT http_parser_t* parser, HTTP parser object
* IN http_method_t request_method ; HTTP request method
* IN OUT int* timeout_secs ; time out
* OUT int* http_error_code ; HTTP error code returned
*
* Description:
* Get the data on the socket and take actions based on the read data
* to modify the parser objects buffer. If an error is reported while
* parsing the data, the error code is passed in the http_errr_code
* Description: Get the data on the socket and take actions based on the
* read data to modify the parser objects buffer. If an error is reported
* while parsing the data, the error code is passed in the http_errr_code
* parameter
*
* Returns:
@@ -136,8 +131,7 @@ int http_RecvMessage( IN SOCKINFO *info, OUT http_parser_t* parser,
* IN OUT int * TimeOut ; time out value
* IN const char* fmt, ... Pattern format to take actions upon
*
* Description:
* Sends a message to the destination based on the
* Description: Sends a message to the destination based on the
* IN const char* fmt parameter
* fmt types:
* 'f': arg = const char * file name
@@ -154,12 +148,9 @@ int http_RecvMessage( IN SOCKINFO *info, OUT http_parser_t* parser,
* UPNP_E_FILE_READ_ERROR
* UPNP_E_SUCCESS
************************************************************************/
int http_SendMessage(
IN SOCKINFO *info,
IN OUT int* timeout_secs,
int http_SendMessage( IN SOCKINFO *info, IN OUT int* timeout_secs,
IN const char* fmt, ... );
/************************************************************************
* Function: http_RequestAndResponse
*
@@ -172,8 +163,7 @@ int http_SendMessage(
* IN int timeout_secs ; time out value
* OUT http_parser_t* response ; Parser object to receive the repsonse
*
* Description:
* Initiates socket, connects to the destination, sends a
* Description: Initiates socket, connects to the destination, sends a
* request and waits for the response from the remote end
*
* Returns:
@@ -182,15 +172,12 @@ int http_SendMessage(
* Error Codes returned by http_SendMessage
* Error Codes returned by http_RecvMessage
************************************************************************/
int http_RequestAndResponse(
IN uri_type* destination,
IN const char* request,
IN size_t request_length,
int http_RequestAndResponse( IN uri_type* destination,
IN const char* request, IN size_t request_length,
IN http_method_t req_method,
IN int timeout_secs,
OUT http_parser_t* response );
/************************************************************************
* return codes:
* 0 -- success
@@ -203,31 +190,30 @@ int http_RequestAndResponse(
* UPNP_E_SOCKET_WRITE
************************************************************************/
/************************************************************************
* Function : http_Download
*
* Parameters :
* IN const char* url_str; String as a URL
* IN int timeout_secs; time out value
* OUT char** document; buffer to store the document extracted
* IN const char* url_str : String as a URL
* IN int timeout_secs : time out value
* OUT char** document : buffer to store the document extracted
* from the donloaded message.
* OUT int* doc_length; length of the extracted document
* OUT char* content_type; Type of content
* OUT int* doc_length : length of the extracted document
* OUT char* content_type : Type of content
*
* Description:
* Download the document message and extract the document
* Description : Download the document message and extract the document
* from the message.
*
* Return: int
* UPNP_E_SUCCESS
* UPNP_E_INVALID_URL
* Return : int;
* UPNP_E_SUCCESS;
* UPNP_E_INVALID_URL;
*
*
* Note :
************************************************************************/
int http_Download(
IN const char* url,
int http_Download( IN const char* url,
IN int timeout_secs,
OUT char** document,
OUT int* doc_length,
OUT char** document, OUT int* doc_length,
OUT char* content_type );
@@ -241,66 +227,67 @@ int http_Download(
* IN unsigned int *size : Size of the data to be sent.
* IN int timeout : time out value
*
* Description:
* Formats data if format used is UPNP_USING_CHUNKED.
* Description : Formats data if format used is UPNP_USING_CHUNKED.
* Writes data on the socket connected to the peer.
*
* Return: int
* Return : int ;
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Parameter
* -1 - On Socket Error.
*
* Note :
************************************************************************/
int http_WriteHttpPost(IN void *Handle,
IN char *buf,
IN unsigned int *size,
IN int timeout);
/************************************************************************
* Function : http_CloseHttpPost
*
* Parameters :
* IN void *Handle; Handle to the http post object
* IN OUT int *httpStatus; HTTP status returned on receiving a
* IN void *Handle : Handle to the http post object
* IN OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout; time out value
* IN int timeout : time out value
*
* Description:
* Sends remaining data if using UPNP_USING_CHUNKED
* Description : Sends remaining data if using UPNP_USING_CHUNKED
* format. Receives any more messages. Destroys socket and any socket
* associated memory. Frees handle associated with the HTTP POST msg.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
*
* Note :
************************************************************************/
int http_CloseHttpPost(IN void *Handle,
IN OUT int *httpStatus,
IN int timeout);
/************************************************************************
* Function : http_OpenHttpPost
*
* Parameters :
* IN const char *url_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN const char *contentType; Type of content
* IN int contentLength; length of content
* IN int timeout; time out value
* IN const char *contentType : Type of content
* IN int contentLength : length of content
* IN int timeout : time out value
*
* Description:
* Makes the HTTP POST message, connects to the peer,
* Description : Makes the HTTP POST message, connects to the peer,
* sends the HTTP POST request. Adds the post handle to buffer of
* such handles
*
* Return : int;
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_SOCKET_CONNECT
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Paramter ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_SOCKET_CONNECT ;
*
* Note :
************************************************************************/
int http_OpenHttpPost(IN const char *url_str,
IN OUT void **Handle,
@@ -308,72 +295,69 @@ int http_OpenHttpPost(IN const char *url_str,
IN int contentLength,
IN int timeout);
/************************************************************************
* Function : http_ReadHttpGet
*
* Parameters :
* IN void *Handle; Handle to the HTTP get object
* IN OUT char *buf; Buffer to get the read and parsed data
* IN OUT unsigned int *size; Size of the buffer passed
* IN int timeout; time out value
* IN void *Handle : Handle to the HTTP get object
* IN OUT char *buf : Buffer to get the read and parsed data
* IN OUT unsigned int *size : Size of tge buffer passed
* IN int timeout : time out value
*
* Description:
* Parses already existing data, then gets new data.
* Description : Parses already existing data, then gets new data.
* Parses and extracts information from the new data.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* UPNP_E_BAD_RESPONSE
* UPNP_E_BAD_HTTPMSG
* UPNP_E_CANCELED
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
* UPNP_E_BAD_RESPONSE ;
* UPNP_E_BAD_HTTPMSG ;
*
* Note :
************************************************************************/
int http_ReadHttpGet(
IN void *Handle,
int http_ReadHttpGet(IN void *Handle,
IN OUT char *buf,
IN OUT unsigned int *size,
IN int timeout);
/************************************************************************
* Function : http_HttpGetProgress
*
* Parameters :
* IN void *Handle; Handle to the HTTP get object
* OUT unsigned int *length; Buffer to get the read and parsed data
* OUT unsigned int *total; Size of tge buffer passed
* IN void *Handle : Handle to the HTTP get object
* OUT unsigned int *length : Buffer to get the read and parsed data
* OUT unsigned int *total : Size of tge buffer passed
*
* Description:
* Extracts information from the Handle to the HTTP get object.
* Description : Extracts information from the Handle to the HTTP get
* object.
*
* Return: int
* UPNP_E_SUCCESS - On Sucess
* UPNP_E_INVALID_PARAM - Invalid Parameter
* Return : int ;
* UPNP_E_SUCCESS - On Sucess ;
* UPNP_E_INVALID_PARAM - Invalid Parameter;
*
* Note :
************************************************************************/
int http_HttpGetProgress(
IN void *Handle,
int http_HttpGetProgress(IN void *Handle,
OUT unsigned int *length,
OUT unsigned int *total );
/************************************************************************
* Function : http_CloseHttpGet
*
* Parameters :
* IN void *Handle ; Handle to HTTP get object
*
* Description:
* Clears the handle allocated for the HTTP GET operation
* Description : Clears the handle allocated for the HTTP GET operation
* Clears socket states and memory allocated for socket operations.
*
* Return: int
* Return : int ;
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Parameter
*
* Note :
************************************************************************/
int http_CloseHttpGet(IN void *Handle);
/************************************************************************
* Function : http_OpenHttpGet
*
@@ -387,52 +371,54 @@ int http_CloseHttpGet(IN void *Handle);
* response message
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
************************************************************************/
int http_OpenHttpGet(
IN const char *url_str,
int http_OpenHttpGet(IN const char *url_str,
IN OUT void **Handle,
IN OUT char **contentType,
OUT int *contentLength,
OUT int *httpStatus,
IN int timeout);
/************************************************************************
* Function : http_OpenHttpGetProxy
*
* Parameters :
* IN const char *url_str; String as a URL
* IN const char *proxy_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN const char *proxy_str : String as a URL to the proxy
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN OUT char **contentType; Type of content
* OUT int *contentLength; length of content
* OUT int *httpStatus; HTTP status returned on receiving a
* IN OUT char **contentType : Type of content
* OUT int *contentLength : length of content
* OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the response.
* If a proxy URL is defined then the connection is made there.
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
*
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
************************************************************************/
int http_OpenHttpGetProxy(IN const char *url_str,
IN const char *proxy_str,
@@ -447,25 +433,24 @@ int http_OpenHttpGetProxy(IN const char *url_str,
* Function : http_SendStatusResponse
*
* Parameters :
* IN SOCKINFO *info; Socket information object
* IN int http_status_code; error code returned while making
* IN SOCKINFO *info : Socket information object
* IN int http_status_code : error code returned while making
* or sending the response message
* IN int request_major_version; request major version
* IN int request_minor_version; request minor version
* IN int request_major_version : request major version
* IN int request_minor_version : request minor version
*
* Description:
* Generate a response message for the status query and send the
* status response.
* Description : Generate a response message for the status query and
* send the status response.
*
* Return: int
* Return : int;
* 0 -- success
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_WRITE
* UPNP_E_TIMEDOUT
*
* Note :
************************************************************************/
int http_SendStatusResponse(
IN SOCKINFO *info,
IN int http_status_code,
int http_SendStatusResponse( IN SOCKINFO *info, IN int http_status_code,
IN int request_major_version,
IN int request_minor_version );
@@ -474,103 +459,96 @@ int http_SendStatusResponse(
* Function : http_MakeMessage
*
* Parameters :
* INOUT membuffer* buf; buffer with the contents of the
* INOUT membuffer* buf : buffer with the contents of the
* message
* IN int http_major_version; HTTP major version
* IN int http_minor_version; HTTP minor version
* IN const char* fmt; Pattern format
* ...;
* IN int http_major_version : HTTP major version
* IN int http_minor_version : HTTP minor version
* IN const char* fmt : Pattern format
* ... :
*
* Description:
* Generate an HTTP message based on the format that is specified
* in the input parameters.
* Description : Generate an HTTP message based on the format that is
* specified in the input parameters.
*
* fmt types:
* 'B': arg = int status_code
* appends content-length, content-type and HTML body
* for given code
* 'b': arg1 = const char* buf;
* arg2 = size_t buf_length memory ptr
* 's': arg = const char* C_string
* 'b': arg1 = const char* buf; arg2 = size_t buf_length
* memory ptr
* 'c': (no args) appends CRLF "\r\n"
* 'd': arg = int number // appends decimal number
* 'h': arg = off_t number // appends off_t number
* 't': arg = time_t * gmt_time // appends time in RFC 1123 fmt
* 'D': (no args) appends HTTP DATE: header
* 'S': (no args) appends HTTP SERVER: header
* 'U': (no args) appends HTTP USER-AGENT: header
* 'C': (no args) appends a HTTP CONNECTION: close header
* depending on major,minor version
* 'c': (no args) appends CRLF "\r\n"
* 'D': (no args) appends HTTP DATE: header
* 'd': arg = int number // appends decimal number
* 'G': arg = range information // add range header
* 'h': arg = off_t number // appends off_t number
* 'K': (no args) // add chunky header
* 'N': arg1 = off_t content_length // content-length header
* 'q': arg1 = http_method_t // request start line and HOST header
* arg2 = (uri_type *)
* 'Q': arg1 = http_method_t; // start line of request
* arg2 = char* url;
* arg3 = size_t url_length
* 'N': arg1 = int content_length // content-length header
* 'Q': arg1 = http_method_t; arg2 = char* url;
* arg3 = int url_length // start line of request
* 'R': arg = int status_code // adds a response start line
* 'S': (no args) appends HTTP SERVER: header
* 's': arg = const char* C_string
* 'T': arg = char * content_type; format
* e.g: "text/html"; content-type header
* 't': arg = time_t * gmt_time // appends time in RFC 1123 fmt
* 'U': (no args) appends HTTP USER-AGENT: header
* 'X': arg = const char useragent; "redsonic" HTTP X-User-Agent: useragent
* 'B': arg = int status_code
* appends content-length, content-type and HTML body for given code
* 'T': arg = char * content_type; format e.g: "text/html";
* content-type header
*
* Return: int
* Return : int;
* 0 - On Success
* UPNP_E_OUTOF_MEMORY
* UPNP_E_INVALID_URL
* UPNP_E_INVALID_URL;
*
* Note :
************************************************************************/
int http_MakeMessage(
INOUT membuffer* buf,
int http_MakeMessage( INOUT membuffer* buf,
IN int http_major_version,
IN int http_minor_version,
IN const char* fmt, ... );
/************************************************************************
* Function : http_CalcResponseVersion
*
* Parameters :
* IN int request_major_vers; Request major version
* IN int request_minor_vers; Request minor version
* OUT int* response_major_vers; Response mojor version
* OUT int* response_minor_vers; Response minor version
* IN int request_major_vers : Request major version
* IN int request_minor_vers : Request minor version
* OUT int* response_major_vers : Response mojor version
* OUT int* response_minor_vers : Response minor version
*
* Description:
* Calculate HTTP response versions based on the request versions.
* Description : Calculate HTTP response versions based on the request
* versions.
*
* Return : void
*
* Note :
************************************************************************/
void http_CalcResponseVersion(
IN int request_major_vers,
IN int request_minor_vers,
OUT int* response_major_vers,
OUT int* response_minor_vers );
IN int request_major_vers, IN int request_minor_vers,
OUT int* response_major_vers, OUT int* response_minor_vers );
/************************************************************************
* Function : http_OpenHttpGetEx
*
* Parameters :
* IN const char *url_str; String as a URL
* IN OUT void **Handle; Pointer to buffer to store HTTP
* IN const char *url_str : String as a URL
* IN OUT void **Handle : Pointer to buffer to store HTTP
* post handle
* IN OUT char **contentType; Type of content
* OUT int *contentLength; length of content
* OUT int *httpStatus; HTTP status returned on receiving a
* IN OUT char **contentType : Type of content
* OUT int *contentLength : length of content
* OUT int *httpStatus : HTTP status returned on receiving a
* response message
* IN int timeout; time out value
* IN int timeout : time out value
*
* Description:
* Makes the HTTP GET message, connects to the peer,
* Description : Makes the HTTP GET message, connects to the peer,
* sends the HTTP GET request, gets the response and parses the
* response.
*
* Return: int
* UPNP_E_SUCCESS - On Success
* UPNP_E_INVALID_PARAM - Invalid Paramters
* UPNP_E_OUTOF_MEMORY
* UPNP_E_SOCKET_ERROR
* UPNP_E_BAD_RESPONSE
* Return : int;
* UPNP_E_SUCCESS - On Success ;
* UPNP_E_INVALID_PARAM - Invalid Paramters ;
* UPNP_E_OUTOF_MEMORY ;
* UPNP_E_SOCKET_ERROR ;
* UPNP_E_BAD_RESPONSE ;
*
* Note :
*
************************************************************************/
int http_OpenHttpGetEx(IN const char *url_str,
IN OUT void **Handle,
@@ -581,18 +559,18 @@ int http_OpenHttpGetEx(IN const char *url_str,
IN int highRange,
IN int timeout);
/************************************************************************
* Function : get_sdk_info
*
* Parameters :
* OUT char *info; buffer to store the operating system information
* OUT char *info ;
*
* Description:
* Returns the server information for the operating system
* Description : Returns the server information for the operating
* system
*
* Return:
* UPNP_INLINE void
* Return : void ;
*
* Note :
************************************************************************/
void get_sdk_info( OUT char *info );
@@ -602,4 +580,3 @@ void get_sdk_info( OUT char *info );
#endif // GENLIB_NET_HTTP_HTTPREADWRITE_H

View File

@@ -1,67 +1,63 @@
/************************************************************************
*
* Copyright (c) 2000-2003 Intel Corporation
* 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.
* Neither name of Intel Corporation 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 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 INTEL 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.
*
************************************************************************/
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000-2003 Intel Corporation
// 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.
// * Neither name of Intel Corporation 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 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 INTEL 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.
//
///////////////////////////////////////////////////////////////////////////
#ifndef MINISERVER_H
#define MINISERVER_H
#include "sock.h"
#include "httpparser.h"
extern SOCKET gMiniServerStopSock;
typedef struct MServerSockArray {
/* socket for listening for miniserver requests */
int miniServerSock;
/* socket for stopping miniserver */
int miniServerStopSock;
/* socket for incoming advertisments and search requests */
int ssdpSock;
int miniServerSock; //socket for listening for miniserver
//requests
int miniServerStopSock; //socket for stopping miniserver
int ssdpSock; //socket for incoming advertisments and search requests
int stopPort;
int miniServerPort;
/* socket for sending search requests and receiving search replies */
CLIENTONLY(int ssdpReqSock;)
CLIENTONLY(int ssdpReqSock;) //socket for sending search
//requests and receiving
// search replies
} MiniServerSockArray;
//typedef void (*MiniServerCallback) ( const char* document, int sockfd );
typedef void (*MiniServerCallback)(
IN http_parser_t *parser,
typedef void (*MiniServerCallback) ( IN http_parser_t *parser,
IN http_message_t* request,
IN SOCKINFO *info );
#ifdef __cplusplus
extern "C" {
#endif
@@ -75,6 +71,8 @@ extern "C" {
* Description : Set HTTP Get Callback
*
* Return : void
*
* Note :
************************************************************************/
void SetHTTPGetCallback( MiniServerCallback callback );
@@ -87,12 +85,14 @@ void SetHTTPGetCallback( MiniServerCallback callback );
* Description : Set SOAP Callback
*
* Return : void
*
* Note :
************************************************************************/
#ifdef INCLUDE_DEVICE_APIS
void SetSoapCallback( MiniServerCallback callback );
#else /* INCLUDE_DEVICE_APIS */
#else
static inline void SetSoapCallback( MiniServerCallback callback ) {}
#endif /* INCLUDE_DEVICE_APIS */
#endif
/************************************************************************
* Function : SetGenaCallback
@@ -100,9 +100,11 @@ static inline void SetSoapCallback( MiniServerCallback callback ) {}
* Parameters :
* MiniServerCallback callback ; - GENA Callback to be invoked
*
* D6escription: Set GENA Callback
* Description : Set GENA Callback
*
* Return : void
*
* Note :
************************************************************************/
void SetGenaCallback( MiniServerCallback callback );
@@ -124,6 +126,7 @@ void SetGenaCallback( MiniServerCallback callback );
* Return : int ;
* Actual port socket is bound to - On Success:
* A negative number UPNP_E_XXX - On Error
* Note :
************************************************************************/
int StartMiniServer( unsigned short listen_port );
@@ -133,18 +136,19 @@ int StartMiniServer( unsigned short listen_port );
* Parameters :
* void ;
*
* Description: Stop and Shutdown the MiniServer and free socket resources.
* Description : Stop and Shutdown the MiniServer and free socket
* resources.
*
* Return : int ;
* Always returns 0
*
* Note :
************************************************************************/
int StopMiniServer();
int StopMiniServer( void );
#ifdef __cplusplus
} /* extern C */
#endif
#endif /* MINISERVER_H */

View File

@@ -98,25 +98,18 @@ struct Handle_Info
int aliasInstalled; // 0 = not installed; otherwise installed
};
extern ithread_rwlock_t GlobalHndRWLock;
extern ithread_mutex_t GlobalHndMutex;
Upnp_Handle_Type GetHandleInfo(int Hnd, struct Handle_Info **HndInfo);
#define HandleLock() HandleWriteLock()
#define HandleWriteLock() \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Trying a write lock"); \
ithread_rwlock_wrlock(&GlobalHndRWLock); \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Write lock acquired");
#define HandleReadLock() \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Trying a read lock"); \
ithread_rwlock_rdlock(&GlobalHndRWLock); \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Read lock acquired");
#define HandleLock() \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Trying Lock"); \
ithread_mutex_lock(&GlobalHndMutex); \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "LOCK");
#define HandleUnlock() \
UpnpPrintf(UPNP_INFO, API,__FILE__, __LINE__, "Trying Unlock"); \
ithread_rwlock_unlock(&GlobalHndRWLock); \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Unlocked rwlock");
ithread_mutex_unlock(&GlobalHndMutex); \
UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__, "Unlock");
Upnp_Handle_Type GetClientHandleInfo(int *client_handle_out,
struct Handle_Info **HndInfo);

View File

@@ -125,7 +125,7 @@ ssdp_handle_ctrlpt_msg( IN http_message_t * hmsg,
// we are assuming that there can be only one client supported at a time
HandleReadLock();
HandleLock();
if( GetClientHandleInfo( &handle, &ctrlpt_info ) != HND_CLIENT ) {
HandleUnlock();
@@ -538,7 +538,8 @@ SearchByTarget( IN int Mx,
if( ReqBuf == NULL )
return UPNP_E_OUTOF_MEMORY;
UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__, ">>> SSDP SEND >>>\n");
UpnpPrintf( UPNP_INFO, SSDP, __FILE__, __LINE__,
">>> SSDP SEND >>>\n%s\n", ReqBuf );
timeTillRead = Mx;

View File

@@ -242,7 +242,7 @@ NewRequestHandler( IN struct sockaddr_in *DestAddr,
// "If a multicast resource would send a response(s) to any copy of the
// request, it SHOULD send its response(s) to each copy of the request
// it receives. It MUST NOT repeat its response(s) per copy of the
// request."
// reuqest."
//
// http://www.upnp.org/download/draft-goland-http-udp-04.txt
//
@@ -530,6 +530,7 @@ SendReply( IN struct sockaddr_in *DestAddr,
* IN char * Udn: Device UDN
* IN char * Location: Location of Device description document.
* IN int Duration :Life time of this device.
* Description:
* This function creates the reply packet based on the input parameter,
* and send it to the client address given in its input parameter DestAddr.
@@ -606,9 +607,11 @@ DeviceReply( IN struct sockaddr_in *DestAddr,
* IN char *ServType: Service Type.
* IN char * Location: Location of Device description document.
* IN int Duration :Life time of this device.
* Description:
* This function creates the advertisement packet based
* on the input parameter, and send it to the multicast channel.
*
* Returns: int
* UPNP_E_SUCCESS if successful else appropriate error
@@ -653,9 +656,11 @@ ServiceAdvertisement( IN char *Udn,
* IN char *ServType: Service Type.
* IN char * Location: Location of Device description document.
* IN int Duration :Life time of this device.
* Description:
* This function creates the advertisement packet based
* on the input parameter, and send it to the multicast channel.
*
* Returns: int
* UPNP_E_SUCCESS if successful else appropriate error
@@ -695,6 +700,7 @@ ServiceReply( IN struct sockaddr_in *DestAddr,
* IN char *ServType: Service Type.
* IN char * Location: Location of Device description document.
* IN int Duration :Service duration in sec.
* Description:
* This function creates a HTTP service shutdown request packet
* and sent it to the multicast channel through RequestHandler.
@@ -815,4 +821,3 @@ DeviceShutdown( IN char *DevType,
#endif // EXCLUDE_SSDP
#endif // INCLUDE_DEVICE_APIS

View File

@@ -50,7 +50,8 @@
#define MAX_TIME_TOREAD 45
CLIENTONLY( SOCKET gSsdpReqSocket = 0; )
CLIENTONLY( SOCKET gSsdpReqSocket = 0;
)
void RequestHandler( );
Event ErrotEvt;
@@ -60,10 +61,11 @@ enum Listener { Idle, Stopping, Running };
unsigned short ssdpStopPort;
struct SSDPSockArray {
// socket for incoming advertisments and search requests
int ssdpSock;
// socket for sending search requests and receiving search replies
CLIENTONLY( int ssdpReqSock; )
int ssdpSock; //socket for incoming advertisments and search requests
CLIENTONLY( int ssdpReqSock;
) //socket for sending search
//requests and receiving
// search replies
};
#ifdef INCLUDE_DEVICE_APIS
@@ -73,9 +75,7 @@ struct SSDPSockArray {
* Function : AdvertiseAndReply
*
* Parameters:
* IN int AdFlag:
* -1 = Send shutdown,
* 0 = send reply,
* IN int AdFlag: -1 = Send shutdown, 0 = send reply,
* 1 = Send Advertisement
* IN UpnpDevice_Handle Hnd: Device handle
* IN enum SsdpSearchType SearchType:Search type for sending replies
@@ -120,14 +120,18 @@ int AdvertiseAndReply( IN int AdFlag,
"Inside AdvertiseAndReply with AdFlag = %d\n",
AdFlag );
// Use a read lock
HandleReadLock();
HandleLock();
if( GetHandleInfo( Hnd, &SInfo ) != HND_DEVICE ) {
HandleUnlock();
return UPNP_E_INVALID_HANDLE;
}
defaultExp = SInfo->MaxAge;
//Modifed to prevent more than one thread from accessing the
//UpnpDocument stored with the handle at the same time
// HandleUnlock();
nodeList = NULL;
//get server info
get_sdk_info( SERVER );
@@ -147,12 +151,14 @@ int AdvertiseAndReply( IN int AdFlag,
dbgStr = ixmlNode_getNodeName( tmpNode );
UpnpPrintf( UPNP_INFO, API, __FILE__, __LINE__,
"Extracting device type once for %s\n", dbgStr );
"Extracting device type once for %s\n",
dbgStr );
// extract device type
ixmlNodeList_free( nodeList );
nodeList = NULL;
nodeList = ixmlElement_getElementsByTagName(
( IXML_Element * ) tmpNode, "deviceType" );
nodeList =
ixmlElement_getElementsByTagName( ( IXML_Element * ) tmpNode,
"deviceType" );
if( nodeList == NULL ) {
continue;
}
@@ -160,6 +166,7 @@ int AdvertiseAndReply( IN int AdFlag,
dbgStr = ixmlNode_getNodeName( tmpNode );
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Extracting UDN for %s\n", dbgStr );
UpnpPrintf( UPNP_ALL, API, __FILE__, __LINE__,
"Extracting device type\n" );
@@ -234,7 +241,8 @@ int AdvertiseAndReply( IN int AdFlag,
if( AdFlag == 1 ) {
DeviceAdvertisement( devType, i == 0,
UDNstr, SInfo->DescURL, Exp );
} else { // AdFlag == -1
} else // AdFlag == -1
{
DeviceShutdown( devType, i == 0, UDNstr,
SERVER, SInfo->DescURL, Exp );
}
@@ -316,9 +324,8 @@ int AdvertiseAndReply( IN int AdFlag,
}
for( j = 0;; j++ ) {
tmpNode = ixmlNodeList_item( nodeList, j );
if( tmpNode == NULL ) {
if( tmpNode == NULL )
break;
}
ixmlNodeList_free( tmpNodeList );
tmpNodeList = NULL;
@@ -360,21 +367,26 @@ int AdvertiseAndReply( IN int AdFlag,
} else {
switch ( SearchType ) {
case SSDP_ALL:
{
ServiceReply( DestAddr, servType,
UDNstr, SInfo->DescURL,
defaultExp );
break;
}
case SSDP_SERVICE:
{
if( ServiceType != NULL ) {
if( !strncasecmp( ServiceType,
servType,
strlen( ServiceType ) ) ) {
strlen( ServiceType ) ) )
{
ServiceReply( DestAddr, servType,
UDNstr, SInfo->DescURL,
defaultExp );
}
}
break;
}
default:
break;
} // switch(SearchType)
@@ -395,8 +407,8 @@ int AdvertiseAndReply( IN int AdFlag,
} /****************** End of AdvertiseAndReply *********************/
#endif /* EXCLUDE_SSDP == 0 */
#endif /* INCLUDE_DEVICE_APIS */
#endif
#endif
/************************************************************************
* Function : Make_Socket_NoBlocking
@@ -734,7 +746,8 @@ ssdp_event_handler_thread( void *the_data )
// send msg to device or ctrlpt
if( ( hmsg->method == HTTPMETHOD_NOTIFY ) ||
( hmsg->request_method == HTTPMETHOD_MSEARCH ) ) {
CLIENTONLY( ssdp_handle_ctrlpt_msg( hmsg, &data->dest_addr, FALSE, NULL );)
CLIENTONLY( ssdp_handle_ctrlpt_msg( hmsg, &data->dest_addr,
FALSE, NULL ););
} else {
ssdp_handle_device_request( hmsg, &data->dest_addr );
}
@@ -806,20 +819,18 @@ readFromSSDPSocket( SOCKET socket )
( struct sockaddr * )&clientAddr, &socklen );
if( byteReceived > 0 ) {
requestBuf[byteReceived] = '\0';
UpnpPrintf( UPNP_INFO, SSDP,
__FILE__, __LINE__,
"Start of received response ----------------------------------------------------\n"
"%s\n"
"End of received response ------------------------------------------------------\n"
"From host %s\n",
"Received response !!! "
"%s From host %s \n",
requestBuf,
inet_ntoa( clientAddr.sin_addr ) );
UpnpPrintf( UPNP_PACKET, SSDP, __FILE__, __LINE__,
"Start of received multicast packet --------------------------------------------\n"
"%s\n"
"End of received multicast packet ----------------------------------------------\n",
requestBuf );
"Received multicast packet:"
"\n %s\n", requestBuf );
//add thread pool job to handle request
if( data != NULL ) {
data->parser.msg.msg.length += byteReceived;
@@ -856,45 +867,48 @@ readFromSSDPSocket( SOCKET socket )
int
get_ssdp_sockets( MiniServerSockArray * out )
{
SOCKET ssdpSock;
CLIENTONLY( SOCKET ssdpReqSock;
)
int onOff = 1;
u_char ttl = 4;
struct ip_mreq ssdpMcastAddr;
struct sockaddr_in ssdpAddr;
int option = 1;
struct in_addr addr;
SOCKET ssdpSock;
#if INCLUDE_CLIENT_APIS
SOCKET ssdpReqSock;
if( ( ssdpReqSock = socket( AF_INET, SOCK_DGRAM, 0 ) ) == UPNP_INVALID_SOCKET ) {
CLIENTONLY( if( ( ssdpReqSock = socket( AF_INET, SOCK_DGRAM, 0 ) )
== UPNP_INVALID_SOCKET ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in socket operation !!!\n" );
return UPNP_E_OUTOF_SOCKET;
}
setsockopt( ssdpReqSock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof( ttl ) );
return UPNP_E_OUTOF_SOCKET;}
setsockopt( ssdpReqSock,
IPPROTO_IP,
IP_MULTICAST_TTL, &ttl, sizeof( ttl ) );
// just do it, regardless if fails or not.
Make_Socket_NoBlocking( ssdpReqSock );
gSsdpReqSocket = ssdpReqSock;
#endif /* INCLUDE_CLIENT_APIS */
Make_Socket_NoBlocking( ssdpReqSock ); gSsdpReqSocket = ssdpReqSock; ) //CLIENTONLY
if( ( ssdpSock = socket( AF_INET, SOCK_DGRAM, 0 ) ) == UPNP_INVALID_SOCKET ) {
if( ( ssdpSock = socket( AF_INET, SOCK_DGRAM, 0 ) )
== UPNP_INVALID_SOCKET ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in socket operation !!!\n" );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
return UPNP_E_OUTOF_SOCKET;
}
onOff = 1;
if( setsockopt( ssdpSock, SOL_SOCKET, SO_REUSEADDR,
( char * )&onOff, sizeof( onOff ) ) != 0 ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in set reuse addr !!!\n" );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
shutdown( ssdpSock, SD_BOTH );
UpnpCloseSocket( ssdpSock );
return UPNP_E_SOCKET_ERROR;
@@ -903,31 +917,33 @@ get_ssdp_sockets( MiniServerSockArray * out )
#ifdef __FreeBSD__
if( setsockopt( ssdpSock, SOL_SOCKET, SO_REUSEPORT,
( char * )&onOff, sizeof( onOff ) ) != 0 ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in set reuse port !!!\n" );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
shutdown( ssdpSock, SD_BOTH );
UpnpCloseSocket( ssdpSock );
return UPNP_E_SOCKET_ERROR;
}
#endif /* __FreeBSD__ */
#endif
memset( ( void * )&ssdpAddr, 0, sizeof( struct sockaddr_in ) );
ssdpAddr.sin_family = AF_INET;
// ssdpAddr.sin_addr.s_addr = inet_addr(LOCAL_HOST);
ssdpAddr.sin_addr.s_addr = htonl( INADDR_ANY );
ssdpAddr.sin_port = htons( SSDP_PORT );
if( bind( ssdpSock, ( struct sockaddr * )&ssdpAddr,
if( bind
( ssdpSock, ( struct sockaddr * )&ssdpAddr,
sizeof( ssdpAddr ) ) != 0 ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in binding !!!\n" );
shutdown( ssdpSock, SD_BOTH );
UpnpCloseSocket( ssdpSock );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
return UPNP_E_SOCKET_BIND;
}
@@ -935,14 +951,15 @@ get_ssdp_sockets( MiniServerSockArray * out )
ssdpMcastAddr.imr_interface.s_addr = inet_addr( LOCAL_HOST );
ssdpMcastAddr.imr_multiaddr.s_addr = inet_addr( SSDP_IP );
if( setsockopt( ssdpSock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
( char * )&ssdpMcastAddr, sizeof( struct ip_mreq ) ) != 0 ) {
( char * )&ssdpMcastAddr,
sizeof( struct ip_mreq ) ) != 0 ) {
UpnpPrintf( UPNP_CRITICAL,
SSDP, __FILE__, __LINE__,
"Error in joining" " multicast group !!!\n" );
shutdown( ssdpSock, SD_BOTH );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
UpnpCloseSocket( ssdpSock );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
return UPNP_E_SOCKET_ERROR;
}
@@ -956,7 +973,7 @@ get_ssdp_sockets( MiniServerSockArray * out )
/* This is probably not a critical error, so let's continue. */
}
/* result is not checked becuase it will fail in WinMe and Win9x. */
// result is not checked becuase it will fail in WinMe and Win9x.
setsockopt( ssdpSock, IPPROTO_IP,
IP_MULTICAST_TTL, &ttl, sizeof( ttl ) );
if( setsockopt( ssdpSock, SOL_SOCKET, SO_BROADCAST,
@@ -965,16 +982,16 @@ get_ssdp_sockets( MiniServerSockArray * out )
SSDP, __FILE__, __LINE__,
"Error in setting broadcast !!!\n" );
shutdown( ssdpSock, SD_BOTH );
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ); )
CLIENTONLY( shutdown( ssdpReqSock, SD_BOTH ) );
UpnpCloseSocket( ssdpSock );
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ); )
CLIENTONLY( UpnpCloseSocket( ssdpReqSock ) );
return UPNP_E_NETWORK_ERROR;
}
CLIENTONLY( out->ssdpReqSock = ssdpReqSock; )
CLIENTONLY( out->ssdpReqSock = ssdpReqSock;
);
out->ssdpSock = ssdpSock;
return UPNP_E_SUCCESS;
}
#endif /* EXCLUDE_SSDP */
#endif // EXCLUDE_SSDP

View File

@@ -50,11 +50,22 @@
#define S43 15
#define S44 21
static void MD5Transform PROTO_LIST((UINT4[4], unsigned char[64]));
static void Encode PROTO_LIST((unsigned char *, UINT4 *, unsigned int));
static void Decode PROTO_LIST((UINT4 *, unsigned char *, unsigned int));
static void MD5_memcpy PROTO_LIST((POINTER, POINTER, unsigned int));
static void MD5_memset PROTO_LIST((POINTER, int, unsigned int));
static void MD5Transform PROTO_LIST( ( UINT4[4],
unsigned char[64] ) );
static void Encode PROTO_LIST( ( unsigned char *,
UINT4 *,
unsigned int ) );
static void Decode PROTO_LIST( ( UINT4 *,
unsigned char *,
unsigned int ) );
static void MD5_memcpy PROTO_LIST( ( POINTER,
POINTER,
unsigned int ) );
static void MD5_memset PROTO_LIST( ( POINTER,
int,
unsigned int ) );
static unsigned char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -107,10 +118,14 @@ static unsigned char PADDING[64] = {
MD5 initialization. Begins an MD5 operation, writing a new context.
*/
void
MD5Init(MD5_CTX * context)
MD5Init( context )
MD5_CTX *context; /* context */
{
context->count[0] = context->count[1] = 0;
/* Load magic initialization constants. */
/*
Load magic initialization constants.
*/
context->state[0] = 0x67452301;
context->state[1] = 0xefcdab89;
context->state[2] = 0x98badcfe;
@@ -124,72 +139,114 @@ MD5Init(MD5_CTX * context)
*/
void
MD5Update(MD5_CTX *context, unsigned char *input, unsigned int inputLen)
MD5Update( context,
input,
inputLen )
MD5_CTX *context; /* context */
unsigned char *input; /* input block */
unsigned int inputLen; /* length of input block */
{
unsigned int i;
unsigned int index;
unsigned int partLen;
unsigned int i,
index,
partLen;
/* Compute number of bytes mod 64 */
/*
Compute number of bytes mod 64
*/
index = ( unsigned int )( ( context->count[0] >> 3 ) & 0x3F );
/* Update number of bits */
if ((context->count[0] += ((UINT4)inputLen << 3)) < ((UINT4)inputLen << 3)) {
/*
Update number of bits
*/
if( ( context->count[0] +=
( ( UINT4 ) inputLen << 3 ) ) < ( ( UINT4 ) inputLen << 3 ) )
context->count[1]++;
}
context->count[1] += ( ( UINT4 ) inputLen >> 29 );
partLen = 64 - index;
/* Transform as many times as possible. */
/*
Transform as many times as possible.
*/
if( inputLen >= partLen ) {
MD5_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
MD5Transform(context->state, context->buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
MD5Transform(context->state, &input[i]);
}
index = 0;
} else {
i = 0;
}
/* Buffer remaining input */
MD5_memcpy((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen - i);
MD5_memcpy
( ( POINTER ) & context->buffer[index], ( POINTER ) input,
partLen );
MD5Transform( context->state, context->buffer );
for( i = partLen; i + 63 < inputLen; i += 64 )
MD5Transform( context->state, &input[i] );
index = 0;
} else
i = 0;
/*
Buffer remaining input
*/
MD5_memcpy
( ( POINTER ) & context->buffer[index], ( POINTER ) & input[i],
inputLen - i );
}
/*
MD5 finalization. Ends an MD5 message-digest operation, writing the
the message digest and zeroizing the context.
*/
void
MD5Final(unsigned char digest[16], MD5_CTX *context)
{
unsigned char bits[8];
unsigned int index;
unsigned int padLen;
/* Save number of bits */
void
MD5Final( digest,
context )
unsigned char digest[16]; /* message digest */
MD5_CTX *context; /* context */
{
unsigned char bits[8];
unsigned int index,
padLen;
/*
Save number of bits
*/
Encode( bits, context->count, 8 );
/* Pad out to 56 mod 64. */
/*
Pad out to 56 mod 64.
*/
index = ( unsigned int )( ( context->count[0] >> 3 ) & 0x3f );
padLen = ( index < 56 ) ? ( 56 - index ) : ( 120 - index );
MD5Update( context, PADDING, padLen );
/* Append length (before padding) */
/*
Append length (before padding)
*/
MD5Update( context, bits, 8 );
/* Store state in digest */
/*
Store state in digest
*/
Encode( digest, context->state, 16 );
/* Zeroize sensitive information. */
/*
Zeroize sensitive information.
*/
MD5_memset( ( POINTER ) context, 0, sizeof( *context ) );
}
/*
MD5 basic transformation. Transforms state based on block.
*/
static void
MD5Transform(UINT4 state[4], unsigned char block[64])
MD5Transform( state,
block )
UINT4 state[4];
unsigned char block[64];
{
UINT4 a = state[0],
b = state[1],
@@ -296,16 +353,23 @@ MD5Transform(UINT4 state[4], unsigned char block[64])
a multiple of 4.
*/
static void
Encode(unsigned char *output, UINT4 *input, unsigned int len)
Encode( output,
input,
len )
unsigned char *output;
UINT4 *input;
unsigned int len;
{
unsigned int i;
unsigned int j;
for (i = 0, j = 0; j < len; ++i, j += 4) {
output[j+0] = (unsigned char)((input[i] >> 0) & 0xff);
unsigned int i,
j;
for( i = 0, j = 0; j < len; i++, j += 4 ) {
output[j] = ( unsigned char )( input[i] & 0xff );
output[j + 1] = ( unsigned char )( ( input[i] >> 8 ) & 0xff );
output[j + 2] = ( unsigned char )( ( input[i] >> 16 ) & 0xff );
output[j + 3] = ( unsigned char )( ( input[i] >> 24 ) & 0xff );
}
}
/*
@@ -314,40 +378,55 @@ Encode(unsigned char *output, UINT4 *input, unsigned int len)
*/
static void
Decode(UINT4 *output, unsigned char *input, unsigned int len)
Decode( output,
input,
len )
UINT4 *output;
unsigned char *input;
unsigned int len;
{
unsigned int i;
unsigned int j;
for (i = 0, j = 0; j < len; ++i, j += 4) {
unsigned int i,
j;
for( i = 0, j = 0; j < len; i++, j += 4 )
output[i] =
(((UINT4)input[j+0]) << 0) |
(((UINT4)input[j+1]) << 8) |
( ( UINT4 ) input[j] ) | ( ( ( UINT4 ) input[j + 1] ) << 8 ) |
( ( ( UINT4 ) input[j + 2] ) << 16 ) |
( ( ( UINT4 ) input[j + 3] ) << 24 );
}
}
/*
Note: Replace for loop with standard memcpy if possible.
Note: Replace &quot;for loop&quot; with standard memcpy if possible.
*/
static void
MD5_memcpy(POINTER output, POINTER input, unsigned int len)
MD5_memcpy( output,
input,
len )
POINTER output;
POINTER input;
unsigned int len;
{
unsigned int i;
for (i = 0; i < len; ++i) {
for( i = 0; i < len; i++ )
output[i] = input[i];
}
}
/*
Note: Replace for loop with standard memset if possible.
Note: Replace &quot;for loop&quot; with standard memset if possible.
*/
static void
MD5_memset(POINTER output, int value, unsigned int len)
MD5_memset( output,
value,
len )
POINTER output;
int value;
unsigned int len;
{
unsigned int i;
for (i = 0; i < len; ++i) {
((char *)output)[i] = (char)value;
}
}
for( i = 0; i < len; i++ )
( ( char * )output )[i] = ( char )value;
}

View File

@@ -43,6 +43,7 @@ get_ieee_node_identifier(uuid_node_t *node)
get_random_info( seed );
seed[0] |= 0x80;
memcpy( &saved_node, seed, sizeof( uuid_node_t ) );
inited = 1;
};
@@ -96,30 +97,34 @@ get_random_info(char seed[16])
} randomness;
randomness r;
/* Initialize memory area so that valgrind does not complain */
memset(&r, 0, sizeof r);
/* memory usage stats */
MD5Init( &c );
/*
memory usage stats
*/
GlobalMemoryStatus( &r.m );
/* random system stats */
/*
random system stats
*/
GetSystemInfo( &r.s );
/* 100ns resolution (nominally) time of day */
/*
100ns resolution (nominally) time of day
*/
GetSystemTimeAsFileTime( &r.t );
/* high resolution performance counter */
/*
high resolution performance counter
*/
QueryPerformanceCounter( &r.pc );
/* milliseconds since last boot */
/*
milliseconds since last boot
*/
r.tc = GetTickCount( );
r.l = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName( r.hostname, &r.l );
/* MD5 it */
MD5Init(&c);
MD5Update(&c, &r, sizeof r);
MD5Update( &c, &r, sizeof( randomness ) );
MD5Final( seed, &c );
};
#else /* _WINDOWS_ */
#else
/*-----------------------------------------------------------------------------*/
void
@@ -150,18 +155,12 @@ get_random_info(char seed[16])
} randomness;
randomness r;
/* Initialize memory area so that valgrind does not complain */
memset(&r, 0, sizeof r);
MD5Init( &c );
/* Get some random stuff */
gettimeofday( &r.t, ( struct timezone * )0 );
gethostname( r.hostname, 256 );
/* MD5 it */
MD5Init(&c);
MD5Update(&c, &r, sizeof r);
MD5Update( &c, &r, sizeof( randomness ) );
MD5Final( seed, &c );
};
#endif /* _WINDOWS_ */
#endif

View File

@@ -55,8 +55,8 @@ static unsigned16 true_random( void );
int
uuid_create( uuid_upnp * uid )
{
uuid_time_t timestamp;
uuid_time_t last_time;
uuid_time_t timestamp,
last_time;
unsigned16 clockseq;
uuid_node_t node;
uuid_node_t last_node;
@@ -86,11 +86,10 @@ uuid_create(uuid_upnp *uid)
if no NV state, or if clock went backwards, or node ID changed
(e.g., net card swap) change clockseq
*/
if (!f || memcmp(&node, &last_node, sizeof(uuid_node_t))) {
if( !f || memcmp( &node, &last_node, sizeof( uuid_node_t ) ) )
clockseq = true_random( );
} else if (timestamp < last_time) {
else if( timestamp < last_time )
clockseq++;
}
/*
stuff fields into the UUID
@@ -103,26 +102,24 @@ uuid_create(uuid_upnp *uid)
write_state( clockseq, timestamp, node );
UUIDUnlock( );
return 1;
return ( 1 );
};
/*-----------------------------------------------------------------------------*/
void
uuid_unpack(uuid_upnp *u, char *out)
uuid_unpack( uuid_upnp * u,
char *out )
{
sprintf( out,
"%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x",
(unsigned int)u->time_low,
u->time_mid,
u->time_hi_and_version,
u->clock_seq_hi_and_reserved,
u->clock_seq_low,
u->node[0],
u->node[1],
u->node[2],
u->node[3],
u->node[4],
u->node[5]);
( unsigned int )u->time_low, u->time_mid,
u->time_hi_and_version, u->clock_seq_hi_and_reserved,
u->clock_seq_low, u->node[0], u->node[1], u->node[2],
u->node[3], u->node[4], u->node[5] );
*( out + 36 ) = '\0';
};
/*-----------------------------------------------------------------------------*/
@@ -142,7 +139,8 @@ format_uuid_v1( uuid_upnp * uid,
*/
uid->time_low = ( unsigned long )( timestamp & 0xFFFFFFFF );
uid->time_mid = ( unsigned short )( ( timestamp >> 32 ) & 0xFFFF );
uid->time_hi_and_version = (unsigned short)((timestamp >> 48) & 0x0FFF);
uid->time_hi_and_version = ( unsigned short )( ( timestamp >> 48 ) &
0x0FFF );
uid->time_hi_and_version |= ( 1 << 12 );
uid->clock_seq_low = clock_seq & 0xFF;
uid->clock_seq_hi_and_reserved = ( clock_seq & 0x3F00 ) >> 8;
@@ -229,6 +227,7 @@ get_current_time( uuid_time_t * timestamp )
static int inited = 0;
if( !inited ) {
get_system_time( &time_now );
uuids_this_tick = UUIDS_PER_TICK;
inited = 1;
};

View File

@@ -105,7 +105,7 @@ main (int argc, char* argv[])
* Test library initialisation
*/
printf ("\n");
printf ("Initializing UPnP ... \n");
printf ("Intializing UPnP ... \n");
rc = UpnpInit (NULL, 0);
if ( UPNP_E_SUCCESS == rc ) {
const char* ip_address = UpnpGetServerIpAddress();