Exemplo n.º 1
0
    def reply_message(self):

        # Open the WebSocket and subscribe it to a channel:
        request_body = self.rfile.read(int(self.headers.get('Content-Length')))
        cookies = SimpleCookie(self.headers.get('Cookie'))
        token = cookies['SP_SSO_JWT_COOKIE'].value
        if (not verify_cookie(token)):
            self.send_response(401)
            return ;

        # Set the headers required by the GRIP proxy:
        self.send_response(200)
        self.send_header('Sec-WebSocket-Extensions', 'grip; message-prefix=""')
        self.send_header('Content-Type', 'application/websocket-events')
        self.end_headers()
        in_events = decode_websocket_events(request_body)
        if in_events[0].type == 'OPEN':
            out_events = []
            out_events.append(WebSocketEvent('OPEN'))
            self.wfile.write(encode_websocket_events(out_events))
            logger.info("Connection Opened with Client")
            print("Connection Opened with Client")
        if in_events[0].type == 'TEXT':
            print("Text received from client")
            message = in_events[0].content
            print(message)
            cname = get_channel_name(message)
            print(cname)
            if cname != "all":
                try:
                    create_siddhi_common(message, cname)
                except Exception as e:
                    logger.info("Exception occurred:" +  str(e))
                    print("Exception occurred:" +  str(e))
                    threading.Thread(target=self.publish_message(cname, 'Error while creating the Siddhi app')).start()
                else:
                    logger.info("Siddhi app created")
                    print("Siddhi app created")
                    threading.Thread(target=self.publish_message(cname, 'Created Siddhi app: ' + cname)).start()
            else:
                threading.Thread(target=self.publish_message(cname, 'Please publish a valid Json.' )).start()
                print("Invalid JSON")
            out_events = []
            out_events.append(WebSocketEvent('TEXT', 'c:' + websocket_control_message('subscribe', {'channel': cname})))
            self.wfile.write(encode_websocket_events(out_events))
            print("End of the response")
Exemplo n.º 2
0
    def post(self, channel: str) -> Response:

        try:
            # in_events = decode_websocket_events(request.get_data())
            in_events = decode_websocket_events(request.get_data())
        except ValueError as e:
            log.error(e)
            raise BadRequest("Cannot decode websocket request: invalid format")

        if in_events is None or len(in_events) <= 0:
            log.error("Websocket request: {}", request.data)
            raise BadRequest(
                "Cannot decode websocket request: invalid in_event")
        in_events = in_events[0]

        event_type = None

        try:
            event_type = in_events.type
        except BaseException as e:  # pragma: no cover
            log.error(e)
            raise BadRequest("Cannot decode websocket request: invalid type")

        if event_type is None:  # pragma: no cover
            raise BadRequest("Cannot decode websocket request, no event type")

        out_events = []
        if event_type == "OPEN":
            ctrl_msg = websocket_control_message("subscribe",
                                                 {"channel": channel})
            out_events.append(WebSocketEvent("OPEN"))
            out_events.append(WebSocketEvent(
                "TEXT",
                f"c:{ctrl_msg}",
            ))
            headers = {"Sec-WebSocket-Extensions": "grip"}
            resp = FlaskResponse(
                encode_websocket_events(out_events),
                mimetype="application/websocket-events",
                headers=headers,
            )
            return resp

        log.error("Unknkown event type: {}", event_type)
        raise BadRequest("Cannot understand websocket request")
Exemplo n.º 3
0
def lambda_get_websocket(event):
    lower_headers = {}
    for k, v in six.iteritems(event.get('headers', {})):
        lower_headers[k.lower()] = v

    content_type = lower_headers.get('content-type')
    if content_type:
        at = content_type.find(';')
        if at != -1:
            content_type = content_type[:at].strip()

    if event[
            'httpMethod'] != 'POST' or content_type != 'application/websocket-events':
        raise ValueError(
            'request does not seem to be a websocket-over-http request')

    cid = lower_headers.get('connection-id')

    meta = {}
    for k, v in six.iteritems(lower_headers):
        if k.startswith('meta-'):
            meta[k[5:]] = v

    # read body as binary
    if event.get('isBase64Encoded'):
        body = b64decode(event['body'])
    else:
        body = event['body']

    if is_python3:
        if isinstance(body, str):
            body = body.encode('utf-8')
    else:
        if isinstance(body, unicode):
            body = body.encode('utf-8')

    events = decode_websocket_events(body)

    wscontext = WebSocketContext(cid, meta, events, grip_prefix=_get_prefix())

    wscontext.to_response = types.MethodType(lambda_websocket_to_response,
                                             wscontext)

    return wscontext
