/*----------------------------------------------------------------------
|   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);
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
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);
	}
}
Ejemplo n.º 4
0
void JNICore::dmrOpen(const NPT_String& url, const NPT_String& mimeType, const NPT_String& metaData)
{
	VMGuard vmguard;
	if (JNIEnv *env = vmguard.env()) {
		jstring urlStr = env->NewStringUTF(url.GetChars());
		jstring mimeTypeStr = env->NewStringUTF(mimeType.GetChars());
		jstring metaDataStr = env->NewStringUTF(metaData.GetChars());
		env->CallVoidMethod(m_delegateObj, CG::f_DLNACore_hookDmrOpen, urlStr, mimeTypeStr, metaDataStr);
		env->DeleteLocalRef(urlStr);
		env->DeleteLocalRef(mimeTypeStr);
		env->DeleteLocalRef(metaDataStr);
	}
}
Ejemplo n.º 5
0
/*----------------------------------------------------------------------
|   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;
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
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);
    }
Ejemplo n.º 8
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;
}
Ejemplo n.º 9
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;
}
Ejemplo n.º 10
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;
}
Ejemplo n.º 11
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));
}
Ejemplo n.º 12
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());
    }
}
Ejemplo n.º 13
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)); 
}
Ejemplo n.º 14
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);
}
Ejemplo n.º 15
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;
}
 NPT_Result SendResponseBody(const NPT_HttpRequestContext& /*context*/,
                             NPT_HttpResponse&             /*response*/,
                             NPT_OutputStream&             output) {
     NPT_HttpChunkedOutputStream chunker(output);
     chunker.WriteString("<html><body>\r\n");
     for (unsigned int i=0; i<30; i++) {
         NPT_String line = "Line ";
         line += NPT_String::FromInteger(i).GetChars();
         chunker.WriteString(line.GetChars());
         chunker.Flush();
         NPT_System::Sleep(NPT_TimeInterval(0.2f));
     }
     chunker.WriteString("</body></html>\r\n");
     return NPT_SUCCESS;
 }
Ejemplo n.º 17
0
Archivo: UPnP.cpp Proyecto: MrMC/mrmc
    // PLT_MediaContainerChangesListener methods
    virtual void OnContainerChanged(PLT_DeviceDataReference& device,
                                    const char*              item_id,
                                    const char*              update_id)
    {
        NPT_String path = "upnp://"+device->GetUUID()+"/";
        if (!NPT_StringsEqual(item_id, "0")) {
            std::string id(CURL::Encode(item_id));
            URIUtils::AddSlashAtEnd(id);
            path += id.c_str();
        }

        CLog::Log(LOGDEBUG, "UPNP: notfified container update %s", (const char*)path);
        CGUIMessage message(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_PATH);
        message.SetStringParam(path.GetChars());
        g_windowManager.SendThreadMessage(message);
    }
