/*---------------------------------------------------------------------- | ParseCommandLine +---------------------------------------------------------------------*/ static void ParseCommandLine(char** args) { const char* arg; char** tmp = args+1; /* default values */ Options.port = 0; Options.path = ""; while ((arg = *tmp++)) { if (Options.port == 0 && !strcmp(arg, "-p")) { long port; if (NPT_FAILED(NPT_ParseInteger(*tmp++, port, false))) { fprintf(stderr, "ERROR: invalid port\n"); exit(1); } Options.port = port; } else if (Options.path.IsEmpty() && !strcmp(arg, "-f")) { Options.path = *tmp++; } else { fprintf(stderr, "ERROR: too many arguments\n"); PrintUsageAndExit(args); } } }
/*---------------------------------------------------------------------- | NPT_Url::SetHost +---------------------------------------------------------------------*/ NPT_Result NPT_Url::SetHost(const char* host) { const char* port = host; while (*port && *port != ':') port++; if (*port) { m_Host.Assign(host, (NPT_Size)(port-host)); unsigned int port_number; if (NPT_SUCCEEDED(NPT_ParseInteger(port+1, port_number, false))) { m_Port = (short)port_number; } } else { m_Host = host; } return NPT_SUCCESS; }
/*---------------------------------------------------------------------- | 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; }
int SimpleDMR::onAction(const ServiceDecl *serviceDecl, const ActionDecl *actionDecl, AbortableTask *task, const FrontEnd::InterfaceContext *ifctx, const FrontEnd::RequestContext& reqCtx, const NPT_HttpRequest *req, const NPT_List<NPT_String>& inputArgNames, const NPT_List<NPT_String>& inputArgValues, NPT_List<NPT_String>& outputArgValues) { WriteLocker locker(m_stateLock); if (NPT_String::Compare(serviceDecl->serviceId, "urn:upnp-org:serviceId:AVTransport") == 0) { if (NPT_String::Compare(actionDecl->name, "SetAVTransportURI") == 0) { if (inputArgValues.GetItemCount() != 3) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } NPT_HttpClient httpClient; NPT_HttpRequest req(*inputArgValues.GetItem(1), NPT_HTTP_METHOD_GET, NPT_HTTP_PROTOCOL_1_1); Helper::setupHttpRequest(req); NPT_HttpResponse *resp; NPT_Result nr; HttpClientAbortCallback abortCallback(&httpClient); if (task->registerAbortCallback(&abortCallback)) { nr = httpClient.SendRequest(req, resp); task->unregisterAbortCallback(&abortCallback); } else { return 715; } if (NPT_FAILED(nr)) { return 716; } PtrHolder<NPT_HttpResponse> resp1(resp); if (resp->GetStatusCode() != 200) { return 716; } NPT_HttpHeader *hdrContentType = resp->GetHeaders().GetHeader(NPT_HTTP_HEADER_CONTENT_TYPE); if (!hdrContentType) { return 714; } setVar(DMRVAR_AVTransportURI, *inputArgValues.GetItem(1)); setVar(DMRVAR_AVTransportURIMetaData, *inputArgValues.GetItem(2)); setVar(DMRVAR_CurrentTrackMetaData, *inputArgValues.GetItem(2)); m_callback->doDmrOpen(this, *inputArgValues.GetItem(1), hdrContentType->GetValue(), *inputArgValues.GetItem(2)); return 0; } if (NPT_String::Compare(actionDecl->name, "GetMediaInfo") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } *outputArgValues.GetItem(0) = m_avtVars[DMRVAR_NumberOfTracks - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(1) = m_avtVars[DMRVAR_CurrentMediaDuration - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(2) = m_avtVars[DMRVAR_AVTransportURI - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(3) = m_avtVars[DMRVAR_AVTransportURIMetaData - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(4) = m_avtVars[DMRVAR_NextAVTransportURI - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(5) = m_avtVars[DMRVAR_NextAVTransportURIMetaData - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(6) = m_avtVars[DMRVAR_PlaybackStorageMedium - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(7) = m_avtVars[DMRVAR_RecordStorageMedium - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(8) = m_avtVars[DMRVAR_RecordMediumWriteStatus - DMRVAR_BaseIndexAVT]; return 0; } if (NPT_String::Compare(actionDecl->name, "GetTransportInfo") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } *outputArgValues.GetItem(0) = m_avtVars[DMRVAR_TransportState - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(1) = m_avtVars[DMRVAR_TransportStatus - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(2) = m_avtVars[DMRVAR_TransportPlaySpeed - DMRVAR_BaseIndexAVT]; return 0; } if (NPT_String::Compare(actionDecl->name, "GetPositionInfo") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } *outputArgValues.GetItem(0) = m_avtVars[DMRVAR_CurrentTrack - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(1) = m_avtVars[DMRVAR_CurrentTrackDuration - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(2) = m_avtVars[DMRVAR_CurrentTrackMetaData - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(3) = m_avtVars[DMRVAR_CurrentTrackURI - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(4) = m_avtVars[DMRVAR_RelativeTimePosition - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(5) = m_avtVars[DMRVAR_AbsoluteTimePosition - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(6) = m_avtVars[DMRVAR_RelativeCounterPosition - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(7) = m_avtVars[DMRVAR_AbsoluteCounterPosition - DMRVAR_BaseIndexAVT]; return 0; } if (NPT_String::Compare(actionDecl->name, "GetDeviceCapabilities") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } *outputArgValues.GetItem(0) = m_avtVars[DMRVAR_PossiblePlaybackStorageMedia - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(1) = m_avtVars[DMRVAR_PossibleRecordStorageMedia - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(2) = m_avtVars[DMRVAR_PossibleRecordQualityModes - DMRVAR_BaseIndexAVT]; return 0; } if (NPT_String::Compare(actionDecl->name, "GetTransportSettings") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } *outputArgValues.GetItem(0) = m_avtVars[DMRVAR_CurrentPlayMode - DMRVAR_BaseIndexAVT]; *outputArgValues.GetItem(1) = m_avtVars[DMRVAR_CurrentRecordQualityMode - DMRVAR_BaseIndexAVT]; return 0; } if (NPT_String::Compare(actionDecl->name, "Stop") == 0) { m_callback->doDmrStop(this); return 0; } if (NPT_String::Compare(actionDecl->name, "Play") == 0) { m_callback->doDmrPlay(this); return 0; } if (NPT_String::Compare(actionDecl->name, "Pause") == 0) { m_callback->doDmrPause(this); return 0; } if (NPT_String::Compare(actionDecl->name, "Seek") == 0) { if (inputArgValues.GetItemCount() != 3) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 718; } const NPT_String& seekMode = *inputArgValues.GetItem(1); const NPT_String& seekTarget = *inputArgValues.GetItem(2); if (seekMode.Compare("TRACK_NR") == 0) { // TODO: } else if (seekMode.Compare("REL_TIME") == 0) { NPT_UInt64 pos; if (NPT_FAILED(Helper::parseTrackDurationString(seekTarget, pos))) { // Illegal seek target return 711; } m_callback->doDmrSeekTo(this, pos); } else { // Seek mode not supported return 710; } return 0; } if (NPT_String::Compare(actionDecl->name, "Next") == 0) { return 0; } if (NPT_String::Compare(actionDecl->name, "Previous") == 0) { return 0; } return 602; } if (NPT_String::Compare(serviceDecl->serviceId, "urn:upnp-org:serviceId:RenderingControl") == 0) { if (NPT_String::Compare(actionDecl->name, "ListPresets") == 0) { if (inputArgValues.GetItemCount() != 1) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 702; } *outputArgValues.GetItem(0) = m_rcsVars[DMRVAR_PresetNameList - DMRVAR_BaseIndexRCS]; return 0; } if (NPT_String::Compare(actionDecl->name, "SelectPreset") == 0) { return 0; } if (NPT_String::Compare(actionDecl->name, "GetMute") == 0) { if (inputArgValues.GetItemCount() != 2) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 702; } *outputArgValues.GetItem(0) = m_rcsVars[DMRVAR_Mute - DMRVAR_BaseIndexRCS]; return 0; } if (NPT_String::Compare(actionDecl->name, "SetMute") == 0) { if (inputArgValues.GetItemCount() != 3) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 702; } const NPT_String& desiredMute = *inputArgValues.GetItem(2); m_callback->doDmrSetMute(this, desiredMute.Compare("true", true) == 0 || desiredMute.Compare("1") == 0); return 0; } if (NPT_String::Compare(actionDecl->name, "GetVolume") == 0) { if (inputArgValues.GetItemCount() != 2) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 702; } *outputArgValues.GetItem(0) = m_rcsVars[DMRVAR_Volume - DMRVAR_BaseIndexRCS]; return 0; } if (NPT_String::Compare(actionDecl->name, "SetVolume") == 0) { if (inputArgValues.GetItemCount() != 3) { // Invalid Args return 402; } if (inputArgValues.GetFirstItem()->Compare("0") != 0) { // Invalid InstanceID return 702; } const NPT_String& desiredVolume = *inputArgValues.GetItem(2); int volume; if (NPT_FAILED(NPT_ParseInteger(desiredVolume, volume))) { // Invalid Args return 402; } m_callback->doDmrSetVolume(this, volume); return 0; } return 602; } if (NPT_String::Compare(serviceDecl->serviceId, "urn:upnp-org:serviceId:ConnectionManager") == 0) { if (NPT_String::Compare(actionDecl->name, "GetProtocolInfo") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SourceProtocolInfo", v)) { *outputArgValues.GetItem(0) = v; } if (getStateValue(serviceDecl->serviceId, "SinkProtocolInfo", v)) { *outputArgValues.GetItem(1) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetCurrentConnectionIDs") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SourceProtocolInfo", v)) { *outputArgValues.GetItem(0) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetCurrentConnectionInfo") == 0) { *outputArgValues.GetItem(0) = "0"; *outputArgValues.GetItem(1) = "0"; *outputArgValues.GetItem(2) = ""; *outputArgValues.GetItem(3) = ""; *outputArgValues.GetItem(4) = "-1"; *outputArgValues.GetItem(5) = "Input"; // or "Output"? WTF! *outputArgValues.GetItem(6) = "OK"; return 0; } return 602; } return 501; }
/*---------------------------------------------------------------------- | NPT_String::ToInteger +---------------------------------------------------------------------*/ NPT_Result NPT_String::ToInteger(unsigned long& value, bool relaxed) const { return NPT_ParseInteger(GetChars(), value, relaxed); }
/*---------------------------------------------------------------------- | 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; }
/*---------------------------------------------------------------------- | NPT_DateTime::FromString +--------------------------------------------------------------------*/ NPT_Result NPT_DateTime::FromString(const char* date, Format format) { if (date == NULL || date[0] == '\0') return NPT_ERROR_INVALID_PARAMETERS; // create a local copy to work with NPT_String workspace(date); char* input = workspace.UseChars(); NPT_Size input_size = workspace.GetLength(); switch (format) { case FORMAT_W3C: { if (input_size < 17 && input_size != 10) return NPT_ERROR_INVALID_SYNTAX; // check separators if (input[4] != '-' || input[7] != '-') { return NPT_ERROR_INVALID_SYNTAX; } // replace separators with terminators input[4] = input[7] = '\0'; bool no_seconds = true; if (input_size > 10) { if (input[10] != 'T' || input[13] != ':') { return NPT_ERROR_INVALID_SYNTAX; } input[10] = input[13] = '\0'; if (input[16] == ':') { input[16] = '\0'; no_seconds = false; if (input_size < 20) return NPT_ERROR_INVALID_SYNTAX; } else { m_Seconds = 0; } } // parse CCYY-MM-DD fields if (NPT_FAILED(NPT_ParseInteger(input, m_Year, false)) || NPT_FAILED(NPT_ParseInteger(input+5, m_Month, false)) || NPT_FAILED(NPT_ParseInteger(input+8, m_Day, false))) { return NPT_ERROR_INVALID_SYNTAX; } // parse remaining fields if any if (input_size > 10) { // parse the timezone part if (input[input_size-1] == 'Z') { m_TimeZone = 0; input[input_size-1] = '\0'; } else if (input[input_size-6] == '+' || input[input_size-6] == '-') { if (input[input_size-3] != ':') return NPT_ERROR_INVALID_SYNTAX; input[input_size-3] = '\0'; unsigned int hh, mm; if (NPT_FAILED(NPT_ParseInteger(input+input_size-5, hh, false)) || NPT_FAILED(NPT_ParseInteger(input+input_size-2, mm, false))) { return NPT_ERROR_INVALID_SYNTAX; } if (hh > 59 || mm > 59) return NPT_ERROR_INVALID_SYNTAX; m_TimeZone = hh*60+mm; if (input[input_size-6] == '-') m_TimeZone = -m_TimeZone; input[input_size-6] = '\0'; } // parse fields if (NPT_FAILED(NPT_ParseInteger(input+11, m_Hours, false)) || NPT_FAILED(NPT_ParseInteger(input+14, m_Minutes, false))) { return NPT_ERROR_INVALID_SYNTAX; } if (!no_seconds && input[19] == '.') { char fraction[10]; fraction[9] = '\0'; unsigned int fraction_size = NPT_StringLength(input+20); if (fraction_size == 0) return NPT_ERROR_INVALID_SYNTAX; for (unsigned int i=0; i<9; i++) { if (i < fraction_size) { fraction[i] = input[20+i]; } else { fraction[i] = '0'; } } if (NPT_FAILED(NPT_ParseInteger(fraction, m_NanoSeconds, false))) { return NPT_ERROR_INVALID_SYNTAX; } input[19] = '\0'; } else { m_NanoSeconds = 0; } if (!no_seconds) { if (NPT_FAILED(NPT_ParseInteger(input+17, m_Seconds, false))) { return NPT_ERROR_INVALID_SYNTAX; } } } break; } case FORMAT_RFC_1036: case FORMAT_RFC_1123: { if (input_size < 26) return NPT_ERROR_INVALID_SYNTAX; // look for the weekday and separtor const char* wday = input; while (*input && *input != ',') { ++input; --input_size; } if (*input == '\0' || *wday == ',') return NPT_ERROR_INVALID_SYNTAX; *input++ = '\0'; --input_size; // look for the timezone char* timezone = input+input_size-1; unsigned int timezone_size = 0; while (input_size && *timezone != ' ') { --timezone; ++timezone_size; --input_size; } if (input_size == 0) return NPT_ERROR_INVALID_SYNTAX; *timezone++ = '\0'; // check separators if (input_size < 20) return NPT_ERROR_INVALID_SYNTAX; unsigned int yl = input_size-18; if (yl != 2 && yl != 4) return NPT_ERROR_INVALID_SYNTAX; char sep; int wday_index; if (format == FORMAT_RFC_1036) { sep = '-'; wday_index = MatchString(wday, NPT_TIME_DAYS_LONG, 7); } else { sep = ' '; wday_index = MatchString(wday, NPT_TIME_DAYS_SHORT, 7); } if (input[0] != ' ' || input[3] != sep || input[7] != sep || input[8+yl] != ' ' || input[11+yl] != ':' || input[14+yl] != ':') { return NPT_ERROR_INVALID_SYNTAX; } input[3] = input[7] = input[8+yl] = input[11+yl] = input[14+yl] = '\0'; // parse fields m_Month = 1+MatchString(input+4, NPT_TIME_MONTHS, 12); if (NPT_FAILED(NPT_ParseInteger(input+1, m_Day, false)) || NPT_FAILED(NPT_ParseInteger(input+8, m_Year, false)) || NPT_FAILED(NPT_ParseInteger(input+9+yl, m_Hours, false)) || NPT_FAILED(NPT_ParseInteger(input+12+yl, m_Minutes, false)) || NPT_FAILED(NPT_ParseInteger(input+15+yl, m_Seconds, false))) { return NPT_ERROR_INVALID_SYNTAX; } // adjust short year lengths if (yl == 2) m_Year += 1900; // parse the timezone if (NPT_StringsEqual(timezone, "GMT") || NPT_StringsEqual(timezone, "UT") || NPT_StringsEqual(timezone, "Z")) { m_TimeZone = 0; } else if (NPT_StringsEqual(timezone, "EDT")) { m_TimeZone = -4*60; } else if (NPT_StringsEqual(timezone, "EST") || NPT_StringsEqual(timezone, "CDT")) { m_TimeZone = -5*60; } else if (NPT_StringsEqual(timezone, "CST") || NPT_StringsEqual(timezone, "MDT")) { m_TimeZone = -6*60; } else if (NPT_StringsEqual(timezone, "MST") || NPT_StringsEqual(timezone, "PDT")) { m_TimeZone = -7*60; } else if (NPT_StringsEqual(timezone, "PST")) { m_TimeZone = -8*60; } else if (timezone_size == 1) { if (timezone[0] >= 'A' && timezone[0] <= 'I') { m_TimeZone = -60*(1+timezone[0]-'A'); } else if (timezone[0] >= 'K' && timezone[0] <= 'M') { m_TimeZone = -60*(timezone[0]-'A'); } else if (timezone[0] >= 'N' && timezone[0] <= 'Y') { m_TimeZone = 60*(1+timezone[0]-'N'); } else { return NPT_ERROR_INVALID_SYNTAX; } } else if (timezone_size == 5) { int sign; if (timezone[0] == '-') { sign = -1; } else if (timezone[0] == '+') { sign = 1; } else { return NPT_ERROR_INVALID_SYNTAX; } NPT_UInt32 tz; if (NPT_FAILED(NPT_ParseInteger(timezone+1, tz, false))) { return NPT_ERROR_INVALID_SYNTAX; } unsigned int hh = (tz/100); unsigned int mm = (tz%100); if (hh > 59 || mm > 59) return NPT_ERROR_INVALID_SYNTAX; m_TimeZone = sign*(hh*60+mm); } else { return NPT_ERROR_INVALID_SYNTAX; } // compute the number of days elapsed since 1900 NPT_UInt32 days = ElapsedDaysSince1900(*this); if ((int)((days+1)%7) != wday_index) { return NPT_ERROR_INVALID_PARAMETERS; } m_NanoSeconds = 0; break; } case FORMAT_ANSI: { if (input_size != 24) return NPT_ERROR_INVALID_SYNTAX; // check separators if (input[3] != ' ' || input[7] != ' ' || input[10] != ' ' || input[13] != ':' || input[16] != ':' || input[19] != ' ') { return NPT_ERROR_INVALID_SYNTAX; } input[3] = input[7] = input[10] = input[13] = input[16] = input[19] = '\0'; if (input[8] == ' ') input[8] = '0'; m_Month = 1+MatchString(input+4, NPT_TIME_MONTHS, 12); if (NPT_FAILED(NPT_ParseInteger(input+8, m_Day, false)) || NPT_FAILED(NPT_ParseInteger(input+11, m_Hours, false)) || NPT_FAILED(NPT_ParseInteger(input+14, m_Minutes, false)) || NPT_FAILED(NPT_ParseInteger(input+17, m_Seconds, false)) || NPT_FAILED(NPT_ParseInteger(input+20, m_Year, false))) { return NPT_ERROR_INVALID_SYNTAX; } // compute the number of days elapsed since 1900 NPT_UInt32 days = ElapsedDaysSince1900(*this); if ((int)((days+1)%7) != MatchString(input, NPT_TIME_DAYS_SHORT, 7)) { return NPT_ERROR_INVALID_PARAMETERS; } m_TimeZone = 0; m_NanoSeconds = 0; break; } default: return NPT_ERROR_INVALID_PARAMETERS; } return CheckDate(*this); }
/*---------------------------------------------------------------------- | 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; }
/*---------------------------------------------------------------------- | BtPlayerServer::SetupResponse +---------------------------------------------------------------------*/ NPT_Result BtPlayerServer::SetupResponse(NPT_HttpRequest& request, const NPT_HttpRequestContext& /*context*/, NPT_HttpResponse& response) { const NPT_Url& url = request.GetUrl(); const NPT_String& path = url.GetPath(); NPT_UrlQuery query; // parse the query part, if any if (url.HasQuery()) { query.Parse(url.GetQuery()); } // lock the player NPT_AutoLock lock(m_Lock); // handle form requests if (path == "/") { response.GetHeaders().SetHeader("Location", "/control/ajax"); response.SetStatus(301, "Moved Permanently"); return BLT_SUCCESS; } // handle form requests if (path == "/control/form") { return SendControlForm(response, NULL); } // handle status requests if (path == "/player/status") { return SendStatus(response, query); } // handle commands const char* mode_field = query.GetField("mode"); const char* form_msg = "OK"; bool use_form = false; if (mode_field && NPT_StringsEqual(mode_field, "form")) { use_form = true; } if (path == "/player/set-input") { const char* name_field = query.GetField("name"); if (name_field) { NPT_String name = NPT_UrlQuery::UrlDecode(name_field); m_Player.SetInput(name); } else { form_msg = "INVALID PARAMETERS"; } } else if (path == "/player/set-output") { const char* name_field = query.GetField("name"); if (name_field) { NPT_String name = NPT_UrlQuery::UrlDecode(name_field); m_Player.SetOutput(name); } else { form_msg = "INVALID PARAMETERS"; } } else if (path == "/player/play") { m_Player.Play(); } else if (path == "/player/pause") { m_Player.Pause(); } else if (path == "/player/stop") { m_Player.Stop(); } else if (path == "/player/seek") { const char* timecode_field = query.GetField("timecode"); const char* position_field = query.GetField("position"); if (timecode_field) { NPT_String timecode = NPT_UrlQuery::UrlDecode(timecode_field); DoSeekToTimecode(timecode); } else if (position_field) { unsigned int position; if (NPT_SUCCEEDED(NPT_ParseInteger(position_field, position))) { m_Player.SeekToPosition(position, 100); } } else { form_msg = "INVALID PARAMETER"; } } else if (path == "/player/set-volume") { const char* volume_field = query.GetField("volume"); if (volume_field) { unsigned int volume; if (NPT_SUCCEEDED(NPT_ParseInteger(volume_field, volume))) { m_Player.SetVolume((float)volume/100.0f); } } else { form_msg = "INVALID PARAMETER"; } } if (use_form) { return SendControlForm(response, form_msg); } else { NPT_HttpEntity* entity = response.GetEntity(); entity->SetContentType("application/json"); entity->SetInputStream("{}"); return NPT_SUCCESS; } printf("BtPlayerServer::SetupResponse - command not found\n"); response.SetStatus(404, "Command Not Found"); return NPT_SUCCESS; }
void FrontEnd::processSsdpSearch(SsdpServerTask *task, Interface *intf, const NPT_DataBuffer& data, const NPT_SocketAddress& fromAddr) { do { NPT_HttpRequest *req; NPT_InputStreamReference inputStream0(new NPT_MemoryStream(data.GetData(), data.GetDataSize())); NPT_BufferedInputStream inputStream(inputStream0); if (NPT_FAILED(NPT_HttpRequest::Parse(inputStream, NULL, req))) { break; } PtrHolder<NPT_HttpRequest> req1(req); if (req->GetMethod().Compare("M-SEARCH") != 0 || req->GetProtocol().Compare(NPT_HTTP_PROTOCOL_1_1) != 0 || req->GetUrl().GetPath().Compare("*") != 0) { break; } NPT_HttpHeader *hdrMan = req->GetHeaders().GetHeader("MAN"); if (!hdrMan || hdrMan->GetValue().Compare("\"ssdp:discover\"") != 0) { break; } NPT_HttpHeader *hdrHost = req->GetHeaders().GetHeader("HOST"); if (!hdrHost || (hdrHost->GetValue().Compare("239.255.255.250:1900") != 0 && hdrHost->GetValue().Compare("239.255.255.250") != 0)) { break; } int mx; NPT_HttpHeader *hdrMX = req->GetHeaders().GetHeader("MX"); if (!hdrMX || NPT_FAILED(NPT_ParseInteger(hdrMX->GetValue(), mx)) || mx < 1) { break; } if (mx > 120) { mx = 120; } NPT_HttpHeader *hdrST = req->GetHeaders().GetHeader("ST"); if (!hdrST) { break; } NPT_List<MatchContext*> matchList; NPT_UdpSocket sock(NPT_SOCKET_FLAG_CANCELLABLE); sock.Bind(NPT_SocketAddress(intf->m_context.m_ifAddr, 0)); NPT_SharedVariable waitVar; waitVar.SetValue(0); { ReadLocker locker(m_dsLock); for (NPT_Ordinal i = 0; i < m_deviceImplList.GetItemCount(); i++) { NPT_List<DeviceImplInfo*>::Iterator it = m_deviceImplList.GetItem(i); DeviceImplInfo *info = *it; MatchContext *matchContext = new MatchContext(); if (info->m_deviceImpl->match(hdrST->GetValue(), matchContext->matches)) { matchList.Add(matchContext); matchContext->deviceUuid = info->m_deviceImpl->uuid(); matchContext->expireSeconds = info->m_deviceImpl->m_expireSeconds; matchContext->descPath = info->m_deviceImpl->m_descPath; matchContext->httpRoot = info->m_context.m_httpRoot; } else { delete matchContext; } } } SsdpSearchAbortCallback abortCallback(&sock, &waitVar); if (task->registerAbortCallback(&abortCallback)) { for (NPT_Ordinal i = 0; i < matchList.GetItemCount(); i++) { MatchContext *matchContext = *matchList.GetItem(i); NPT_String location = NPT_String::Format("http://%s:%d%s%s", intf->m_context.m_ifAddr.ToString().GetChars(), intf->m_context.m_httpPort, matchContext->httpRoot.GetChars(), matchContext->descPath.GetChars()); bool broken = false; for (NPT_Ordinal j = 0; j < matchContext->matches.GetItemCount(); j++) { NPT_List<DeviceImplMatch>::Iterator it2 = matchContext->matches.GetItem(j); NPT_Timeout timeout = NPT_System::GetRandomInteger() % (mx * 1000); // TODO: wait or not ??? timeout = 0; if (NPT_SUCCEEDED(waitVar.WaitWhileEquals(0, timeout))) { break; } { ReadLocker locker(m_dsLock); if (m_deviceImplIndex.HasKey(matchContext->deviceUuid)) { NPT_TimeStamp ts; NPT_System::GetCurrentTimeStamp(ts); NPT_String dateStr = NPT_DateTime(ts).ToString(NPT_DateTime::FORMAT_RFC_1123); NPT_String resp = NPT_String::Format("HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=%d\r\nDATE: %s\r\nEXT: \r\nLOCATION: %s\r\nSERVER: %s\r\nST: %s\r\nUSN: %s\r\nCUSTOM:%s\r\n\r\n", matchContext->expireSeconds, dateStr.GetChars(), location.GetChars(), m_serverHeader.GetChars(), it2->m_st.GetChars(), it2->m_usn.GetChars(), m_DevName.GetChars()); NPT_DataBuffer packet(resp.GetChars(), resp.GetLength(), false); sock.Send(packet, &fromAddr); } } } if (broken) { break; } } task->unregisterAbortCallback(&abortCallback); } matchList.Apply(NPT_ObjectDeleter<MatchContext>()); } while (false); }
int SimpleDMS::onAction(const ServiceDecl *serviceDecl, const ActionDecl *actionDecl, AbortableTask *task, const FrontEnd::InterfaceContext *ifctx, const FrontEnd::RequestContext& reqCtx, const NPT_HttpRequest *req, const NPT_List<NPT_String>& inputArgNames, const NPT_List<NPT_String>& inputArgValues, NPT_List<NPT_String>& outputArgValues) { if (NPT_String::Compare(serviceDecl->serviceId, "urn:upnp-org:serviceId:ContentDirectory") == 0) { if (NPT_String::Compare(actionDecl->name, "Browse") == 0) { NPT_UInt32 startingIndex; NPT_UInt32 requestedCount; NPT_ParseInteger(*inputArgValues.GetItem(3), startingIndex); NPT_ParseInteger(*inputArgValues.GetItem(4), requestedCount); NPT_String result; NPT_UInt32 numberReturned; NPT_UInt32 totalMatches; NPT_UInt32 updateID; int errorCode = m_store->browse(task, ifctx, reqCtx, NPT_String::Format("http://%s:%d%sdms/%%s", ifctx->m_ifAddr.ToString().GetChars(), ifctx->m_httpPort, frontEndContext()->m_httpRoot.GetChars()), *inputArgValues.GetItem(0), *inputArgValues.GetItem(1), *inputArgValues.GetItem(2), startingIndex, requestedCount, *inputArgValues.GetItem(5), result, numberReturned, totalMatches, updateID); if (errorCode == 0) { *outputArgValues.GetItem(0) = result; *outputArgValues.GetItem(1) = NPT_String::FromIntegerU(numberReturned); *outputArgValues.GetItem(2) = NPT_String::FromIntegerU(totalMatches); *outputArgValues.GetItem(3) = NPT_String::FromIntegerU(updateID); } return errorCode; } if (NPT_String::Compare(actionDecl->name, "Search") == 0) { NPT_UInt32 startingIndex; NPT_UInt32 requestedCount; NPT_ParseInteger(*inputArgValues.GetItem(3), startingIndex); NPT_ParseInteger(*inputArgValues.GetItem(4), requestedCount); NPT_String result; NPT_UInt32 numberReturned; NPT_UInt32 totalMatches; NPT_UInt32 updateID; int errorCode = m_store->search(task, ifctx, reqCtx, NPT_String::Format("http://%s:%d%sdms/%%s", ifctx->m_ifAddr.ToString().GetChars(), ifctx->m_httpPort, frontEndContext()->m_httpRoot.GetChars()), *inputArgValues.GetItem(0), *inputArgValues.GetItem(1), *inputArgValues.GetItem(2), startingIndex, requestedCount, *inputArgValues.GetItem(5), result, numberReturned, totalMatches, updateID); if (errorCode == 0) { *outputArgValues.GetItem(0) = result; *outputArgValues.GetItem(1) = NPT_String::FromIntegerU(numberReturned); *outputArgValues.GetItem(2) = NPT_String::FromIntegerU(totalMatches); *outputArgValues.GetItem(3) = NPT_String::FromIntegerU(updateID); } return errorCode; } if (NPT_String::Compare(actionDecl->name, "GetSearchCapabilities") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SearchCapabilities", v)) { *outputArgValues.GetItem(0) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetSortCapabilities") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SortCapabilities", v)) { *outputArgValues.GetItem(0) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetSystemUpdateID") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SystemUpdateID", v)) { *outputArgValues.GetItem(0) = v; } return 0; } return 602; } if (NPT_String::Compare(serviceDecl->serviceId, "urn:upnp-org:serviceId:ConnectionManager") == 0) { if (NPT_String::Compare(actionDecl->name, "GetProtocolInfo") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SourceProtocolInfo", v)) { *outputArgValues.GetItem(0) = v; } if (getStateValue(serviceDecl->serviceId, "SinkProtocolInfo", v)) { *outputArgValues.GetItem(1) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetCurrentConnectionIDs") == 0) { NPT_String v; if (getStateValue(serviceDecl->serviceId, "SourceProtocolInfo", v)) { *outputArgValues.GetItem(0) = v; } return 0; } if (NPT_String::Compare(actionDecl->name, "GetCurrentConnectionInfo") == 0) { *outputArgValues.GetItem(0) = "0"; *outputArgValues.GetItem(1) = "0"; *outputArgValues.GetItem(2) = ""; *outputArgValues.GetItem(3) = ""; *outputArgValues.GetItem(4) = "-1"; *outputArgValues.GetItem(5) = "Input"; // or "Output"? WTF! *outputArgValues.GetItem(6) = "OK"; return 0; } return 602; } if (NPT_String::Compare(serviceDecl->serviceId, "urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar") == 0) { if (NPT_String::Compare(actionDecl->name, "IsAuthorized") == 0) { *outputArgValues.GetItem(0) = "1"; return 0; } if (NPT_String::Compare(actionDecl->name, "IsValidated") == 0) { *outputArgValues.GetItem(0) = "1"; return 0; } if (NPT_String::Compare(actionDecl->name, "RegisterDevice") == 0) { return 0; } return 602; } return 501; }