"""Gopher protocol client interface."""
__all__
= ["send_selector","send_query"]
# Default selector, host and port
DEF_HOST
= 'gopher.micro.umn.edu'
A_WWW
= 'w' # WWW address
"""Map all file types to strings; unknown types become TYPE='x'."""
if _type_to_name_map
=={}:
_type_to_name_map
[eval(name
)] = name
[2:]
if gtype
in _type_to_name_map
:
return _type_to_name_map
[gtype
]
return 'TYPE=%r' % (gtype
,)
# Names for characters and strings
def send_selector(selector
, host
, port
= 0):
"""Send a selector to a given host and port, return a file with the reply."""
host
, port
= host
[:i
], int(host
[i
+1:])
elif type(port
) == type(''):
s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
s
.sendall(selector
+ CRLF
)
def send_query(selector
, query
, host
, port
= 0):
"""Send a selector and a query string."""
return send_selector(selector
+ '\t' + query
, host
, port
)
def path_to_selector(path
):
"""Takes a path as returned by urlparse and returns the appropriate selector."""
return path
[2:] # Cuts initial slash and data type identifier
def path_to_datatype_name(path
):
"""Takes a path as returned by urlparse and maps it to a string.
See section 3.4 of RFC 1738 for details."""
# No way to tell, although "INDEX" is likely
return type_to_name(path
[1])
# The following functions interpret the data returned by the gopher
# server according to the expected type, e.g. textfile or directory
"""Get a directory in the form of a list of entries."""
print '(Unexpected EOF from server)'
print '(Empty line from server)'
parts
= line
[1:].split(TAB
)
print '(Bad line from server: %r)' % (line
,)
print '(Extra info from server:',
"""Get a text file as a list of lines, with trailing CRLF stripped."""
get_alt_textfile(f
, lines
.append
)
def get_alt_textfile(f
, func
):
"""Get a text file and pass each line to a function, with trailing CRLF stripped."""
print '(Unexpected EOF from server)'
"""Get a binary file as one solid data block."""
def get_alt_binary(f
, func
, blocksize
):
"""Get a binary file and pass each block to a function."""
"""Trivial test program."""
opts
, args
= getopt
.getopt(sys
.argv
[1:], '')
type, selector
= type[0], type
f
= send_query(selector
, query
, host
)
f
= send_selector(selector
, host
)
for item
in lines
: print item
elif type in (A_MENU
, A_INDEX
):
entries
= get_directory(f
)
for item
in entries
: print item
print 'binary data:', len(data
), 'bytes:', repr(data
[:100])[:40]
# Run the test when run as script
if __name__
== '__main__':