Ejemplo n.º 18
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();
}
Ejemplo n.º 19
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;
}
Ejemplo n.º 20
0
/*----------------------------------------------------------------------
|    BtPlayerServer::SendStatus
+---------------------------------------------------------------------*/
NPT_Result
BtPlayerServer::SendStatus(NPT_HttpResponse& response, NPT_UrlQuery& query)
{
    NPT_String json;
    
    // json start
    const char* json_callback = query.GetField("callback");
    if (json_callback) {
        json += NPT_UrlQuery::UrlDecode(json_callback)+'(';
    }
    json += '{';
    
    // state
    json += "\"state\": ";
    switch (m_DecoderState) {
      case BLT_DecoderServer::STATE_STOPPED:
        json += "\"STOPPED\"";
        break;

      case BLT_DecoderServer::STATE_PLAYING:
        json += "\"PLAYING\"";
        break;

      case BLT_DecoderServer::STATE_PAUSED:
        json += "\"PAUSED\"";
        break;

      case BLT_DecoderServer::STATE_EOS:
        json += "\"END OF STREAM\"";
        break;

      default:
        json += "\"UNKNOWN\"";
        break;
    }
    json += ',';
    
    // timecode
    json += NPT_String::Format("\"timecode\": \"%02d:%02d:%02d\", ",
                               m_DecoderTimecode.h,
                               m_DecoderTimecode.m,
                               m_DecoderTimecode.s);
    
    // position
    json += NPT_String::Format("\"position\": %f, ", m_DecoderPosition);

    // stream info
    json += "\"streamInfo\": {";
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_NOMINAL_BITRATE) {
        json += NPT_String::Format("\"nominalBitrate\": %d, ", m_StreamInfo.nominal_bitrate);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_AVERAGE_BITRATE) {
        json += NPT_String::Format("\"averageBitrate\": %d, ", m_StreamInfo.average_bitrate);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_INSTANT_BITRATE) {
        json += NPT_String::Format("\"instantBitrate\": %d, ", m_StreamInfo.instant_bitrate);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_SIZE) {
        json += NPT_String::Format("\"size\": %d, ", m_StreamInfo.size);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_DURATION) {
        unsigned int seconds = m_StreamInfo.duration/1000;
        json += NPT_String::Format("\"duration\": \"%02d:%02d:%02d\", ", 
                                   (seconds)/36000,
                                   (seconds%3600)/60,
                                   (seconds%60));
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_SAMPLE_RATE) {
        json += NPT_String::Format("\"sampleRate\": %d, ", m_StreamInfo.sample_rate);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_CHANNEL_COUNT) {
        json += NPT_String::Format("\"channelCount\": %d, ", m_StreamInfo.channel_count);
    }
    if (m_StreamInfo.mask & BLT_STREAM_INFO_MASK_DATA_TYPE) {
        json += NPT_String::Format("\"dataType\": \"%s\", ", m_StreamInfo.data_type);
    }
    json += "},";
    
    // stream properties
    
    // json end
    json += '}';
    if (json_callback) {
        json += ')';
    }
    
    // send the html document
    NPT_HttpEntity* entity = response.GetEntity();
    entity->SetContentType("application/json");
    entity->SetInputStream(json);        
    
    NPT_LOG_FINE_1("status: %s", json.GetChars());
    
    return NPT_SUCCESS;
}
Ejemplo n.º 21
0
/*----------------------------------------------------------------------
|   NPT_Log::FormatRecordToStream
+---------------------------------------------------------------------*/
void
NPT_Log::FormatRecordToStream(const NPT_LogRecord& record,
                              NPT_OutputStream&    stream,
                              bool                 use_colors,
                              NPT_Flags            format_filter)
{
    const char* level_name = GetLogLevelName(record.m_Level);
    NPT_String  level_string;

    /* format and emit the record */
    if (level_name[0] == '\0') {
        level_string = NPT_String::FromInteger(record.m_Level);
        level_name = level_string;
    }
    if ((format_filter & NPT_LOG_FORMAT_FILTER_NO_SOURCE) == 0) {
        unsigned int start = 0;
        /* remove source file path if requested */
        if (format_filter & NPT_LOG_FORMAT_FILTER_NO_SOURCEPATH) {
            for (start = NPT_StringLength(record.m_SourceFile);
                 start;
                 --start) {
                if (record.m_SourceFile[start-1] == '\\' ||
                    record.m_SourceFile[start-1] == '/') {
                    break;
                }
            }
        }
        stream.WriteString(record.m_SourceFile + start);
        stream.Write("(", 1, NULL);
        stream.WriteString(NPT_String::FromIntegerU(record.m_SourceLine));
        stream.Write("): ", 3, NULL);
    }
    if ((format_filter & NPT_LOG_FORMAT_FILTER_NO_LOGGER_NAME) == 0) {
        stream.Write("[", 1, NULL);
        stream.WriteString(record.m_LoggerName);
        stream.Write("] ", 2, NULL);
    }
    if ((format_filter & NPT_LOG_FORMAT_FILTER_NO_TIMESTAMP) == 0) {
        NPT_String ts = NPT_DateTime(record.m_TimeStamp, true).ToString(NPT_DateTime::FORMAT_W3C, 
                                                                        NPT_DateTime::FLAG_EMIT_FRACTION | 
                                                                        NPT_DateTime::FLAG_EXTENDED_PRECISION);
        stream.WriteString(ts.GetChars());
        stream.Write(" ", 1);
    }
    if ((format_filter & NPT_LOG_FORMAT_FILTER_NO_FUNCTION_NAME) == 0) {
        stream.WriteFully("[",1);
        if (record.m_SourceFunction) {
            stream.WriteString(record.m_SourceFunction);
        }
        stream.WriteFully("] ",2);
    }
    if ((format_filter & NPT_LOG_FORMAT_FILTER_NO_THREAD_ID) == 0) {
        stream.Write("(", 1, NULL);
        stream.WriteString(NPT_String::FromIntegerU(record.m_ThreadId));
        stream.Write(") ", 2, NULL);
    }
    const char* ansi_color = NULL;
    if (use_colors) {
        ansi_color = GetLogLevelAnsiColor(record.m_Level);
        if (ansi_color) {
            stream.Write("\033[", 2, NULL);
            stream.WriteString(ansi_color);
            stream.Write(";1m", 3, NULL);
        }
    }
    stream.WriteString(level_name);
    if (use_colors && ansi_color) {
        stream.Write("\033[0m", 4, NULL);
    }
    stream.Write(": ", 2, NULL);
    stream.WriteString(record.m_Message);
    stream.Write("\r\n", 2, NULL);
}
Ejemplo n.º 22
0
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int /*argc*/, char** /*argv*/)
{
    NPT_Result result;


    NPT_String t = "hello";
    NPT_String base64;
    NPT_DataBuffer data;
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8=");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    NPT_String tt((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);

    t = "hello!";
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8h");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    tt.Assign((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);

    t = "hello!!";
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8hIQ==");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    tt.Assign((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);
    
    unsigned char r256_bin[] = {
        0x7d, 0x5f, 0xd0, 0xf4, 0x6a, 0xa8, 0xae, 0x34, 0x6e, 0x32, 0x1d, 0xa1,
        0xef, 0x66, 0xdd, 0x82, 0x76, 0xa6, 0xfd, 0x8c, 0x75, 0x97, 0xa0, 0x01,
        0x00, 0xde, 0x52, 0xef, 0xdf, 0xb6, 0x3e, 0xe4, 0x7b, 0x45, 0xdd, 0x2b,
        0xa1, 0x9c, 0xb0, 0x6d, 0x2c, 0x75, 0xb1, 0x87, 0x43, 0x0f, 0xea, 0x24,
        0x36, 0x11, 0x7e, 0xee, 0xd1, 0x91, 0x7f, 0x7b, 0x02, 0xea, 0x9a, 0x2a,
        0x25, 0xc0, 0xac, 0x99, 0xa4, 0x89, 0x55, 0x5b, 0x82, 0xdf, 0xb0, 0x7e,
        0xa1, 0x78, 0x0f, 0xdf, 0x25, 0x5f, 0x3d, 0xba, 0xcb, 0xbc, 0x35, 0x04,
        0xc3, 0xf4, 0xb8, 0xc0, 0x17, 0x8e, 0x75, 0x01, 0xe6, 0x2f, 0x88, 0x2c,
        0x76, 0x0a, 0x8c, 0x3f, 0x83, 0xd4, 0x10, 0xa8, 0x00, 0xfc, 0xa0, 0x92,
        0x7b, 0xae, 0xa3, 0x8c, 0x47, 0xea, 0x25, 0xf9, 0x29, 0x81, 0x1c, 0x21,
        0xf2, 0xf4, 0xfe, 0x07, 0x7e, 0x4b, 0x01, 0x79, 0x41, 0x3a, 0xb6, 0x71,
        0x0b, 0x75, 0xa7, 0x9d, 0x1b, 0x12, 0xc4, 0x46, 0x06, 0xf3, 0x5f, 0x00,
        0x05, 0x2a, 0x1b, 0x34, 0xd6, 0x87, 0xc4, 0x70, 0xcc, 0xc3, 0x9e, 0xa8,
        0x24, 0x2c, 0x97, 0x4e, 0xfc, 0x91, 0x70, 0x1c, 0x29, 0x66, 0xc3, 0x23,
        0xbf, 0xd7, 0x4d, 0x35, 0x51, 0xff, 0xeb, 0xde, 0x45, 0xbd, 0x8d, 0x80,
        0x44, 0x2a, 0x8d, 0xc0, 0xe8, 0x6a, 0xe2, 0x86, 0x46, 0x9f, 0xf2, 0x3c,
        0x93, 0x0d, 0x27, 0x02, 0xe4, 0x79, 0xa1, 0x21, 0xf4, 0x43, 0xcd, 0x4c,
        0x22, 0x25, 0x9e, 0x93, 0xeb, 0x77, 0x8e, 0x1e, 0x57, 0x1e, 0x9b, 0xcb,
        0x91, 0x86, 0xcf, 0x15, 0xaf, 0xd5, 0x03, 0x0f, 0x70, 0xbe, 0x6e, 0x37,
        0xea, 0x37, 0xdd, 0xf6, 0xa1, 0xb1, 0xf7, 0x05, 0xbc, 0x2d, 0x44, 0x60,
        0x35, 0xa4, 0x05, 0x0b, 0x22, 0x7d, 0x7a, 0x71, 0xe5, 0x1d, 0x8e, 0xcb,
        0xc3, 0xb8, 0x3a, 0xe1
    };
    NPT_String b64;
    NPT_Base64::Encode(r256_bin, sizeof(r256_bin), b64);
    NPT_DataBuffer r256_out;
    NPT_Base64::Decode(b64.GetChars(), b64.GetLength(), r256_out);
    NPT_ASSERT(r256_out.GetDataSize() == sizeof(r256_bin));
    NPT_ASSERT(r256_bin[sizeof(r256_bin)-1] == r256_out.GetData()[sizeof(r256_bin)-1]);

    unsigned char random_bytes[] = {
        0xc7, 0xee, 0x49, 0x9e, 0x2c, 0x8b, 0x1c, 0x16, 0x9e, 0x7f, 0x30, 0xd0,
        0xc6, 0x12, 0x30, 0x80, 0x81, 0xcd, 0x20, 0x20, 0x26, 0xaf, 0x4f, 0xd6,
        0xfc, 0x86, 0x2e, 0x85, 0xf3, 0x10, 0x38, 0x2b, 0x0e, 0xbb, 0x80, 0x68,
        0xbe, 0xff, 0x1c, 0xdc, 0x72, 0xb5, 0x0d, 0x8f, 0x8e, 0x6c, 0x09, 0x63,
        0xba, 0x21, 0x23, 0xb2, 0x24, 0x17, 0xd3, 0x17, 0x69, 0x44, 0x77, 0x11,
        0x36, 0x6a, 0x6e, 0xf2, 0x44, 0x87, 0xa1, 0xd3, 0xf3, 0x1f, 0x6c, 0x38,
        0x22, 0x4a, 0x44, 0x70, 0x66, 0xef, 0x8c, 0x3a, 0x51, 0xc8, 0xee, 0x85,
        0x00, 0x25, 0x93, 0x10, 0x2e, 0x0b, 0x1b, 0x03, 0x94, 0x47, 0x05, 0x22,
        0xd0, 0xc4, 0xec, 0x2e, 0xcc, 0xbc, 0xbb, 0x67, 0xfd, 0xec, 0x0e, 0xb1,
        0x3f, 0xbc, 0x82, 0xe0, 0xa7, 0x9c, 0xf3, 0xae, 0xbd, 0xb7, 0xab, 0x02,
        0xf1, 0xd9, 0x17, 0x4c, 0x9d, 0xeb, 0xe2, 0x00, 0x1e, 0x19, 0x6e, 0xb3,
        0xfd, 0x7d, 0xea, 0x49, 0x85, 0x43, 0x2f, 0x56, 0x81, 0x89, 0xba, 0x71,
        0x37, 0x10, 0xb5, 0x74, 0xab, 0x90, 0x4d, 0xc4, 0xd1, 0x0d, 0x8d, 0x6f,
        0x01, 0xf5, 0x2c, 0xc9, 0x1a, 0x79, 0xa1, 0x41, 0x71, 0x2b, 0xfb, 0xf3,
        0xd5, 0xe4, 0x2a, 0xf5, 0xad, 0x80, 0x7a, 0x03, 0xff, 0x5f, 0x45, 0x8c,
        0xec, 0x6a, 0x4b, 0x05, 0xe3, 0x65, 0x19, 0x70, 0x05, 0xad, 0xc4, 0xb8,
        0x4e, 0x9e, 0x9a, 0x36, 0x4a, 0x86, 0x9d, 0xf5, 0x99, 0xcb, 0x00, 0xb8,
        0xb9, 0xa7, 0x86, 0x18, 0xfc, 0x9a, 0xe7, 0x00, 0x6a, 0x67, 0xfa, 0x42,
        0x9d, 0xff, 0x4d, 0x7a, 0xe4, 0xe8, 0x03, 0x88, 0xff, 0x60, 0xe1, 0x8d,
        0x09, 0x5f, 0x6f, 0xde, 0x6b
    };
    NPT_Array<unsigned char> random(random_bytes, NPT_ARRAY_SIZE(random_bytes));

    t = "x+5JniyLHBaefzDQxhIwgIHNICAmr0/W/IYuhfMQOCsOu4Bovv8c3HK1DY+ObAlj\r\n"
        "uiEjsiQX0xdpRHcRNmpu8kSHodPzH2w4IkpEcGbvjDpRyO6FACWTEC4LGwOURwUi\r\n"
        "0MTsLsy8u2f97A6xP7yC4Kec8669t6sC8dkXTJ3r4gAeGW6z/X3qSYVDL1aBibpx\r\n"
        "NxC1dKuQTcTRDY1vAfUsyRp5oUFxK/vz1eQq9a2AegP/X0WM7GpLBeNlGXAFrcS4\r\n"
        "Tp6aNkqGnfWZywC4uaeGGPya5wBqZ/pCnf9NeuToA4j/YOGNCV9v3ms=";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == 233);
    NPT_Array<unsigned char> verif(data.GetData(), data.GetDataSize());
    NPT_ASSERT(verif == random);

    result = NPT_Base64::Encode(&random[0], random.GetItemCount(), base64, NPT_BASE64_PEM_BLOCKS_PER_LINE);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == t);

    NPT_String t_url = t;
    t.Replace('/', '_');
    t.Replace('+', '-');
    result = NPT_Base64::Encode(&random[0], random.GetItemCount(), base64, NPT_BASE64_PEM_BLOCKS_PER_LINE, true);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == t);
    
    t = "76768484767685839";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "76869=978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "7686=8978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "7686==978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    // test IP address parsing
    NPT_IpAddress ip;
    NPT_ASSERT(NPT_FAILED(ip.Parse("")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("a.b.c.d")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4.5")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4.")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4f")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.g.3.4")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2..3.4")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.300.4")));
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("1.2.3.4")));
    NPT_ASSERT(ip.AsBytes()[0] == 1);
    NPT_ASSERT(ip.AsBytes()[1] == 2);
    NPT_ASSERT(ip.AsBytes()[2] == 3);
    NPT_ASSERT(ip.AsBytes()[3] == 4);
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("255.255.0.1")));
    NPT_ASSERT(ip.AsBytes()[0] == 255);
    NPT_ASSERT(ip.AsBytes()[1] == 255);
    NPT_ASSERT(ip.AsBytes()[2] == 0);
    NPT_ASSERT(ip.AsBytes()[3] == 1);
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("0.0.0.0")));
    NPT_ASSERT(ip.AsBytes()[0] == 0);
    NPT_ASSERT(ip.AsBytes()[1] == 0);
    NPT_ASSERT(ip.AsBytes()[2] == 0);
    NPT_ASSERT(ip.AsBytes()[3] == 0);

    // MIME parameter parser
    NPT_Map<NPT_String,NPT_String> params;
    result = NPT_ParseMimeParameters(NULL, params);
    NPT_ASSERT(result == NPT_ERROR_INVALID_PARAMETERS);
    
    result = NPT_ParseMimeParameters("", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 0);
        
    result = NPT_ParseMimeParameters("foo=bar", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar");
    params.Clear();

    result = NPT_ParseMimeParameters(" foo =bar", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar");
    params.Clear();

    result = NPT_ParseMimeParameters(" foo= bar", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar");
    params.Clear();
    
    result = NPT_ParseMimeParameters(" foo= bar;", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar");
    params.Clear();

    result = NPT_ParseMimeParameters("foo=\"bar\"", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar");
    params.Clear();

    result = NPT_ParseMimeParameters("foo=\"ba\"r\"", params);
    NPT_ASSERT(result == NPT_ERROR_INVALID_SYNTAX);
    params.Clear();

    result = NPT_ParseMimeParameters("foo=\"ba\\\"r\"", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "ba\"r");
    params.Clear();

    result = NPT_ParseMimeParameters("foo=\"bar\\\"\"", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar\"");
    params.Clear();

    result = NPT_ParseMimeParameters("foo=\"bar\\\\\"", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 1);
    NPT_ASSERT(params["foo"] == "bar\\");
    params.Clear();

    result = NPT_ParseMimeParameters("a=1;b=2; c=3; d=4 ; e=\"\\;\"; f=\";\"", params);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(params.GetEntryCount() == 6);
    NPT_ASSERT(params["a"] == "1");
    NPT_ASSERT(params["b"] == "2");
    NPT_ASSERT(params["c"] == "3");
    NPT_ASSERT(params["d"] == "4");
    NPT_ASSERT(params["e"] == ";");
    NPT_ASSERT(params["f"] == ";");
    params.Clear();

    // number parsing
    float      f;
    int        i;
    NPT_Int32  i32;
    NPT_UInt32 ui32;
    NPT_Int64  i64;
    NPT_UInt64 ui64;

    SHOULD_FAIL(NPT_ParseInteger("ssdfsdf", i, false));
    SHOULD_FAIL(NPT_ParseInteger("", i, false));
    SHOULD_FAIL(NPT_ParseInteger(NULL, i, false));
    SHOULD_FAIL(NPT_ParseInteger("123a", i, false));
    SHOULD_FAIL(NPT_ParseInteger("a123", i, false));
    SHOULD_FAIL(NPT_ParseInteger(" 123", i, false));
    SHOULD_FAIL(NPT_ParseInteger("a 123", i, true));
    SHOULD_FAIL(NPT_ParseInteger(" a123", i, true));

    SHOULD_SUCCEED(NPT_ParseInteger("+1", i, false));
    SHOULD_EQUAL_I(i, 1);
    SHOULD_SUCCEED(NPT_ParseInteger("+123", i, false));
    SHOULD_EQUAL_I(i, 123);
    SHOULD_SUCCEED(NPT_ParseInteger("-1", i, false));
    SHOULD_EQUAL_I(i, -1);
    SHOULD_SUCCEED(NPT_ParseInteger("-123", i, false));
    SHOULD_EQUAL_I(i, -123);
    SHOULD_SUCCEED(NPT_ParseInteger("-123fgs", i, true));
    SHOULD_EQUAL_I(i, -123);
    SHOULD_SUCCEED(NPT_ParseInteger("  -123fgs", i, true));
    SHOULD_EQUAL_I(i, -123);
    SHOULD_SUCCEED(NPT_ParseInteger("0", i, true));
    SHOULD_EQUAL_I(i, 0);
    SHOULD_SUCCEED(NPT_ParseInteger("7768", i, true));
    SHOULD_EQUAL_I(i, 7768);

    SHOULD_SUCCEED(NPT_ParseInteger32("2147483647", i32, false));
    SHOULD_EQUAL_I(i32, 2147483647);
    SHOULD_SUCCEED(NPT_ParseInteger32("-2147483647", i32, false));
    SHOULD_EQUAL_I(i32, -2147483647);
    SHOULD_SUCCEED(NPT_ParseInteger32("-2147483648", i32, false));
    SHOULD_EQUAL_I(i32, (-2147483647 - 1));
    SHOULD_FAIL(NPT_ParseInteger32("2147483648", i32, false));
    SHOULD_FAIL(NPT_ParseInteger32("-2147483649", i32, false));
    SHOULD_FAIL(NPT_ParseInteger32("-21474836480", i32, false));
    SHOULD_FAIL(NPT_ParseInteger32("21474836470", i32, false));

    SHOULD_SUCCEED(NPT_ParseInteger32U("4294967295", ui32, false));
    SHOULD_EQUAL_I(ui32, 4294967295U);
    SHOULD_FAIL(NPT_ParseInteger32U("4294967296", ui32, false));
    SHOULD_FAIL(NPT_ParseInteger32U("-1", ui32, false));

    SHOULD_SUCCEED(NPT_ParseInteger64("9223372036854775807", i64, false));
    SHOULD_EQUAL_I(i64, NPT_INT64_C(9223372036854775807));
    SHOULD_SUCCEED(NPT_ParseInteger64("-9223372036854775807", i64, false));
    SHOULD_EQUAL_I(i64, NPT_INT64_C(-9223372036854775807));
    SHOULD_SUCCEED(NPT_ParseInteger64("-9223372036854775808", i64, false));
    SHOULD_EQUAL_I(i64, (NPT_INT64_C(-9223372036854775807) - NPT_INT64_C(1)));
    SHOULD_FAIL(NPT_ParseInteger64("9223372036854775808", i64, false));
    SHOULD_FAIL(NPT_ParseInteger64("-9223372036854775809", i64, false));
    SHOULD_FAIL(NPT_ParseInteger64("-9223372036854775897", i64, false));
    SHOULD_FAIL(NPT_ParseInteger64("9223372036854775897", i64, false));

    SHOULD_SUCCEED(NPT_ParseInteger64U("18446744073709551615", ui64, false));
    SHOULD_EQUAL_I(ui64, NPT_UINT64_C(18446744073709551615));
    SHOULD_FAIL(NPT_ParseInteger64U("18446744073709551616", ui64, false));
    SHOULD_FAIL(NPT_ParseInteger64U("-1", ui64, false));

    SHOULD_FAIL(NPT_ParseFloat("ssdfsdf", f, false));
    SHOULD_FAIL(NPT_ParseFloat("", f, false));
    SHOULD_FAIL(NPT_ParseFloat(NULL, f, false));
    SHOULD_FAIL(NPT_ParseFloat("123.", f, false));
    SHOULD_FAIL(NPT_ParseFloat("a123", f, false));
    SHOULD_FAIL(NPT_ParseFloat(" 123", f, false));
    SHOULD_FAIL(NPT_ParseFloat(" 127.89E5ff", f, false));

    SHOULD_SUCCEED(NPT_ParseFloat("+1.0", f, false));
    SHOULD_EQUAL_F(f, 1.0f);
    SHOULD_SUCCEED(NPT_ParseFloat("+123", f, false));
    SHOULD_EQUAL_F(f, 123.0f);
    SHOULD_SUCCEED(NPT_ParseFloat("-0.1", f, false));
    SHOULD_EQUAL_F(f, -0.1f);
    SHOULD_SUCCEED(NPT_ParseFloat("0.23e-13", f, false));
    SHOULD_EQUAL_F(f, 0.23e-13f);
    SHOULD_SUCCEED(NPT_ParseFloat(" 127.89E5ff", f, true));
    SHOULD_EQUAL_F(f, 127.89E5f);
    SHOULD_SUCCEED(NPT_ParseFloat("+0.3db", f, true));
    SHOULD_EQUAL_F(f, 0.3f);
    SHOULD_SUCCEED(NPT_ParseFloat("+.3db", f, true));
    SHOULD_EQUAL_F(f, 0.3f);
    SHOULD_SUCCEED(NPT_ParseFloat("-.3db", f, true));
    SHOULD_EQUAL_F(f, -0.3f);
    SHOULD_SUCCEED(NPT_ParseFloat(".3db", f, true));
    SHOULD_EQUAL_F(f, .3f);

    return 0;
}
Ejemplo n.º 23
0
/*----------------------------------------------------------------------
|   NPT_File::Save
+---------------------------------------------------------------------*/
NPT_Result
NPT_File::Save(const char* filename, NPT_String& data)
{
    NPT_DataBuffer buffer(data.GetChars(), data.GetLength());
    return NPT_File::Save(filename, buffer);
}
Ejemplo n.º 24
0
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
    // check command line
    if (argc < 2) {
        PrintUsageAndExit();
    }

    // init endpoints
    EndPoint in_endpoint;
    in_endpoint.direction = ENDPOINT_DIRECTION_IN;
    EndPoint out_endpoint;
    out_endpoint.direction = ENDPOINT_DIRECTION_OUT;
    EndPoint* current_endpoint = &in_endpoint;

    // init other parameters
    unsigned int packet_size = PUMP_DEFAULT_PACKET_SIZE;

    // init options
    Options.verbose       = false;
    Options.show_progress = false;

    // parse command line
    argv++;
    char* arg;
    while ((arg = *argv++)) {
        if (current_endpoint == NULL) {
            NPT_Debug("ERROR: unexpected argument (%s)\n", arg);
            exit(1);    
        }
                 
        if (!strcmp(arg, "--packet-size")) {
            packet_size = strtoul(*argv++, NULL, 10);
            continue;
        } else if (!strcmp(arg, "--verbose")) {
            Options.verbose = true;
            continue;
        } else if (!strcmp(arg, "--show-progress")) {
            Options.show_progress = true;
            continue;
        } else if (!strcmp(arg, "udp")) {
            if (argv[0] && argv[1]) {
                if (!strcmp(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        NPT_Debug("ERROR: cannot use 'udp server' as output\n");
                        exit(1);
                    }
                    current_endpoint->type = ENDPOINT_TYPE_UDP_SERVER;
                    current_endpoint->info.udp_server.port = 
                        strtoul(argv[1], NULL, 10);
                    argv += 2;
                } else if (!strcmp(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        NPT_Debug("ERROR: cannot use 'udp client' as input\n");
                        exit(1);
                    }
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_UDP_CLIENT;
                        current_endpoint->info.udp_client.hostname = argv[1];
                        current_endpoint->info.udp_client.port = 
                            strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        NPT_Debug("ERROR: missing argument for 'udp client'\n");
                        exit(1);
                    }
                }
            } else {
                NPT_Debug("ERROR: missing argument for 'udp' endpoint\n");
                exit(1);
            }
         } else if (!strcmp(arg, "multicast")) {
            if (argv[0] && argv[1]) {
                if (!strcmp(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        NPT_Debug("ERROR: cannot use 'multicast server' as output\n");
                        exit(1);
                    }
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_MULTICAST_SERVER;
                        current_endpoint->info.multicast_server.groupname = argv[1];
                        current_endpoint->info.multicast_server.port = 
                            strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        NPT_Debug("ERROR: missing argument for 'multicast server'\n");
                        exit(1);
                    }
                } else if (!strcmp(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        NPT_Debug("ERROR: cannot use 'udp client' as input\n");
                        exit(1);
                    }
                    if (argv[2] && argv[3]) {
                        current_endpoint->type = ENDPOINT_TYPE_MULTICAST_CLIENT;
                        current_endpoint->info.multicast_client.groupname = argv[1];
                        current_endpoint->info.multicast_client.port = 
                            strtoul(argv[2], NULL, 10);
                        current_endpoint->info.multicast_client.ttl = 
                            strtoul(argv[3], NULL, 10);
                        argv += 4;                        
                    } else {
                        NPT_Debug("ERROR: missing argument for 'multicast client'\n");
                        exit(1);
                    }
                }
            } else {
                NPT_Debug("ERROR: missing argument for 'multicast' endpoint\n");
                exit(1);
            }
        } else if (!strcmp(arg, "tcp")) {
            if (argv[0] && argv[1]) {
                if (!strcmp(argv[0], "server")) {
                    current_endpoint->type = ENDPOINT_TYPE_TCP_SERVER;
                    current_endpoint->info.tcp_server.port = 
                        strtoul(argv[1], NULL, 10);
                    argv += 2;
                } else if (!strcmp(argv[0], "client")) {
                    if (argv[2]) {
                        current_endpoint->type = ENDPOINT_TYPE_TCP_CLIENT;
                        current_endpoint->info.tcp_client.hostname = argv[1];
                        current_endpoint->info.tcp_client.port = 
                            strtoul(argv[2], NULL, 10);
                        argv += 3;                        
                    } else {
                        NPT_Debug("ERROR: missing argument for 'tcp client'\n");
                        exit(1);
                    }
                }
            } else {
                NPT_Debug("ERROR: missing argument for 'tcp' endpoint\n");
                exit(1);
            }
        } else if (!strcmp(arg, "file")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_FILE;
                current_endpoint->info.file.name = *argv++;
            } else {
                NPT_Debug("ERROR: missing argument for 'file' endpoint\n");
                exit(1);
            }
        } else if (!strcmp(arg, "serial")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_SERIAL_PORT;
                current_endpoint->info.serial_port.name = *argv++;
            } else {
                NPT_Debug("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
            if (argv[0]) {
                long speed = 0;
                if (NPT_FAILED(NPT_ParseInteger(*argv++, speed))) {
                    NPT_Debug("ERROR: invalid speed for 'serial' endpoint\n");
                    exit(1);
                } 
                current_endpoint->info.serial_port.speed = (unsigned int)speed;
            } else {
                NPT_Debug("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
        } else {
            NPT_Debug("ERROR: invalid argument (%s)\n", arg);
            exit(1);
        }

        if (current_endpoint == &in_endpoint) {
            current_endpoint = &out_endpoint;
        } else {
            current_endpoint = NULL;
        }
    }

    if (current_endpoint) {
        NPT_Debug("ERROR: missing endpoint specification\n");
        exit(1);
    }

    // data pump
    NPT_Result result;

    // allocate buffer
    unsigned char* buffer;
    buffer = (unsigned char*)malloc(packet_size);
    if (buffer == NULL) {
        NPT_Debug("ERROR: out of memory\n");
        exit(1);
    }

    // get output stream
    NPT_OutputStreamReference out;
    result = GetEndPointStreams(&out_endpoint, NULL, &out);
    if (NPT_FAILED(result)) {
        NPT_Debug("ERROR: failed to get stream for output (%d)", result);
        exit(1);
    }

    unsigned long offset = 0;
    unsigned long total  = 0;
    if (in_endpoint.type == ENDPOINT_TYPE_UDP_SERVER ||
        in_endpoint.type == ENDPOINT_TYPE_MULTICAST_SERVER) {
        NPT_UdpSocket* udp_socket;
        result = GetEndPointUdpSocket(&in_endpoint, udp_socket);

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

        do {
            result = udp_socket->Receive(packet, &address);
            if (NPT_SUCCEEDED(result)) {
                if (Options.verbose) {
                    NPT_String ip = address.GetIpAddress().ToString();
                    NPT_Debug("Received %d bytes from %s\n", packet.GetDataSize(), ip.GetChars());
                }
                result = out->Write(packet.GetData(), packet.GetDataSize(), NULL);
                offset += packet.GetDataSize();
                total  += packet.GetDataSize();
            }
        } while (NPT_SUCCEEDED(result));
    } else {
        // get the input stream
        NPT_InputStreamReference in;
        result = GetEndPointStreams(&in_endpoint, &in, NULL);
        if (NPT_FAILED(result)) {
            NPT_Debug("ERROR: failed to get stream for input (%d)\n", result);
            exit(1);
        }

        // stream loop 
        do {
            NPT_Size bytes_read;
            NPT_Size bytes_written;

            // send 
            result = in->Read(buffer, packet_size, &bytes_read);
            if (Options.show_progress) {
                NPT_Debug("[%d]\r", total);
            }
            if (NPT_SUCCEEDED(result) && bytes_read) {
                result = out->Write(buffer, bytes_read, &bytes_written);
                if (Options.show_progress) {
                    NPT_Debug("[%d]\r", total);
                }
                offset += bytes_written;
                total  += bytes_written;
            } else {
                printf("[%d] *******************\n", result);
                exit(1);
            }
        } while (NPT_SUCCEEDED(result));
    }

    delete buffer;
    return 0;
}
Ejemplo n.º 25
0
/*----------------------------------------------------------------------
|       main
+---------------------------------------------------------------------*/
int
main(int /*argc*/, char** /*argv*/)
{
    NPT_Result result;


    NPT_String t = "hello";
    NPT_String base64;
    NPT_DataBuffer data;
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8=");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    NPT_String tt((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);

    t = "hello!";
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8h");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    tt.Assign((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);

    t = "hello!!";
    result = NPT_Base64::Encode((const NPT_Byte*)t.GetChars(), t.GetLength(), base64);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == "aGVsbG8hIQ==");
    result = NPT_Base64::Decode(base64.GetChars(), base64.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == t.GetLength());
    tt.Assign((const char*)data.GetData(), data.GetDataSize());
    NPT_ASSERT(tt == t);
    
    unsigned char r256_bin[] = {
        0x7d, 0x5f, 0xd0, 0xf4, 0x6a, 0xa8, 0xae, 0x34, 0x6e, 0x32, 0x1d, 0xa1,
        0xef, 0x66, 0xdd, 0x82, 0x76, 0xa6, 0xfd, 0x8c, 0x75, 0x97, 0xa0, 0x01,
        0x00, 0xde, 0x52, 0xef, 0xdf, 0xb6, 0x3e, 0xe4, 0x7b, 0x45, 0xdd, 0x2b,
        0xa1, 0x9c, 0xb0, 0x6d, 0x2c, 0x75, 0xb1, 0x87, 0x43, 0x0f, 0xea, 0x24,
        0x36, 0x11, 0x7e, 0xee, 0xd1, 0x91, 0x7f, 0x7b, 0x02, 0xea, 0x9a, 0x2a,
        0x25, 0xc0, 0xac, 0x99, 0xa4, 0x89, 0x55, 0x5b, 0x82, 0xdf, 0xb0, 0x7e,
        0xa1, 0x78, 0x0f, 0xdf, 0x25, 0x5f, 0x3d, 0xba, 0xcb, 0xbc, 0x35, 0x04,
        0xc3, 0xf4, 0xb8, 0xc0, 0x17, 0x8e, 0x75, 0x01, 0xe6, 0x2f, 0x88, 0x2c,
        0x76, 0x0a, 0x8c, 0x3f, 0x83, 0xd4, 0x10, 0xa8, 0x00, 0xfc, 0xa0, 0x92,
        0x7b, 0xae, 0xa3, 0x8c, 0x47, 0xea, 0x25, 0xf9, 0x29, 0x81, 0x1c, 0x21,
        0xf2, 0xf4, 0xfe, 0x07, 0x7e, 0x4b, 0x01, 0x79, 0x41, 0x3a, 0xb6, 0x71,
        0x0b, 0x75, 0xa7, 0x9d, 0x1b, 0x12, 0xc4, 0x46, 0x06, 0xf3, 0x5f, 0x00,
        0x05, 0x2a, 0x1b, 0x34, 0xd6, 0x87, 0xc4, 0x70, 0xcc, 0xc3, 0x9e, 0xa8,
        0x24, 0x2c, 0x97, 0x4e, 0xfc, 0x91, 0x70, 0x1c, 0x29, 0x66, 0xc3, 0x23,
        0xbf, 0xd7, 0x4d, 0x35, 0x51, 0xff, 0xeb, 0xde, 0x45, 0xbd, 0x8d, 0x80,
        0x44, 0x2a, 0x8d, 0xc0, 0xe8, 0x6a, 0xe2, 0x86, 0x46, 0x9f, 0xf2, 0x3c,
        0x93, 0x0d, 0x27, 0x02, 0xe4, 0x79, 0xa1, 0x21, 0xf4, 0x43, 0xcd, 0x4c,
        0x22, 0x25, 0x9e, 0x93, 0xeb, 0x77, 0x8e, 0x1e, 0x57, 0x1e, 0x9b, 0xcb,
        0x91, 0x86, 0xcf, 0x15, 0xaf, 0xd5, 0x03, 0x0f, 0x70, 0xbe, 0x6e, 0x37,
        0xea, 0x37, 0xdd, 0xf6, 0xa1, 0xb1, 0xf7, 0x05, 0xbc, 0x2d, 0x44, 0x60,
        0x35, 0xa4, 0x05, 0x0b, 0x22, 0x7d, 0x7a, 0x71, 0xe5, 0x1d, 0x8e, 0xcb,
        0xc3, 0xb8, 0x3a, 0xe1
    };
    NPT_String b64;
    NPT_Base64::Encode(r256_bin, sizeof(r256_bin), b64);
    NPT_DataBuffer r256_out;
    NPT_Base64::Decode(b64.GetChars(), b64.GetLength(), r256_out);
    NPT_ASSERT(r256_out.GetDataSize() == sizeof(r256_bin));
    NPT_ASSERT(r256_bin[sizeof(r256_bin)-1] == r256_out.GetData()[sizeof(r256_bin)-1]);

    unsigned char random_bytes[] = {
        0xc7, 0xee, 0x49, 0x9e, 0x2c, 0x8b, 0x1c, 0x16, 0x9e, 0x7f, 0x30, 0xd0,
        0xc6, 0x12, 0x30, 0x80, 0x81, 0xcd, 0x20, 0x20, 0x26, 0xaf, 0x4f, 0xd6,
        0xfc, 0x86, 0x2e, 0x85, 0xf3, 0x10, 0x38, 0x2b, 0x0e, 0xbb, 0x80, 0x68,
        0xbe, 0xff, 0x1c, 0xdc, 0x72, 0xb5, 0x0d, 0x8f, 0x8e, 0x6c, 0x09, 0x63,
        0xba, 0x21, 0x23, 0xb2, 0x24, 0x17, 0xd3, 0x17, 0x69, 0x44, 0x77, 0x11,
        0x36, 0x6a, 0x6e, 0xf2, 0x44, 0x87, 0xa1, 0xd3, 0xf3, 0x1f, 0x6c, 0x38,
        0x22, 0x4a, 0x44, 0x70, 0x66, 0xef, 0x8c, 0x3a, 0x51, 0xc8, 0xee, 0x85,
        0x00, 0x25, 0x93, 0x10, 0x2e, 0x0b, 0x1b, 0x03, 0x94, 0x47, 0x05, 0x22,
        0xd0, 0xc4, 0xec, 0x2e, 0xcc, 0xbc, 0xbb, 0x67, 0xfd, 0xec, 0x0e, 0xb1,
        0x3f, 0xbc, 0x82, 0xe0, 0xa7, 0x9c, 0xf3, 0xae, 0xbd, 0xb7, 0xab, 0x02,
        0xf1, 0xd9, 0x17, 0x4c, 0x9d, 0xeb, 0xe2, 0x00, 0x1e, 0x19, 0x6e, 0xb3,
        0xfd, 0x7d, 0xea, 0x49, 0x85, 0x43, 0x2f, 0x56, 0x81, 0x89, 0xba, 0x71,
        0x37, 0x10, 0xb5, 0x74, 0xab, 0x90, 0x4d, 0xc4, 0xd1, 0x0d, 0x8d, 0x6f,
        0x01, 0xf5, 0x2c, 0xc9, 0x1a, 0x79, 0xa1, 0x41, 0x71, 0x2b, 0xfb, 0xf3,
        0xd5, 0xe4, 0x2a, 0xf5, 0xad, 0x80, 0x7a, 0x03, 0xff, 0x5f, 0x45, 0x8c,
        0xec, 0x6a, 0x4b, 0x05, 0xe3, 0x65, 0x19, 0x70, 0x05, 0xad, 0xc4, 0xb8,
        0x4e, 0x9e, 0x9a, 0x36, 0x4a, 0x86, 0x9d, 0xf5, 0x99, 0xcb, 0x00, 0xb8,
        0xb9, 0xa7, 0x86, 0x18, 0xfc, 0x9a, 0xe7, 0x00, 0x6a, 0x67, 0xfa, 0x42,
        0x9d, 0xff, 0x4d, 0x7a, 0xe4, 0xe8, 0x03, 0x88, 0xff, 0x60, 0xe1, 0x8d,
        0x09, 0x5f, 0x6f, 0xde, 0x6b
    };
    NPT_Array<unsigned char> random(random_bytes, NPT_ARRAY_SIZE(random_bytes));

    t = "x+5JniyLHBaefzDQxhIwgIHNICAmr0/W/IYuhfMQOCsOu4Bovv8c3HK1DY+ObAlj\r\n"
        "uiEjsiQX0xdpRHcRNmpu8kSHodPzH2w4IkpEcGbvjDpRyO6FACWTEC4LGwOURwUi\r\n"
        "0MTsLsy8u2f97A6xP7yC4Kec8669t6sC8dkXTJ3r4gAeGW6z/X3qSYVDL1aBibpx\r\n"
        "NxC1dKuQTcTRDY1vAfUsyRp5oUFxK/vz1eQq9a2AegP/X0WM7GpLBeNlGXAFrcS4\r\n"
        "Tp6aNkqGnfWZywC4uaeGGPya5wBqZ/pCnf9NeuToA4j/YOGNCV9v3ms=";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(data.GetDataSize() == 233);
    NPT_Array<unsigned char> verif(data.GetData(), data.GetDataSize());
    NPT_ASSERT(verif == random);

    result = NPT_Base64::Encode(&random[0], random.GetItemCount(), base64, NPT_BASE64_PEM_BLOCKS_PER_LINE);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == t);

    NPT_String t_url = t;
    t.Replace('/', '_');
    t.Replace('+', '-');
    result = NPT_Base64::Encode(&random[0], random.GetItemCount(), base64, NPT_BASE64_PEM_BLOCKS_PER_LINE, true);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(base64 == t);
    
    t = "76768484767685839";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "76869=978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "7686=8978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    t = "7686==978686";
    result = NPT_Base64::Decode(t.GetChars(), t.GetLength(), data);
    NPT_ASSERT(result == NPT_ERROR_INVALID_FORMAT);

    // test IP address parsing
    NPT_IpAddress ip;
    NPT_ASSERT(NPT_FAILED(ip.Parse("")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("a.b.c.d")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4.5")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4.")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.3.4f")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.g.3.4")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2..3.4")));
    NPT_ASSERT(NPT_FAILED(ip.Parse("1.2.300.4")));
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("1.2.3.4")));
    NPT_ASSERT(ip.AsBytes()[0] == 1);
    NPT_ASSERT(ip.AsBytes()[1] == 2);
    NPT_ASSERT(ip.AsBytes()[2] == 3);
    NPT_ASSERT(ip.AsBytes()[3] == 4);
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("255.255.0.1")));
    NPT_ASSERT(ip.AsBytes()[0] == 255);
    NPT_ASSERT(ip.AsBytes()[1] == 255);
    NPT_ASSERT(ip.AsBytes()[2] == 0);
    NPT_ASSERT(ip.AsBytes()[3] == 1);
    NPT_ASSERT(NPT_SUCCEEDED(ip.Parse("0.0.0.0")));
    NPT_ASSERT(ip.AsBytes()[0] == 0);
    NPT_ASSERT(ip.AsBytes()[1] == 0);
    NPT_ASSERT(ip.AsBytes()[2] == 0);
    NPT_ASSERT(ip.AsBytes()[3] == 0);

    return 0;
}
Ejemplo n.º 26
0
/*----------------------------------------------------------------------
|   main
+---------------------------------------------------------------------*/
int
main(int argc, char** argv)
{
    NPT_COMPILER_UNUSED(argc);

    NPT_HttpRequestHandler *handler, *custom_handler;
    NPT_Reference<NPT_DataBuffer> buffer;
    NPT_Size size;
    bool result;
    PLT_RingBufferStreamReference ringbuffer_stream(new PLT_RingBufferStream());

    /* parse command line */
    ParseCommandLine(argv);

    /* create http server */
    PLT_HttpServer http_server(Options.port?Options.port:80);
    NPT_String url = "http://127.0.0.1:" + NPT_String::FromInteger(http_server.GetPort());
    NPT_String custom_url = url;

    if (!Options.path.IsEmpty()) {
        /* extract folder path */
        int index1 = Options.path.ReverseFind('\\');
        int index2 = Options.path.ReverseFind('/');
        if (index1 <= 0 && index2 <=0) {
            fprintf(stderr, "ERROR: invalid path\n");
            exit(1);
        }

        NPT_DirectoryEntryInfo info;
        NPT_CHECK_SEVERE(NPT_DirectoryEntry::GetInfo(Options.path, &info));

        /* add file request handler */
        handler = new NPT_HttpFileRequestHandler(
            Options.path.Left(index1>index2?index1:index2), 
            "/");
        http_server.AddRequestHandler(handler, "/", true);

        /* build url*/
        url += "/" + Options.path.SubString((index1>index2?index1:index2)+1);
    } else {
        /* create random data */
        buffer = new NPT_DataBuffer(32768);
        buffer->SetDataSize(32768);

        /* add static handler */
        handler = new NPT_HttpStaticRequestHandler(buffer->GetData(),
            buffer->GetDataSize(),
            "text/xml");
        http_server.AddRequestHandler(handler, "/test");

        /* build url*/
        url += "/test";
    }

    /* add custom handler */
    NPT_InputStreamReference stream(ringbuffer_stream);
    custom_handler = new PLT_HttpCustomRequestHandler(stream,
        "text/xml");
    http_server.AddRequestHandler(custom_handler, "/custom");
    custom_url += "/custom";

    /* start server */
    NPT_CHECK_SEVERE(http_server.Start());

    /* a task manager for the tests downloader */
    PLT_TaskManager task_manager;

    /* small delay to let the server start */
    NPT_System::Sleep(NPT_TimeInterval(1, 0));
    
    /* execute tests */
    result = Test1(&task_manager, url.GetChars(), size);
    if (!result) return -1;

    result = Test2(&task_manager, url.GetChars(), size);
    if (!result) return -1;

    result = Test3(&task_manager, custom_url.GetChars(), ringbuffer_stream, size);
    if (!result) return -1;

    NPT_System::Sleep(NPT_TimeInterval(1, 0));

    http_server.Stop();
    delete handler;
    delete custom_handler;
    return 0;
}
Ejemplo n.º 27
0
//////////////////////////////////////////////////////////////////////////
// Callback
 void DLNAProxy::onDiscoveryListChaned(const NPT_String& ip, const NPT_String& devName, const int type)
 {
	 emit dlnaChange(ip.GetChars(),devName.GetChars(),type);
 }
