예제 #1
0
/*----------------------------------------------------------------------
|   CMediaCrawler::SplitObjectId
+---------------------------------------------------------------------*/
NPT_Result
CMediaCrawler::SplitObjectId(const NPT_String& object_id, NPT_String& server_uuid, NPT_String& server_object_id)
{
    // reset output params
    server_uuid = "";
    server_object_id = "";

    if (object_id.GetLength() == 0 || object_id[0] != '0')
        return NPT_ERROR_INVALID_FORMAT;

    if (object_id.GetLength() > 1) {
        if (object_id[1] != '/') return NPT_ERROR_INVALID_FORMAT;
    
        server_uuid = object_id.SubString(2);

        // look for next delimiter
        int index = server_uuid.Find('/');
        if (index >= 0) {
            server_object_id = server_uuid.SubString(index+1);
            server_uuid.SetLength(index);
        }
    }

    return NPT_SUCCESS;
}
예제 #2
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_FATAL(path.SetLength(i-1));

    // remove excessive delimiters
    path.TrimRight("/");
    path.TrimRight("\\");
    return NPT_SUCCESS;
}
예제 #3
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;
}
예제 #4
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());
    }
}
예제 #5
0
/*----------------------------------------------------------------------
|   PLT_FileMediaServer::ProcessFileRequest
+---------------------------------------------------------------------*/
NPT_Result 
PLT_FileMediaServer::ProcessFileRequest(NPT_HttpRequest&  request, 
                                        NPT_HttpResponse& response, 
                                        NPT_SocketInfo&   client_info)
{
    NPT_COMPILER_UNUSED(client_info);

    NPT_LOG_FINE("PLT_FileMediaServer::ProcessFileRequest Received Request:");
    PLT_LOG_HTTP_MESSAGE(NPT_LOG_LEVEL_FINE, &request);

    response.GetHeaders().SetHeader("Accept-Ranges", "bytes");

    if (request.GetMethod().Compare("GET") && request.GetMethod().Compare("HEAD")) {
        response.SetStatus(500, "Internal Server Error");
        return NPT_SUCCESS;
    }

    // File requested
    NPT_String path = m_FileBaseUri.GetPath();
    NPT_String strUri = NPT_Uri::PercentDecode(request.GetUrl().GetPath());

    NPT_HttpUrlQuery query(request.GetUrl().GetQuery());
    NPT_String file_path = query.GetField("path");

    // hack for XBMC support for 360, we urlencoded the ? to that the 360 doesn't strip out the query
    // but then the query ends being parsed as part of the path
    int index = strUri.Find("path=");
    if (index>0) file_path = strUri.Right(strUri.GetLength()-index-5);
    if (file_path.GetLength() == 0) goto failure;

    // HACK for wmp: somehow they inverse our slashes !
    // do it only if we're on windows
    if (m_DirDelimiter == "\\") {
        file_path.Replace('/', '\\');
    }

    if (path.Compare(strUri.Left(path.GetLength()), true) == 0) {
        NPT_Integer start, end;
        PLT_HttpHelper::GetRange(&request, start, end);

        return PLT_FileServer::ServeFile(m_Path + file_path, &response, start, end, !request.GetMethod().Compare("HEAD"));
    } 

    // Album Art requested
    path = m_AlbumArtBaseUri.GetPath();
    if (path.Compare(strUri.Left(path.GetLength()), true) == 0) {
        return OnAlbumArtRequest(m_Path + file_path, response);
    } 

failure:
    response.SetStatus(404, "File Not Found");
    return NPT_SUCCESS;
}
예제 #6
0
/*----------------------------------------------------------------------
|   PLT_MediaBrowser::OnSearchResponse
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaBrowser::OnSearchResponse(NPT_Result               res, 
                                   PLT_DeviceDataReference& device, 
                                   PLT_ActionReference&     action, 
                                   void*                    userdata)
{
    NPT_String     value;
    PLT_BrowseInfo info;
    NPT_String     unescaped;

    if (NPT_FAILED(res) || action->GetErrorCode() != 0) {
        goto bad_action;
    }

    if (NPT_FAILED(action->GetArgumentValue("ContainerId", info.object_id)))  {
        goto bad_action;
    }
    if (NPT_FAILED(action->GetArgumentValue("UpdateID", value)) || 
        value.GetLength() == 0 || 
        NPT_FAILED(value.ToInteger(info.uid))) {
        goto bad_action;
    }
    if (NPT_FAILED(action->GetArgumentValue("NumberReturned", value)) || 
        value.GetLength() == 0 || 
        NPT_FAILED(value.ToInteger(info.nr))) {
        goto bad_action;
    }
    if (NPT_FAILED(action->GetArgumentValue("TotalMatches", value)) || 
        value.GetLength() == 0 || 
        NPT_FAILED(value.ToInteger(info.tm))) {
        goto bad_action;
    }
    if (NPT_FAILED(action->GetArgumentValue("Result", value)) || 
        value.GetLength() == 0) {
        goto bad_action;
    }
    
    if (NPT_FAILED(PLT_Didl::FromDidl(value, info.items))) {
        goto bad_action;
    }

    if (m_Delegate) m_Delegate->OnSearchResult(NPT_SUCCESS, device, &info, userdata);
    return NPT_SUCCESS;

bad_action:
    if (m_Delegate) m_Delegate->OnSearchResult(NPT_FAILURE, device, NULL, userdata);
    return NPT_FAILURE;
}
예제 #7
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;
}
예제 #8
0
bool DeviceDesc::matchDeviceType(const NPT_String& deviceType) const
{
	if (deviceType.EndsWith(":*")) {
		return m_private->m_deviceType.CompareN(deviceType, deviceType.GetLength() - 1) == 0;
	}
	return m_private->m_deviceType.Compare(deviceType) == 0;
}
예제 #9
0
/*----------------------------------------------------------------------
|   NPT_String::Replace
+---------------------------------------------------------------------*/
const NPT_String&
NPT_String::Replace(char a, const char* str) 
{
    // check args
    if (m_Chars == NULL || a == '\0' || str == NULL || str[0] == '\0') return *this;

    // 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());
    return *this;
}
/*----------------------------------------------------------------------
|   PLT_MicroMediaController::ChooseDevice
+---------------------------------------------------------------------*/
PLT_DeviceDataReference
PLT_MicroMediaController::ChooseDevice(const NPT_Lock<PLT_DeviceMap>& deviceList)
{
    PLT_StringMap            namesTable;
    PLT_DeviceDataReference* result = NULL;
    NPT_String               chosenUUID;
    NPT_AutoLock             lock(m_MediaServers);

    // create a map with the device UDN -> device Name
    const NPT_List<PLT_DeviceMapEntry*>& entries = deviceList.GetEntries();
    NPT_List<PLT_DeviceMapEntry*>::Iterator entry = entries.GetFirstItem();
    while (entry) {
        PLT_DeviceDataReference device = (*entry)->GetValue();
        NPT_String              name   = device->GetFriendlyName();
        namesTable.Put((*entry)->GetKey(), name);

        ++entry;
    }

    // ask user to choose
    chosenUUID = ChooseIDFromTable(namesTable);
    if (chosenUUID.GetLength()) {
        deviceList.Get(chosenUUID, result);
    }

    return result?*result:PLT_DeviceDataReference(); // return empty reference if not device was selected
}
예제 #11
0
/*----------------------------------------------------------------------
|   CUPnPDirectory::GetFriendlyName
+---------------------------------------------------------------------*/
const char*
CUPnPDirectory::GetFriendlyName(const char* url)
{
    NPT_String path = url;
    if (!path.EndsWith("/")) path += "/";

    if (path.Left(7).Compare("upnp://", true) != 0) {
        return NULL;
    } else if (path.Compare("upnp://", true) == 0) {
        return "UPnP Media Servers (Auto-Discover)";
    }

    // look for nextslash
    int next_slash = path.Find('/', 7);
    if (next_slash == -1)
        return NULL;

    NPT_String uuid = path.SubString(7, next_slash-7);
    NPT_String object_id = path.SubString(next_slash+1, path.GetLength()-next_slash-2);

    // look for device
    PLT_DeviceDataReference device;
    if(!FindDeviceWait(CUPnP::GetInstance(), uuid, device))
        return NULL;

    return (const char*)device->GetFriendlyName();
}
예제 #12
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);
    }
