/*---------------------------------------------------------------------- | 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; }
/*---------------------------------------------------------------------- | PLT_MediaRenderer::OnSetAVTransportURI +---------------------------------------------------------------------*/ NPT_Result PLT_MediaRenderer::OnSetAVTransportURI(PLT_ActionReference& action) { 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", "STOPPED"); serviceAVT->SetStateVariable("TransportStatus", "OK"); serviceAVT->SetStateVariable("TransportPlaySpeed", "1"); NPT_CHECK_SEVERE(action->SetArgumentsOutFromStateVariable()); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | 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; }
/*---------------------------------------------------------------------- | PLT_MediaConnect::OnRegisterDevice +---------------------------------------------------------------------*/ NPT_Result PLT_MediaConnect::OnRegisterDevice(PLT_ActionReference& action) { NPT_String reqMsgBase64; NPT_CHECK_WARNING(action->GetArgumentValue("RegistrationReqMsg", reqMsgBase64)); NPT_String respMsgBase64; NPT_CHECK_WARNING(action->SetArgumentValue("RegistrationRespMsg", respMsgBase64)); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_MediaBrowser::Browse +---------------------------------------------------------------------*/ NPT_Result PLT_MediaBrowser::Browse(PLT_DeviceDataReference& device, const char* obj_id, NPT_UInt32 start_index, NPT_UInt32 count, bool browse_metadata, const char* filter, const char* sort_criteria, void* userdata) { // verify device still in our list PLT_DeviceDataReference device_data; NPT_CHECK_WARNING(FindServer(device->GetUUID(), device_data)); // create action PLT_ActionReference action; NPT_CHECK_SEVERE(m_CtrlPoint->CreateAction( device, "urn:schemas-upnp-org:service:ContentDirectory:1", "Browse", action)); // Set the object id PLT_Arguments args; if (NPT_FAILED(action->SetArgumentValue("ObjectID", obj_id))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the browse_flag if (NPT_FAILED(action->SetArgumentValue("BrowseFlag", browse_metadata?"BrowseMetadata":"BrowseDirectChildren"))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Filter if (NPT_FAILED(action->SetArgumentValue("Filter", filter))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Starting Index if (NPT_FAILED(action->SetArgumentValue("StartingIndex", NPT_String::FromInteger(start_index)))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Requested Count if (NPT_FAILED(action->SetArgumentValue("RequestedCount", NPT_String::FromInteger(count)))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Requested Count if (NPT_FAILED(action->SetArgumentValue("SortCriteria", sort_criteria))) { return NPT_ERROR_INVALID_PARAMETERS; } // invoke the action if (NPT_FAILED(m_CtrlPoint->InvokeAction(action, userdata))) { return NPT_ERROR_INVALID_PARAMETERS; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_File::RemoveDir +---------------------------------------------------------------------*/ NPT_Result NPT_File::RemoveDir(const char* path, bool force_if_not_empty) { NPT_String root_path = path; // normalize path separators root_path.Replace((NPT_FilePath::Separator[0] == '/')?'\\':'/', NPT_FilePath::Separator); // remove superfluous delimiters at the end root_path.TrimRight(NPT_FilePath::Separator); // remove all entries in the directory if required if (force_if_not_empty) { // enumerate all entries NPT_File dir(root_path); NPT_List<NPT_String> entries; NPT_CHECK_WARNING(dir.ListDir(entries)); for (NPT_List<NPT_String>::Iterator it = entries.GetFirstItem(); it; ++it) { NPT_File::Remove(NPT_FilePath::Create(root_path, *it), true); } } // remove the (now empty) directory return NPT_File::RemoveDir(root_path); }
/*---------------------------------------------------------------------- | PLT_MediaBrowser::Search +---------------------------------------------------------------------*/ NPT_Result PLT_MediaBrowser::Search(PLT_DeviceDataReference& device, const char* container_id, const char* search_criteria, NPT_UInt32 start_index, NPT_UInt32 count, const char* filter, void* userdata) { // verify device still in our list PLT_DeviceDataReference device_data; NPT_CHECK_WARNING(FindServer(device->GetUUID(), device_data)); // create action PLT_ActionReference action; NPT_CHECK_SEVERE(m_CtrlPoint->CreateAction( device, "urn:schemas-upnp-org:service:ContentDirectory:1", "Search", action)); // Set the container id PLT_Arguments args; if (NPT_FAILED(action->SetArgumentValue("ContainerID", container_id))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Search Criteria if (NPT_FAILED(action->SetArgumentValue("SearchCriteria", search_criteria))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Filter if (NPT_FAILED(action->SetArgumentValue("Filter", filter))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Starting Index if (NPT_FAILED(action->SetArgumentValue("StartingIndex", NPT_String::FromInteger(start_index)))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Requested Count if (NPT_FAILED(action->SetArgumentValue("RequestedCount", NPT_String::FromInteger(count)))) { return NPT_ERROR_INVALID_PARAMETERS; } // set the Requested Count if (NPT_FAILED(action->SetArgumentValue("SortCriteria", ""))) { return NPT_ERROR_INVALID_PARAMETERS; } // invoke the action if (NPT_FAILED(m_CtrlPoint->InvokeAction(action, userdata))) { return NPT_ERROR_INVALID_PARAMETERS; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_File::GetSize +---------------------------------------------------------------------*/ NPT_Result NPT_File::GetSize(NPT_LargeSize& size) { // default value size = 0; // get the file info NPT_FileInfo info; GetInfo(info); switch (info.m_Type) { case NPT_FileInfo::FILE_TYPE_DIRECTORY: { NPT_List<NPT_String> entries; NPT_CHECK_WARNING(ListDir(entries)); size = entries.GetItemCount(); break; } case NPT_FileInfo::FILE_TYPE_REGULAR: case NPT_FileInfo::FILE_TYPE_OTHER: size = info.m_Size; return NPT_SUCCESS; default: break; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_SsdpSender::SendSsdp +---------------------------------------------------------------------*/ NPT_Result PLT_SsdpSender::SendSsdp(NPT_HttpResponse& response, const char* usn, const char* target, NPT_UdpSocket& socket, bool notify, const NPT_SocketAddress* addr /* = NULL */) { NPT_CHECK_SEVERE(FormatPacket(response, usn, target, socket, notify)); // logging NPT_String prefix = NPT_String::Format("Sending SSDP Response:"); PLT_LOG_HTTP_MESSAGE(NPT_LOG_LEVEL_FINER, prefix, &response); // use a memory stream to write all the data NPT_MemoryStream stream; NPT_Result res = response.Emit(stream); if (NPT_FAILED(res)) return res; // copy stream into a data packet and send it NPT_LargeSize size; stream.GetSize(size); if (size != (NPT_Size)size) NPT_CHECK(NPT_ERROR_OUT_OF_RANGE); NPT_DataBuffer packet(stream.GetData(), (NPT_Size)size); NPT_CHECK_WARNING(socket.Send(packet, addr)); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_File::Load +---------------------------------------------------------------------*/ NPT_Result NPT_File::Load(NPT_DataBuffer& buffer) { NPT_InputStreamReference input; // get the input stream for the file NPT_CHECK_WARNING(GetInputStream(input)); // read the stream return input->Load(buffer); }
/*---------------------------------------------------------------------- | NPT_File::Save +---------------------------------------------------------------------*/ NPT_Result NPT_File::Save(const NPT_DataBuffer& buffer) { NPT_OutputStreamReference output; // get the output stream for the file NPT_CHECK_WARNING(GetOutputStream(output)); // write to the stream return output->WriteFully(buffer.GetData(), buffer.GetDataSize()); }
/*---------------------------------------------------------------------- | PLT_TaskManager::StopTask +---------------------------------------------------------------------*/ NPT_Result PLT_TaskManager::StopTask(PLT_ThreadTask* task) { { NPT_AutoLock lock(m_TasksLock); // if task is not found, then it might // have been auto-destroyed already so return now NPT_CHECK_WARNING(m_Tasks.Remove(task)); } return task->Stop(); }
/*---------------------------------------------------------------------- | PLT_SsdpDeviceSearchResponseInterfaceIterator class +---------------------------------------------------------------------*/ NPT_Result PLT_SsdpDeviceSearchResponseInterfaceIterator::operator()(NPT_NetworkInterface*& net_if) const { const NPT_SocketAddress* remote_addr = &m_RemoteAddr; NPT_List<NPT_NetworkInterfaceAddress>::Iterator niaddr = net_if->GetAddresses().GetFirstItem(); if (!niaddr) return NPT_SUCCESS; // don't try to bind on port 1900 or connect will fail later NPT_UdpSocket socket; //socket.Bind(NPT_SocketAddress(NPT_IpAddress::Any, 1900), true); // by connecting, the kernel chooses which interface to use to route to the remote // this is the IP we should use in our Location URL header NPT_CHECK_WARNING(socket.Connect(m_RemoteAddr, 5000)); NPT_SocketInfo info; socket.GetInfo(info); // did we successfully connect and found out which interface is used? if (info.local_address.GetIpAddress().AsLong()) { // check that the interface the kernel chose matches the interface // we wanted to send on if ((*niaddr).GetPrimaryAddress().AsLong() != info.local_address.GetIpAddress().AsLong()) { return NPT_SUCCESS; } // socket already connected, so we don't need to specify where to go remote_addr = NULL; } NPT_HttpResponse response(200, "OK", NPT_HTTP_PROTOCOL_1_1); PLT_UPnPMessageHelper::SetLocation(response, m_Device->GetDescriptionUrl(info.local_address.GetIpAddress().ToString())); PLT_UPnPMessageHelper::SetLeaseTime(response, m_Device->GetLeaseTime()); PLT_UPnPMessageHelper::SetServer(response, PLT_HTTP_DEFAULT_SERVER, false); response.GetHeaders().SetHeader("EXT", ""); // process search response twice to be DLNA compliant #if defined(PLATINUM_UPNP_SPECS_STRICT) { //NPT_UdpSocket socket; NPT_CHECK_SEVERE(m_Device->SendSsdpSearchResponse(response, socket, m_ST, remote_addr)); } NPT_System::Sleep(NPT_TimeInterval(PLT_DLNA_SSDP_DELAY_GROUP)); #endif { //NPT_UdpSocket socket; NPT_CHECK_SEVERE(m_Device->SendSsdpSearchResponse(response, socket, m_ST, remote_addr)); } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_HttpServerSocketTask::Write +---------------------------------------------------------------------*/ NPT_Result PLT_HttpServerSocketTask::Write(NPT_HttpResponse* response, bool& keep_alive, bool headers_only /* = false */) { // get the socket output stream NPT_OutputStreamReference output_stream; NPT_CHECK_WARNING(m_Socket->GetOutputStream(output_stream)); // send headers NPT_CHECK_WARNING(SendResponseHeaders(response, *output_stream, keep_alive)); // send the body if (!headers_only) { NPT_CHECK_WARNING(SendResponseBody(response, *output_stream)); } // flush output_stream->Flush(); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_Didl::ParseTimeStamp +---------------------------------------------------------------------*/ NPT_Result PLT_Didl::ParseTimeStamp(const NPT_String& timestamp, NPT_UInt32& seconds) { // assume a timestamp in the format HH:MM:SS.FFF int separator; NPT_String str = timestamp; NPT_UInt32 value; // reset output params first seconds = 0; // remove milliseconds first if any if ((separator = str.ReverseFind('.')) != -1) { str = str.Left(separator); } // look for next separator if ((separator = str.ReverseFind(':')) == -1) return NPT_FAILURE; // extract seconds NPT_CHECK_WARNING(str.SubString(separator+1).ToInteger(value)); seconds = value; str = str.Left(separator); // look for next separator if ((separator = str.ReverseFind(':')) == -1) return NPT_FAILURE; // extract minutes NPT_CHECK_WARNING(str.SubString(separator+1).ToInteger(value)); seconds += 60*value; str = str.Left(separator); // extract hours NPT_CHECK_WARNING(str.ToInteger(value)); seconds += 3600*value; return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_HttpHelper::ParseBody +---------------------------------------------------------------------*/ NPT_Result PLT_HttpHelper::ParseBody(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_CHECK_WARNING(parser.Parse(body, node)); tree = node->AsElementNode(); if (!tree) { delete node; return NPT_FAILURE; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_File::Remove +---------------------------------------------------------------------*/ NPT_Result NPT_File::Remove(const char* path, bool recurse /* = false */) { NPT_FileInfo info; // make sure the path exists NPT_CHECK_WARNING(GetInfo(path, &info)); if (info.m_Type == NPT_FileInfo::FILE_TYPE_DIRECTORY) { return RemoveDir(path, recurse); } else { return RemoveFile(path); } }
/*---------------------------------------------------------------------- | PLT_MediaBrowser::OnEventNotify +---------------------------------------------------------------------*/ NPT_Result PLT_MediaBrowser::OnEventNotify(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars) { if (!service->GetDevice()->GetType().StartsWith("urn:schemas-upnp-org:device:MediaServer")) return NPT_FAILURE; if (!m_Delegate) return NPT_SUCCESS; /* make sure device associated to service is still around */ PLT_DeviceDataReference data; NPT_CHECK_WARNING(FindServer(service->GetDevice()->GetUUID(), data)); if (m_Delegate) m_Delegate->OnMSStateVariablesChanged(service, vars); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_Zip::Inflate +---------------------------------------------------------------------*/ NPT_Result NPT_Zip::Inflate(const NPT_DataBuffer& in, NPT_DataBuffer& out, bool raw) { // assume an output buffer twice the size of the input plus a bit NPT_CHECK_WARNING(out.Reserve(32+2*in.GetDataSize())); // setup the stream z_stream stream; stream.next_in = (Bytef*)in.GetData(); stream.avail_in = (uInt)in.GetDataSize(); stream.next_out = out.UseData(); stream.avail_out = (uInt)out.GetBufferSize(); // setup the memory functions stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; // initialize the decompressor int err = inflateInit2(&stream, raw?-15:15+32); // 15 = default window bits, +32 = automatic header if (err != Z_OK) return MapError(err); // decompress until the end do { err = inflate(&stream, Z_SYNC_FLUSH); if (err == Z_STREAM_END || err == Z_OK || err == Z_BUF_ERROR) { out.SetDataSize((NPT_Size)stream.total_out); if ((err == Z_OK && stream.avail_out == 0) || err == Z_BUF_ERROR) { // grow the output buffer out.Reserve(out.GetBufferSize()*2); stream.next_out = out.UseData()+stream.total_out; stream.avail_out = out.GetBufferSize()-(NPT_Size)stream.total_out; } } } while (err == Z_OK); // check for errors if (err != Z_STREAM_END) { inflateEnd(&stream); return MapError(err); } // cleanup err = inflateEnd(&stream); return MapError(err); }
/*---------------------------------------------------------------------- | NPT_DirectoryRemove +---------------------------------------------------------------------*/ NPT_Result NPT_DirectoryRemove(const char* path, bool recursively) { NPT_Result res; NPT_DirectoryEntryInfo info; NPT_String root_path = path; // replace delimiters with the proper one for the platform root_path.Replace((NPT_DIR_DELIMITER_CHR == '/')?'\\':'/', NPT_DIR_DELIMITER_CHR); // remove excessive delimiters root_path.TrimRight(NPT_DIR_DELIMITER_CHR); NPT_CHECK_WARNING(NPT_DirectoryEntry::GetInfo(root_path, &info)); if (info.type == NPT_FILE_TYPE || !recursively) { return NPT_Directory::Remove(root_path); } { // enumerate all entries NPT_Directory dir(path); NPT_String entry_path; NPT_String name; do { res = dir.GetNextEntry(name, &info); if (NPT_SUCCEEDED(res)) { // build full path to entry entry_path = root_path; // append filename NPT_DirectoryAppendToPath(entry_path, name); // try to remove entry recursively res = NPT_DirectoryRemove(entry_path, true); } } while (NPT_SUCCEEDED(res)); } // if no more items in directory, try to delete it if (res == NPT_ERROR_NO_SUCH_ITEM) { return NPT_Directory::Remove(path); } return res; }
/*---------------------------------------------------------------------- | PLT_MediaController::GetProtocolInfoSink +---------------------------------------------------------------------*/ NPT_Result PLT_MediaController::GetProtocolInfoSink(PLT_DeviceDataReference& device, NPT_List<NPT_String>& sinks) { PLT_DeviceDataReference renderer; NPT_CHECK_WARNING(FindRenderer(device->GetUUID(), renderer)); // look for ConnectionManager service PLT_Service* serviceCMR; NPT_CHECK_SEVERE(device->FindServiceByType( "urn:schemas-upnp-org:service:ConnectionManager:*", serviceCMR)); NPT_String value; NPT_CHECK_SEVERE(serviceCMR->GetStateVariableValue( "SinkProtocolInfo", value)); sinks = value.Split(","); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | NPT_File::CreateDir +---------------------------------------------------------------------*/ NPT_Result NPT_File::CreateDir(const char* path, bool create_intermediate_dirs) { NPT_String full_path = path; // normalize path separators full_path.Replace((NPT_FilePath::Separator[0] == '/')?'\\':'/', NPT_FilePath::Separator); // remove superfluous delimiters at the end full_path.TrimRight(NPT_FilePath::Separator); // create intermediate directories if needed if (create_intermediate_dirs) { NPT_String dir_path; // look for the next path separator int separator = full_path.Find(NPT_FilePath::Separator, 1); while (separator > 0) { // copy the path up to the separator dir_path = full_path.SubString(0, separator); // create the directory non recursively NPT_CHECK_WARNING(NPT_File::CreateDir(dir_path, false)); // look for the next delimiter separator = full_path.Find(NPT_FilePath::Separator, separator + 1); } } // create the final directory NPT_Result result = NPT_File::CreateDir(full_path); // return error only if file didn't exist if (NPT_FAILED(result) && result != NPT_ERROR_FILE_ALREADY_EXISTS) { return result; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_HttpServerSocketTask::Read +---------------------------------------------------------------------*/ NPT_Result PLT_HttpServerSocketTask::Read(NPT_BufferedInputStreamReference& buffered_input_stream, NPT_HttpRequest*& request, NPT_HttpRequestContext* context) { NPT_SocketInfo info; GetInfo(info); // update context with socket info if needed if (context) { context->SetLocalAddress(info.local_address); context->SetRemoteAddress(info.remote_address); } // put back in buffered mode to be able to parse HTTP request properly buffered_input_stream->SetBufferSize(NPT_BUFFERED_BYTE_STREAM_DEFAULT_SIZE); // parse request NPT_Result res = NPT_HttpRequest::Parse(*buffered_input_stream, &info.local_address, request); if (NPT_FAILED(res) || !request) { // only log if not timeout res = NPT_FAILED(res)?res:NPT_FAILURE; if (res != NPT_ERROR_TIMEOUT && res != NPT_ERROR_EOS) NPT_CHECK_WARNING(res); return res; } // update context with socket info again // to refresh the remote address in case it was a non connected udp socket GetInfo(info); if (context) { context->SetLocalAddress(info.local_address); context->SetRemoteAddress(info.remote_address); } // return right away if no body is expected if (request->GetMethod() == NPT_HTTP_METHOD_GET || request->GetMethod() == NPT_HTTP_METHOD_HEAD) { return NPT_SUCCESS; } // create an entity NPT_HttpEntity* request_entity = new NPT_HttpEntity(request->GetHeaders()); request->SetEntity(request_entity); NPT_MemoryStream* body_stream = new NPT_MemoryStream(); request_entity->SetInputStream((NPT_InputStreamReference)body_stream); // unbuffer the stream to read body fast buffered_input_stream->SetBufferSize(0); // check for chunked Transfer-Encoding if (request_entity->GetTransferEncoding() == "chunked") { NPT_CHECK_SEVERE(NPT_StreamToStreamCopy( *NPT_InputStreamReference(new NPT_HttpChunkedInputStream(buffered_input_stream)).AsPointer(), *body_stream)); request_entity->SetTransferEncoding(NULL); } else if (request_entity->GetContentLength()) { // a request with a body must always have a content length if not chunked NPT_CHECK_SEVERE(NPT_StreamToStreamCopy( *buffered_input_stream.AsPointer(), *body_stream, 0, request_entity->GetContentLength())); } else { request->SetEntity(NULL); } // rebuffer the stream buffered_input_stream->SetBufferSize(NPT_BUFFERED_BYTE_STREAM_DEFAULT_SIZE); return NPT_SUCCESS; }
static NPT_Result TestCheckWarning(void) { NPT_CHECK_WARNING(NPT_FAILURE); NPT_LOG_SEVERE("###"); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_MediaConnect::OnIsValidated +---------------------------------------------------------------------*/ NPT_Result PLT_MediaConnect::OnIsValidated(PLT_ActionReference& action) { NPT_CHECK_WARNING(action->SetArgumentValue("Result", "1")); return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | PLT_HttpServerSocketTask::SendResponseHeaders +---------------------------------------------------------------------*/ NPT_Result PLT_HttpServerSocketTask::SendResponseHeaders(NPT_HttpResponse* response, NPT_OutputStream& output_stream, bool& keep_alive) { // add any headers that may be missing NPT_HttpHeaders& headers = response->GetHeaders(); // get the request entity to set additional headers NPT_InputStreamReference body_stream; NPT_HttpEntity* entity = response->GetEntity(); if (entity && NPT_SUCCEEDED(entity->GetInputStream(body_stream))) { // set the content length if known if (entity->ContentLengthIsKnown()) { headers.SetHeader(NPT_HTTP_HEADER_CONTENT_LENGTH, NPT_String::FromIntegerU(entity->GetContentLength())); } // content type NPT_String content_type = entity->GetContentType(); if (!content_type.IsEmpty()) { headers.SetHeader(NPT_HTTP_HEADER_CONTENT_TYPE, content_type); } // content encoding NPT_String content_encoding = entity->GetContentEncoding(); if (!content_encoding.IsEmpty()) { headers.SetHeader(NPT_HTTP_HEADER_CONTENT_ENCODING, content_encoding); } // transfer encoding const NPT_String& transfer_encoding = entity->GetTransferEncoding(); if (!transfer_encoding.IsEmpty()) { headers.SetHeader(NPT_HTTP_HEADER_TRANSFER_ENCODING, transfer_encoding); } } else if (!headers.GetHeader(NPT_HTTP_HEADER_CONTENT_LENGTH)) { // force content length to 0 if there is no message body // (necessary for 1.1 or 1.0 with keep-alive connections) headers.SetHeader(NPT_HTTP_HEADER_CONTENT_LENGTH, "0"); } const NPT_String* content_length = headers.GetHeaderValue(NPT_HTTP_HEADER_CONTENT_LENGTH); const NPT_String* transfer_encoding = headers.GetHeaderValue(NPT_HTTP_HEADER_TRANSFER_ENCODING); const NPT_String* connection_header = headers.GetHeaderValue(NPT_HTTP_HEADER_CONNECTION); if (keep_alive) { if (connection_header && connection_header->Compare("close") == 0) { keep_alive = false; } else { // the request says client supports keep-alive // but override if response has content-length header or // transfer chunked encoding keep_alive = content_length || (transfer_encoding && transfer_encoding->Compare(NPT_HTTP_TRANSFER_ENCODING_CHUNKED) == 0); } } // only write keep-alive header for 1.1 if it's close NPT_String protocol = response->GetProtocol(); if (protocol.Compare(NPT_HTTP_PROTOCOL_1_0, true) == 0 || !keep_alive) { headers.SetHeader(NPT_HTTP_HEADER_CONNECTION, keep_alive?"keep-alive":"close", true); } headers.SetHeader(NPT_HTTP_HEADER_SERVER, PLT_HTTP_DEFAULT_SERVER, false); // set but don't replace PLT_LOG_HTTP_RESPONSE(NPT_LOG_LEVEL_FINE, "PLT_HttpServerSocketTask::Write", response); // create a memory stream to buffer the headers NPT_MemoryStream header_stream; response->Emit(header_stream); // send the headers NPT_CHECK_WARNING(output_stream.WriteFully(header_stream.GetData(), header_stream.GetDataSize())); return NPT_SUCCESS; }