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; }
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 = 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; }
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); }
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) { 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 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); }
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); }
unsigned short IUpnp::GetUpnpPort() { return UpnpGetServerPort(); }
std::string WebServer::getWebRootUrl() { return stringops::format("http://%s:%d/", UpnpGetServerIpAddress(), UpnpGetServerPort()); }