Commits

Ginés Martínez Sánchez  committed b14e340 Draft

fixing python3

  • Participants
  • Parent commits 964869e

Comments (0)

Files changed (8)

File ginsfsm/c_sock.py

 
 from ginsfsm.gobj import GObj
 from ginsfsm.gconfig import GConfig
+from ginsfsm.compat import binary_type
 from ginsfsm.utils import (
     hexdump,
 )
             Equivalent to waitress' write_soon().
             The data are not really sent until _send_some() is called.
         """
+        assert isinstance(data, binary_type)
         if data:
             if data.__class__ is ReadOnlyFileBasedBuffer:
                 # they used wsgi.file_wrapper

File ginsfsm/examples/router/test_router.py

         'GRouter.server': True,
         'GRouter.trace_router': True,
         'GRouter.localhost_route_ports': 8000,
-        'GSock.trace_dump': False,
+        'GSock.trace_dump': True,
         'GObj.trace_mach': False,
         'GObj.logger': logging,
     }
         'GRouter.server': False,
         'GRouter.trace_router': True,
         'GRouter.static_routes': 'TOTO, toto, http://localhost:8000',
-        'GSock.trace_dump': False,
+        'GSock.trace_dump': True,
         'GObj.trace_mach': False,
         'GObj.logger': logging,
     }

File ginsfsm/protocols/http/common/parser.py

     tostr,
     urlparse,
     unquote_bytes_to_wsgi,
-    )
+)
 
 from ginsfsm.buffers import OverflowableBuffer
 
 from ginsfsm.protocols.http.common.receiver import (
     FixedStreamReceiver,
     ChunkedReceiver,
-    )
+)
 
 from ginsfsm.protocols.http.common.utilities import (
     find_double_newline,
     RequestEntityTooLarge,
     RequestHeaderFieldsTooLarge,
-    )
+)
 
 rename_headers = {
-    'CONTENT_LENGTH' : 'CONTENT_LENGTH',
-    'CONTENT_TYPE'   : 'CONTENT_TYPE',
+    'CONTENT_LENGTH': 'CONTENT_LENGTH',
+    'CONTENT_TYPE': 'CONTENT_TYPE',
 }
 
 
 
         # version, status, status_info will be bytes
         version, status, status_info = crack_response_first_line(first_line)
-        version = tostr(version)
         try:
             status = int(tostr(status))
         except ValueError:
             status = 0
 
+        version = tostr(version)
         status_info = tostr(status_info)
         self.version = version
         self.status = status
         unquote_bytes_to_wsgi(path),
         tostr(query),
         tostr(fragment),
-        )
+    )
 
 
 def get_header_lines(header):
 
     if m is not None and m.end() == len(line):
         version = m.group(1)
-        status = int(m.group(2))
+        status = m.group(2)
         status_info = m.group(3)
         return version, status, status_info
     else:

File ginsfsm/protocols/sockjs/server/c_websocket.py

 import base64
 import array
 from os import urandom
-from hashlib import sha1
+import hashlib
 import struct
 import uuid
 import logging
 
 from ginsfsm import __version__
-from ginsfsm.protocols.sockjs.server import proto
 from ginsfsm.utils import hexdump
 import ginsfsm.escape
 from ginsfsm.gconfig import GConfig
 from ginsfsm.gmsg import GMsg
 from ginsfsm.gobj import GObj
 from ginsfsm.c_timer import GTimer
-from ginsfsm.compat import binary_type
+from ginsfsm.compat import (
+    binary_type,
+)
 from ginsfsm.circular_fifo import CircularFIFO
 from ginsfsm.buffers import OverflowableBuffer
 from ginsfsm.protocols.http.common.parser import (
         if hd.h_payload_len >= 126:
             # control frames must have payload < 126; abort
             hd.error = True
-            logging.error("ERROR websocket header: too big control frame payloda")
+            logging.error(
+                "ERROR websocket header: too big control frame payloda")
     else:
         #
         #   Data h_opcode
         if iam_server and not hd.h_mask:
             # Unmasked frame; abort
             hd.error = True
-            logging.error("ERROR websocket header: iam_server but unmasked frame")
+            logging.error(
+                "ERROR websocket header: iam_server but unmasked frame")
 
     return hd
 
         'EV_ON_CLOSE:top output',
         'EV_ON_MESSAGE:top output',
         'EV_RX_DATA:bottom input',
-#        'EV_TRANSMIT_READY:bottom input',
+        # 'EV_TRANSMIT_READY:bottom input',
         'EV_CONNECTED:bottom input',
         'EV_DISCONNECTED:bottom input',
         'EV_SET_TIMER:bottom output',
 
     def do_request(self, host, port, resource, **options):
         headers = []
-        #headers.append("GET %s HTTP/1.1" % resource)
-        #headers.append("User-Agent: ginsfsm-%s" % __version__)
-        #headers.append("Upgrade: websocket")
-        #headers.append("Connection: Upgrade")
-        #if port == 80:
-        #    hostport = host
-        #else:
-        #    hostport = "%s:%d" % (host, port)
-        #headers.append("Host: %s" % hostport)
-        #
-        #if "origin" in options:
-        #    headers.append("Origin: %s" % options["origin"])
-        #else:
-        #    headers.append("Origin: %s" % hostport)
-        #
-        #key = _create_sec_websocket_key()
-        #headers.append("Sec-WebSocket-Key: %s" % key)
-        #headers.append("Sec-WebSocket-Version: %s" % VERSION)
-        #if "header" in options:
-        #    headers.extend(options["header"])
-        #
-        #headers.append("")
-        #headers.append("")
-        #
-        #header_str = "\r\n".join(headers)
-
-        headers.append(b"GET " + resource + b" HTTP/1.1")
-        headers.append(b"User-Agent: ginsfsm-" + __version__)
-        headers.append(b"Upgrade: websocket")
-        headers.append(b"Connection: Upgrade")
+        headers.append("GET %s HTTP/1.1" % resource)
+        headers.append("User-Agent: ginsfsm-%s" % __version__)
+        headers.append("Upgrade: websocket")
+        headers.append("Connection: Upgrade")
         if port == 80:
             hostport = host
         else:
-            hostport = host + ":" + str(port)
-        headers.append(b"Host: " + hostport)
+            hostport = "%s:%d" % (host, port)
+        headers.append("Host: %s" % hostport)
 
         if "origin" in options:
-            headers.append(b"Origin: " + options["origin"])
+            headers.append("Origin: %s" % options["origin"])
         else:
-            headers.append(b"Origin: " + hostport)
+            headers.append("Origin: %s" % hostport)
 
         key = _create_sec_websocket_key()
-        headers.append(b"Sec-WebSocket-Key: " + key)
-        headers.append(b"Sec-WebSocket-Version: " + VERSION)
+        headers.append("Sec-WebSocket-Key: %s" % key)
+        headers.append("Sec-WebSocket-Version: %s" % VERSION)
         if "header" in options:
             headers.extend(options["header"])
 
-        headers.append(b"")
-        headers.append(b"")
+        headers.append("")
+        headers.append("")
 
-        header_str = b"\r\n".join(headers)
+        header_str = "\r\n".join(headers)
+        data = ginsfsm.escape.utf8(header_str)
 
-        self.send_event(self.gsock, 'EV_SEND_DATA', data=header_str)
+        self.send_event(self.gsock, 'EV_SEND_DATA', data=data)
 
     def do_response(self):
         """ Got the request: analyze it and send the response.
         # Connection header should be upgrade.
         # Some proxy servers/load balancers
         # might mess with it.