Exemplo n.º 4
0
    def post(self, channel):

        in_events = decode_websocket_events(request.data)
        if in_events is None or len(in_events) <= 0:
            log.error("Websocket request: {}", request.data)
            raise RestApiException("Cannot decode websocket request")
        in_events = in_events[0]

        event_type = None

        try:
            event_type = in_events.type
        except BaseException as e:
            log.error(e)
            raise RestApiException("Cannot decode websocket request")

        if event_type is None:
            log.error("Event type is None")
            raise RestApiException("Cannot decode websocket request")

        out_events = []
        if event_type == 'OPEN':
            out_events.append(WebSocketEvent('OPEN'))
            out_events.append(
                WebSocketEvent(
                    'TEXT',
                    'c:' + websocket_control_message('subscribe',
                                                     {'channel': channel}),
                ))
            headers = {'Sec-WebSocket-Extensions': 'grip'}
            resp = Response(
                encode_websocket_events(out_events),
                mimetype='application/websocket-events',
                headers=headers,
            )
            return resp

        log.error("Unknkown event type: {}", event_type)
        raise RestApiException("Cannot understand websocket request")
Exemplo n.º 5
0
	def process_request(self, request):
		# make sure these fields are always set
		request.grip = GripData()
		request.wscontext = None

		# old
		request.grip_proxied = False
		request.grip_signed = False

		proxied = False
		signed = False

		grip_sig_header = request.META.get('HTTP_GRIP_SIG')
		if grip_sig_header:
			proxies = _get_proxies()

			all_proxies_have_keys = True
			for entry in proxies:
				if 'key' not in entry:
					all_proxies_have_keys = False
					break

			if all_proxies_have_keys:
				# if all proxies have keys, then don't
				#   consider the request to be proxied unless
				#   one of them signed it
				for entry in proxies:
					if validate_sig(grip_sig_header, entry['key']):
						proxied = True
						signed = True
						break
			else:
				# if even one proxy doesn't have a key, then
				#   don't require verification in order to
				#   consider the request to have been proxied
				proxied = True

		# parse Grip-Feature
		hvalue = request.META.get('HTTP_GRIP_FEATURE')
		if hvalue:
			parsed = parse_options_header(hvalue, multiple=True)
			features = set()
			for n in range(0, len(parsed), 2):
				features.add(parsed[n])
			request.grip.features = features

		# parse Grip-Last
		hvalue = request.META.get('HTTP_GRIP_LAST')
		if hvalue:
			parsed = parse_options_header(hvalue, multiple=True)

			last = {}
			for n in range(0, len(parsed), 2):
				channel = parsed[n]
				params = parsed[n + 1]
				last[channel] = params.get('last-id', '')

			request.grip.last = last

		if hasattr(request, 'content_type'):
			content_type = request.content_type
		else:
			content_type = ''
			hvalue = request.META.get('CONTENT_TYPE')
			if hvalue:
				parsed = parse_options_header(hvalue)
				content_type = parsed[0]

		# detect WebSocket-Over-HTTP request
		wscontext = None
		if (request.method == 'POST' and
				content_type == 'application/websocket-events'):
			cid = request.META.get('HTTP_CONNECTION_ID')
			meta = {}
			for k, v in six.iteritems(request.META):
				if k.startswith('HTTP_META_'):
					meta[_convert_header_name(k[10:])] = v
			body = request.body
			if isinstance(body, six.text_type):
				body = body.encode('utf-8')
			try:
				events = decode_websocket_events(body)
			except:
				return HttpResponseBadRequest(
						'Error parsing WebSocket events.\n')

			wscontext = WebSocketContext(cid, meta, events,
					grip_prefix=_get_prefix())

		request.grip.proxied = proxied
		request.grip.signed = signed
		request.wscontext = wscontext

		# old
		request.grip_proxied = proxied
		request.grip_signed = signed