Ejemplo n.º 28
0
void SimpleDMR::setFriendlyName(const NPT_String& friendlyName)
{
	m_friendlyName = NPT_String::Format("Genie Media Player (%s)", friendlyName.GetChars());
}
Ejemplo n.º 29
0
void SimpleDMR::setPlatformName(const NPT_String& platformName)
{
	m_modelDescription = NPT_String::Format("%s Genie DMR", platformName.GetChars());
}
Ejemplo n.º 30
0
/*----------------------------------------------------------------------
|   PLT_FileMediaServer::OnBrowseDirectChildren
+---------------------------------------------------------------------*/
NPT_Result
PLT_FileMediaServer::OnBrowseDirectChildren(PLT_ActionReference&          action, 
                                            const char*                   object_id, 
                                            const NPT_HttpRequestContext& context)
{
    /* locate the file from the object ID */
    NPT_String dir;
    if (NPT_FAILED(GetFilePath(object_id, dir))) {
        /* error */
        NPT_LOG_WARNING("PLT_FileMediaServer::OnBrowse - ObjectID not found.");
        action->SetError(701, "No Such Object.");
        return NPT_FAILURE;
    }

    /* retrieve the item type */
    NPT_FileInfo info;
    NPT_Result res = NPT_File::GetInfo(dir, &info);
    if (NPT_FAILED(res)) {
        /* Object does not exist */
        NPT_LOG_WARNING_1("PLT_FileMediaServer::OnBrowse - BROWSEDIRECTCHILDREN failed for item %s", dir.GetChars());
        action->SetError(800, "Can't retrieve info " + dir);
        return NPT_FAILURE;
    }

    if (info.m_Type != NPT_FileInfo::FILE_TYPE_DIRECTORY) {
        /* error */
        NPT_LOG_WARNING("PLT_FileMediaServer::OnBrowse - BROWSEDIRECTCHILDREN not allowed on an item.");
        action->SetError(710, "item is not a container.");
        return NPT_FAILURE;
    }

    NPT_String filter;
    NPT_String startingInd;
    NPT_String reqCount;

    NPT_CHECK_SEVERE(action->GetArgumentValue("Filter", filter));
    NPT_CHECK_SEVERE(action->GetArgumentValue("StartingIndex", startingInd));
    NPT_CHECK_SEVERE(action->GetArgumentValue("RequestedCount", reqCount));   

    NPT_UInt32 start_index, req_count;
    if (NPT_FAILED(startingInd.ToInteger(start_index)) ||
        NPT_FAILED(reqCount.ToInteger(req_count))) {        
        action->SetError(412, "Precondition failed");
        return NPT_FAILURE;
    }

    NPT_List<NPT_String> entries;
    res = NPT_File::ListDirectory(dir, entries, 0, 0);
    if (NPT_FAILED(res)) {
        NPT_LOG_WARNING_1("PLT_FileMediaServer::OnBrowseDirectChildren - failed to open dir %s", (const char*) dir);
        return res;
    }

    unsigned long cur_index = 0;
    unsigned long num_returned = 0;
    unsigned long total_matches = 0;
    NPT_String didl = didl_header;

    PLT_MediaObjectReference item;
    for (NPT_List<NPT_String>::Iterator it = entries.GetFirstItem();
        it;
        ++it) {
        NPT_String& filename = *it;
        item = BuildFromFilePath(
            NPT_FilePath::Create(dir, filename), 
            true, 
            &context.GetLocalAddress());

        if (!item.IsNull()) {
            if ((cur_index >= start_index) && ((num_returned < req_count) || (req_count == 0))) {
                NPT_String tmp;
                NPT_CHECK_SEVERE(PLT_Didl::ToDidl(*item.AsPointer(), filter, tmp));

                didl += tmp;
                num_returned++;
            }
            cur_index++;
            total_matches++;        
        }
    };

    didl += didl_footer;

    NPT_CHECK_SEVERE(action->SetArgumentValue("Result", didl));
    NPT_CHECK_SEVERE(action->SetArgumentValue("NumberReturned", NPT_String::FromInteger(num_returned)));
    NPT_CHECK_SEVERE(action->SetArgumentValue("TotalMatches", NPT_String::FromInteger(total_matches))); // 0 means we don't know how many we have but most browsers don't like that!!
    NPT_CHECK_SEVERE(action->SetArgumentValue("UpdateId", "1"));

    return NPT_SUCCESS;
}