-        connection = map(lambda s: s.strip().lower(),
-                         environ.get("HTTP_CONNECTION", "").split(","))
+        connection = list(map(lambda s: s.strip().lower(),
+                         environ.get("HTTP_CONNECTION", "").split(",")))
         if "upgrade" not in connection:
             data = ginsfsm.escape.utf8(
                 "HTTP/1.1 400 Bad Request\r\n"
             "HTTP_SEC_WEBSOCKET_KEY",
             "HTTP_SEC_WEBSOCKET_VERSION"
         )
-        if not all(map(lambda f: environ.get(f), fields)):
+        if not all(list(map(lambda f: environ.get(f), fields))):
             data = ginsfsm.escape.utf8(
                 "HTTP/1.1 400 Bad Request\r\n"
                 "Connection: Close\r\n"
             return False
 
         key = environ.get("HTTP_SEC_WEBSOCKET_KEY", None)
-        if not key or len(base64.b64decode(key)) != 16:
+        if not key or len(base64.b64decode(ginsfsm.escape.utf8(key))) != 16:
             data = ginsfsm.escape.utf8(
                 "HTTP/1.1 400 Bad Request\r\n"
                 "Connection: Close\r\n"
                 "\r\n"
                 "Sec-Websocket-Key is invalid key."
             )
-            self.send_event(self.gsock, 'EV_SEND_DATA', data=data)
-            return False
+            # TODO: review
+            #self.send_event(self.gsock, 'EV_SEND_DATA', data=data)
+            #return False
 
         #------------------------------#
         #   Accept the connection
             "Sec-WebSocket-Accept: %s\r\n"
             "%s"
             "\r\n" % (
-                base64.b64encode(sha1(key + self.KEY).digest()),
+                self._challenge_response(key),
                 subprotocol_header)
         )
         self.send_event(self.gsock, 'EV_SEND_DATA', data=data)
 
         return True
 