Exemplo n.º 6
0
    def process_request(self, request):
        # make sure these fields are always set
        request.grip = GripData()
        request.wscontext = None

        # old
        request.grip_proxied = False
        request.grip_signed = False

        proxied = False
        signed = False

        grip_sig_header = request.META.get('HTTP_GRIP_SIG')
        if grip_sig_header:
            proxies = _get_proxies()

            all_proxies_have_keys = True
            for entry in proxies:
                if 'key' not in entry:
                    all_proxies_have_keys = False
                    break

            if all_proxies_have_keys:
                # if all proxies have keys, then don't
                #   consider the request to be proxied unless
                #   one of them signed it
                for entry in proxies:
                    if validate_sig(grip_sig_header, entry['key']):
                        proxied = True
                        signed = True
                        break
            else:
                # if even one proxy doesn't have a key, then
                #   don't require verification in order to
                #   consider the request to have been proxied
                proxied = True

        # parse Grip-Feature
        hvalue = request.META.get('HTTP_GRIP_FEATURE')
        if hvalue:
            parsed = parse_options_header(hvalue, multiple=True)
            features = set()
            for n in range(0, len(parsed), 2):
                features.add(parsed[n])
            request.grip.features = features

        # parse Grip-Last
        hvalue = request.META.get('HTTP_GRIP_LAST')
        if hvalue:
            parsed = parse_options_header(hvalue, multiple=True)

            last = {}
            for n in range(0, len(parsed), 2):
                channel = parsed[n]
                params = parsed[n + 1]
                last[channel] = params.get('last-id', '')

            request.grip.last = last

        if hasattr(request, 'content_type'):
            content_type = request.content_type
        else:
            content_type = ''
            hvalue = request.META.get('CONTENT_TYPE')
            if hvalue:
                parsed = parse_options_header(hvalue)
                content_type = parsed[0]

        # detect WebSocket-Over-HTTP request
        wscontext = None
        if (request.method == 'POST'
                and content_type == 'application/websocket-events'):
            cid = request.META.get('HTTP_CONNECTION_ID')
            meta = {}
            for k, v in six.iteritems(request.META):
                if k.startswith('HTTP_META_'):
                    meta[_convert_header_name(k[10:])] = v
            body = request.body
            if isinstance(body, six.text_type):
                body = body.encode('utf-8')
            try:
                events = decode_websocket_events(body)
            except:
                return HttpResponseBadRequest(
                    'Error parsing WebSocket events.\n')

            wscontext = WebSocketContext(cid,
                                         meta,
                                         events,
                                         grip_prefix=_get_prefix())

        request.grip.proxied = proxied
        request.grip.signed = signed
        request.wscontext = wscontext

        # old
        request.grip_proxied = proxied
        request.grip_signed = signed
Exemplo n.º 7
0
    def post(self):
        #####################################
        # FIXME add connection last seen timestamp
        connection_id = self.request.headers['Connection-Id']
        in_events = decode_websocket_events(self.request.body)
        out_events = []
        if len(in_events) == 0:
            return

        logger.debug(in_events[0].type)
        if in_events[0].type == 'OPEN':
            out_events.append(WebSocketEvent('OPEN'))
            out_events.append(
                WebSocketEvent('TEXT', 'm:' +
                               json.dumps({'__restream_type': 'ready'})))
        elif in_events[0].type == 'TEXT':
            msg = in_events[0].content
            logger.debug(msg)
            command = parse_message(msg)
            if command['__restream_type'] == 'error':
                out_events.append(
                    WebSocketEvent('TEXT', 'm:' + json.dumps(command)))
            elif command['action'] == 'subscribe':
                if connection_id in connection_channels and command[
                        'channel_id'] in connection_channels[connection_id]:
                    logger.info(
                        "Connection {} already subscribed to {}".format(
                            connection_id, command['channel_id']))
                else:
                    out_events.append(
                        WebSocketEvent(
                            'TEXT',
                            'm:' + json.dumps({
                                '__restream_type': 'subscribe',
                                'channel': command['channel']
                            })))
                    out_events.append(
                        WebSocketEvent(
                            'TEXT', 'c:' + websocket_control_message(
                                'subscribe',
                                {'channel': command['channel_id']})))
                    process_subscribe(command, self.channel_fetchers,
                                      connection_id)
                    logger.info('subscribe {} to {}'.format(
                        connection_id, command['channel_id']))
            elif command['action'] == 'unsubscribe':
                if connection_id not in connection_channels or command[
                        'channel_id'] not in connection_channels[connection_id]:
                    logger.info(
                        "Connection {} not subscribed to {}; won't unsubscribe"
                        .format(connection_id, command['channel_id']))
                else:
                    out_events.append(
                        WebSocketEvent(
                            'TEXT',
                            'm:' + json.dumps({
                                '__restream_type': 'unsubscribe',
                                'channel': command['channel']
                            })))
                    out_events.append(
                        WebSocketEvent(
                            'TEXT', 'c:' + websocket_control_message(
                                'unsubscribe',
                                {'channel': command['channel_id']})))
                    process_unsubscribe(command['channel_id'], connection_id)
                    logger.info('unsubscribe {} from {}'.format(
                        connection_id, command['channel_id']))
        elif in_events[0].type == 'DISCONNECT' or in_events[0].type == 'CLOSE':
            out_events.append(WebSocketEvent(in_events[0].type))
            if connection_id in connection_channels:
                disconnect_all(connection_id)
        else:
            logger.info('event type not recognized: ' + in_events[0].type)

        self.write(encode_websocket_events(out_events))
        self.set_header('Sec-WebSocket-Extensions', 'grip')
        self.set_header('Content-Type', 'application/websocket-events')
        self.finish()
