int web_server_init() { int ret = 0; if (bWebServerState == WEB_SERVER_DISABLED) { /* decode media list */ media_list_init(); membuffer_init(&gDocumentRootDir); glob_alias_init(); pVirtualDirList = NULL; /* Initialize callbacks */ virtualDirCallback.get_info = NULL; virtualDirCallback.open = NULL; virtualDirCallback.read = NULL; virtualDirCallback.write = NULL; virtualDirCallback.seek = NULL; virtualDirCallback.close = NULL; if (ithread_mutex_init(&gWebMutex, NULL) == -1) ret = UPNP_E_OUTOF_MEMORY; else bWebServerState = WEB_SERVER_ENABLED; } return ret; }
/***************************************************************************** * ContentDir_Create *****************************************************************************/ ContentDir* ContentDir_Create (void* talloc_context, UpnpClient_Handle ctrlpt_handle, IXML_Element* serviceDesc, const char* base_url) { OBJECT_SUPER_CONSTRUCT (ContentDir, Service_Create, talloc_context, ctrlpt_handle, serviceDesc, base_url); if (self == NULL) goto error; // ----------> if (CACHE_SIZE > 0 && CACHE_TIMEOUT > 0) { self->cache = Cache_Create (self, CACHE_SIZE, CACHE_TIMEOUT, cache_free_expired_data); if (self->cache == NULL) goto error; // ----------> ithread_mutex_init (&self->cache_mutex, NULL); } return self; // ----------> error: Log_Print (LOG_ERROR, "ContentDir_Create error"); if (self) talloc_free (self); return NULL; }
/************************************************************************ * Function: TimerThreadInit * * Description: * Initializes and starts timer thread. * * Parameters: * timer - valid timer thread pointer. * tp - valid thread pool to use. Must be * started. Must be valid for lifetime * of timer. Timer must be shutdown * BEFORE thread pool. * Return: * 0 on success, nonzero on failure * Returns error from ThreadPoolAddPersistent if failure. ************************************************************************/ int TimerThreadInit( TimerThread * timer, ThreadPool * tp ) { int rc = 0; ThreadPoolJob timerThreadWorker; assert( timer != NULL ); assert( tp != NULL ); if( ( timer == NULL ) || ( tp == NULL ) ) { return EINVAL; } rc += ithread_mutex_init( &timer->mutex, NULL ); assert( rc == 0 ); rc += ithread_mutex_lock( &timer->mutex ); assert( rc == 0 ); rc += ithread_cond_init( &timer->condition, NULL ); assert( rc == 0 ); rc += FreeListInit( &timer->freeEvents, sizeof( TimerEvent ), 100 ); assert( rc == 0 ); timer->shutdown = 0; timer->tp = tp; timer->lastEventId = 0; rc += ListInit( &timer->eventQ, NULL, NULL ); assert( rc == 0 ); if( rc != 0 ) { rc = EAGAIN; } else { TPJobInit( &timerThreadWorker, TimerThreadWorker, timer ); TPJobSetPriority( &timerThreadWorker, HIGH_PRIORITY ); rc = ThreadPoolAddPersistent( tp, &timerThreadWorker, NULL ); } ithread_mutex_unlock( &timer->mutex ); if( rc != 0 ) { ithread_cond_destroy( &timer->condition ); ithread_mutex_destroy( &timer->mutex ); FreeListDestroy( &timer->freeEvents ); ListDestroy( &timer->eventQ, 0 ); } return rc; }
/******************************************************************************** * TvCtrlPointStart * * Description: * Call this function to initialize the UPnP library and start the TV Control * Point. This function creates a timer thread and provides a callback * handler to process any UPnP events that are received. * * Parameters: * None * * Returns: * TV_SUCCESS if everything went well, else TV_ERROR * ********************************************************************************/ int TvCtrlPointStart( print_string printFunctionPtr, state_update updateFunctionPtr ) { ithread_t timer_thread; int rc; unsigned short port = 0; char *ip_address = NULL; SampleUtil_Initialize( printFunctionPtr ); SampleUtil_RegisterUpdateFunction( updateFunctionPtr ); ithread_mutex_init( &DeviceListMutex, 0 ); SampleUtil_Print( "Initializing UPnP Sdk with\n" "\tipaddress = %s port = %u\n", ip_address, port ); rc = UpnpInit( ip_address, port ); if( UPNP_E_SUCCESS != rc ) { SampleUtil_Print( "WinCEStart: UpnpInit() Error: %d", rc ); UpnpFinish(); return TV_ERROR; } if( NULL == ip_address ) { ip_address = UpnpGetServerIpAddress(); } if( 0 == port ) { port = UpnpGetServerPort(); } SampleUtil_Print( "UPnP Initialized\n" "\tipaddress= %s port = %u\n", ip_address, port ); SampleUtil_Print( "Registering Control Point" ); rc = UpnpRegisterClient( TvCtrlPointCallbackEventHandler, &ctrlpt_handle, &ctrlpt_handle ); if( UPNP_E_SUCCESS != rc ) { SampleUtil_Print( "Error registering CP: %d", rc ); UpnpFinish(); return TV_ERROR; } SampleUtil_Print( "Control Point Registered" ); TvCtrlPointRefresh(); // start a timer thread ithread_create( &timer_thread, NULL, TvCtrlPointTimerLoop, NULL ); return TV_SUCCESS; }
int UpnpInitLog(void) { ithread_mutex_init(&GlobalDebugMutex, NULL); if (DEBUG_TARGET == 1) { if ((ErrFileHnd = fopen(errFileName, "a")) == NULL) { return -1; } if ((InfoFileHnd = fopen(infoFileName, "a")) == NULL) { return -1; } } return UPNP_E_SUCCESS; }
/***************************************************************************** * _ObjectClass_Lock *****************************************************************************/ int _ObjectClass_Lock() { if (! g_mutex_initialized) { ithread_mutexattr_t attr; ithread_mutexattr_init (&attr); ithread_mutexattr_setkind_np (&attr, ITHREAD_MUTEX_RECURSIVE_NP ); ithread_mutex_init (&g_class_mutex, &attr); ithread_mutexattr_destroy (&attr); g_mutex_initialized = true; } return pthread_mutex_lock (&g_class_mutex); }
int CtrlPointStart() { //ithread_t timer_thread; int rc; unsigned short port = 0; char *ip_address = NULL; ithread_mutex_init(&DeviceListMutex, 0); g_print("Initializing UPnP Sdk with\n" "\tipaddress = %s port = %u\n", ip_address ? ip_address : "{NULL}", port); rc = UpnpInit(ip_address, port); if (rc != UPNP_E_SUCCESS) { g_print("WinCEStart: UpnpInit() Error: %d\n", rc); UpnpFinish(); return CP_ERROR; } if (!ip_address) { ip_address = UpnpGetServerIpAddress(); } if (!port) { port = UpnpGetServerPort(); } g_print("UPnP Initialized\n" "\tipaddress = %s port = %u\n", ip_address ? ip_address : "{NULL}", port); g_print("Registering Control Point\n"); rc = UpnpRegisterClient(CtrlPointCallbackEventHandler, &ctrlpt_handle, &ctrlpt_handle); if (rc != UPNP_E_SUCCESS) { g_print("Error registering CP: %d\n", rc); UpnpFinish(); return CP_ERROR; } g_print("Control Point Registered\n"); CtrlPointRefresh(); /* start a timer thread */ //ithread_create(&timer_thread, NULL, TvCtrlPointTimerLoop, NULL); //ithread_detach(timer_thread); return CP_SUCCESS; }
/******************************************************************************** * SampleUtil_Initialize * * Description: * Initializes the sample util. Must be called before any sample util * functions. May be called multiple times. * * Parameters: * print_function - print function to use in SampleUtil_Print * ********************************************************************************/ int SampleUtil_Initialize( print_string print_function ) { if( initialize ) { ithread_mutexattr_t attr; gPrintFun = print_function; ithread_mutexattr_init( &attr ); ithread_mutexattr_setkind_np( &attr, ITHREAD_MUTEX_RECURSIVE_NP ); ithread_mutex_init( &display_mutex, &attr ); ithread_mutexattr_destroy( &attr ); initialize = 0; } return UPNP_E_SUCCESS; }
int Log_Initialize (Log_PrintFunction print_function ) { if (! g_initialized) { ithread_mutexattr_t attr; ithread_mutexattr_init (&attr); ithread_mutexattr_setkind_np (&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init (&g_log_mutex, &attr); ithread_mutexattr_destroy (&attr); g_initialized = true; } gPrintFun = print_function; return 0; }
int SampleUtil_Initialize(print_string print_function) { if (initialize_init) { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&display_mutex, &attr); ithread_mutexattr_destroy(&attr); /* To shut up valgrind mutex warning. */ ithread_mutex_lock(&display_mutex); gPrintFun = print_function; ithread_mutex_unlock(&display_mutex); /* Finished initializing. */ initialize_init = 0; } return UPNP_E_SUCCESS; }
struct upnp_device *upnp_device_init(struct upnp_device_descriptor *device_def, const char *ip_address, unsigned short port) { int rc; char *buf; struct service *srv; struct icon *icon_entry; assert(device_def != NULL); if (device_def->init_function) { rc = device_def->init_function(); if (rc != 0) { return NULL; } } struct upnp_device *result_device = malloc(sizeof(*result_device)); result_device->upnp_device_descriptor = device_def; ithread_mutex_init(&(result_device->device_mutex), NULL); /* register icons in web server */ for (int i = 0; (icon_entry = device_def->icons[i]); i++) { webserver_register_file(icon_entry->url, "image/png"); } /* generate and register service schemas in web server */ for (int i = 0; (srv = device_def->services[i]); i++) { buf = upnp_get_scpd(srv); assert(buf != NULL); webserver_register_buf(srv->scpd_url, buf, "text/xml"); } if (!initialize_device(device_def, result_device, ip_address, port)) { UpnpFinish(); free(result_device); return NULL; } return result_device; }
int TvDeviceStart(char *ip_address, unsigned short port, const char *desc_doc_name, const char *web_dir_path, print_string pfun, int combo) { int ret = UPNP_E_SUCCESS; char desc_doc_url[DESC_URL_SIZE]; ithread_mutex_init(&TVDevMutex, NULL); SampleUtil_Initialize(pfun); SampleUtil_Print("Initializing UPnP Sdk with\n" "\tipaddress = %s port = %u\n", ip_address ? ip_address : "{NULL}", port); ret = UpnpInit2(ip_address, port); if (ret != UPNP_E_SUCCESS) { SampleUtil_Print("Error with UpnpInit2 -- %d\n", ret); UpnpFinish(); return ret; } ip_address = UpnpGetServerIpAddress(); port = UpnpGetServerPort(); SampleUtil_Print("UPnP Initialized\n" "\tipaddress = %s port = %u\n", ip_address ? ip_address : "{NULL}", port); if (!desc_doc_name) { if (combo) { desc_doc_name = "tvcombodesc.xml"; } else { desc_doc_name = "tvdevicedesc.xml"; } } if (!web_dir_path) { web_dir_path = DEFAULT_WEB_DIR; } snprintf(desc_doc_url, DESC_URL_SIZE, "http://%s:%d/%s", ip_address, port, desc_doc_name); SampleUtil_Print("Specifying the webserver root directory -- %s\n", web_dir_path); ret = UpnpSetWebServerRootDir(web_dir_path); if (ret != UPNP_E_SUCCESS) { SampleUtil_Print ("Error specifying webserver root directory -- %s: %d\n", web_dir_path, ret); UpnpFinish(); return ret; } SampleUtil_Print("Registering the RootDevice\n" "\t with desc_doc_url: %s\n", desc_doc_url); ret = UpnpRegisterRootDevice(desc_doc_url, TvDeviceCallbackEventHandler, &device_handle, &device_handle); if (ret != UPNP_E_SUCCESS) { SampleUtil_Print("Error registering the rootdevice : %d\n", ret); UpnpFinish(); return ret; } else { SampleUtil_Print("RootDevice Registered\n" "Initializing State Table\n"); TvDeviceStateTableInit(desc_doc_url); SampleUtil_Print("State Table Initialized\n"); ret = UpnpSendAdvertisement(device_handle, default_advr_expire); if (ret != UPNP_E_SUCCESS) { SampleUtil_Print("Error sending advertisements : %d\n", ret); UpnpFinish(); return ret; } SampleUtil_Print("Advertisements Sent\n"); } return UPNP_E_SUCCESS; }
/******************************************************************************** * upnp_igd_create * * Description: * Create and return uPnP IGD context if there is no error otherwise * NULL. * * Parameters: * cb_fct -- The function to call back for each events * print_fct -- The function used for print logs * cookie -- The cookie pass in cb_fct or print_fct * ********************************************************************************/ upnp_igd_context* upnp_igd_create(upnp_igd_callback_function cb_fct, upnp_igd_print_function print_fct, const char *address, void *cookie) { int ret; unsigned short port = 0; const char *ip_address = address; upnp_igd_context *igd_ctxt = (upnp_igd_context*)malloc(sizeof(upnp_igd_context)); igd_ctxt->devices = NULL; igd_ctxt->callback_fct = cb_fct; igd_ctxt->callback_events = NULL; igd_ctxt->print_fct = print_fct; igd_ctxt->cookie = cookie; igd_ctxt->max_adv_timeout = 60*3; igd_ctxt->timer_timeout = igd_ctxt->max_adv_timeout/2; igd_ctxt->upnp_handle = -1; igd_ctxt->client_count = 0; igd_ctxt->timer_thread = (ithread_t)NULL; /* Initialize mutex */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&igd_ctxt->mutex, &attr); ithread_mutexattr_destroy(&attr); } /* Initialize print mutex */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&igd_ctxt->print_mutex, &attr); ithread_mutexattr_destroy(&attr); } /* Initialize callback mutex */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&igd_ctxt->callback_mutex, &attr); ithread_mutexattr_destroy(&attr); } /* Initialize device mutex */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&igd_ctxt->devices_mutex, &attr); ithread_mutexattr_destroy(&attr); } /* Initialize timer stuff */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_FAST_NP); ithread_mutex_init(&igd_ctxt->timer_mutex, &attr); ithread_mutexattr_destroy(&attr); ithread_cond_init(&igd_ctxt->timer_cond, NULL); } /* Initialize client stuff */ { ithread_mutexattr_t attr; ithread_mutexattr_init(&attr); ithread_mutexattr_setkind_np(&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init(&igd_ctxt->client_mutex, &attr); ithread_mutexattr_destroy(&attr); ithread_cond_init(&igd_ctxt->client_cond, NULL); } upnp_igd_print(igd_ctxt, UPNP_IGD_DEBUG, "Initializing uPnP IGD with ipaddress:%s port:%u", ip_address ? ip_address : "{NULL}", port); ret = UpnpInit(ip_address, port); if (ret != UPNP_E_SUCCESS) { upnp_igd_print(igd_ctxt, UPNP_IGD_ERROR, "UpnpInit() Error: %d", ret); UpnpFinish(); ithread_mutex_destroy(&igd_ctxt->print_mutex); ithread_mutex_destroy(&igd_ctxt->devices_mutex); ithread_mutex_destroy(&igd_ctxt->timer_mutex); ithread_cond_destroy(&igd_ctxt->timer_cond); ithread_mutex_destroy(&igd_ctxt->callback_mutex); ithread_mutex_destroy(&igd_ctxt->client_mutex); ithread_cond_destroy(&igd_ctxt->client_cond); ithread_mutex_destroy(&igd_ctxt->mutex); free(igd_ctxt); return NULL; } if (!ip_address) { ip_address = UpnpGetServerIpAddress(); } if (!port) { port = UpnpGetServerPort(); } upnp_igd_print(igd_ctxt, UPNP_IGD_MESSAGE, "uPnP IGD Initialized ipaddress:%s port:%u", ip_address ? ip_address : "{NULL}", port); return igd_ctxt; }
} ithread_mutex_unlock(&Device->ActionsMutex); }
struct device_private *upnp_device_init(struct device *device_def, const char *ip_address) { int rc; #ifdef HAVE_LIBUPNP short int port = 0; #endif struct service *srv; struct icon *icon_entry; char *buf; struct device_private *priv = NULL; int i; assert(device_def != NULL); if (device_def->init_function) { rc = device_def->init_function(); if (rc != 0) { goto out; } } priv = malloc(sizeof(*priv)); priv->upnp_device = device_def; #ifdef HAVE_LIBUPNP ithread_mutex_init(&(priv->device_mutex), NULL); #endif //upnp_device = device_def; /* register icons in web server */ for (i=0; (icon_entry = device_def->icons[i]); i++) { webserver_register_file(icon_entry->url, "image/png"); } /* generate and register service schemas in web server */ for (i=0; (srv = device_def->services[i]); i++) { buf = upnp_get_scpd(srv); assert(buf != NULL); printf("registering '%s'\n", srv->scpd_url); webserver_register_buf(srv->scpd_url,buf,"text/xml"); } #ifdef HAVE_LIBUPNP rc = UpnpInit(ip_address, port); if (UPNP_E_SUCCESS != rc) { printf("UpnpInit() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpEnableWebserver(TRUE); if (UPNP_E_SUCCESS != rc) { printf("UpnpEnableWebServer() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpSetVirtualDirCallbacks(&virtual_dir_callbacks); if (UPNP_E_SUCCESS != rc) { printf("UpnpSetVirtualDirCallbacks() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpAddVirtualDir("/upnp"); if (UPNP_E_SUCCESS != rc) { printf("UpnpAddVirtualDir() Error: %d\n", rc); goto upnp_err_out; } buf = upnp_get_device_desc(device_def); rc = UpnpRegisterRootDevice2(UPNPREG_BUF_DESC, buf, strlen(buf), 1, &event_handler, priv, &(priv->device_handle)); if (UPNP_E_SUCCESS != rc) { printf("UpnpRegisterRootDevice2() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpSendAdvertisement(priv->device_handle, 100); if (UPNP_E_SUCCESS != rc) { fprintf(stderr, "Error sending advertisements: %d\n", rc); goto upnp_err_out; } #endif goto out; #ifdef HAVE_LIBUPNP upnp_err_out: UpnpFinish(); #endif out: return priv; }
int wphoto_upnp_handshake(void) { int ret = -1, err; char descurl[256]; const char *desc_xml = "MobileDevDesc.xml"; struct timespec timer; int camera_responded_save; char *camera_url_save; int pinged_camera; ithread_mutex_init(&state_mutex, NULL); ithread_cond_init(&state_cond, NULL); camera_url = NULL; camera_responded = 0; err = UpnpInit(NULL, 0); if (err != UPNP_E_SUCCESS) { upnp_perror("UpnpInit", err); goto err_init; } server_ip = UpnpGetServerIpAddress(); server_port = UpnpGetServerPort(); if (init_xml_docs() < 0) { perror("init_xml_docs"); goto err_init; } printf("address: %s:%d\n", server_ip, server_port); snprintf(descurl, sizeof(descurl), "http://%s:%d/%s", server_ip, server_port, desc_xml); err = web_add_callback("/MobileDevDesc.xml", web_MobileDevDesc, NULL); if (err) { perror("web_add_callback"); goto err_init; } err = web_add_callback("/desc_iml/CameraConnectedMobile.xml", web_CameraConnectedMobile, NULL); if (err) { perror("web_add_callback"); goto err_init; } if (web_start() < 0) { printf("web_init error\n"); goto err_init; } err = UpnpRegisterRootDevice(descurl, upnp_device_event_handler, &device_handle, &device_handle); if (err != UPNP_E_SUCCESS) { upnp_perror("UpnpRegisterRootDevice", err); goto err_init; } err = UpnpRegisterClient(upnp_client_event_handler, &client_handle, &client_handle); if (err != UPNP_E_SUCCESS) { upnp_perror("UpnpRegisterClient", err); goto err_register; } clock_gettime(CLOCK_REALTIME, &timer); discovery_timeout = 1; camera_responded_save = 0; camera_url_save = NULL; pinged_camera = 0; do { int wait_err; if (!camera_responded_save) { err = UpnpSendAdvertisement(device_handle, 0); if (err != UPNP_E_SUCCESS) { upnp_perror("UpnpSendAdvertisement", err); goto err_register; } printf("NOTIFY sent\n"); } if (camera_url_save && !pinged_camera) if (ping_camera(camera_url_save) == 0) pinged_camera = 1; timer.tv_sec += ADVERTISEMENT_INTERVAL; wait: ithread_mutex_lock(&state_mutex); wait_err = 0; while (camera_responded == camera_responded_save && strcmp_null(camera_url, camera_url_save) == 0 && !discovery_timeout && wait_err == 0) wait_err = ithread_cond_timedwait( &state_cond, &state_mutex, &timer); camera_responded_save = camera_responded; if (strcmp_null(camera_url, camera_url_save) != 0) { free(camera_url_save); camera_url_save = strdup(camera_url); } /* * Once we have the camera url, we stop sending M-SEARCH * requests */ if (discovery_timeout && !camera_url_save) { err = UpnpSearchAsync(client_handle, MSEARCH_INTERVAL, CAMERA_SERVICE_NAME, (void*)42); if (err != UPNP_E_SUCCESS) { upnp_perror("UpnpSearchAsync", err); goto err_register; } printf("M-SEARCH sent\n"); } discovery_timeout = 0; ithread_mutex_unlock(&state_mutex); if (wait_err != ETIMEDOUT && (!pinged_camera || !camera_responded_save)) goto wait; } while (!pinged_camera || !camera_responded_save); return 0; err_register: UpnpUnRegisterRootDevice(device_handle); err_init: UpnpFinish(); return ret; }
/**************************************************************************** * Function: ThreadPoolInit * * Description: * Initializes and starts ThreadPool. Must be called first. * And only once for ThreadPool. * Parameters: * tp - must be valid, non null, pointer to ThreadPool. * minWorkerThreads - minimum number of worker threads * thread pool will never have less than this * number of threads. * maxWorkerThreads - maximum number of worker threads * thread pool will never have more than this * number of threads. * maxIdleTime - maximum time that a worker thread will spend * idle. If a worker is idle longer than this * time and there are more than the min * number of workers running, than the * worker thread exits. * jobsPerThread - ratio of jobs to thread to try and maintain * if a job is scheduled and the number of jobs per * thread is greater than this number,and * if less than the maximum number of * workers are running then a new thread is * started to help out with efficiency. * schedPolicy - scheduling policy to try and set (OS dependent) * Returns: * 0 on success, nonzero on failure. * EAGAIN if not enough system resources to create minimum threads. * INVALID_POLICY if schedPolicy can't be set * EMAXTHREADS if minimum threads is greater than maximum threads *****************************************************************************/ int ThreadPoolInit( ThreadPool *tp, ThreadPoolAttr *attr ) { int retCode = 0; int i = 0; //printf("%s, %d\n", __FUNCTION__, __LINE__); assert( tp != NULL ); if( tp == NULL ) { return EINVAL; } #ifdef WIN32 #ifdef PTW32_STATIC_LIB pthread_win32_process_attach_np(); #endif #endif //printf("%s, %d\n", __FUNCTION__, __LINE__); retCode += ithread_mutex_init( &tp->mutex, NULL ); assert( retCode == 0 ); retCode += ithread_mutex_lock( &tp->mutex ); assert( retCode == 0 ); retCode += ithread_cond_init( &tp->condition, NULL ); assert( retCode == 0 ); retCode += ithread_cond_init( &tp->start_and_shutdown, NULL ); assert( retCode == 0 ); //printf("%s, %d\n", __FUNCTION__, __LINE__); if( retCode != 0 ) { return EAGAIN; } if( attr ) { tp->attr = ( *attr ); } else { TPAttrInit( &tp->attr ); } //printf("%s, %d, minthreads: %d\n", __FUNCTION__, __LINE__, tp->attr.minThreads); if( SetPolicyType( tp->attr.schedPolicy ) != 0 ) { ithread_mutex_unlock( &tp->mutex ); ithread_mutex_destroy( &tp->mutex ); ithread_cond_destroy( &tp->condition ); ithread_cond_destroy( &tp->start_and_shutdown ); return INVALID_POLICY; } //printf("%s, %d\n", __FUNCTION__, __LINE__); retCode += FreeListInit( &tp->jobFreeList, sizeof( ThreadPoolJob ), JOBFREELISTSIZE ); assert( retCode == 0 ); StatsInit( &tp->stats ); retCode += ListInit( &tp->highJobQ, CmpThreadPoolJob, NULL ); assert( retCode == 0 ); retCode += ListInit( &tp->medJobQ, CmpThreadPoolJob, NULL ); assert( retCode == 0 ); retCode += ListInit( &tp->lowJobQ, CmpThreadPoolJob, NULL ); assert( retCode == 0 ); //printf("%s, %d, retcode is %d\n", __FUNCTION__, __LINE__, retCode); if( retCode != 0 ) { retCode = EAGAIN; //printf("%s, %d\n", __FUNCTION__, __LINE__); } else { //printf("%s, %d\n", __FUNCTION__, __LINE__); tp->persistentJob = NULL; tp->lastJobId = 0; tp->shutdown = 0; tp->totalThreads = 0; tp->persistentThreads = 0; //printf("%s, %d\n", __FUNCTION__, __LINE__); for( i = 0; i < tp->attr.minThreads; ++i ) { if( ( retCode = CreateWorker( tp ) ) != 0 ) { //printf("%s, %d\n", __FUNCTION__, __LINE__); break; } } } //printf("%s, %d\n", __FUNCTION__, __LINE__); ithread_mutex_unlock( &tp->mutex ); if( retCode != 0 ) { // clean up if the min threads could not be created ThreadPoolShutdown( tp ); } //printf("%s, %d\n", __FUNCTION__, __LINE__); return retCode; }
int ThreadPoolInit(ThreadPool *tp, ThreadPoolAttr *attr) { int retCode = 0; int i = 0; if (!tp) { return EINVAL; } retCode += ithread_mutex_init(&tp->mutex, NULL); retCode += ithread_mutex_lock(&tp->mutex); retCode += ithread_cond_init(&tp->condition, NULL); retCode += ithread_cond_init(&tp->start_and_shutdown, NULL); if (retCode) { ithread_mutex_unlock(&tp->mutex); ithread_mutex_destroy(&tp->mutex); ithread_cond_destroy(&tp->condition); ithread_cond_destroy(&tp->start_and_shutdown); return EAGAIN; } if (attr) { tp->attr = *attr; } else { TPAttrInit(&tp->attr); } if (SetPolicyType(tp->attr.schedPolicy) != 0) { ithread_mutex_unlock(&tp->mutex); ithread_mutex_destroy(&tp->mutex); ithread_cond_destroy(&tp->condition); ithread_cond_destroy(&tp->start_and_shutdown); return INVALID_POLICY; } retCode += FreeListInit( &tp->jobFreeList, sizeof(ThreadPoolJob), JOBFREELISTSIZE); StatsInit(&tp->stats); retCode += ListInit(&tp->highJobQ, CmpThreadPoolJob, NULL); retCode += ListInit(&tp->medJobQ, CmpThreadPoolJob, NULL); retCode += ListInit(&tp->lowJobQ, CmpThreadPoolJob, NULL); if (retCode) { retCode = EAGAIN; } else { tp->persistentJob = NULL; tp->lastJobId = 0; tp->shutdown = 0; tp->totalThreads = 0; tp->busyThreads = 0; tp->persistentThreads = 0; tp->pendingWorkerThreadStart = 0; for (i = 0; i < tp->attr.minThreads; ++i) { retCode = CreateWorker(tp); if (retCode) { break; } } } ithread_mutex_unlock(&tp->mutex); if (retCode) { /* clean up if the min threads could not be created */ ThreadPoolShutdown(tp); } return retCode; }
/****************************************************************************** * BrowseOrSearchAll *****************************************************************************/ static ContentDir_Children* BrowseOrSearchAll (ContentDir* cds, void* result_context, const char* objectId, const char* const criteria) { ContentDir_Children* result = talloc (result_context, ContentDir_Children); if (result == NULL) return NULL; // ----------> PtrArray* objects = PtrArray_Create (result); if (objects == NULL) goto FAIL; // ----------> *result = (ContentDir_Children) { .objects = objects }; #if CONTENT_DIR_HAVE_CHILDREN_MUTEX ithread_mutexattr_t attr; ithread_mutexattr_init (&attr); ithread_mutexattr_setkind_np (&attr, ITHREAD_MUTEX_RECURSIVE_NP); ithread_mutex_init (&result->mutex, &attr); ithread_mutexattr_destroy (&attr); #endif talloc_set_destructor (result, DestroyChildren); // Request all objects Count nb_matched = 0; Count nb_returned = 0; int rc = BrowseOrSearchAction (cds, objects, objectId, criteria, /* starting_index => */ 0, /* requested_count => */ 0, &nb_matched, &nb_returned, objects); if (rc != UPNP_E_SUCCESS) goto FAIL; // ----------> // Loop if missing entries // (this is not normal : "RequestedCount" == 0 means to request // all entries according to ContentDirectory specification). // Note: it is allowed to have nb_matched == 0 if it cannot be // computed by the CDS. int nb_retry = 0; while (PtrArray_GetSize (objects) < nb_matched && nb_retry++ < 2) { Log_Printf (LOG_WARNING, "ContentDir_BrowseId ObjectId=%s : " "got %d results, expected %d. Retry %d ...", objectId, (int) PtrArray_GetSize (objects), (int) nb_matched, nb_retry); // Workaround : request missing entries. rc = BrowseOrSearchAction (cds, objects, objectId, criteria, /* starting_index => */ PtrArray_GetSize (objects), /* requested_count => */ nb_matched - PtrArray_GetSize (objects), &nb_matched, &nb_returned, objects); // Stop if error, or no more results (to prevent infinite loop) if (rc != UPNP_E_SUCCESS || nb_returned == 0) break; // ----------> } return result; FAIL: talloc_free (result); return NULL; }
//////upnp init/////////////////////////////////// int init_upnp_ctl(void) { ithread_t timer_thread; char * ip_address; char *desc_doc_name; char *web_dir_path; char tmp_ipadd[20] ;//"192.168.61.22"; char tmp_namedoc[]="ctl_xml.xml"; unsigned short port; int ret = UPNP_E_SUCCESS; //= (*cyber_tem_ip) char iptmp[20]; char * ip_data; get_ip(iptmp); port=80; desc_doc_name=tmp_namedoc; web_dir_path=DEFAULT_WEB_DIR; //strcpy (cyber_tem_ip, tmp_ipadd); ip_address =iptmp;//tmp_ipadd; // creat_xml_file(iptmp); // ithread_mutex_init( &TVDevMutex, NULL ); ithread_mutex_init( &DeviceListMutex, 0 ); printf("the iptmp is =%s\n",iptmp); printf("zdy is ok1"); //printf("the tmp_ipadd=%s\n",tmp_ipadd); /* if( desc_doc_name == NULL ) desc_doc_name = tmp_namedoc; printf("%s\n",*desc_doc_name); if( web_dir_path == NULL ) web_dir_path = DEFAULT_WEB_DIR; printf("%s\n",*web_dir_path); */ if((ret=UpnpInit(ip_address, port)) != UPNP_E_SUCCESS ) { printf( "Error with UpnpInit -- %d\n", ret ); UpnpFinish( ); printf("%d\n", ret); return ret; } if( ip_address == NULL ) { ip_address = UpnpGetServerIpAddress( ); } printf("ip_address is %s\n",ip_address); if( port == 0 ) { port = UpnpGetServerPort( ); } printf( "UPnP Initialized\n ipaddress= %s port = %d\n", ip_address, port ); // printf("zdy is ok1"); printf("bigin open the snprintf\n"); // snprintf( desc_doc_url, DESC_URL_SIZE, "http://%s:%d/cgi-bin/%s", ip_address, // port, desc_doc_name ); printf("end the snprintf\n"); // printf("desc_doc_url %s",desc_doc_url); ret=1; if ((ret=UpnpRegisterClient( TvCtrlPointCallbackEventHandler, &ctrlpt_handle, &ctrlpt_handle ))!=UPNP_E_SUCCESS) { printf( "Error registering the rootdevice : %d\n", ret ); UpnpFinish( ); return 0; } // //TvCtrlPointRemoveAll( ); printf("TvCtrlPointRemoveAll\n"); ret=1; printf("the TvDeviceType=%s\n",TvDeviceType); Tvctrlpointrefresh(); ithread_create( &timer_thread, NULL, TvCtrlPointTimerLoop, NULL ); //sleep(5); printf("ithread_create after\n"); }
int StartMiniServer( /*! [in,out] Port on which the server listens for incoming IPv4 * connections. */ uint16_t *listen_port4, /*! [in,out] Port on which the server listens for incoming IPv6 * connections. */ uint16_t *listen_port6) { int ret_code; int count; int max_count = 10000; ThreadPoolJob job; memset(&job, 0, sizeof(job)); switch (gMServState) { case MSERV_IDLE: break; default: /* miniserver running. */ return UPNP_E_INTERNAL_ERROR; } gMiniSocket = (MiniServerSockArray *)malloc( sizeof (MiniServerSockArray)); if (!gMiniSocket) { return UPNP_E_OUTOF_MEMORY; } InitMiniServerSockArray(gMiniSocket); #ifdef INTERNAL_WEB_SERVER /* V4 and V6 http listeners. */ /*ret_code = get_miniserver_sockets( miniSocket, *listen_port4 #ifdef UPNP_ENABLE_IPV6 , *listen_port6 #endif ); if (ret_code != UPNP_E_SUCCESS) { free(miniSocket); return ret_code; }*/ #endif /* Stop socket (To end miniserver processing). */ ret_code = get_miniserver_stopsock(gMiniSocket); if (ret_code != UPNP_E_SUCCESS) { /*sock_close(miniSocket->miniServerSock4); sock_close(miniSocket->miniServerSock6);*/ free(gMiniSocket); gMiniSocket = 0; return ret_code; } /* SSDP socket for discovery/advertising. */ /*ret_code = get_ssdp_sockets(miniSocket); if (ret_code != UPNP_E_SUCCESS) { sock_close(miniSocket->miniServerSock4); sock_close(miniSocket->miniServerSock6); sock_close(miniSocket->miniServerStopSock); free(miniSocket); return ret_code; }*/ if (ithread_mutex_init(&gMiniServerMutex, NULL) != 0) { sock_close(gMiniSocket->miniServerStopSock); return UPNP_E_INTERNAL_ERROR; } TPJobInit(&job, (start_routine)RunMiniServer, (void *)gMiniSocket); TPJobSetPriority(&job, MED_PRIORITY); TPJobSetFreeFunction(&job, (free_routine)free); ret_code = ThreadPoolAddPersistent(&gMiniServerThreadPool, &job, NULL); if (ret_code < 0) { /*sock_close(miniSocket->miniServerSock4); sock_close(miniSocket->miniServerSock6);*/ sock_close(gMiniSocket->miniServerStopSock); /*for (i = 0; i < MAX_NETWORK_INTERFACES; ++i) sock_close(miniSocket->ssdpSock4[i]); sock_close(miniSocket->ssdpSock6); sock_close(miniSocket->ssdpSock6UlaGua); #ifdef INCLUDE_CLIENT_APIS for (i = 0; i < MAX_NETWORK_INTERFACES; ++i) sock_close(miniSocket->ssdpReqSock4[i]); sock_close(miniSocket->ssdpReqSock6); #endif*/ /* INCLUDE_CLIENT_APIS */ return UPNP_E_OUTOF_MEMORY; } /* Wait for miniserver to start. */ count = 0; while (gMServState != (MiniServerState)MSERV_RUNNING && count < max_count) { /* 0.05s */ usleep(50u * 1000u); count++; } if (count >= max_count) { /* Took it too long to start that thread. */ /*sock_close(miniSocket->miniServerSock4); sock_close(miniSocket->miniServerSock6);*/ sock_close(gMiniSocket->miniServerStopSock); /*for (i = 0; i < MAX_NETWORK_INTERFACES; ++i) sock_close(miniSocket->ssdpSock4[i]); sock_close(miniSocket->ssdpSock6); sock_close(miniSocket->ssdpSock6UlaGua); #ifdef INCLUDE_CLIENT_APIS for (i = 0; i < MAX_NETWORK_INTERFACES; ++i) sock_close(miniSocket->ssdpReqSock4[i]); sock_close(miniSocket->ssdpReqSock6); #endif*/ /* INCLUDE_CLIENT_APIS */ return UPNP_E_INTERNAL_ERROR; } #ifdef INTERNAL_WEB_SERVER /**listen_port4 = miniSocket->miniServerPort4; *listen_port6 = miniSocket->miniServerPort6;*/ #endif return UPNP_E_SUCCESS; }