+    @staticmethod
+    def compute_accept_value(key):
+        """Computes the value for the Sec-WebSocket-Accept header,
+        given the value for Sec-WebSocket-Key.
+        """
+        sha1 = hashlib.sha1()
+        sha1.update(ginsfsm.escape.utf8(key))
+        sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")  # Magic value
+        return ginsfsm.escape.native_str(base64.b64encode(sha1.digest()))
+
+    def _challenge_response(self, key):
+        return GWebSocket.compute_accept_value(key)
+
     def select_subprotocol(self, subprotocols):
         """Invoked when a new WebSocket requests specific subprotocols.
 
             unmasked = gmsg.getdata(ln)
             if cur_frame.h_mask:
                 h_mask = cur_frame.masking_key
-                for i in xrange(ln):
+                for i in range(ln):
                     unmasked[i] = unmasked[i] ^ h_mask[i % 4]
 
         if cur_frame.h_fin:
             if not self.message_header:
                 self.message_header = cur_frame
             if not self.message_buffer:
-                self.message_buffer = OverflowableBuffer(self.config.outbuf_overflow)
+                self.message_buffer = OverflowableBuffer(
+                    self.config.outbuf_overflow)
             self.message_buffer.append(unmasked)
 
         gmsg.reset_wr()  # Reset buffer for next frame
         """ Send message to the client.
             Api websocket.
         """
+        if isinstance(message, dict):
+            message = ginsfsm.escape.json_encode(message)
+
         self.write_message(message, binary)
 
     def send_message(self, msg):
         """ Send jsonfied message compatible with sockjs.
 
-        Compatible with sockjs session interface.
+        Compatible with sockjs protocol.
         """
-        msg = proto.json_encode(msg)
-        assert isinstance(msg, basestring), 'Can only send strings'
-
-        if isinstance(msg, unicode):
-            msg = msg.encode('utf-8')
-
+        msg = ginsfsm.escape.json_encode(msg)
         self.write_message('a[%s]' % msg)
 
     def send_jsonfied_message(self, msg):
         """ Send jsonfied message. Not sockjs compatible.
         """
-        msg = proto.json_encode(msg)
-        assert isinstance(msg, basestring), 'Can only send strings'
-
-        if isinstance(msg, unicode):
-            msg = msg.encode('utf-8')
-
+        msg = ginsfsm.escape.json_encode(msg)
         self.write_message(msg)
 
     def write_message(self, message, binary=False):
             h_opcode = 0x2
         else:
             h_opcode = 0x1
-        if not binary:
-            message = ginsfsm.escape.utf8(message)
+        message = ginsfsm.escape.utf8(message)
         assert isinstance(message, binary_type)
         self._write_frame(True, h_opcode, message)
 
 
         if not self.config.iam_server:
             mask_key = urandom(4)
-            s = self.mask(mask_key, data)
-            data = mask_key + "".join(s)
+            #s = self.mask(mask_key, data)
+            #data = mask_key + b"".join(s)
+            data = mask_key + self.mask(mask_key, data)
 
         frame += data
         self.send_event(self.gsock, 'EV_SEND_DATA', data=frame)
         """
         _m = array.array("B", mask_key)
         _d = array.array("B", data)
-        for i in xrange(len(_d)):
+        for i in range(len(_d)):
             _d[i] ^= _m[i % 4]
         return _d.tostring()
 

