Example #1
0
/*----------------------------------------------------------------------
|   PLT_MediaRenderer::OnSetAVTransportURI
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaRenderer::OnSetAVTransportURI(PLT_ActionReference& action)
{
	/*test*/
	PLT_Service* serviceAVT;
	NPT_CHECK_WARNING(FindServiceByType("urn:schemas-upnp-org:service:AVTransport:1", serviceAVT));

	// update service state variables
	//serviceAVT->SetStateVariable("TransportState", "TRANSITIONING");
	/*test*/
    if (m_Delegate) {
        return m_Delegate->OnSetAVTransportURI(action);
    }
    
    // default implementation is using state variable
	NPT_String uri;
	NPT_CHECK_WARNING(action->GetArgumentValue("CurrentURI", uri));

    NPT_String metadata;
    NPT_CHECK_WARNING(action->GetArgumentValue("CurrentURIMetaData", metadata));
    
    //PLT_Service* serviceAVT;
    //NPT_CHECK_WARNING(FindServiceByType("urn:schemas-upnp-org:service:AVTransport:1", serviceAVT));

    // update service state variables
    serviceAVT->SetStateVariable("AVTransportURI", uri);
    serviceAVT->SetStateVariable("AVTransportURIMetaData", metadata);

	//serviceAVT->SetStateVariable("TransportState", "PLAYING");//test
	OutputDebugString(uri.GetChars());

    return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