Exemplo n.º 8
0
    def process_request(self, request):
        # make sure these are always set
        request.grip_proxied = False
        request.grip_signed = False
        request.wscontext = None

        grip_proxied = False
        grip_signed = False

        grip_sig_header = request.META.get('HTTP_GRIP_SIG')
        if grip_sig_header:
            proxies = getattr(settings, 'GRIP_PROXIES', [])

            all_proxies_have_keys = True
            for entry in proxies:
                if 'key' not in entry:
                    all_proxies_have_keys = False
                    break

            if all_proxies_have_keys:
                # if all proxies have keys, then don't
                #   consider the request to be proxied unless
                #   one of them signed it
                for entry in proxies:
                    if validate_sig(grip_sig_header, entry['key']):
                        grip_proxied = True
                        grip_signed = True
                        break
            else:
                # if even one proxy doesn't have a key, then
                #   don't require verification in order to
                #   consider the request to have been proxied
                grip_proxied = True

        content_type = request.META.get('CONTENT_TYPE')
        if content_type:
            at = content_type.find(';')
            if at != -1:
                content_type = content_type[:at]

        # legacy check using accept
        accept_types = request.META.get('HTTP_ACCEPT')
        if accept_types:
            tmp = accept_types.split(',')
            accept_types = list()
            for s in tmp:
                accept_types.append(s.strip())

        wscontext = None
        if request.method == 'POST' and (
            (content_type and content_type == 'application/websocket-events')
                or
            (accept_types and 'application/websocket-events' in accept_types)):
            cid = request.META.get('HTTP_CONNECTION_ID')
            meta = dict()
            for k, v in request.META.iteritems():
                if k.startswith('HTTP_META_'):
                    meta[_convert_header_name(k[10:])] = v
            body = request.body
            assert (not isinstance(body, unicode))
            try:
                events = decode_websocket_events(body)
            except:
                return HttpResponseBadRequest(
                    'Error parsing WebSocket events.\n')

            wscontext = WebSocketContext(cid, meta, events)

        request.grip_proxied = grip_proxied
        request.grip_signed = grip_signed
        request.wscontext = wscontext
Exemplo n.º 9
0
import sys
import json
from pubcontrol import Item
from gripcontrol import GripPubControl, WebSocketEvent, \
    WebSocketMessageFormat, decode_websocket_events, encode_websocket_events

pub = GripPubControl({'control_uri': 'http://localhost:5561'})

opening = False
out_headers = []
out = []
for e in decode_websocket_events(sys.stdin.read()):
    if e.type == 'OPEN':
        if not opening:
            opening = True

            # enable GRIP
            out_headers.append(('Sec-WebSocket-Extensions', 'grip'))

            # ack the open
            out.append(e)

            # subscribe connection to channel
            cm = {'type': 'subscribe', 'channel': 'room'}
            out.append(WebSocketEvent('TEXT', 'c:%s' % json.dumps(cm)))
    elif e.type == 'CLOSE':
        out.append(e) # ack
        break
    elif e.type == 'TEXT':
        # broadcast to everyone
        pub.publish('room', Item(WebSocketMessageFormat(e.content)))
Exemplo n.º 10
0
import sys
import json
from pubcontrol import Item
from gripcontrol import GripPubControl, WebSocketEvent, \
    WebSocketMessageFormat, decode_websocket_events, encode_websocket_events

pub = GripPubControl({'control_uri': 'http://localhost:5561'})

opening = False
out_headers = []
out = []
for e in decode_websocket_events(sys.stdin.read()):
    if e.type == 'OPEN':
        if not opening:
            opening = True

            # enable GRIP
            out_headers.append(('Sec-WebSocket-Extensions', 'grip'))

            # ack the open
            out.append(e)

            # subscribe connection to channel
            cm = {'type': 'subscribe', 'channel': 'room'}
            out.append(WebSocketEvent('TEXT', 'c:%s' % json.dumps(cm)))
    elif e.type == 'CLOSE':
        out.append(e)  # ack
        break
    elif e.type == 'TEXT':
        # broadcast to everyone
        pub.publish('room', Item(WebSocketMessageFormat(e.content)))