File ginsfsm/protocols/wsgi/common/urlmap.py

         if mapper:
             matches = [p for p, a in mapper.applications]
             extra = 'defined apps: %s' % (
-                ',\n  '.join(map(repr, matches)))
+                ',\n  '.join(list(map(repr, matches))))
         else:
             extra = ''
         extra += '\nSCRIPT_NAME: %r' % environ.get('SCRIPT_NAME')

File ginsfsm/router.py

         ret = {}
         fn = lambda f: ret.update({f: getattr(self, f)})
         if message_type == '__event__':
-            map(fn, self.event_fields)
+            list(map(fn, self.event_fields))
         elif message_type == '__event_ack__':
-            map(fn, self.event_ack_fields)
+            list(map(fn, self.event_ack_fields))
         elif message_type == '__event_nack__':
-            map(fn, self.event_nack_fields)
+            list(map(fn, self.event_nack_fields))
         elif message_type == '__identity_card__':
-            map(fn, self.identity_card_fields)
+            list(map(fn, self.identity_card_fields))
         elif message_type == '__identity_card_ack__':
-            map(fn, self.identity_card_ack_fields)
+            list(map(fn, self.identity_card_ack_fields))
         else:
             self.logger.info(
                 'ERROR unknown message type %r' % message_type)
         fields = {}
         fn = lambda f: fields.update({f: getattr(self, f)})
         if new_message_type == '__event__':
-            map(fn, self.event_fields)
+            list(map(fn, self.event_fields))
         elif new_message_type == '__event_ack__':
-            map(fn, self.event_ack_fields)
+            list(map(fn, self.event_ack_fields))
         elif new_message_type == '__event_nack__':
-            map(fn, self.event_nack_fields)
+            list(map(fn, self.event_nack_fields))
         elif new_message_type == '__identity_card__':
-            map(fn, self.identity_card_fields)
+            list(map(fn, self.identity_card_fields))
         elif new_message_type == '__identity_card_ack__':
-            map(fn, self.identity_card_ack_fields)
+            list(map(fn, self.identity_card_ack_fields))
         else:
             self.logger.info(
                 'ERROR unknown message type %r' % new_message_type)
                     self.logger.info("    * route_dst BUSY!!")
 
     else:
+        self.logger.error("=================================================")
         self.logger.error("ERROR message_type UNKNOWN: %r" % message_type)
 
 
 
 def ac_subscription(self, event):
     subscription_reference = event.__subscription_reference__
-    subscription = self.external_subscriptions.get(subscription_reference, None)
+    subscription = self.external_subscriptions.get(
+        subscription_reference, None)
     if subscription:
         self.mt_send_event_to_external_route(
             subscription.route_ref,
         if self.config.trace_router:
             prefix = '%s ==> %s' % (my_gaplic_name, '')
             self.trace_intra_event(prefix, idc)
-        write(idc.toJSON())
+        x = idc.toJSON()
+        write(x)
 
     def find_local_router(self):
         """ Find the localhost router.
             except ValueError:
                 pass
 
-        destinations = map(lambda x: ('localhost', x), ports)
+        destinations = list((lambda x: ('localhost', x), ports))
         self.local_router = self.create_gobj(
             'local_router_client',
             GConnex,

File ginsfsm/sphinxext.py

         return int(ceil((96.0 / 72.0) * float(x)))
 
     if dimensions:
-        style = ' width="%s" height="%s"' % tuple(map(pt2px, dimensions))
+        style = ' width="%s" height="%s"' % tuple(list(map(pt2px, dimensions)))
     else:
         style = ''
 

File ginsfsm/utils.py

 def random_key():
     """Return random session key"""
     i = md5()
-    #i.update('%s%s' % (random(), time()))
     s = '%s%s' % (random(), time())
     i.update(s.encode(encoding='utf-8', errors='strict'))
     return i.hexdigest()
     return s
 
 
-def string_to_bytes(s, encoding='utf-8', errors='strict'):
-    if isinstance(s, text_type):
-        s = bytes(s, encoding, errors)
-    s = bytes(s)
-
-
 def hexdump(prefix, byts, length=16):
     ''' hd: hexdump
     dump in hex with pretty formating the hex value and ascii value (if any)