|   BLT_DecoderServer::OnSetPropertyCommand
+---------------------------------------------------------------------*/
void 
BLT_DecoderServer::OnSetPropertyCommand(BLT_PropertyScope        scope,
                                        const NPT_String&        /*target*/,
                                        const NPT_String&        name,
                                        const ATX_PropertyValue* value)
{
    BLT_Result result;
    ATX_LOG_FINE_1("[%s]", name.GetChars());

    ATX_Properties* properties = NULL;
    switch (scope) {
        case BLT_PROPERTY_SCOPE_CORE:
            result = BLT_Decoder_GetProperties(m_Decoder, &properties);
            break;
            
        case BLT_PROPERTY_SCOPE_STREAM:
            result = BLT_Decoder_GetStreamProperties(m_Decoder, &properties);
            break;
            
        default:
            // not handled yet
            result = BLT_ERROR_NOT_SUPPORTED;
    }
    if (ATX_SUCCEEDED(result) && properties != NULL) {
        result = ATX_Properties_SetProperty(properties, name.GetChars(), value);
    }
    SendReply(BLT_DecoderServer_Message::COMMAND_ID_SET_PROPERTY, result);
}
/*----------------------------------------------------------------------
|   PLT_HttpHelper::ParseBody
+---------------------------------------------------------------------*/
NPT_Result
PLT_HttpHelper::ParseBody(const NPT_HttpMessage& message, 
                          NPT_XmlElementNode*&   tree) 
{
    // reset tree
    tree = NULL;

    // read body
    NPT_String body;
    NPT_CHECK_WARNING(GetBody(message, body));

    // parse body
    NPT_XmlParser parser;
    NPT_XmlNode*  node;
    NPT_Result result = parser.Parse(body, node);
    if (NPT_FAILED(result)) {
        NPT_LOG_FINEST_1("Failed to parse %s", body.IsEmpty()?"(empty string)":body.GetChars());
        NPT_CHECK_WARNING(result);
    }
    
    tree = node->AsElementNode();
    if (!tree) {
        delete node;
        return NPT_FAILURE;
    }

    return NPT_SUCCESS;
}
Example #4
0
/*----------------------------------------------------------------------
|       UdpServerLoop
+---------------------------------------------------------------------*/
static void
UdpServerLoop(int port)
{
    NPT_UdpSocket listener;

    // info
    if (Options.verbose) {
        NPT_Debug("listening on port %d\n", port);
    }

    NPT_Result result = listener.Bind(NPT_SocketAddress(NPT_IpAddress::Any, port));
    if (NPT_FAILED(result)) {
        NPT_Debug("ERROR: Bind() failed (%d)\n", result);
    }

    // packet loop
    NPT_DataBuffer packet(32768);
    NPT_SocketAddress address;

    do {
        result = listener.Receive(packet, &address);
        if (NPT_SUCCEEDED(result)) {
            if (Options.verbose) {
                NPT_String ip = address.GetIpAddress().ToString();
                NPT_Debug("Received %d bytes from %s:%d\n", packet.GetDataSize(), ip.GetChars(), address.GetPort());
            }

            listener.Send(packet, &address);
        }
    } while (NPT_SUCCEEDED(result));
}
Example #5
0
/*----------------------------------------------------------------------
|   NPT_UrlQuery::UrlDecode
+---------------------------------------------------------------------*/
NPT_String
NPT_UrlQuery::UrlDecode(const char* str)
{
    NPT_String decoded = NPT_Uri::PercentDecode(str);
    decoded.Replace('+', ' ');
    return decoded;
}
Example #6
0
bool CUPnPPlayer::QueueNextFile(const CFileItem& file)
{
  CFileItem item(file);
  NPT_Reference<CThumbLoader> thumb_loader;
  NPT_Reference<PLT_MediaObject> obj;
  NPT_String path(file.GetPath().c_str());
  NPT_String tmp;

  if (file.IsVideoDb())
    thumb_loader = NPT_Reference<CThumbLoader>(new CVideoThumbLoader());
  else if (item.IsMusicDb())
    thumb_loader = NPT_Reference<CThumbLoader>(new CMusicThumbLoader());


  obj = BuildObject(item, path, 0, thumb_loader, NULL, CUPnP::GetServer());
  if(!obj.IsNull())
  {
    NPT_CHECK_LABEL_SEVERE(PLT_Didl::ToDidl(*obj, "", tmp), failed);
    tmp.Insert(didl_header, 0);
    tmp.Append(didl_footer);
  }

  NPT_CHECK_LABEL_WARNING(m_control->SetNextAVTransportURI(m_delegate->m_device
                                                         , m_delegate->m_instance
                                                         , file.GetPath().c_str()
                                                         , (const char*)tmp
                                                         , m_delegate), failed);
  if(!m_delegate->m_resevent.WaitMSec(10000)) goto failed;
  NPT_CHECK_LABEL_WARNING(m_delegate->m_resstatus, failed);
  return true;

failed:
  CLog::Log(LOGERROR, "UPNP: CUPnPPlayer::QueueNextFile - unable to queue file %s", file.GetPath().c_str());
  return false;
}
Example #7
0
/*----------------------------------------------------------------------
|   NPT_String::Replace
+---------------------------------------------------------------------*/
void
NPT_String::Replace(char a, const char* str) 
{
    // check args
    if (m_Chars == NULL || a == '\0' || str == NULL || str[0] == '\0') return;

    // optimization
    if (NPT_StringLength(str) == 1) return Replace(a, str[0]);

    // we are going to create a new string
    NPT_String dst;
    char* src = m_Chars;

    // reserve at least as much as input
    dst.Reserve(GetLength());

    // process the buffer
    while (*src) {
        if (*src == a) {
            dst += str;
        } else {
            dst += *src;
        }
        src++;
    }

    Assign(dst.GetChars(), dst.GetLength());
}
Example #8
0
/*----------------------------------------------------------------------
|   NPT_String::Format
+---------------------------------------------------------------------*/
NPT_String
NPT_String::Format(const char* format, ...)
{
    NPT_String result;
    NPT_Size   buffer_size = NPT_STRING_FORMAT_BUFFER_DEFAULT_SIZE; // default value
    
    va_list  args;
    va_start(args, format);

    for(;;) {
        /* try to format (it might not fit) */
        result.Reserve(buffer_size);
        char* buffer = result.UseChars();
        int f_result = NPT_FormatStringVN(buffer, buffer_size, format, args);
        if (f_result >= (int)(buffer_size)) f_result = -1;
        if (f_result >= 0) {
            result.SetLength(f_result);
            break;
        }
        
        /* the buffer was too small, try something bigger         */
        /* (we don't trust the return value of NPT_FormatStringVN */
        /* for the actual size needed)                            */
        buffer_size *= 2;
        if (buffer_size > NPT_STRING_FORMAT_BUFFER_MAX_SIZE) break;
    }

    va_end(args);
    
    return result;
}
Example #9
0
/*----------------------------------------------------------------------
|   PLT_MediaServer::ParseSort
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaServer::ParseSort(const NPT_String& sort, NPT_List<NPT_String>& list)
{
    // reset output params first
    list.Clear();
    
    // easy out
    if (sort.GetLength() == 0 || sort == "*") return NPT_SUCCESS;
    
    list = sort.Split(",");
    
    // verify each property has a namespace
    NPT_List<NPT_String>::Iterator property = list.GetFirstItem();
    while (property) {
        NPT_List<NPT_String> parsed_property = (*property).Split(":");
        if (parsed_property.GetItemCount() != 2)
          parsed_property = (*property).Split("@");
        if (parsed_property.GetItemCount() != 2 || 
            (!(*property).StartsWith("-") && !(*property).StartsWith("+"))) {
            NPT_LOG_WARNING_1("Invalid SortCriteria property %s", (*property).GetChars());
            return NPT_FAILURE;
        }
        property++;
    }
    
    return NPT_SUCCESS;
}
Example #10
0
/*----------------------------------------------------------------------
|       PLT_MediaConnect::OnIsValidated
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaConnect::OnIsValidated(PLT_ActionReference&  action, 
                                PLT_MediaConnectInfo* mc_info)
{
    bool validated = true;

    NPT_String deviceID;
    action->GetArgumentValue("DeviceID", deviceID);

    /* is there a device ID passed ? */
    if (deviceID.GetLength()) {
        /* lookup the MediaConnectInfo from the UDN */
        NPT_String MAC;
        PLT_MediaConnectInfo* device_info;
        if (NPT_FAILED(LookUpMediaConnectInfo(deviceID, device_info))) {
            validated = false;
        } else {
            validated = device_info->m_Validated;
        }
    } else {
        validated = mc_info?mc_info->m_Validated:true;
    }

    action->SetArgumentValue("Result", validated?"1":"0");
    return NPT_SUCCESS;
}
Example #11
0
    void Run() {
        do {
            // wait for a connection
            NPT_Socket* client = NULL;
            NPT_LOG_FINE_1("waiting for connection on port %d...", m_Port);
            NPT_Result result = m_Socket.WaitForNewClient(client, NPT_TIMEOUT_INFINITE);
            if (NPT_FAILED(result) || client == NULL) return;
                    
            NPT_SocketInfo client_info;
            client->GetInfo(client_info);
            NPT_LOG_FINE_2("client connected (%s -> %s)",
                client_info.local_address.ToString().GetChars(),
                client_info.remote_address.ToString().GetChars());

            // get the output stream
            NPT_OutputStreamReference output;
            client->GetOutputStream(output);

            // generate policy based on our current IP
            NPT_String policy = "<cross-domain-policy>";
            policy += "<allow-access-from domain=\""+client_info.local_address.GetIpAddress().ToString()+"\" to-ports=\""+m_AuthorizedPorts+"\"/>";
            policy += "<allow-access-from domain=\""+client_info.remote_address.GetIpAddress().ToString()+"\" to-ports=\""+m_AuthorizedPorts+"\"/>";
            policy += "</cross-domain-policy>";

            NPT_MemoryStream* mem_input = new NPT_MemoryStream();
            mem_input->Write(policy.GetChars(), policy.GetLength());
            NPT_InputStreamReference input(mem_input);
            
            NPT_StreamToStreamCopy(*input, *output);
            
            
            delete client;
        } while (!m_Aborted);
    }
