bool UPnP::init() { int res; if((res = UpnpInit(0, 0)) != UPNP_E_SUCCESS) { Log::err("UpnpInit error: %s",UpnpGetErrorMessage(res)); return false; } if((res = UpnpRegisterClient(Callback, this, &CtrlPnt)) != UPNP_E_SUCCESS) { Log::err("UpnpRegisterClient error: %s",UpnpGetErrorMessage(res)); return false; } deviceList = new DeviceList(); cfg = new Config("config.xml", &deviceList, CtrlPnt); if((res = UpnpSetMaxContentLength(atoi(cfg->UpnpMaxContentLength.c_str()))) != UPNP_E_SUCCESS) { Log::err("UpnpSetMaxContentLength error: %s",UpnpGetErrorMessage(res)); return false; } isInited = true; return isInited; }
UpnpInstanceWrapper *UpnpInstanceWrapper::get(vlc_object_t *p_obj, Upnp_FunPtr callback, SD::MediaServerList *opaque) { vlc_mutex_locker lock( &s_lock ); if ( s_instance == NULL ) { UpnpInstanceWrapper* instance = new(std::nothrow) UpnpInstanceWrapper; if ( unlikely( !instance ) ) return NULL; #ifdef UPNP_ENABLE_IPV6 char* psz_miface = var_InheritString( p_obj, "miface" ); msg_Info( p_obj, "Initializing libupnp on '%s' interface", psz_miface ); int i_res = UpnpInit2( psz_miface, 0 ); free( psz_miface ); #else /* If UpnpInit2 isnt available, initialize on first IPv4-capable interface */ int i_res = UpnpInit( 0, 0 ); #endif if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_obj, "Initialization failed: %s", UpnpGetErrorMessage( i_res ) ); delete instance; return NULL; } ixmlRelaxParser( 1 ); /* Register a control point */ i_res = UpnpRegisterClient( Callback, instance, &instance->handle_ ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_obj, "Client registration failed: %s", UpnpGetErrorMessage( i_res ) ); delete instance; return NULL; } /* libupnp does not treat a maximum content length of 0 as unlimited * until 64dedf (~ pupnp v1.6.7) and provides no sane way to discriminate * between versions */ if( (i_res = UpnpSetMaxContentLength( INT_MAX )) != UPNP_E_SUCCESS ) { msg_Err( p_obj, "Failed to set maximum content length: %s", UpnpGetErrorMessage( i_res )); delete instance; return NULL; } s_instance = instance; } s_instance->refcount_++; // This assumes a single UPNP SD instance if (callback && opaque) { assert(!s_instance->callback_ && !s_instance->opaque_); s_instance->opaque_ = opaque; s_instance->callback_ = callback; } return s_instance; }
/* * Initializes UPNP instance. */ static int Open( vlc_object_t *p_this ) { int i_res; services_discovery_t *p_sd = ( services_discovery_t* )p_this; services_discovery_sys_t *p_sys = ( services_discovery_sys_t * ) calloc( 1, sizeof( services_discovery_sys_t ) ); if( !( p_sd->p_sys = p_sys ) ) return VLC_ENOMEM; /* Initialize on first IPv4-capable adapter and first open port * TODO: use UpnpInit2() to utilize IPv6. */ i_res = UpnpInit( 0, 0 ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Initialization failed: %s", UpnpGetErrorMessage( i_res ) ); free( p_sys ); return VLC_EGENERIC; } p_sys->p_server_list = new MediaServerList( p_sd ); vlc_mutex_init( &p_sys->callback_lock ); /* Register a control point */ i_res = UpnpRegisterClient( Callback, p_sd, &p_sys->client_handle ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Client registration failed: %s", UpnpGetErrorMessage( i_res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } /* Search for media servers */ i_res = UpnpSearchAsync( p_sys->client_handle, 5, MEDIA_SERVER_DEVICE_TYPE, p_sd ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Error sending search request: %s", UpnpGetErrorMessage( i_res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } /* libupnp does not treat a maximum content length of 0 as unlimited * until 64dedf (~ pupnp v1.6.7) and provides no sane way to discriminate * between versions */ if( (i_res = UpnpSetMaxContentLength( INT_MAX )) != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Failed to set maximum content length: %s", UpnpGetErrorMessage( i_res )); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } return VLC_SUCCESS; }
static gboolean initialize_device(struct upnp_device_descriptor *device_def, struct upnp_device *result_device, const char *ip_address, unsigned short port) { int rc; char *buf; rc = UpnpInit(ip_address, port); if (UPNP_E_SUCCESS != rc) { Log_error("upnp", "UpnpInit(ip=%s, port=%d) Error: %s (%d)", ip_address, port, UpnpGetErrorMessage(rc), rc); return FALSE; } Log_info("upnp", "Registered IP=%s port=%d\n", UpnpGetServerIpAddress(), UpnpGetServerPort()); rc = UpnpEnableWebserver(TRUE); if (UPNP_E_SUCCESS != rc) { Log_error("upnp", "UpnpEnableWebServer() Error: %s (%d)", UpnpGetErrorMessage(rc), rc); return FALSE; } if (!webserver_register_callbacks()) return FALSE; rc = UpnpAddVirtualDir("/upnp"); if (UPNP_E_SUCCESS != rc) { Log_error("upnp", "UpnpAddVirtualDir() Error: %s (%d)", UpnpGetErrorMessage(rc), rc); return FALSE; } buf = upnp_create_device_desc(device_def); rc = UpnpRegisterRootDevice2(UPNPREG_BUF_DESC, buf, strlen(buf), 1, &event_handler, result_device, &(result_device->device_handle)); free(buf); if (UPNP_E_SUCCESS != rc) { Log_error("upnp", "UpnpRegisterRootDevice2() Error: %s (%d)", UpnpGetErrorMessage(rc), rc); return FALSE; } rc = UpnpSendAdvertisement(result_device->device_handle, 100); if (UPNP_E_SUCCESS != rc) { Log_error("unpp", "Error sending advertisements: %s (%d)", UpnpGetErrorMessage(rc), rc); return FALSE; } return TRUE; }
/******************************************************************************** * 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 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; }
static int Open( vlc_object_t *p_this ) { int res; services_discovery_t *p_sd = ( services_discovery_t* )p_this; services_discovery_sys_t *p_sys = ( services_discovery_sys_t * ) calloc( 1, sizeof( services_discovery_sys_t ) ); if(!(p_sd->p_sys = p_sys)) return VLC_ENOMEM; res = UpnpInit( 0, 0 ); if( res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) ); free( p_sys ); return VLC_EGENERIC; } p_sys->serverList = new MediaServerList( p_sd ); vlc_mutex_init( &p_sys->callbackLock ); res = UpnpRegisterClient( Callback, p_sd, &p_sys->clientHandle ); if( res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } res = UpnpSearchAsync( p_sys->clientHandle, 5, MEDIA_SERVER_DEVICE_TYPE, p_sd ); if( res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "%s", UpnpGetErrorMessage( res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } return VLC_SUCCESS; }
int main(int argc, char *argv[]) { int rc = 0; rc = UpnpInit (NULL, 0); if ( UPNP_E_SUCCESS == rc ) { const char* ip_address = UpnpGetServerIpAddress(); unsigned short port = UpnpGetServerPort(); printf ("UPnP Initialized OK ip=%s, port=%d\n", (ip_address ? ip_address : "UNKNOWN"), port); } else { printf ("** ERROR UpnpInit(): %d\n", rc); } (void) UpnpFinish(); printf("\n"); return 0; }
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 = UpnpInit(ip_address, port); if (ret != UPNP_E_SUCCESS) { SampleUtil_Print("Error with UpnpInit -- %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; }
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; }
int main (int argc, char** argv) { int ret = UPNP_E_SUCCESS; int signal; char descDocUrl[50]; char descDocName[20]; char xmlPath[50]; char intIpAddress[16]; // Server internal ip address char extIpAddress[16]; // Server internal ip address sigset_t sigsToCatch; FILE *f; pid_t pid,sid; if (argc != 3) { printf("Usage: upnpd <external ifname> <internal ifname>\n"); printf("Example: upnpd ppp0 eth0\n"); printf("Example: upnpd eth1 eth0\n"); exit(0); } parseConfigFile(&g_forwardRules,&g_debug,g_iptables, g_forwardChainName,g_preroutingChainName, g_upstreamBitrate,g_downstreamBitrate, descDocName,xmlPath); // Save the interface names for later uses strcpy(g_extInterfaceName, argv[1]); strcpy(g_intInterfaceName, argv[2]); openlog("upnpd", LOG_PID | LOG_CONS, LOG_USER); // Get the internal ip address to start the daemon on GetIpAddressStr(intIpAddress, g_intInterfaceName); GetIpAddressStr(extIpAddress, g_extInterfaceName); // Put igd in the background as a daemon process. pid = fork(); if (pid < 0) { perror("Error forking a new process."); cleanup(); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); /* if we are here, we know we are the demonized version */ //open a state file f = fopen(STATE_FILE, "w"); if (!f) { syslog(LOG_ERR, "failed to open %s: %m", STATE_FILE); } else { fprintf(f, "external %s %s\ninternal %s %s\n", g_extInterfaceName, extIpAddress, g_intInterfaceName, intIpAddress); fclose(f); } atexit(cleanup); if ((sid = setsid()) < 0) { perror("Error running setsid"); exit(EXIT_FAILURE); } if ((chdir("/")) < 0) { perror("Error setting root directory"); exit(EXIT_FAILURE); } umask(0); close(STDERR_FILENO); close (STDIN_FILENO); close (STDOUT_FILENO); // End Daemon initialization // Initialize UPnP SDK on the internal Interface if (g_debug) syslog(LOG_DEBUG, "Initializing UPnP SDK ... "); if ( (ret = UpnpInit(intIpAddress,0) ) != UPNP_E_SUCCESS) { syslog (LOG_ERR, "Error Initializing UPnP SDK on IP %s ",intIpAddress); syslog (LOG_ERR, " UpnpInit returned %d", ret); UpnpFinish(); exit(1); } if (g_debug) syslog(LOG_DEBUG, "UPnP SDK Successfully Initialized."); // Set the Device Web Server Base Directory if (g_debug) syslog(LOG_DEBUG, "Setting the Web Server Root Directory to %s",xmlPath); if ( (ret = UpnpSetWebServerRootDir(xmlPath)) != UPNP_E_SUCCESS ) { syslog (LOG_ERR, "Error Setting Web Server Root Directory to: %s", xmlPath); syslog (LOG_ERR, " UpnpSetWebServerRootDir returned %d", ret); UpnpFinish(); exit(1); } if (g_debug) syslog(LOG_DEBUG, "Succesfully set the Web Server Root Directory."); // Form the Description Doc URL to pass to RegisterRootDevice sprintf(descDocUrl, "http://%s:%d/%s", UpnpGetServerIpAddress(), UpnpGetServerPort(), descDocName); // Register our IGD as a valid UPnP Root device if (g_debug) syslog(LOG_DEBUG, "Registering the root device with descDocUrl %s", descDocUrl); if ( (ret = UpnpRegisterRootDevice(descDocUrl, EventHandler, &deviceHandle, &deviceHandle)) != UPNP_E_SUCCESS ) { syslog(LOG_ERR, "Error registering the root device with descDocUrl: %s", descDocUrl); syslog(LOG_ERR, " UpnpRegisterRootDevice returned %d", ret); UpnpFinish(); exit(1); } syslog (LOG_DEBUG, "IGD root device successfully registered."); // Initialize the state variable table. StateTableInit(descDocUrl); // Record the startup time, for uptime startup_time = time(NULL); // Send out initial advertisements of our device's services with timeouts of 30 minutes if ( (ret = UpnpSendAdvertisement(deviceHandle, 1800) != UPNP_E_SUCCESS )) { syslog(LOG_ERR, "Error Sending Advertisements. Exiting ..."); UpnpFinish(); exit(1); } syslog(LOG_DEBUG, "Advertisements Sent. Listening for requests ... "); // Loop until program exit signals recieved // and now also recreate the current portmappings on SIGUSR1 while (1) { sigemptyset(&sigsToCatch); sigaddset(&sigsToCatch, SIGINT); sigaddset(&sigsToCatch, SIGTERM); sigaddset(&sigsToCatch, SIGQUIT); sigaddset(&sigsToCatch, SIGABRT); sigaddset(&sigsToCatch, SIGHUP); sigaddset(&sigsToCatch, SIGUSR1); sigaddset(&sigsToCatch, SIGUSR2); //sigwait(&sigsToCatch, &signal); pthread_sigmask(SIG_SETMASK, &sigsToCatch, NULL); sigwait(&sigsToCatch, &signal); if (signal == SIGUSR1) { syslog(LOG_DEBUG, "signal SIGUSR1 received - rebuilding portmappings\n"); //rebuild all the portmappings pmlist_RecreateAll(); } else if (signal == SIGHUP || signal == SIGUSR2) { //nothing } else { break; } } syslog(LOG_DEBUG, "Shutting down on signal %d...\n", signal); // Cleanup UPnP SDK and free memory pmlist_FreeList(); UpnpUnRegisterRootDevice(deviceHandle); UpnpFinish(); // Exit normally return (1); }
int main(int argc, char *argv[]) { UpnpDevice_Handle upnp_handle; UpnpDevice_Handle upnp_device; char *device_desc = NULL; int rv = EXIT_FAILURE; struct sigaction sa; shutdown_flag = 0; /* init options, preset some defaults and parse command line arguments */ options = options_init(); options_parse_cli(argc, argv, options); memset(&sa, 0, sizeof(sa)); sa.sa_handler = signal_handler; sa.sa_flags = 0; sigfillset(&sa.sa_mask); if (sigaction(SIGINT, &sa, NULL) < 0) { perror("sigaction"); return EXIT_FAILURE; } if (sigaction(SIGTERM, &sa, NULL) < 0) { perror("sigaction"); return EXIT_FAILURE; } #ifdef UPNP_ENABLE_IPV6 rv = UpnpInit2(options->interface, 0); #else if (options->interface) fprintf(stderr, "Warning: ignoring interface argument, not supported by libupnp.\n"); rv = UpnpInit(NULL, 0); #endif if (rv != UPNP_E_SUCCESS) { fprintf(stderr, "UpnpInit failed: %d\n", rv); return EXIT_FAILURE; } rv = UpnpEnableWebserver(1); if (rv != UPNP_E_SUCCESS) { fprintf(stderr, "Could not enabled UPnP's internal HTTP server.\n"); goto upnp_finish; } device_desc = generate_device_desc(options); if (!device_desc) { fprintf(stderr, "Could not generated the UPnP device description.\n"); goto upnp_finish; } rv = UpnpRegisterRootDevice2(UPNPREG_BUF_DESC, device_desc, strlen(device_desc), 1, upnp_callback, &upnp_device, &upnp_device); if (rv != UPNP_E_SUCCESS) { fprintf(stderr, "Failed to register UPnP root device.\n"); goto free_out; } rv = UpnpSendAdvertisement(upnp_device, UPNP_ALIVE_INTERVAL); if (rv != UPNP_E_SUCCESS) { fprintf(stderr, "Failed to announce UPnP device.\n"); goto upnp_unregister; } while (!shutdown_flag) pause(); rv = EXIT_SUCCESS; upnp_unregister: UpnpUnRegisterRootDevice(upnp_device); free_out: if (device_desc) free(device_desc); upnp_finish: UpnpFinish(); err_out: options_free(options); return rv; }
int main(int argc, char *argv[]) { int retVal, i; int i_ifIndex; char logFile[1024]; mpsync.cmdLine = ZUtilParseCommandLine(argc, argv); PCP_DEV_NODE dmsNode = NULL; sprintf(logFile, "%s/mpsync.log", mpsync.cmdLine->logFolder); if (ZUtilInit(mpsync.cmdLine->dbgLevel, 0xFFFFFFFF & ~(DBG_UPNP_LIB), PRINT_CONSOLE_FILE, logFile, MAX_LOG_SIZE) != Z_SUCCESS) { exit(-1); } if (ZQSyncStart(mpsync.cmdLine, syncEventCallback )) { exit(-1); } /* testFetchResourceFromURL(); */ AssignIPAddresses(); if ((retVal = UpnpInit(NULL, 0)) != UPNP_E_SUCCESS) { ZError(DBG_INIT, "Error with UpnpInit -- %d\n", retVal); exit(-1); } for (i = 0; i < mpsync.numAddr; i++) { InitializeDMC(i); } #ifndef __ARM__ signal(SIGINT , catchKill); #endif signal(SIGKILL , catchKill); signal(SIGTERM, catchKill); signal(SIGHUP , catchKill); signal(SIGQUIT , catchKill); /* Other signals */ signal( SIGALRM, SIG_IGN ); signal( SIGPIPE, SIG_IGN ); //mkdir("/data/test", O_CREAT|O_RDWR|S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH ); //rmdir("/data/test"); // fetchResourceFromURL("http://192.168.168.17:8081/track01.wav","*/*","/home/yimin/test.wav"); /* The Big Loop */ //uuid:fe792ea0-1dd1-11b2-88b6-111111111111 //uuid:f437b3b2-1dd1-11b2-b4a9-faaaddaaf8ea while (!( dmsNode =findDMSByUDN("uuid:fe792ea0-1dd1-11b2-88b6-111111111111", &i_ifIndex)) ) { /* Do some task here ... */ sleep(5); /* wait 30 seconds */ printAllDMS(); sleep(3); /* wait 30 seconds */ } ZError( DBG_MISC, "Start sync..." ); if (ZQSyncSessStart( 0, mpsync.dmcHandle[i_ifIndex], dmsNode->UDN, NULL, "144", NULL, &i_ifIndex )) { ZError( DBG_MISC, "Start sync session failure..." ); } /* The Big Loop */ while ( 1 ) { /* Do some task here ... */ sleep(30); /* wait 30 seconds */ } return 0; }
ERROR_TYPE IUpnp::Start(const char* ip,unsigned short usPort) { return (ERROR_TYPE)UpnpInit(ip,usPort); }
int dial_init() { list_init(&devices); int status = UpnpInit(NULL, 0); UpnpRegisterClient(callback, NULL, &handle); return status; }
int main (int argc, char** argv) { int ret = UPNP_E_SUCCESS; int signal; char descDocUrl[50]; char descDocName[20]; char xmlPath[50]; char intIpAddress[32]; // Server internal ip address char extIpAddress[32]; sigset_t sigsToCatch; pid_t pid,sid; if (argc != 3) { printf("Usage: upnpd <external ifname> <internal ifname>\n"); printf("Example: upnpd ppp0 eth0\n"); printf("Example: upnpd eth1 eth0\n"); exit(0); } parseConfigFile(&g_forwardRules,&g_debug,g_iptables, g_forwardChainName,g_preroutingChainName, g_upstreamBitrate,g_downstreamBitrate, descDocName,xmlPath); // Save the interface names for later uses strcpy(g_extInterfaceName, argv[1]); strcpy(g_intInterfaceName, argv[2]); // Get the internal and external ip address to start the daemon on /* Added by Yanhua */ while( (GetIpAddressStr(intIpAddress, g_intInterfaceName)==0) || (GetIpAddressStr(extIpAddress, g_extInterfaceName)==0) ) { sleep(2); } #if 0 // Put igd in the background as a daemon process. pid = vfork(); if (pid < 0) { perror("Error forking a new process."); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); if ((sid = setsid()) < 0) { perror("Error running setsid"); exit(EXIT_FAILURE); } if ((chdir("/")) < 0) { perror("Error setting root directory"); exit(EXIT_FAILURE); } umask(0); close(STDERR_FILENO); close (STDIN_FILENO); close (STDOUT_FILENO); #endif // End Daemon initialization // Initialize UPnP SDK on the internal Interface if (g_debug) syslog(LOG_DEBUG, "Initializing UPnP SDK ... "); if ( (ret = UpnpInit(intIpAddress,0) ) != UPNP_E_SUCCESS) { syslog (LOG_ERR, "Error Initializing UPnP SDK on IP %s ",intIpAddress); syslog (LOG_ERR, " UpnpInit returned %d", ret); UpnpFinish(); exit(1); } if (g_debug) syslog(LOG_DEBUG, "UPnP SDK Successfully Initialized."); // Set the Device Web Server Base Directory if (g_debug) syslog(LOG_DEBUG, "Setting the Web Server Root Directory to %s",xmlPath); if ( (ret = UpnpSetWebServerRootDir(xmlPath)) != UPNP_E_SUCCESS ) { syslog (LOG_ERR, "Error Setting Web Server Root Directory to: %s", xmlPath); syslog (LOG_ERR, " UpnpSetWebServerRootDir returned %d", ret); UpnpFinish(); exit(1); } if (g_debug) syslog(LOG_DEBUG, "Succesfully set the Web Server Root Directory."); // Form the Description Doc URL to pass to RegisterRootDevice sprintf(descDocUrl, "http://%s:%d/%s", UpnpGetServerIpAddress(), UpnpGetServerPort(), descDocName); // Register our IGD as a valid UPnP Root device if (g_debug) syslog(LOG_DEBUG, "Registering the root device with descDocUrl %s", descDocUrl); if ( (ret = UpnpRegisterRootDevice(descDocUrl, EventHandler, &deviceHandle, &deviceHandle)) != UPNP_E_SUCCESS ) { syslog(LOG_ERR, "Error registering the root device with descDocUrl: %s", descDocUrl); syslog(LOG_ERR, " UpnpRegisterRootDevice returned %d", ret); UpnpFinish(); exit(1); } syslog (LOG_DEBUG, "IGD root device successfully registered."); // Initialize the state variable table. StateTableInit(descDocUrl); // Record the startup time, for uptime /* Modified by Yanhua */ #if 0 startup_time = time(NULL); #endif { struct sysinfo info; sysinfo(&info); startup_time = (long int)info.uptime; } // Send out initial advertisements of our device's services with timeouts of 30 minutes if ( (ret = UpnpSendAdvertisement(deviceHandle, 1800) != UPNP_E_SUCCESS )) { syslog(LOG_ERR, "Error Sending Advertisements. Exiting ..."); UpnpFinish(); exit(1); } syslog(LOG_DEBUG, "Advertisements Sent. Listening for requests ... "); // Loop until program exit signals recieved sigemptyset(&sigsToCatch); sigaddset(&sigsToCatch, SIGINT); sigaddset(&sigsToCatch, SIGTERM); //sigwait(&sigsToCatch, &signal); pthread_sigmask(SIG_SETMASK, &sigsToCatch, NULL); sigwait(&sigsToCatch, &signal); syslog(LOG_DEBUG, "Shutting down on signal %d...\n", signal); // Cleanup UPnP SDK and free memory pmlist_FreeList(); UpnpUnRegisterRootDevice(deviceHandle); UpnpFinish(); // Exit normally return (1); }
//////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"); }
/****************************************************************************** * main * * Description: * Main entry point for WSC device application. * Initializes and registers with the sdk. * Initializes the state stables of the service. * Starts the command loop. * * Parameters: * int argc - count of arguments * char ** argv -arguments. The application * accepts the following optional arguments: * * -ip ipAddress * -port port * -desc descDoc * -webdir webRootDir" * -help * -i ioctl binding interface. * *****************************************************************************/ int main(int argc, char **argv) { unsigned int portTemp = 0; char *ipAddr = NULL, *descDoc = NULL, *webRootDir = NULL, *infName = NULL; unsigned short port = 0; int sig; sigset_t sigs_to_catch; FILE *fp; int retVal; int opt; if (argc < 2) usage(); /* first, parsing the input options */ while((opt = getopt(argc, argv, "a:i:p:f:w:m:d:Dh"))!= -1) { switch (opt) { case 'a': ipAddr = optarg; break; case 'p': sscanf(optarg, "%u", &portTemp); break; case 'f': descDoc = optarg; break; case 'i': infName = optarg; memset(&WSC_IOCTL_IF[0], 0, IFNAMSIZ); if (strlen(infName)) strncpy(&WSC_IOCTL_IF[0], infName, IFNAMSIZ); else strcpy(&WSC_IOCTL_IF[0], "ra0"); break; case 'w': webRootDir = optarg; break; case 'm': WscUPnPOpMode = strtol(optarg, NULL, 10); if (WscUPnPOpMode < UPNP_OPMODE_DEV || WscUPnPOpMode > UPNP_OPMODE_BOTH) usage(); break; case 'D': enableDaemon = 1; break; case 'd': wsc_debug_level = strtol(optarg, NULL, 10); break; case 'h': usage(); break; } } if ((WscUPnPOpMode < 1) || (WscUPnPOpMode > 3)) { fprintf(stderr, "Wrong UPnP Operation Mode: %d\n", WscUPnPOpMode); usage(); } if ((wsc_debug_level > RT_DBG_ALL) || (wsc_debug_level < RT_DBG_OFF)) { fprintf(stderr, "Wrong Debug Level: %d\n", wsc_debug_level); usage(); } port = (unsigned short)portTemp; if (enableDaemon) { pid_t childPid; childPid = fork(); if(childPid < 0) { fprintf(stderr, "Run in deamon mode failed --ErrMsg=%s!\n", strerror(errno)); exit(0); } else if (childPid >0) exit(0); else { close(0); close(1); } } // Write the pid file #ifdef MULTIPLE_CARD_SUPPORT memset(&pid_file_path[0], 0, FILE_PATH_LEN); sprintf(pid_file_path, "%s.%s", DEFAULT_PID_FILE_PATH, WSC_IOCTL_IF); DBGPRINTF(RT_DBG_INFO, "The pid file is: %s!\n", pid_file_path); if ((fp = fopen(pid_file_path, "w")) != NULL) #else if((fp = fopen(DEFAULT_PID_FILE_PATH, "w"))!= NULL) #endif // MULTIPLE_CARD_SUPPORT // { fprintf(fp, "%d", getpid()); fclose(fp); } /* Systme paramters initialization */ if (wscSystemInit() == WSC_SYS_ERROR) { fprintf(stderr, "wsc MsgQ System Initialization failed!\n"); goto STOP; } wscMsgQInit = TRUE; /* Initialize the netlink interface from kernel space */ if(wscK2UModuleInit() != WSC_SYS_SUCCESS) { fprintf(stderr, "creat netlink socket thread failed!\n"); goto STOP; } else { DBGPRINTF(RT_DBG_INFO, "Create netlink socket thread success!\n"); wscK2UMInit = TRUE; } /* Initialize the ioctl interface for data path to kernel space */ ioctl_sock = wscU2KModuleInit(); if(ioctl_sock == -1) { fprintf(stderr, "creat ioctl socket failed!err=%d!\n", errno); goto STOP; } else { DBGPRINTF(RT_DBG_INFO, "Create ioctl socket(%d) success!\n", ioctl_sock); wscU2KMInit = TRUE; } /* Initialize the upnp related data structure and start upnp service */ if(WscUPnPOpMode) { struct ifreq ifr; // Initializing UPnP SDK if ((retVal = UpnpInit(ipAddr, port)) != UPNP_E_SUCCESS) { DBGPRINTF(RT_DBG_ERROR, "Error with UpnpInit -- %d\n", retVal); UpnpFinish(); goto STOP; } wscUPnPSDKInit = TRUE; // Get the IP/Port the UPnP services want to bind. if (ipAddr == NULL) ipAddr = UpnpGetServerIpAddress(); if (port == 0) port = UpnpGetServerPort(); inet_aton(ipAddr, (struct in_addr *)&HostIPAddr); // Get the Mac Address of wireless interface memset(&ifr, 0, sizeof(struct ifreq)); strcpy(ifr.ifr_name, WSC_IOCTL_IF); if (ioctl(ioctl_sock, SIOCGIFHWADDR, &ifr) > 0) { perror("ioctl to get Mac Address"); goto STOP; } memcpy(HostMacAddr, ifr.ifr_hwaddr.sa_data, MAC_ADDR_LEN); DBGPRINTF(RT_DBG_INFO, "UPnP Initialized\n \t IP-Addr: %s Port: %d\n", ipAddr, port); DBGPRINTF(RT_DBG_INFO, "\t HW-Addr: %02x:%02x:%02x:%02x:%02x:%02x!\n", HostMacAddr[0], HostMacAddr[1], HostMacAddr[2], HostMacAddr[3], HostMacAddr[4], HostMacAddr[5]); // Start UPnP Device Service. if (WscUPnPOpMode & UPNP_OPMODE_DEV) { retVal = WscUPnPDevStart(ipAddr, port, descDoc, webRootDir); if (retVal != WSC_SYS_SUCCESS) goto STOP; port++; wscUPnPDevInit = TRUE; } // Start UPnP Control Point Service. if(WscUPnPOpMode & UPNP_OPMODE_CP) { retVal = WscUPnPCPStart(ipAddr, port); if (retVal != WSC_SYS_SUCCESS) goto STOP; wscUPnPCPInit = TRUE; } } /* Catch Ctrl-C and properly shutdown */ sigemptyset(&sigs_to_catch); sigaddset(&sigs_to_catch, SIGINT); //YYHuang@Ralink 07/11/06 sigaddset(&sigs_to_catch, SIGTERM); sigwait(&sigs_to_catch, &sig); DBGPRINTF(RT_DBG_INFO, "Shutting down on signal %d...\n", sig); wscSystemStop(); STOP: // Trigger other thread to stop the procedures. stopThread = 1; #ifdef MULTIPLE_CARD_SUPPORT unlink(pid_file_path); #else unlink(DEFAULT_PID_FILE_PATH); #endif // MULTIPLE_CARD_SUPPORT // exit(0); }
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; }
/* * Initializes UPNP instance. */ static int Open( vlc_object_t *p_this ) { int i_res; services_discovery_t *p_sd = ( services_discovery_t* )p_this; services_discovery_sys_t *p_sys = ( services_discovery_sys_t * ) calloc( 1, sizeof( services_discovery_sys_t ) ); if( !( p_sd->p_sys = p_sys ) ) return VLC_ENOMEM; #ifdef UPNP_ENABLE_IPV6 char* psz_miface; psz_miface = var_InheritString( p_sd, "miface" ); msg_Info( p_sd, "Initializing libupnp on '%s' interface", psz_miface ); i_res = UpnpInit2( psz_miface, 0 ); free( psz_miface ); #else /* If UpnpInit2 isnt available, initialize on first IPv4-capable interface */ i_res = UpnpInit( 0, 0 ); #endif if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Initialization failed: %s", UpnpGetErrorMessage( i_res ) ); free( p_sys ); return VLC_EGENERIC; } ixmlRelaxParser( 1 ); p_sys->p_server_list = new MediaServerList( p_sd ); vlc_mutex_init( &p_sys->callback_lock ); /* Register a control point */ i_res = UpnpRegisterClient( Callback, p_sd, &p_sys->client_handle ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Client registration failed: %s", UpnpGetErrorMessage( i_res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } /* Search for media servers */ i_res = UpnpSearchAsync( p_sys->client_handle, 5, MEDIA_SERVER_DEVICE_TYPE, p_sd ); if( i_res != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Error sending search request: %s", UpnpGetErrorMessage( i_res ) ); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } /* libupnp does not treat a maximum content length of 0 as unlimited * until 64dedf (~ pupnp v1.6.7) and provides no sane way to discriminate * between versions */ if( (i_res = UpnpSetMaxContentLength( INT_MAX )) != UPNP_E_SUCCESS ) { msg_Err( p_sd, "Failed to set maximum content length: %s", UpnpGetErrorMessage( i_res )); Close( (vlc_object_t*) p_sd ); return VLC_EGENERIC; } return VLC_SUCCESS; }
void UpnpStart( void ) //Upnp init { UpnpInit(); UpnpThread(); }
int main (int argc, char** argv) { char descDocUrl[7+15+1+5+1+sizeof(g_vars.descDocName)+1]; // http://ipaddr:port/docName<null> char intIpAddress[16]; // Server internal ip address sigset_t sigsToCatch; int ret, signum, arg = 1, foreground = 0; if (argc < 3 || argc > 4) { printf("Usage: upnpd [-f] <external ifname> <internal ifname>\n"); printf(" -f\tdon't daemonize\n"); printf("Example: upnpd ppp0 eth0\n"); exit(0); } parseConfigFile(&g_vars); // check for '-f' option if (strcmp(argv[arg], "-f") == 0) { foreground = 1; arg++; } // Save interface names for later use strncpy(g_vars.extInterfaceName, argv[arg++], IFNAMSIZ); strncpy(g_vars.intInterfaceName, argv[arg++], IFNAMSIZ); // Get the internal ip address to start the daemon on if (GetIpAddressStr(intIpAddress, g_vars.intInterfaceName) == 0) { fprintf(stderr, "Invalid internal interface name '%s'\n", g_vars.intInterfaceName); exit(EXIT_FAILURE); } if (!foreground) { struct rlimit resourceLimit = { 0, 0 }; pid_t pid, sid; unsigned int i; // Put igd in the background as a daemon process. pid = fork(); if (pid < 0) { perror("Error forking a new process."); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); // become session leader if ((sid = setsid()) < 0) { perror("Error running setsid"); exit(EXIT_FAILURE); } // close all file handles resourceLimit.rlim_max = 0; ret = getrlimit(RLIMIT_NOFILE, &resourceLimit); if (ret == -1) /* shouldn't happen */ { perror("error in getrlimit()"); exit(EXIT_FAILURE); } if (0 == resourceLimit.rlim_max) { fprintf(stderr, "Max number of open file descriptors is 0!!\n"); exit(EXIT_FAILURE); } for (i = 0; i < resourceLimit.rlim_max; i++) close(i); // fork again so child can never acquire a controlling terminal pid = fork(); if (pid < 0) { perror("Error forking a new process."); exit(EXIT_FAILURE); } if (pid > 0) exit(EXIT_SUCCESS); if ((chdir("/")) < 0) { perror("Error setting root directory"); exit(EXIT_FAILURE); } } umask(0); // End Daemon initialization openlog("upnpd", LOG_CONS | LOG_NDELAY | LOG_PID | (foreground ? LOG_PERROR : 0), LOG_LOCAL6); // Initialize UPnP SDK on the internal Interface trace(3, "Initializing UPnP SDK ... "); if ( (ret = UpnpInit(intIpAddress,0) ) != UPNP_E_SUCCESS) { syslog (LOG_ERR, "Error Initializing UPnP SDK on IP %s ",intIpAddress); syslog (LOG_ERR, " UpnpInit returned %d", ret); UpnpFinish(); exit(1); } trace(2, "UPnP SDK Successfully Initialized."); // Set the Device Web Server Base Directory trace(3, "Setting the Web Server Root Directory to %s",g_vars.xmlPath); if ( (ret = UpnpSetWebServerRootDir(g_vars.xmlPath)) != UPNP_E_SUCCESS ) { syslog (LOG_ERR, "Error Setting Web Server Root Directory to: %s", g_vars.xmlPath); syslog (LOG_ERR, " UpnpSetWebServerRootDir returned %d", ret); UpnpFinish(); exit(1); } trace(2, "Succesfully set the Web Server Root Directory."); //initialize the timer thread for expiration of mappings if (ExpirationTimerThreadInit()!=0) { syslog(LOG_ERR,"ExpirationTimerInit failed"); UpnpFinish(); exit(1); } // Form the Description Doc URL to pass to RegisterRootDevice sprintf(descDocUrl, "http://%s:%d/%s", UpnpGetServerIpAddress(), UpnpGetServerPort(), g_vars.descDocName); // Register our IGD as a valid UPnP Root device trace(3, "Registering the root device with descDocUrl %s", descDocUrl); if ( (ret = UpnpRegisterRootDevice(descDocUrl, EventHandler, &deviceHandle, &deviceHandle)) != UPNP_E_SUCCESS ) { syslog(LOG_ERR, "Error registering the root device with descDocUrl: %s", descDocUrl); syslog(LOG_ERR, " UpnpRegisterRootDevice returned %d", ret); UpnpFinish(); exit(1); } trace(2, "IGD root device successfully registered."); // Initialize the state variable table. StateTableInit(descDocUrl); // Record the startup time, for uptime startup_time = time(NULL); // Send out initial advertisements of our device's services with timeouts of 30 minutes if ( (ret = UpnpSendAdvertisement(deviceHandle, 1800) != UPNP_E_SUCCESS )) { syslog(LOG_ERR, "Error Sending Advertisements. Exiting ..."); UpnpFinish(); exit(1); } trace(2, "Advertisements Sent. Listening for requests ... "); // Loop until program exit signals received do { sigemptyset(&sigsToCatch); sigaddset(&sigsToCatch, SIGINT); sigaddset(&sigsToCatch, SIGTERM); sigaddset(&sigsToCatch, SIGUSR1); pthread_sigmask(SIG_SETMASK, &sigsToCatch, NULL); sigwait(&sigsToCatch, &signum); trace(3, "Caught signal %d...\n", signum); switch (signum) { case SIGUSR1: DeleteAllPortMappings(); break; default: break; } } while (signum!=SIGTERM && signum!=SIGINT); trace(2, "Shutting down on signal %d...\n", signum); // Cleanup UPnP SDK and free memory DeleteAllPortMappings(); ExpirationTimerThreadShutdown(); UpnpUnRegisterRootDevice(deviceHandle); UpnpFinish(); // Exit normally return (0); }
/******************************************************************************** * 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; }
int upnp_device_init(struct device *device_def, char *ip_address) { int rc; int result = -1; short int port = 0; struct service *srv; struct icon *icon_entry; char *buf; int i; if (device_def->init_function) { rc = device_def->init_function(); if (rc != 0) { goto out; } } upnp_device = device_def; /* register icons in web server */ for (i=0; (icon_entry = upnp_device->icons[i]); i++) { webserver_register_file(icon_entry->url, "image/png"); } /* generate and register service schemas in web server */ for (i=0; (srv = upnp_device->services[i]); i++) { buf = upnp_get_scpd(srv); debug_printf(MSG_INFO, "registering '%s'\n", srv->scpd_url); webserver_register_buf(srv->scpd_url,buf,"text/xml"); } rc = UpnpInit(ip_address, port); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "UpnpInit() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpEnableWebserver(TRUE); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "UpnpEnableWebServer() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpSetVirtualDirCallbacks(&virtual_dir_callbacks); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "UpnpSetVirtualDirCallbacks() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpAddVirtualDir("/upnp"); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "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, &device_def, &device_handle); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "UpnpRegisterRootDevice2() Error: %d\n", rc); goto upnp_err_out; } rc = UpnpSendAdvertisement(device_handle, 100); if (UPNP_E_SUCCESS != rc) { debug_printf(MSG_ERROR, "Error sending advertisements: %d\n", rc); goto upnp_err_out; } result = 0; goto out; upnp_err_out: UpnpFinish(); out: return result; }