Ejemplo n.º 1
0
def py_niget():
    """
    @brief Command line program to perform a NetInf 'get' operation using http
    @brief convergence layer.
    
    Uses NIproc global instance of NI operations class

    Run:
    
    >  niget.py --help

    to see usage and options.

    Exit code is 0 for success, 1 if HTTP returned something except 200,
    and negative for local errors.
    """
    
    # Options parsing and verification stuff
    usage = "%prog [-q] [-l] [-d] [-m|-v] [-f <pathname of content file>] <ni name>\n" + \
            "<ni name> must include location (netloc) from which to retrieve object."
    parser = OptionParser(usage)
    
    parser.add_option("-f", "--file", dest="file_name",
                      type="string",
                      help="File to hold retrieved content. Defaults to hash code in current directory if not present")
    parser.add_option("-q", "--quiet", default=False,
                      action="store_true", dest="quiet",
                      help="Suppress textual output")
    parser.add_option("-s", "--server", dest="server",
                      type="string",
                      help="hostname:port of server to send the NetInf GET to")
    parser.add_option("-l", "--lax", default=False,
                      action="store_true", dest="lax",
                      help="Store returned content even if digest doesn't validate")
    parser.add_option("-m", "--metadata", default=False,
                      action="store_true", dest="metadata",
                      help="Output returned metadata as JSON string")
    parser.add_option("-v", "--view", default=False,
                      action="store_true", dest="view",
                      help="Pretty print returned metadata.")
    parser.add_option("-d", "--dump", default=False,
                      action="store_true", dest="dump",
                      help="Dump raw HTTP response to stdout.")

    (options, args) = parser.parse_args()

    # Check command line options - -q, -f, -l, -m, -v and -d are optional, <ni name> is mandatory
    if len(args) != 1:
        parser.error("URL <ni name> not specified.")
        sys.exit(-1)
    verbose = not options.quiet

    # Create NIname instance for supplied URL and validate it
    ni_url = NIname(args[0])

    # Must be a complete ni: URL with non-empty params field
    rv = ni_url.validate_ni_url(has_params = True)
    if (rv != ni_errs.niSUCCESS):
        if verbose:
            print("Error: %s is not a complete, valid ni scheme URL: %s" % (ni_url.get_url(), ni_errs_txt[rv]))
        sys.exit(-2)

    # Generate file name for output if not specified
    if (options.file_name == None):
        options.file_name = ni_url.get_digest()
        
    # Generate NetInf form access URL
    if (options.server != None):
        server = options.server
    else:
        server = ni_url.get_netloc()

    http_url = "http://%s/netinfproto/get" % server
    """
    if (http_url == None):
        if verbose:
            print("Error: Unable to generate http: transformed URL for ni URL %s" % ni_urlparse.get_url())
        sys.exit(-3)
    """
    
    # Set up HTTP form data for get request
    form_data = urllib.urlencode({ "URI":   ni_url.get_url(),
                                   "msgid": random.randint(1, 32000),
                                   "ext":   "" })

    # Send POST request to destination server
    try:
        http_object = urllib2.urlopen(http_url, form_data)
    except Exception, e:
        if verbose:
            print("Error: Unable to access http URL %s: %s" % (http_url, str(e)))
        sys.exit(-4)