Example #12
0
/*----------------------------------------------------------------------
|   NPT_DirectorySplitFilePath
+---------------------------------------------------------------------*/
NPT_Result 
NPT_DirectorySplitFilePath(const char* filepath, 
                           NPT_String& path, 
                           NPT_String& filename)
{
    if (!filepath || filepath[0] == '\0') 
        return NPT_ERROR_INVALID_PARAMETERS;

    path = filepath;

    char       last_char;
    NPT_Int32  i = path.GetLength();
    do {
        last_char = path[i-1];
        if (last_char == '\\' || last_char == '/') 
            break;
    } while (--i);

    // we need at least one delimiter and it cannot be last
    if (i == 0 || i == (NPT_Int32)path.GetLength())  {
        return NPT_ERROR_INVALID_PARAMETERS;
    }

    // assign filename
    filename = filepath+i;

    // truncate path & remove trailing slashes
    NPT_CHECK(path.SetLength(i-1));

    // remove excessive delimiters
    path.TrimRight("/");
    path.TrimRight("\\");
    return NPT_SUCCESS;
}
Example #13
0
/*----------------------------------------------------------------------
|   PLT_MediaItem::ToDidl
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaItem::ToDidl(NPT_UInt32 mask, NPT_String& didl)
{
    NPT_String tmp;
    // Allocate enough space for a big string we're going to concatenate in
    tmp.Reserve(2048);

    tmp = "<item id=\"";

    PLT_Didl::AppendXmlEscape(tmp, m_ObjectID);
    tmp += "\" parentID=\"";
    PLT_Didl::AppendXmlEscape(tmp, m_ParentID);

    if (!m_ReferenceID.IsEmpty()) {
		tmp += "\" refID=\"";
		PLT_Didl::AppendXmlEscape(tmp, m_ReferenceID);
    }

    tmp += "\" restricted=\"";
    tmp += m_Restricted?"1\"":"0\"";

    tmp += ">";

    NPT_CHECK_SEVERE(PLT_MediaObject::ToDidl(mask, tmp));

    /* close tag */
    tmp += "</item>";

    didl += tmp;
    return NPT_SUCCESS;
}
Example #14
0
/*----------------------------------------------------------------------
|   NPT_UrlQuery::Parse
+---------------------------------------------------------------------*/
NPT_Result 
NPT_UrlQuery::Parse(const char* query)
{
    const char* cursor = query;
    NPT_String  name;
    NPT_String  value;
    bool        in_name = true;
    do {
        if (*cursor == '\0' || *cursor == '&') {
            if (!name.IsEmpty()) {
                AddField(name, value, true);   
            }
            name.SetLength(0);
            value.SetLength(0);
            in_name = true;
        } else if (*cursor == '=' && in_name) {
            in_name = false;
        } else {
            if (in_name) {
                name += *cursor;
            } else {
                value += *cursor;
            }
        }
    } while (*cursor++);
    
    return NPT_SUCCESS;
}
Example #15
0
/*----------------------------------------------------------------------
|   NPT_LogManager::ConfigureLogger
+---------------------------------------------------------------------*/
NPT_Result
NPT_LogManager::ConfigureLogger(NPT_Logger* logger)
{
    /* configure the level */
    NPT_String* level_value = GetConfigValue(logger->m_Name,".level");
    if (level_value) {
        NPT_Int32 value;
        /* try a symbolic name */
        value = NPT_Log::GetLogLevel(*level_value);
        if (value < 0) {
            /* try a numeric value */
            if (NPT_FAILED(level_value->ToInteger(value, false))) {
                value = -1;
            }
        }
        if (value >= 0) {
            logger->m_Level = value;
            logger->m_LevelIsInherited = false;
        }
    }

    /* remove any existing handlers */
    logger->DeleteHandlers();

    /* configure the handlers */
    NPT_String* handlers = GetConfigValue(logger->m_Name,".handlers");
    if (handlers) {
        const char*     handlers_list = handlers->GetChars();
        const char*     cursor = handlers_list;
        const char*     name_start = handlers_list;
        NPT_String      handler_name;
        NPT_LogHandler* handler;
        for (;;) {
            if (*cursor == '\0' || *cursor == ',') {
                if (cursor != name_start) {
                    handler_name.Assign(name_start, (NPT_Size)(cursor-name_start));
                    handler_name.Trim(" \t");
                    
                    /* create a handler */
                    if (NPT_SUCCEEDED(
                        NPT_LogHandler::Create(logger->m_Name, handler_name, handler))) {
                        logger->AddHandler(handler);
                    }

                }
                if (*cursor == '\0') break;
                name_start = cursor+1;
            }
            ++cursor;
        }
    }

    /* configure the forwarding */
    NPT_String* forward = GetConfigValue(logger->m_Name,".forward");
    if (forward && !ConfigValueIsBooleanTrue(*forward)) {
        logger->m_ForwardToParent = false;
    }

    return NPT_SUCCESS;
}
Example #16
0
/*----------------------------------------------------------------------
|   NPT_Uri::PercentDecode
+---------------------------------------------------------------------*/
NPT_String
NPT_Uri::PercentDecode(const char* str)
{
    NPT_String decoded;

    // check args
    if (str == NULL) return decoded;

    // reserve at least the size of the current uri
    decoded.Reserve(NPT_StringLength(str));

    // process each character
    while (unsigned char c = *str++) {
        if (c == '%') {
            // needs to be unescaped
            unsigned char unescaped;
            if (NPT_SUCCEEDED(NPT_HexToByte(str, unescaped))) {
                decoded += unescaped;
                str += 2;
            } else {
                // not a valid escape sequence, just keep the %
                decoded += c;
            }
        } else {
            // no unescaping required
            decoded += c;
        }
    }

    return decoded;
}
Example #17
0
/*----------------------------------------------------------------------
|   PLT_HttpServer::ServeFile
+---------------------------------------------------------------------*/
NPT_Result 
PLT_HttpServer::ServeFile(const NPT_HttpRequest&        request, 
                          const NPT_HttpRequestContext& context,
                          NPT_HttpResponse&             response,
                          NPT_String                    file_path) 
{
    NPT_InputStreamReference stream;
    NPT_File                 file(file_path);
    NPT_FileInfo             file_info;
    
    // prevent hackers from accessing files outside of our root
    if ((file_path.Find("/..") >= 0) || (file_path.Find("\\..") >= 0) ||
        NPT_FAILED(NPT_File::GetInfo(file_path, &file_info))) {
        return NPT_ERROR_NO_SUCH_ITEM;
    }
    
    // check for range requests
    const NPT_String* range_spec = request.GetHeaders().GetHeaderValue(NPT_HTTP_HEADER_RANGE);
    
    // handle potential 304 only if range header not set
    NPT_DateTime  date;
    NPT_TimeStamp timestamp;
    if (NPT_SUCCEEDED(PLT_UPnPMessageHelper::GetIfModifiedSince((NPT_HttpMessage&)request, date)) &&
        !range_spec) {
        date.ToTimeStamp(timestamp);
        
        NPT_LOG_INFO_5("File %s timestamps: request=%d (%s) vs file=%d (%s)", 
                       (const char*)request.GetUrl().GetPath(),
                       (NPT_UInt32)timestamp.ToSeconds(),
                       (const char*)date.ToString(),
                       (NPT_UInt32)file_info.m_ModificationTime,
                       (const char*)NPT_DateTime(file_info.m_ModificationTime).ToString());
        
        if (timestamp >= file_info.m_ModificationTime) {
            // it's a match
            NPT_LOG_FINE_1("Returning 304 for %s", request.GetUrl().GetPath().GetChars());
            response.SetStatus(304, "Not Modified", NPT_HTTP_PROTOCOL_1_1);
            return NPT_SUCCESS;
        }
    }
    
    // open file
    if (NPT_FAILED(file.Open(NPT_FILE_OPEN_MODE_READ)) || 
        NPT_FAILED(file.GetInputStream(stream))        ||
        stream.IsNull()) {
        return NPT_ERROR_NO_SUCH_ITEM;
    }
    
    // set Last-Modified and Cache-Control headers
    if (file_info.m_ModificationTime) {
        NPT_DateTime last_modified = NPT_DateTime(file_info.m_ModificationTime);
        response.GetHeaders().SetHeader("Last-Modified", last_modified.ToString(NPT_DateTime::FORMAT_RFC_1123), true);
        response.GetHeaders().SetHeader("Cache-Control", "max-age=0,must-revalidate", true);
        //response.GetHeaders().SetHeader("Cache-Control", "max-age=1800", true);
    }
    
    PLT_HttpRequestContext tmp_context(request, context);
    return ServeStream(request, context, response, stream, PLT_MimeType::GetMimeType(file_path, &tmp_context));
}
Example #18
0
/*----------------------------------------------------------------------
|   NPT_String::NPT_String
+---------------------------------------------------------------------*/
NPT_String::NPT_String(const NPT_String& str)
{
    if (str.GetLength() == 0) {
        m_Chars = NULL;
    } else {
        m_Chars = Buffer::Create(str.GetChars(), str.GetLength());
    }
}
/*----------------------------------------------------------------------
|   PLT_MicroMediaController::PopDirectoryStackToRoot
+---------------------------------------------------------------------*/
void
PLT_MicroMediaController::PopDirectoryStackToRoot(void)
{
    NPT_String val;
    while (NPT_SUCCEEDED(m_CurBrowseDirectoryStack.Peek(val)) && val.Compare("0")) {
        m_CurBrowseDirectoryStack.Pop(val);
    }
}
Example #20
0
/*----------------------------------------------------------------------
|   PLT_MediaContainer::FromDidl
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaContainer::FromDidl(NPT_XmlElementNode* entry)
{
    NPT_String str;

    /* reset first */
    Reset();

    // check entry type
    if (entry->GetTag().Compare("Container", true) != 0) 
        return NPT_ERROR_INTERNAL;

    // check if item is searchable (is default true?)
    if (NPT_SUCCEEDED(PLT_XmlHelper::GetAttribute(entry, "searchable", str, "", 5))) {
        m_Searchable = PLT_Service::IsTrue(str);
    }

    // look for childCount
    if (NPT_SUCCEEDED(PLT_XmlHelper::GetAttribute(entry, "childCount", str, "", 256))) {
        NPT_UInt32 count;
        NPT_CHECK_SEVERE(str.ToInteger(count));
        m_ChildrenCount = count;
    }

	// upnp:searchClass child elements
    NPT_Array<NPT_XmlElementNode*> children;
	PLT_XmlHelper::GetChildren(entry, children, "upnp:searchClass");

    for (NPT_Cardinal i=0; i<children.GetItemCount(); i++) {
        PLT_SearchClass search_class;

        // extract url
        if (children[i]->GetText() == NULL) {
            NPT_LOG_WARNING_1("No searchClass text found in: %s", 
				(const char*)PLT_XmlHelper::Serialize(*children[i]));
			continue;
        }
		
        // DLNA 7.3.17.4
		search_class.type = children[i]->GetText()->SubString(0, 256);

		// extract optional attribute name
		PLT_XmlHelper::GetAttribute(children[i], "name", search_class.friendly_name);
		    
		// includeDerived property
		if (NPT_FAILED(PLT_XmlHelper::GetAttribute(children[i], "includeDerived", str))) {
            NPT_LOG_WARNING_1("No required attribute [email protected] found in: %s", 
				(const char*)PLT_XmlHelper::Serialize(*children[i]));
			continue;
		}

		search_class.include_derived = PLT_Service::IsTrue(str);
		m_SearchClasses.Add(search_class);
	}

    return PLT_MediaObject::FromDidl(entry);
}
Example #21
0
/*----------------------------------------------------------------------
|   PLT_MediaBrowser::OnDeviceAdded
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaBrowser::OnDeviceAdded(PLT_DeviceDataReference& device)
{
    // verify the device implements the function we need
    PLT_Service* serviceCDS;
    PLT_Service* serviceCMR;
    NPT_String   type;

    if (!device->GetType().StartsWith("urn:schemas-upnp-org:device:MediaServer"))
        return NPT_FAILURE;
    
    type = "urn:schemas-upnp-org:service:ContentDirectory:*";
    if (NPT_FAILED(device->FindServiceByType(type, serviceCDS))) {
        NPT_LOG_WARNING_2("Service %s not found in device \"%s\"", 
            type.GetChars(),
            device->GetFriendlyName().GetChars());
        return NPT_FAILURE;
    } else {
        // in case it's a newer upnp implementation, force to 1
        serviceCDS->ForceVersion(1);
    }
    
    type = "urn:schemas-upnp-org:service:ConnectionManager:*";
    if (NPT_FAILED(device->FindServiceByType(type, serviceCMR))) {
        NPT_LOG_WARNING_2("Service %s not found in device \"%s\"", 
            type.GetChars(), 
            device->GetFriendlyName().GetChars());
        return NPT_FAILURE;
    } else {
        // in case it's a newer upnp implementation, force to 1
        serviceCMR->ForceVersion(1);
    }
    
    {
        NPT_AutoLock lock(m_MediaServers);

        PLT_DeviceDataReference data;
        NPT_String uuid = device->GetUUID();
        
        // is it a new device?
        if (NPT_SUCCEEDED(NPT_ContainerFind(m_MediaServers, PLT_DeviceDataFinder(uuid), data))) {
            NPT_LOG_WARNING_1("Device (%s) is already in our list!", (const char*)uuid);
            return NPT_FAILURE;
        }

        NPT_LOG_FINE_1("Device Found: %s", (const char*)*device);

        m_MediaServers.Add(device);
    }

    if (m_Delegate && m_Delegate->OnMSAdded(device)) {
        m_CtrlPoint->Subscribe(serviceCDS);
        m_CtrlPoint->Subscribe(serviceCMR);
    }
    
    return NPT_SUCCESS;
}
Example #22
0
/*----------------------------------------------------------------------
|   NPT_LogManager::ConfigValueIsBooleanTrue
+---------------------------------------------------------------------*/
bool
NPT_LogManager::ConfigValueIsBooleanTrue(NPT_String& value)
{
    return 
        value.Compare("true", true) == 0 ||
        value.Compare("yes",  true) == 0 ||
        value.Compare("on",   true) == 0 ||
        value.Compare("1",    true) == 0;
}
Example #23
0
/*----------------------------------------------------------------------
|   NPT_LogManager::ConfigValueIsBooleanFalse
+---------------------------------------------------------------------*/
bool
NPT_LogManager::ConfigValueIsBooleanFalse(NPT_String& value)
{
    return 
        value.Compare("false", true) == 0  ||
        value.Compare("no",    true) == 0  ||
        value.Compare("off",   true) == 0  ||
        value.Compare("0",     true) == 0;
}
Example #24
0
/*----------------------------------------------------------------------
|   PLT_FileMediaServer::ServeFile
+---------------------------------------------------------------------*/
NPT_Result 
PLT_FileMediaServer::ServeFile(NPT_HttpRequest&              request, 
                               const NPT_HttpRequestContext& context,
                               NPT_HttpResponse&             response,
                               const NPT_String&             uri_path,
                               const NPT_String&             file_path)
{
    NPT_COMPILER_UNUSED(context);

    // prevent hackers from accessing files outside of our root
    if ((file_path.Find("/..") >= 0) || (file_path.Find("\\..") >= 0)) {
        return NPT_FAILURE;
    }

    // File requested
    NPT_String path = m_FileBaseUri.GetPath();
    if (path.Compare(uri_path.Left(path.GetLength()), true) == 0) {
        NPT_Position start, end;
        PLT_HttpHelper::GetRange(request, start, end);
        
        return PLT_FileServer::ServeFile(response,
                                         NPT_FilePath::Create(m_Path, file_path), 
                                         start, 
                                         end, 
                                         !request.GetMethod().Compare("HEAD"));
    } 

    // Album Art requested
    path = m_AlbumArtBaseUri.GetPath();
    if (path.Compare(uri_path.Left(path.GetLength()), true) == 0) {
        return OnAlbumArtRequest(response, m_Path + file_path);
    } 
    
    return NPT_FAILURE;
}
Example #25
0
/*----------------------------------------------------------------------
|   NPT_LogUdpHandler::Log
+---------------------------------------------------------------------*/
void
NPT_LogUdpHandler::Log(const NPT_LogRecord& record)
{
    // format the record
    NPT_String msg;
    NPT_LogTcpHandler::FormatRecord(record, msg);
    
    // send it in a datagram
    NPT_DataBuffer buffer(msg.GetChars(), msg.GetLength()+1, false);
    m_Socket.Send(buffer, &m_Target);
}
Example #26
0
/*----------------------------------------------------------------------
|   NPT_FilePath::BaseName
+---------------------------------------------------------------------*/
NPT_String 
NPT_FilePath::BaseName(const char* path)
{
    NPT_String result = path;
    int separator = result.ReverseFind(Separator);
    if (separator >= 0) {
        result = path+separator+NPT_StringLength(Separator);
    } 

    return result;
}
/*----------------------------------------------------------------------
|   PLT_HttpHelper::SetBasicAuthorization
+---------------------------------------------------------------------*/
void         
PLT_HttpHelper::SetBasicAuthorization(NPT_HttpRequest& request, 
                                      const char*      username, 
                                      const char*      password)
{ 
	NPT_String encoded;
	NPT_String cred =  NPT_String(username) + ":" + password;

	NPT_Base64::Encode((const NPT_Byte *)cred.GetChars(), cred.GetLength(), encoded);
	request.GetHeaders().SetHeader(NPT_HTTP_HEADER_AUTHORIZATION, NPT_String("Basic " + encoded)); 
}
Example #28
0
/*----------------------------------------------------------------------
|   AppendNumber
+---------------------------------------------------------------------*/
static void
AppendNumber(NPT_String& output, NPT_UInt32 number, unsigned int digit_count)
{
    NPT_Size new_length = output.GetLength()+digit_count;
    output.SetLength(new_length);
    char* dest = output.UseChars()+new_length;
    while (digit_count--) {
        *--dest = '0'+(number%10);
        number /= 10;
    }
}
Example #29
0
void JNICore::onDiscoveryListChaned(const NPT_String& ip, const NPT_String& devName, const int type)
{
	VMGuard vmguard;
	if (JNIEnv *env = vmguard.env()) {
		jstring jsIp = env->NewStringUTF(ip.GetChars());
		jstring jsDev = env->NewStringUTF(devName.GetChars());
		env->CallVoidMethod(m_delegateObj, CG::f_DLNACore_hookDDLC, jsIp, jsDev, type);
		env->DeleteLocalRef(jsIp);
		env->DeleteLocalRef(jsDev);
	}
}
/*----------------------------------------------------------------------
|   PLT_MicroMediaController::HandleCmd_cdup
+---------------------------------------------------------------------*/
void
PLT_MicroMediaController::HandleCmd_cdup()
{
    // we don't want to pop the root off now....
    NPT_String val;
    m_CurBrowseDirectoryStack.Peek(val);
    if (val.Compare("0")) {
        m_CurBrowseDirectoryStack.Pop(val);
    } else {
        printf("Already at root\n");
    }
}