/*----------------------------------------------------------------------
|   NPT_Log::GetLogLevel
+---------------------------------------------------------------------*/
int 
NPT_Log::GetLogLevel(const char* name)
{
    if (       NPT_StringsEqual(name, "FATAL")) {
        return NPT_LOG_LEVEL_SEVERE;
    } else if (NPT_StringsEqual(name, "SEVERE")) {
        return NPT_LOG_LEVEL_WARNING;
    } else if (NPT_StringsEqual(name, "WARNING")) {
        return NPT_LOG_LEVEL_WARNING;
    } else if (NPT_StringsEqual(name, "INFO")) {
        return NPT_LOG_LEVEL_INFO;
    } else if (NPT_StringsEqual(name, "FINE")) {
        return NPT_LOG_LEVEL_FINE;
    } else if (NPT_StringsEqual(name, "FINER")) {
        return NPT_LOG_LEVEL_FINER;
    } else if (NPT_StringsEqual(name, "FINEST")) {
        return NPT_LOG_LEVEL_FINEST;
    } else if (NPT_StringsEqual(name, "ALL")) {
        return NPT_LOG_LEVEL_ALL;
    } else if (NPT_StringsEqual(name, "OFF")) {
        return NPT_LOG_LEVEL_OFF;
    } else {
        return -1;
    }
}
/*----------------------------------------------------------------------
|   NPT_File_ProcessFindData
+---------------------------------------------------------------------*/
static bool
NPT_File_ProcessFindData(WIN32_FIND_DATAW* find_data)
{
    NPT_WIN32_USE_CHAR_CONVERSION;

    // discard system specific files/shortcuts
    if (NPT_StringsEqual(NPT_WIN32_W2A(find_data->cFileName), ".") || 
        NPT_StringsEqual(NPT_WIN32_W2A(find_data->cFileName), "..")) {
        return false;
    }

    return true;
}
Beispiel #3
0
/*----------------------------------------------------------------------
|   PLT_FileMediaConnectDelegate::GetFilePath
+---------------------------------------------------------------------*/
NPT_Result
PLT_FileMediaConnectDelegate::GetFilePath(const char* object_id, NPT_String& filepath) 
{
    if (!object_id) return NPT_ERROR_INVALID_PARAMETERS;

    // Reroute XBox 360 and WMP requests to our route
    if (NPT_StringsEqual(object_id, "15")) {
        return PLT_FileMediaServerDelegate::GetFilePath("", filepath); // Videos
    } else if (NPT_StringsEqual(object_id, "16")) {
        return PLT_FileMediaServerDelegate::GetFilePath("", filepath); // Photos
    } else if (NPT_StringsEqual(object_id, "13") || NPT_StringsEqual(object_id, "4")) {
        return PLT_FileMediaServerDelegate::GetFilePath("", filepath); // Music
    }

    return PLT_FileMediaServerDelegate::GetFilePath(object_id, filepath);;
}
Beispiel #4
0
/*----------------------------------------------------------------------
|   PLT_MediaConnect::GetMappedObjectId
+---------------------------------------------------------------------*/
NPT_Result
PLT_MediaConnect::GetMappedObjectId(const char* object_id, NPT_String& mapped_object_id) 
{
    if (!object_id) return NPT_ERROR_INVALID_PARAMETERS;
    
    // Reroute XBox 360 and WMP requests to our route
    if (NPT_StringsEqual(object_id, "15")) {
        mapped_object_id = "0/Videos"; // Videos
    } else if (NPT_StringsEqual(object_id, "16")) {
        mapped_object_id = "0/Photos"; // Photos
    } else {
        mapped_object_id = object_id;
    }
    
    return NPT_SUCCESS;
}
Beispiel #5
0
/*----------------------------------------------------------------------
|   MatchString
+---------------------------------------------------------------------*/
static int
MatchString(const char* string, const char* const* list, unsigned int list_length)
{
    for (unsigned int i=0; i<list_length; i++) {
        if (NPT_StringsEqual(string, list[i])) return i;
    }
    
    return -1;
}
/*----------------------------------------------------------------------
|   NPT_LogManager::HaveLoggerConfig
+---------------------------------------------------------------------*/
bool
NPT_LogManager::HaveLoggerConfig(const char* name)
{
    NPT_Size name_length = NPT_StringLength(name);
    for (NPT_List<NPT_LogConfigEntry>::Iterator i = m_Config.GetFirstItem();
         i;
         ++i) {
        NPT_LogConfigEntry& entry = *i;
        if (entry.m_Key.StartsWith(name)) {
            const char* suffix = entry.m_Key.GetChars()+name_length;
            if (NPT_StringsEqual(suffix, ".level") ||
                NPT_StringsEqual(suffix, ".handlers") ||
                NPT_StringsEqual(suffix, ".forward")) {
                return true;
            }
        }
    }

    /* no config found */
    return false;
}
/*----------------------------------------------------------------------
|   NPT_LogHandler::Create
+---------------------------------------------------------------------*/
NPT_Result
NPT_LogHandler::Create(const char*      logger_name,
                       const char*      handler_name,
                       NPT_LogHandler*& handler)
{
    handler = NULL;

    if (NPT_StringsEqual(handler_name, "NullHandler")) {
        return NPT_LogNullHandler::Create(handler);
    } else if (NPT_StringsEqual(handler_name, "FileHandler")) {
        return NPT_LogFileHandler::Create(logger_name, handler);
    } else if (NPT_StringsEqual(handler_name, "ConsoleHandler")) {
        return NPT_LogConsoleHandler::Create(logger_name, handler);
    } else if (NPT_StringsEqual(handler_name, "TcpHandler")) {
        return NPT_LogTcpHandler::Create(logger_name, handler);
    } else if (NPT_StringsEqual(handler_name, "UdpHandler")) {
        return NPT_LogUdpHandler::Create(logger_name, handler);
    }

    return NPT_ERROR_NO_SUCH_CLASS;
}
Beispiel #8
0
/*----------------------------------------------------------------------
|   OZN_Database::CheckTableSchema
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Database::CheckTableSchema(const OZN_TableDescription& desc) 
{
    NPT_Result          res = NPT_FAILURE;
    NPT_String          sql;
    NPT_String          sql_create;
    OZN_StringProperty  schema(0, "");
    const char*         result;

    // generate the sql statement we would use to create the table
    NPT_CHECK(OZN_Sql::CreateTable(desc, sql_create));

    // generate the sql statement to query for a table schema
    NPT_CHECK(OZN_Sql::GetTableSchema(desc.name, sql));

    // query the db, if the table doesn't exist it will fail
    res = ExecuteScalar(sql, schema);
    result = schema.GetValue().string;
    if (NPT_SUCCEEDED(res) && result && result[0] != '\0') {
        //if existing table schema sql matches the one we would use
        // then it is the same table and same schema version
        if (NPT_StringsEqual(result, sql_create)) {
            return NPT_SUCCESS;
        }

        // weird, the query succeeded but returned nothing
        return NPT_FAILURE;
    }

    // close bracket
    OZN_Sql::Close(sql_create);

    // table doesn't exist, create it
    NPT_CHECK(ExecuteDML(sql_create, NULL));

    if (desc.unique_index_ids_count && desc.unique_index_ids) {
        res = OZN_Sql::CreateUniqueIndex(desc, 
            desc.unique_index_ids,
            desc.unique_index_ids_count,
            sql);
        NPT_CHECK(res);

        // close bracket
        OZN_Sql::Close(sql);

        // create unique index
        NPT_CHECK(ExecuteDML(sql, NULL));
    }

    return NPT_SUCCESS;
}
Beispiel #9
0
/*----------------------------------------------------------------------
|   PLT_FileMediaConnectDelegate::OnSearchContainer
+---------------------------------------------------------------------*/
NPT_Result
PLT_FileMediaConnectDelegate::OnSearchContainer(PLT_ActionReference&          action, 
                                                const char*                   object_id, 
                                                const char*                   search_criteria,
                                                const char*                   filter,
                                                NPT_UInt32                    starting_index,
                                                NPT_UInt32                    requested_count,
                                                const char*                   sort_criteria,
                                                const PLT_HttpRequestContext& context)
{
    /* parse search criteria */
    
    /* TODO: HACK TO PASS DLNA */
    if (search_criteria && NPT_StringsEqual(search_criteria, "Unknownfieldname")) {
        /* error */
        NPT_LOG_WARNING_1("Unsupported or invalid search criteria %s", search_criteria);
        action->SetError(708, "Unsupported or invalid search criteria");
        return NPT_FAILURE;
    }
    
    /* locate the file from the object ID */
    NPT_String dir;
    if (NPT_FAILED(GetFilePath(object_id, dir))) {
        /* error */
        NPT_LOG_WARNING("ObjectID not found.");
        action->SetError(710, "No Such Container.");
        return NPT_FAILURE;
    }
    
    /* retrieve the item type */
    NPT_FileInfo info;
    NPT_Result res = NPT_File::GetInfo(dir, &info);
    if (NPT_FAILED(res) || (info.m_Type != NPT_FileInfo::FILE_TYPE_DIRECTORY)) {
        /* error */
        NPT_LOG_WARNING("No such container");
        action->SetError(710, "No such container");
        return NPT_FAILURE;
    }
    
    /* hack for now to return something back to XBox 360 */
    return OnBrowseDirectChildren(action, 
                                  object_id, 
                                  filter, 
                                  starting_index, 
                                  requested_count, 
                                  sort_criteria, 
                                  context);
}
Beispiel #10
0
    // 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);
    }