Ejemplo n.º 2
0
def py_nigetalt():
    """
    @brief Command line program to perform a NetInf 'get' operation using http
    @brief convergence layer.
    
    Uses NIproc global instance of NI operations class

    Run:
    
    >  nigetalt.py --help

    to see usage and options.

    Exit code is 0 for success, 1 if HTTP returned something except 200,
    and negative for local errors.
    """
    
    # Options parsing and verification stuff
    usage = "%prog [-q] [-l] [-d] [-m|-v] [-f <pathname of content file>] [-w <locator>] <ni name>\n" + \
            "Either <ni name> must include location (netloc) from which to retrieve object, or\n" + \
            "a locator must be given with the -w/--whence option.\n" + \
            "The locator may be prefixed with an HTTP ('http://')or DTN ('dtn://') URI scheme identifier.\n" + \
            "If no scheme identifier is given then HTTP is assumed.  The DTN scheme does not accept ports."
    parser = OptionParser(usage)
    
    parser.add_option("-f", "--file", dest="file_name",
                      type="string",
                      help="File to hold retrieved content. Defaults to hash code in current directory if not present")
    parser.add_option("-w", "--whence", dest="loc",
                      type="string", default=None,
                      help="Locator to which to send NetInf GET request.  May be prefixed with http:// or dtn://")
    parser.add_option("-q", "--quiet", default=False,
                      action="store_true", dest="quiet",
                      help="Suppress textual output")
    parser.add_option("-l", "--lax", default=False,
                      action="store_true", dest="lax",
                      help="Store returned content even if digest doesn't validate")
    parser.add_option("-m", "--metadata", default=False,
                      action="store_true", dest="metadata",
                      help="Output returned metadata as JSON string")
    parser.add_option("-v", "--view", default=False,
                      action="store_true", dest="view",
                      help="Pretty print returned metadata.")

    (options, args) = parser.parse_args()

    # Check command line options - -q, -f, -l, -m, and -v are optional,
    # <ni name> is mandatory
    # -w is optional if <ni name> contains a netloc
    if len(args) != 1:
        parser.error("URL <ni name> not specified.")
        sys.exit(-1)
    verbose = not options.quiet

    # Create NIname instance for supplied URL and validate it
    ni_url = NIname(args[0])

    # Must be a complete ni: URL with non-empty params field
    rv = ni_url.validate_ni_url(has_params = True)
    if (rv != ni_errs.niSUCCESS):
        if verbose:
            print("Error: %s is not a complete, valid ni scheme URL: %s" % (ni_url.get_url(), ni_errs_txt[rv]))
        sys.exit(-2)

    # Generate file name for output if not specified
    if (options.file_name == None):
        options.file_name = ni_url.get_digest()

    # Decide Convergence Layer to use and locator to access
    netloc = ni_url.get_netloc()
    cl = HTTP_SCHEME
    if netloc == "":
        # Must have -w option
        if options.loc is None:
            if verbose:
                print("Error: Must provide a locator either in ni URI or via -w/--whence")
            sys.exit(-3)
        loc = options.loc.lower()
    elif options.loc is not None:
        if verbose:
            print("Warning: -w/--whence locator option overrides netloc in ni URI")
        loc = options.loc.lower()
    else:
        loc = netloc.lower()

    # See if URI scheme was specified
    if loc.startswith(HTTP_SCHEME):
        loc = loc[len(HTTP_SCHEME):]
    elif loc.startswith(DTN_SCHEME):
        loc = loc[len(DTN_SCHEME):]
        cl = DTN_SCHEME
    else:
        ssep = loc.find("://")
        if ssep != -1:
            if verbose:
                print("Error: Convergence Layer for scheme %s is not supported - use dtn or http" %
                      loc[:ssep])
            sys.exit(-4)
        # Default assume HTTP

    # Action the GET according to CL selected
    if cl == HTTP_SCHEME:
        json_report, got_content, faulty = get_via_http(ni_url, loc,
                                                        options.file_name,
                                                        verbose, options.lax)
    else:
        json_report, got_content, faulty = get_via_dtn(ni_url, loc,
                                                       options.file_name,
                                                       verbose, options.lax)

    if options.view:
        print("Returned metadata for %s:" % args[0])
        print json.dumps(json_report, indent = 4)
    elif options.metadata:
        print json.dumps(json_report, separators=(",", ":"))

    if not got_content:
        rv = 1
    elif faulty:
        rv = 2
    else:
        rv = 0

    if verbose and got_content:
        if not faulty:
            print("Content successfully retrieved and placed in file %s." %
                  options.file_name)
        else:
            print("Content retrieved and placed in file %s but digest didn't verify." %
                  options.file_name)
    elif verbose:
        print("Only metadata retrieved")

    sys.exit(rv)