예제 #13
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;
}
예제 #14
0
/*----------------------------------------------------------------------
|   CUPnPDirectory::GetFriendlyName
+---------------------------------------------------------------------*/
const char*
CUPnPDirectory::GetFriendlyName(const char* url)
{
    NPT_String path = url;
    if (!path.EndsWith("/")) path += "/";

    if (path.Left(7).Compare("upnp://", true) != 0) {
        return NULL;
    } else if (path.Compare("upnp://", true) == 0) {
        return "UPnP Media Servers (Auto-Discover)";
    }

    // look for nextslash
    int next_slash = path.Find('/', 7);
    if (next_slash == -1)
        return NULL;

    NPT_String uuid = path.SubString(7, next_slash-7);
    NPT_String object_id = path.SubString(next_slash+1, path.GetLength()-next_slash-2);

    // look for device
    PLT_DeviceDataReference* device;
    const NPT_Lock<PLT_DeviceMap>& devices = CUPnP::GetInstance()->m_MediaBrowser->GetMediaServers();
    if (NPT_FAILED(devices.Get(uuid, device)) || device == NULL)
        return NULL;

    return (const char*)(*device)->GetFriendlyName();
}
예제 #15
0
/*----------------------------------------------------------------------
|   PLT_HttpHelper::SetBody
+---------------------------------------------------------------------*/
NPT_Result
PLT_HttpHelper::SetBody(NPT_HttpMessage& message, 
                        NPT_String&      body, 
                        NPT_HttpEntity** entity /* = NULL */)
{
    return SetBody(message, (const char*)body, body.GetLength(), entity);
}
예제 #16
0
/*----------------------------------------------------------------------
|       NPT_Win32WindowMessageQueue
+---------------------------------------------------------------------*/
NPT_Win32WindowMessageQueue::NPT_Win32WindowMessageQueue()
{
    // create a hidden window to process our incoming messages
    WNDCLASS wclass;

    // compute a unique class name
    m_ClassName[0] = 'N';
    m_ClassName[1] = 'P';
    m_ClassName[2] = 'T';
    m_ClassName[3] = 'H';
    m_ClassName[4] = 'W';
    NPT_String tid = NPT_String::FromInteger(GetCurrentThreadId());
    for (unsigned int i=0; i<=tid.GetLength(); i++) {
        m_ClassName[5+i] = tid.GetChars()[i];        
    }

    // register a window class
    wclass.style         = 0;
    wclass.lpfnWndProc   = NPT_Win32WindowMessageQueue::WindowProcedure;
    wclass.cbClsExtra    = 0;
    wclass.cbWndExtra    = 0;
    wclass.hInstance     = GetModuleHandle(NULL);
    wclass.hIcon         = NULL;
    wclass.hCursor       = NULL;
    wclass.hbrBackground = NULL;
    wclass.lpszMenuName  = NULL;
    wclass.lpszClassName = m_ClassName;

    // register the class and ignore any error because we might
    // be registering the class more than once                  
    RegisterClass(&wclass);

    // create the hidden window
    m_WindowHandle = CreateWindow(
        wclass.lpszClassName, // pointer to registered class name 
        TEXT(""),             // pointer to window name 
        0,                    // window style 
        0,                    // horizontal position of window 
        0,                    // vertical position of window 
        0,                    // window width 
        0,                    // window height 
        NULL,                 // handle to parent or owner window 
        NULL,                 // handle to menu or child-window identifier 
        wclass.hInstance,     // handle to application instance 
        NULL);

    // set a pointer to ourself as user data */
#if defined(_MSC_VER)
#pragma warning( push )
#pragma warning( disable: 4244) // we have to test for this because SetWindowLongPtr
                                // is incorrectly defined, so we'll get a C4244 warning
#endif // _MSC_VER
    if (m_WindowHandle) {
        SetWindowLongPtr(m_WindowHandle, GWLP_USERDATA, NPT_POINTER_TO_LONG(this));
    }
#if defined(_MSC_VER)
#pragma warning( pop )
#endif // _MSC_VER
    m_hInstance = wclass.hInstance;
}
예제 #17
0
void 
GPAC_MediaController::OnMSStateVariablesChanged(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars)
{
	GPAC_MediaServerItem *ms = NULL;
	gf_mx_p(m_ControlPointLock);

	u32 i, count;
	count = gf_list_count(m_MediaServers);
	for (i=0; i<count; i++) {
		GPAC_MediaServerItem *ms = (GPAC_MediaServerItem *) gf_list_get(m_MediaServers, i);
		if (ms->m_UUID==service->GetDevice()->GetUUID()) {
			break;
		}
		ms = NULL;
	}
	
	if (!ms) {
		gf_mx_v(m_ControlPointLock);
		return;
	}

    PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs");
    if (var) {
        // variable found, parse value
        NPT_String value = var->GetValue();
        NPT_String item_id, update_id;
        int index;

        while (value.GetLength()) {
            // look for container id
            index = value.Find(',');
            if (index < 0) break;
            item_id = value.Left(index);
            value = value.SubString(index+1);

            // look for update id
            if (value.GetLength()) {
                index = value.Find(',');
                update_id = (index<0)?value:value.Left(index);
                value = (index<0)?"":value.SubString(index+1);

				m_pUPnP->ContainerChanged(ms->m_device, item_id, update_id);
            }       
        }
    }        
	gf_mx_v(m_ControlPointLock);
}
예제 #18
0
/*----------------------------------------------------------------------
|   CMediaCrawler::FormatObjectId
+---------------------------------------------------------------------*/
NPT_String
CMediaCrawler::FormatObjectId(const NPT_String& server_uuid, const NPT_String& server_object_id)
{
    NPT_String object_id = NPT_String("0/") + server_uuid;
    if (server_object_id.GetLength())
        object_id += NPT_String("/") + server_object_id;

    return object_id;
}
예제 #19
0
/*----------------------------------------------------------------------
|   CUPnPVirtualPathDirectory::SplitPath
+---------------------------------------------------------------------*/
bool
CUPnPVirtualPathDirectory::SplitPath(const char* object_id, NPT_String& share_name, NPT_String& path)
{
    int index = 0;
    NPT_String id = object_id;
    id.TrimRight("/");

    // reset output params first
    share_name = "";
    path = "";

    if (id.StartsWith("virtualpath://upnproot")) {
        index = 22;
    } else if (id.StartsWith("virtualpath://upnpmusic")) {
        index = 23;
    } else if (id.StartsWith("virtualpath://upnpvideo")) {
        index = 23;
    } else if (id.StartsWith("virtualpath://upnppictures")) {
        index = 26;
    } else {
        return false;
    }

    // nothing to split
    if (id.GetLength() <= (NPT_Cardinal)index) {
        return true;
    }

    // invalid id!
    if (id[index] != '/') {
        return false;
    }

    // look for share
    index = id.Find('/', index+1);
    share_name = id.SubString(0, (index==-1)?id.GetLength():index);

    if (index >= 0) {
        path = id.SubString(index+1);
    }

    return true;
}
예제 #20
0
/*----------------------------------------------------------------------
|   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)); 
}
예제 #21
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);
}
예제 #22
0
파일: NptTime.cpp 프로젝트: 0p3ns0urc3/xbmc
/*----------------------------------------------------------------------
|   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;
    }
}
예제 #23
0
/*----------------------------------------------------------------------
|   PLT_SyncMediaBrowser::OnMSStateVariablesChanged
+---------------------------------------------------------------------*/
void 
PLT_SyncMediaBrowser::OnMSStateVariablesChanged(PLT_Service*                  service, 
                                                NPT_List<PLT_StateVariable*>* vars)
{
    NPT_AutoLock lock(m_MediaServers);
    
    PLT_DeviceDataReference device;
    const NPT_List<PLT_DeviceMapEntry*>::Iterator it = 
        m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(service->GetDevice()->GetUUID()));
    if (!it) return; // device with this service has gone away

    device = (*it)->GetValue();
    PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs");
    if (var) {
        // variable found, parse value
        NPT_String value = var->GetValue();
        NPT_String item_id, update_id;
        int index;

        while (value.GetLength()) {
            // look for container id
            index = value.Find(',');
            if (index < 0) break;
            item_id = value.Left(index);
            value = value.SubString(index+1);

            // look for update id
            if (value.GetLength()) {
                index = value.Find(',');
                update_id = (index<0)?value:value.Left(index);
                value = (index<0)?"":value.SubString(index+1);

                // clear cache for that device
                if (m_UseCache) m_Cache.Clear(device->GetUUID(), item_id);

                // notify listener
                if (m_ContainerListener) m_ContainerListener->OnContainerChanged(device, item_id, update_id);
            }       
        }
    }        
}
예제 #24
0
/*----------------------------------------------------------------------
|   NPT_String::operator+(const NPT_String& , char)
+---------------------------------------------------------------------*/
NPT_String 
operator+(const NPT_String& s1, char c)
{
    // allocate space for the new string
    NPT_String result;
    result.Reserve(s1.GetLength()+1);
    
    // append
    result = s1;
    result += c;

    return result;
}
예제 #25
0
/*----------------------------------------------------------------------
|   PLT_FileMediaServer::OnAlbumArtRequest
+---------------------------------------------------------------------*/
NPT_Result 
PLT_FileMediaServer::OnAlbumArtRequest(NPT_HttpResponse& response,
                                       NPT_String        file_path)
{
    NPT_LargeSize            total_len;
    NPT_File                 file(file_path);
    NPT_InputStreamReference stream;

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

    if (NPT_FAILED(file.Open(NPT_FILE_OPEN_MODE_READ)) || 
        NPT_FAILED(file.GetInputStream(stream))        || 
        NPT_FAILED(stream->GetSize(total_len)) || (total_len == 0)) {
        goto filenotfound;
    } else {
        NPT_String extension = NPT_FilePath::FileExtension(file_path);
        if (extension.GetLength() == 0) {
            goto filenotfound;
        }

        PLT_MetadataHandler* metadataHandler = NULL;
        char* caData;
        int   caDataLen;
        NPT_Result ret = NPT_ContainerFind(m_MetadataHandlers, 
                                           PLT_MetadataHandlerFinder(extension), 
                                           metadataHandler);
        if (NPT_FAILED(ret) || metadataHandler == NULL) {
            goto filenotfound;
        }
        // load the metadatahandler and read the cover art
        if (NPT_FAILED(metadataHandler->Load(*stream)) || 
            NPT_FAILED(metadataHandler->GetCoverArtData(caData, caDataLen))) {
            goto filenotfound;
        }
        
        PLT_HttpHelper::SetContentType(response, "application/octet-stream");
        PLT_HttpHelper::SetBody(response, caData, caDataLen);
        delete caData;
        return NPT_SUCCESS;
    }

filenotfound:
    response.SetStatus(404, "File Not Found");
    return NPT_SUCCESS;
}
예제 #26
0
UUID UUID::fromString(const NPT_String& s)
{
	const char *cc = s.GetChars();
	if (s.GetLength() == 36 && cc[8] == '-' && cc[13] == '-' && cc[18] == '-' && cc[23] == '-') {
		UUID uuid;
		if (!parseHex(*reinterpret_cast<NPT_UInt32*>(uuid.m_data + 0), cc, 8)) return UUID();
		if (!parseHex(*reinterpret_cast<NPT_UInt16*>(uuid.m_data + 4), cc + 9, 4)) return UUID();
		if (!parseHex(*reinterpret_cast<NPT_UInt16*>(uuid.m_data + 6), cc + 14, 4)) return UUID();
		if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 8), cc + 19, 2)) return UUID();
		if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 9), cc + 21, 2)) return UUID();
		for (int i = 0; i < 6; i++) {
			if (!parseHex(*reinterpret_cast<NPT_UInt8*>(uuid.m_data + 10 + i), cc + 24 + i * 2, 2)) return UUID();
		}
		return uuid;
	}
	return UUID();
}
예제 #27
0
/*----------------------------------------------------------------------
|       PLT_MediaConnect::LookUpMediaConnectInfo
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaConnect::LookUpMediaConnectInfo(NPT_String             deviceID, 
                                         PLT_MediaConnectInfo*& mc_info)
{
    mc_info = NULL;

    if (deviceID.GetLength()) {
        /* lookup the MAC from the UDN */
        NPT_String* MAC;
        if (NPT_SUCCEEDED(m_MediaConnectUDNMap.Get(deviceID, MAC))) {
            /* lookup the PLT_MediaConnectInfo from the MAC now */
            return m_MediaConnectDeviceInfoMap.Get(*MAC, mc_info);
        }
    }

    return NPT_FAILURE;
}
예제 #28
0
/*----------------------------------------------------------------------
|   NPT_Url::ToStringWithDefaultPort
+---------------------------------------------------------------------*/
NPT_String
NPT_Url::ToStringWithDefaultPort(NPT_UInt16 default_port, bool with_fragment) const
{
    NPT_String result;
    NPT_String request = ToRequestString(with_fragment);
    NPT_Size   length = m_Scheme.GetLength()+3+m_Host.GetLength()+6+request.GetLength();

    result.Reserve(length);
    result += m_Scheme;
    result += "://";
    result += m_Host;
    if (m_Port != default_port) {
        NPT_String port = NPT_String::FromInteger(m_Port);
        result += ":";
        result += port;
    }
    result += request;
    return result;
}
예제 #29
0
/*----------------------------------------------------------------------
|   NPT_String::operator+(const NPT_String& , const char*)
+---------------------------------------------------------------------*/
NPT_String 
operator+(const char* s1, const NPT_String& s2)
{
    // shortcut
    if (s1 == NULL) return NPT_String(s2);

    // measure strings
    NPT_Size s1_length = NPT_String::StringLength(s1);
    NPT_Size s2_length = s2.GetLength();

    // allocate space for the new string
    NPT_String result;
    char* start = result.PrepareToWrite(s1_length+s2_length);

    // concatenate the two strings into the result
    NPT_String::CopyBuffer(start, s1, s1_length);
    NPT_String::CopyString(start+s1_length, s2.GetChars());
    
    return result;
}
예제 #30
0
/*----------------------------------------------------------------------
|   NPT_LogManager::ParseConfigSource
+---------------------------------------------------------------------*/
NPT_Result
NPT_LogManager::ParseConfigSource(NPT_String& source) 
{
    if (source.StartsWith("file:")) {
        /* file source */
        ParseConfigFile(source.GetChars()+5);
    } else if (source.StartsWith("plist:")) {
        /* property list source */
        ParseConfig(source.GetChars()+6, source.GetLength()-6);
    } else if (source.StartsWith("http:port=")) {
        /* http configurator */
        unsigned int port = 0;
        NPT_Result result = NPT_ParseInteger(source.GetChars()+10, port, true);
        if (NPT_FAILED(result)) return result;
        new NPT_HttpLoggerConfigurator(port);
    } else {
        return NPT_ERROR_INVALID_SYNTAX;
    }

    return NPT_SUCCESS;
}