Beispiel #11
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)
{
    // 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) {
            printf("ERROR: unexpected argument (%s)\n", arg);
            exit(1);    
        }
                 
        if (NPT_StringsEqual(arg, "--packet-size")) {
            packet_size = strtoul(*argv++, NULL, 10);
            continue;
        } else if (NPT_StringsEqual(arg, "--verbose")) {
            Options.verbose = true;
            continue;
        } else if (NPT_StringsEqual(arg, "--show-progress")) {
            Options.show_progress = true;
            continue;
        } else if (NPT_StringsEqual(arg, "udp")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        printf("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;
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.udp_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.udp_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        printf("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 {
                        printf("ERROR: missing argument for 'udp client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'udp' endpoint\n");
                exit(1);
            }
         } else if (NPT_StringsEqual(arg, "multicast")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_OUT){
                        printf("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 {
                        printf("ERROR: missing argument for 'multicast server'\n");
                        exit(1);
                    }
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.multicast_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.multicast_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(argv[0], "client")) {
                    if (current_endpoint->direction == ENDPOINT_DIRECTION_IN) {
                        printf("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 {
                        printf("ERROR: missing argument for 'multicast client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'multicast' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "tcp")) {
            if (argv[0] && argv[1]) {
                if (NPT_StringsEqual(argv[0], "server")) {
                    current_endpoint->type = ENDPOINT_TYPE_TCP_SERVER;
                    current_endpoint->info.tcp_server.port = strtoul(argv[1], NULL, 10);
                    argv += 2;
                    if (argv[0] && NPT_StringsEqual(argv[0], "-r")) {
                        current_endpoint->info.tcp_server.reuse_addr = false;
                        ++argv;
                    } else {
                        current_endpoint->info.tcp_server.reuse_addr = true;
                    }
                } else if (NPT_StringsEqual(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 {
                        printf("ERROR: missing argument for 'tcp client'\n");
                        exit(1);
                    }
                }
            } else {
                printf("ERROR: missing argument for 'tcp' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "file")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_FILE;
                current_endpoint->info.file.name = *argv++;
            } else {
                printf("ERROR: missing argument for 'file' endpoint\n");
                exit(1);
            }
        } else if (NPT_StringsEqual(arg, "serial")) {
            if (argv[0]) {
                current_endpoint->type = ENDPOINT_TYPE_SERIAL_PORT;
                current_endpoint->info.serial_port.name = *argv++;
            } else {
                printf("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
            if (argv[0]) {
                int speed = 0;
                if (NPT_FAILED(NPT_ParseInteger(*argv++, speed))) {
                    printf("ERROR: invalid speed for 'serial' endpoint\n");
                    exit(1);
                } 
                current_endpoint->info.serial_port.speed = (unsigned int)speed;
            } else {
                printf("ERROR: missing argument for 'serial' endpoint\n");
                exit(1);
            }
        } else {
            printf("ERROR: invalid argument (%s)\n", arg);
            exit(1);
        }

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

    if (current_endpoint) {
        printf("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) {
        printf("ERROR: out of memory\n");
        exit(1);
    }

    // get output stream
    NPT_OutputStreamReference out;
    result = GetEndPointStreams(&out_endpoint, NULL, &out);
    if (NPT_FAILED(result)) {
        printf("ERROR: failed to get stream for output (%d)\n", 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);
        if (NPT_FAILED(result)) {
            printf("ERROR: failed to create UDP socket (%d : %s)\n", result, NPT_ResultText(result));
            exit(1);
        }

        // 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();
                    printf("Received %d bytes from %s\n", (int)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)) {
            printf("ERROR: failed to get stream for input (%d : %s)\n", result, NPT_ResultText(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) {
                printf("[%d]\r", (int)total);
            }
            if (NPT_SUCCEEDED(result) && bytes_read) {
                result = out->Write(buffer, bytes_read, &bytes_written);
                if (Options.show_progress) {
                    printf("[%d]\r", (int)total);
                }
                offset += bytes_written;
                total  += bytes_written;
            } else {
                break;
            }
        } while (NPT_SUCCEEDED(result));
    }

    if (NPT_FAILED(result)) {
        printf("[%d] *******************\n", result);
        exit(1);
    }
    
    delete buffer;
    return 0;
}
Beispiel #13
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;
}