Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / test / data / native_messaging / native_hosts / echo.py
blob0af7f73fd15cada85974685ef2950f25e082cbb5
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 # A simple native client in python.
7 # All this client does is echo the text it receives back at the extension.
9 import os
10 import platform
11 import sys
12 import struct
14 def WriteMessage(message):
15 try:
16 sys.stdout.write(struct.pack("I", len(message)))
17 sys.stdout.write(message)
18 sys.stdout.flush()
19 return True
20 except IOError:
21 return False
23 def Main():
24 message_number = 0
26 caller_url = None
27 parent_window = None
29 if len(sys.argv) < 2:
30 sys.stderr.write("URL of the calling application is not specified.\n")
31 return 1
32 # TODO(sergeyu): Use argparse module to parse the arguments (not available in
33 # Python 2.6).
34 for arg in sys.argv[1:]:
35 if arg.startswith('--'):
36 if arg.startswith('--parent-window='):
37 parent_window = long(arg[len('--parent-window='):])
38 elif caller_url == None:
39 caller_url = arg
41 if platform.system() == 'Windows':
42 import win32gui
43 if parent_window and not win32gui.IsWindow(parent_window):
44 sys.stderr.write('Invalid --parent-window.\n')
45 return 1
47 while 1:
48 # Read the message type (first 4 bytes).
49 text_length_bytes = sys.stdin.read(4)
51 if len(text_length_bytes) == 0:
52 break
54 # Read the message length (4 bytes).
55 text_length = struct.unpack('i', text_length_bytes)[0]
57 # Read the text (JSON object) of the message.
58 text = sys.stdin.read(text_length).decode('utf-8')
60 # bigMessage() test sends a special message that is sent to verify that
61 # chrome rejects messages that are too big. Try sending a message bigger
62 # than 1MB after receiving a message that contains 'bigMessageTest'.
63 if 'bigMessageTest' in text:
64 text = '{"key": "' + ("x" * 1024 * 1024) + '"}'
66 # "stopHostTest" verifies that Chrome properly handles the case when the
67 # host quits before port is closed. When the test receives response it
68 # will try sending second message and it should fail becasue the stdin
69 # pipe will be closed at that point.
70 if 'stopHostTest' in text:
71 # Using os.close() here because sys.stdin.close() doesn't really close
72 # the pipe (it just marks it as closed, but doesn't close the file
73 # descriptor).
74 os.close(sys.stdin.fileno())
75 WriteMessage('{"stopped": true }')
76 sys.exit(0)
78 message_number += 1
80 message = '{{"id": {0}, "echo": {1}, "caller_url": "{2}"}}'.format(
81 message_number, text, caller_url).encode('utf-8')
82 if not WriteMessage(message):
83 break
85 if __name__ == '__main__':
86 sys.exit(Main())