You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

700 lines
26 KiB

  1. #! /usr/bin/env python
  2. """ Starts a synapse client console. """
  3. from twisted.internet import reactor, defer, threads
  4. from http import TwistedHttpClient
  5. import argparse
  6. import cmd
  7. import getpass
  8. import json
  9. import shlex
  10. import sys
  11. import time
  12. import urllib
  13. import urlparse
  14. import nacl.signing
  15. import nacl.encoding
  16. from syutil.crypto.jsonsign import verify_signed_json, SignatureVerifyException
  17. CONFIG_JSON = "cmdclient_config.json"
  18. TRUSTED_ID_SERVERS = [
  19. 'localhost:8001'
  20. ]
  21. class SynapseCmd(cmd.Cmd):
  22. """Basic synapse command-line processor.
  23. This processes commands from the user and calls the relevant HTTP methods.
  24. """
  25. def __init__(self, http_client, server_url, identity_server_url, username, token):
  26. cmd.Cmd.__init__(self)
  27. self.http_client = http_client
  28. self.http_client.verbose = True
  29. self.config = {
  30. "url": server_url,
  31. "identityServerUrl": identity_server_url,
  32. "user": username,
  33. "token": token,
  34. "verbose": "on",
  35. "complete_usernames": "on",
  36. "send_delivery_receipts": "on"
  37. }
  38. self.path_prefix = "/matrix/client/api/v1"
  39. self.event_stream_token = "START"
  40. self.prompt = ">>> "
  41. def do_EOF(self, line): # allows CTRL+D quitting
  42. return True
  43. def emptyline(self):
  44. pass # else it repeats the previous command
  45. def _usr(self):
  46. return self.config["user"]
  47. def _tok(self):
  48. return self.config["token"]
  49. def _url(self):
  50. return self.config["url"] + self.path_prefix
  51. def _identityServerUrl(self):
  52. return self.config["identityServerUrl"]
  53. def _is_on(self, config_name):
  54. if config_name in self.config:
  55. return self.config[config_name] == "on"
  56. return False
  57. def _domain(self):
  58. return self.config["user"].split(":")[1]
  59. def do_config(self, line):
  60. """ Show the config for this client: "config"
  61. Edit a key value mapping: "config key value" e.g. "config token 1234"
  62. Config variables:
  63. user: The username to auth with.
  64. token: The access token to auth with.
  65. url: The url of the server.
  66. verbose: [on|off] The verbosity of requests/responses.
  67. complete_usernames: [on|off] Auto complete partial usernames by
  68. assuming they are on the same homeserver as you.
  69. E.g. name >> @name:yourhost
  70. send_delivery_receipts: [on|off] Automatically send receipts to
  71. messages when performing a 'stream' command.
  72. Additional key/values can be added and can be substituted into requests
  73. by using $. E.g. 'config roomid room1' then 'raw get /rooms/$roomid'.
  74. """
  75. if len(line) == 0:
  76. print json.dumps(self.config, indent=4)
  77. return
  78. try:
  79. args = self._parse(line, ["key", "val"], force_keys=True)
  80. # make sure restricted config values are checked
  81. config_rules = [ # key, valid_values
  82. ("verbose", ["on", "off"]),
  83. ("complete_usernames", ["on", "off"]),
  84. ("send_delivery_receipts", ["on", "off"])
  85. ]
  86. for key, valid_vals in config_rules:
  87. if key == args["key"] and args["val"] not in valid_vals:
  88. print "%s value must be one of %s" % (args["key"],
  89. valid_vals)
  90. return
  91. # toggle the http client verbosity
  92. if args["key"] == "verbose":
  93. self.http_client.verbose = "on" == args["val"]
  94. # assign the new config
  95. self.config[args["key"]] = args["val"]
  96. print json.dumps(self.config, indent=4)
  97. save_config(self.config)
  98. except Exception as e:
  99. print e
  100. def do_register(self, line):
  101. """Registers for a new account: "register <userid> <noupdate>"
  102. <userid> : The desired user ID
  103. <noupdate> : Do not automatically clobber config values.
  104. """
  105. args = self._parse(line, ["userid", "noupdate"])
  106. path = "/register"
  107. password = None
  108. pwd = None
  109. pwd2 = "_"
  110. while pwd != pwd2:
  111. pwd = getpass.getpass("(Optional) Type a password for this user: ")
  112. if len(pwd) == 0:
  113. print "Not using a password for this user."
  114. break
  115. pwd2 = getpass.getpass("Retype the password: ")
  116. if pwd != pwd2:
  117. print "Password mismatch."
  118. else:
  119. password = pwd
  120. body = {}
  121. if "userid" in args:
  122. body["user_id"] = args["userid"]
  123. if password:
  124. body["password"] = password
  125. reactor.callFromThread(self._do_register, "POST", path, body,
  126. "noupdate" not in args)
  127. @defer.inlineCallbacks
  128. def _do_register(self, method, path, data, update_config):
  129. url = self._url() + path
  130. json_res = yield self.http_client.do_request(method, url, data=data)
  131. print json.dumps(json_res, indent=4)
  132. if update_config and "user_id" in json_res:
  133. self.config["user"] = json_res["user_id"]
  134. self.config["token"] = json_res["access_token"]
  135. save_config(self.config)
  136. def do_login(self, line):
  137. """Login as a specific user: "login @bob:localhost"
  138. You MAY be prompted for a password, or instructed to visit a URL.
  139. """
  140. try:
  141. args = self._parse(line, ["user_id"], force_keys=True)
  142. can_login = threads.blockingCallFromThread(
  143. reactor,
  144. self._check_can_login)
  145. if can_login:
  146. p = getpass.getpass("Enter your password: ")
  147. user = args["user_id"]
  148. if self._is_on("complete_usernames") and not user.startswith("@"):
  149. user = "@" + user + ":" + self._domain()
  150. reactor.callFromThread(self._do_login, user, p)
  151. print " got %s " % p
  152. except Exception as e:
  153. print e
  154. @defer.inlineCallbacks
  155. def _do_login(self, user, password):
  156. path = "/login"
  157. data = {
  158. "user": user,
  159. "password": password,
  160. "type": "m.login.password"
  161. }
  162. url = self._url() + path
  163. json_res = yield self.http_client.do_request("POST", url, data=data)
  164. print json_res
  165. if "access_token" in json_res:
  166. self.config["user"] = user
  167. self.config["token"] = json_res["access_token"]
  168. save_config(self.config)
  169. print "Login successful."
  170. @defer.inlineCallbacks
  171. def _check_can_login(self):
  172. path = "/login"
  173. # ALWAYS check that the home server can handle the login request before
  174. # submitting!
  175. url = self._url() + path
  176. json_res = yield self.http_client.do_request("GET", url)
  177. print json_res
  178. if ("type" not in json_res or "m.login.password" != json_res["type"] or
  179. "stages" in json_res):
  180. fallback_url = self._url() + "/login/fallback"
  181. print ("Unable to login via the command line client. Please visit "
  182. "%s to login." % fallback_url)
  183. defer.returnValue(False)
  184. defer.returnValue(True)
  185. def do_3pidrequest(self, line):
  186. """Requests the association of a third party identifier
  187. <medium> The medium of the identifer (currently only 'email')
  188. <address> The address of the identifer (ie. the email address)
  189. """
  190. args = self._parse(line, ['medium', 'address'])
  191. if not args['medium'] == 'email':
  192. print "Only email is supported currently"
  193. return
  194. postArgs = {'email': args['address'], 'clientSecret': '____'}
  195. reactor.callFromThread(self._do_3pidrequest, postArgs)
  196. @defer.inlineCallbacks
  197. def _do_3pidrequest(self, args):
  198. url = self._identityServerUrl()+"/matrix/identity/api/v1/validate/email/requestToken"
  199. json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False,
  200. headers={'Content-Type': ['application/x-www-form-urlencoded']})
  201. print json_res
  202. if 'tokenId' in json_res:
  203. print "Token ID %s sent" % (json_res['tokenId'])
  204. def do_3pidvalidate(self, line):
  205. """Validate and associate a third party ID
  206. <medium> The medium of the identifer (currently only 'email')
  207. <tokenId> The identifier iof the token given in 3pidrequest
  208. <token> The token sent to your third party identifier address
  209. """
  210. args = self._parse(line, ['medium', 'tokenId', 'token'])
  211. if not args['medium'] == 'email':
  212. print "Only email is supported currently"
  213. return
  214. postArgs = { 'tokenId' : args['tokenId'], 'token' : args['token'] }
  215. postArgs['mxId'] = self.config["user"]
  216. reactor.callFromThread(self._do_3pidvalidate, postArgs)
  217. @defer.inlineCallbacks
  218. def _do_3pidvalidate(self, args):
  219. url = self._identityServerUrl()+"/matrix/identity/api/v1/validate/email/submitToken"
  220. json_res = yield self.http_client.do_request("POST", url, data=urllib.urlencode(args), jsonreq=False,
  221. headers={'Content-Type': ['application/x-www-form-urlencoded']})
  222. print json_res
  223. def do_join(self, line):
  224. """Joins a room: "join <roomid>" """
  225. try:
  226. args = self._parse(line, ["roomid"], force_keys=True)
  227. self._do_membership_change(args["roomid"], "join", self._usr())
  228. except Exception as e:
  229. print e
  230. def do_joinalias(self, line):
  231. try:
  232. args = self._parse(line, ["roomname"], force_keys=True)
  233. path = "/join/%s" % urllib.quote(args["roomname"])
  234. reactor.callFromThread(self._run_and_pprint, "PUT", path, {})
  235. except Exception as e:
  236. print e
  237. def do_topic(self, line):
  238. """"topic [set|get] <roomid> [<newtopic>]"
  239. Set the topic for a room: topic set <roomid> <newtopic>
  240. Get the topic for a room: topic get <roomid>
  241. """
  242. try:
  243. args = self._parse(line, ["action", "roomid", "topic"])
  244. if "action" not in args or "roomid" not in args:
  245. print "Must specify set|get and a room ID."
  246. return
  247. if args["action"].lower() not in ["set", "get"]:
  248. print "Must specify set|get, not %s" % args["action"]
  249. return
  250. path = "/rooms/%s/topic" % urllib.quote(args["roomid"])
  251. if args["action"].lower() == "set":
  252. if "topic" not in args:
  253. print "Must specify a new topic."
  254. return
  255. body = {
  256. "topic": args["topic"]
  257. }
  258. reactor.callFromThread(self._run_and_pprint, "PUT", path, body)
  259. elif args["action"].lower() == "get":
  260. reactor.callFromThread(self._run_and_pprint, "GET", path)
  261. except Exception as e:
  262. print e
  263. def do_invite(self, line):
  264. """Invite a user to a room: "invite <userid> <roomid>" """
  265. try:
  266. args = self._parse(line, ["userid", "roomid"], force_keys=True)
  267. user_id = args["userid"]
  268. reactor.callFromThread(self._do_invite, args["roomid"], user_id)
  269. except Exception as e:
  270. print e
  271. @defer.inlineCallbacks
  272. def _do_invite(self, roomid, userstring):
  273. if (not userstring.startswith('@') and
  274. self._is_on("complete_usernames")):
  275. url = self._identityServerUrl()+"/matrix/identity/api/v1/lookup"
  276. json_res = yield self.http_client.do_request("GET", url, qparams={'medium':'email','address':userstring})
  277. mxid = None
  278. if 'mxid' in json_res and 'signatures' in json_res:
  279. url = self._identityServerUrl()+"/matrix/identity/api/v1/pubkey/ed25519"
  280. pubKey = None
  281. pubKeyObj = yield self.http_client.do_request("GET", url)
  282. if 'public_key' in pubKeyObj:
  283. pubKey = nacl.signing.VerifyKey(pubKeyObj['public_key'], encoder=nacl.encoding.HexEncoder)
  284. else:
  285. print "No public key found in pubkey response!"
  286. sigValid = False
  287. if pubKey:
  288. for signame in json_res['signatures']:
  289. if signame not in TRUSTED_ID_SERVERS:
  290. print "Ignoring signature from untrusted server %s" % (signame)
  291. else:
  292. try:
  293. verify_signed_json(json_res, signame, pubKey)
  294. sigValid = True
  295. print "Mapping %s -> %s correctly signed by %s" % (userstring, json_res['mxid'], signame)
  296. break
  297. except SignatureVerifyException as e:
  298. print "Invalid signature from %s" % (signame)
  299. print e
  300. if sigValid:
  301. print "Resolved 3pid %s to %s" % (userstring, json_res['mxid'])
  302. mxid = json_res['mxid']
  303. else:
  304. print "Got association for %s but couldn't verify signature" % (userstring)
  305. if not mxid:
  306. mxid = "@" + userstring + ":" + self._domain()
  307. self._do_membership_change(roomid, "invite", mxid)
  308. def do_leave(self, line):
  309. """Leaves a room: "leave <roomid>" """
  310. try:
  311. args = self._parse(line, ["roomid"], force_keys=True)
  312. path = ("/rooms/%s/members/%s/state" %
  313. (urllib.quote(args["roomid"]), self._usr()))
  314. reactor.callFromThread(self._run_and_pprint, "DELETE", path)
  315. except Exception as e:
  316. print e
  317. def do_send(self, line):
  318. """Sends a message. "send <roomid> <body>" """
  319. args = self._parse(line, ["roomid", "body"])
  320. msg_id = "m%s" % int(time.time())
  321. path = "/rooms/%s/messages/%s/%s" % (urllib.quote(args["roomid"]),
  322. self._usr(),
  323. msg_id)
  324. body_json = {
  325. "msgtype": "m.text",
  326. "body": args["body"]
  327. }
  328. reactor.callFromThread(self._run_and_pprint, "PUT", path, body_json)
  329. def do_list(self, line):
  330. """List data about a room.
  331. "list members <roomid> [query]" - List all the members in this room.
  332. "list messages <roomid> [query]" - List all the messages in this room.
  333. Where [query] will be directly applied as query parameters, allowing
  334. you to use the pagination API. E.g. the last 3 messages in this room:
  335. "list messages <roomid> from=END&to=START&limit=3"
  336. """
  337. args = self._parse(line, ["type", "roomid", "qp"])
  338. if not "type" in args or not "roomid" in args:
  339. print "Must specify type and room ID."
  340. return
  341. if args["type"] not in ["members", "messages"]:
  342. print "Unrecognised type: %s" % args["type"]
  343. return
  344. room_id = args["roomid"]
  345. path = "/rooms/%s/%s/list" % (urllib.quote(room_id), args["type"])
  346. qp = {"access_token": self._tok()}
  347. if "qp" in args:
  348. for key_value_str in args["qp"].split("&"):
  349. try:
  350. key_value = key_value_str.split("=")
  351. qp[key_value[0]] = key_value[1]
  352. except:
  353. print "Bad query param: %s" % key_value
  354. return
  355. reactor.callFromThread(self._run_and_pprint, "GET", path,
  356. query_params=qp)
  357. def do_create(self, line):
  358. """Creates a room.
  359. "create [public|private] <roomname>" - Create a room <roomname> with the
  360. specified visibility.
  361. "create <roomname>" - Create a room <roomname> with default visibility.
  362. "create [public|private]" - Create a room with specified visibility.
  363. "create" - Create a room with default visibility.
  364. """
  365. args = self._parse(line, ["vis", "roomname"])
  366. # fixup args depending on which were set
  367. body = {}
  368. if "vis" in args and args["vis"] in ["public", "private"]:
  369. body["visibility"] = args["vis"]
  370. if "roomname" in args:
  371. room_name = args["roomname"]
  372. body["room_alias_name"] = room_name
  373. elif "vis" in args and args["vis"] not in ["public", "private"]:
  374. room_name = args["vis"]
  375. body["room_alias_name"] = room_name
  376. reactor.callFromThread(self._run_and_pprint, "POST", "/rooms", body)
  377. def do_raw(self, line):
  378. """Directly send a JSON object: "raw <method> <path> <data> <notoken>"
  379. <method>: Required. One of "PUT", "GET", "POST", "xPUT", "xGET",
  380. "xPOST". Methods with 'x' prefixed will not automatically append the
  381. access token.
  382. <path>: Required. E.g. "/events"
  383. <data>: Optional. E.g. "{ "msgtype":"custom.text", "body":"abc123"}"
  384. """
  385. args = self._parse(line, ["method", "path", "data"])
  386. # sanity check
  387. if "method" not in args or "path" not in args:
  388. print "Must specify path and method."
  389. return
  390. args["method"] = args["method"].upper()
  391. valid_methods = ["PUT", "GET", "POST", "DELETE",
  392. "XPUT", "XGET", "XPOST", "XDELETE"]
  393. if args["method"] not in valid_methods:
  394. print "Unsupported method: %s" % args["method"]
  395. return
  396. if "data" not in args:
  397. args["data"] = None
  398. else:
  399. try:
  400. args["data"] = json.loads(args["data"])
  401. except Exception as e:
  402. print "Data is not valid JSON. %s" % e
  403. return
  404. qp = {"access_token": self._tok()}
  405. if args["method"].startswith("X"):
  406. qp = {} # remove access token
  407. args["method"] = args["method"][1:] # snip the X
  408. else:
  409. # append any query params the user has set
  410. try:
  411. parsed_url = urlparse.urlparse(args["path"])
  412. qp.update(urlparse.parse_qs(parsed_url.query))
  413. args["path"] = parsed_url.path
  414. except:
  415. pass
  416. reactor.callFromThread(self._run_and_pprint, args["method"],
  417. args["path"],
  418. args["data"],
  419. query_params=qp)
  420. def do_stream(self, line):
  421. """Stream data from the server: "stream <longpoll timeout ms>" """
  422. args = self._parse(line, ["timeout"])
  423. timeout = 5000
  424. if "timeout" in args:
  425. try:
  426. timeout = int(args["timeout"])
  427. except ValueError:
  428. print "Timeout must be in milliseconds."
  429. return
  430. reactor.callFromThread(self._do_event_stream, timeout)
  431. @defer.inlineCallbacks
  432. def _do_event_stream(self, timeout):
  433. res = yield self.http_client.get_json(
  434. self._url() + "/events",
  435. {
  436. "access_token": self._tok(),
  437. "timeout": str(timeout),
  438. "from": self.event_stream_token
  439. })
  440. print json.dumps(res, indent=4)
  441. if "chunk" in res:
  442. for event in res["chunk"]:
  443. if (event["type"] == "m.room.message" and
  444. self._is_on("send_delivery_receipts") and
  445. event["user_id"] != self._usr()): # not sent by us
  446. self._send_receipt(event, "d")
  447. # update the position in the stram
  448. if "end" in res:
  449. self.event_stream_token = res["end"]
  450. def _send_receipt(self, event, feedback_type):
  451. path = ("/rooms/%s/messages/%s/%s/feedback/%s/%s" %
  452. (urllib.quote(event["room_id"]), event["user_id"], event["msg_id"],
  453. self._usr(), feedback_type))
  454. data = {}
  455. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data,
  456. alt_text="Sent receipt for %s" % event["msg_id"])
  457. def _do_membership_change(self, roomid, membership, userid):
  458. path = "/rooms/%s/members/%s/state" % (urllib.quote(roomid), userid)
  459. data = {
  460. "membership": membership
  461. }
  462. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  463. def do_displayname(self, line):
  464. """Get or set my displayname: "displayname [new_name]" """
  465. args = self._parse(line, ["name"])
  466. path = "/profile/%s/displayname" % (self.config["user"])
  467. if "name" in args:
  468. data = {"displayname": args["name"]}
  469. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  470. else:
  471. reactor.callFromThread(self._run_and_pprint, "GET", path)
  472. def _do_presence_state(self, state, line):
  473. args = self._parse(line, ["msgstring"])
  474. path = "/presence/%s/status" % (self.config["user"])
  475. data = {"state": state}
  476. if "msgstring" in args:
  477. data["status_msg"] = args["msgstring"]
  478. reactor.callFromThread(self._run_and_pprint, "PUT", path, data=data)
  479. def do_offline(self, line):
  480. """Set my presence state to OFFLINE"""
  481. self._do_presence_state(0, line)
  482. def do_away(self, line):
  483. """Set my presence state to AWAY"""
  484. self._do_presence_state(1, line)
  485. def do_online(self, line):
  486. """Set my presence state to ONLINE"""
  487. self._do_presence_state(2, line)
  488. def _parse(self, line, keys, force_keys=False):
  489. """ Parses the given line.
  490. Args:
  491. line : The line to parse
  492. keys : A list of keys to map onto the args
  493. force_keys : True to enforce that the line has a value for every key
  494. Returns:
  495. A dict of key:arg
  496. """
  497. line_args = shlex.split(line)
  498. if force_keys and len(line_args) != len(keys):
  499. raise IndexError("Must specify all args: %s" % keys)
  500. # do $ substitutions
  501. for i, arg in enumerate(line_args):
  502. for config_key in self.config:
  503. if ("$" + config_key) in arg:
  504. arg = arg.replace("$" + config_key,
  505. self.config[config_key])
  506. line_args[i] = arg
  507. return dict(zip(keys, line_args))
  508. @defer.inlineCallbacks
  509. def _run_and_pprint(self, method, path, data=None,
  510. query_params={"access_token": None}, alt_text=None):
  511. """ Runs an HTTP request and pretty prints the output.
  512. Args:
  513. method: HTTP method
  514. path: Relative path
  515. data: Raw JSON data if any
  516. query_params: dict of query parameters to add to the url
  517. """
  518. url = self._url() + path
  519. if "access_token" in query_params:
  520. query_params["access_token"] = self._tok()
  521. json_res = yield self.http_client.do_request(method, url,
  522. data=data,
  523. qparams=query_params)
  524. if alt_text:
  525. print alt_text
  526. else:
  527. print json.dumps(json_res, indent=4)
  528. def save_config(config):
  529. with open(CONFIG_JSON, 'w') as out:
  530. json.dump(config, out)
  531. def main(server_url, identity_server_url, username, token, config_path):
  532. print "Synapse command line client"
  533. print "==========================="
  534. print "Server: %s" % server_url
  535. print "Type 'help' to get started."
  536. print "Close this console with CTRL+C then CTRL+D."
  537. if not username or not token:
  538. print "- 'register <username>' - Register an account"
  539. print "- 'stream' - Connect to the event stream"
  540. print "- 'create <roomid>' - Create a room"
  541. print "- 'send <roomid> <message>' - Send a message"
  542. http_client = TwistedHttpClient()
  543. # the command line client
  544. syn_cmd = SynapseCmd(http_client, server_url, identity_server_url, username, token)
  545. # load synapse.json config from a previous session
  546. global CONFIG_JSON
  547. CONFIG_JSON = config_path # bit cheeky, but just overwrite the global
  548. try:
  549. with open(config_path, 'r') as config:
  550. syn_cmd.config = json.load(config)
  551. try:
  552. http_client.verbose = "on" == syn_cmd.config["verbose"]
  553. except:
  554. pass
  555. print "Loaded config from %s" % config_path
  556. except:
  557. pass
  558. # Twisted-specific: Runs the command processor in Twisted's event loop
  559. # to maintain a single thread for both commands and event processing.
  560. # If using another HTTP client, just call syn_cmd.cmdloop()
  561. reactor.callInThread(syn_cmd.cmdloop)
  562. reactor.run()
  563. if __name__ == '__main__':
  564. parser = argparse.ArgumentParser("Starts a synapse client.")
  565. parser.add_argument(
  566. "-s", "--server", dest="server", default="http://localhost:8080",
  567. help="The URL of the home server to talk to.")
  568. parser.add_argument(
  569. "-i", "--identity-server", dest="identityserver", default="http://localhost:8090",
  570. help="The URL of the identity server to talk to.")
  571. parser.add_argument(
  572. "-u", "--username", dest="username",
  573. help="Your username on the server.")
  574. parser.add_argument(
  575. "-t", "--token", dest="token",
  576. help="Your access token.")
  577. parser.add_argument(
  578. "-c", "--config", dest="config", default=CONFIG_JSON,
  579. help="The location of the config.json file to read from.")
  580. args = parser.parse_args()
  581. if not args.server:
  582. print "You must supply a server URL to communicate with."
  583. parser.print_help()
  584. sys.exit(1)
  585. server = args.server
  586. if not server.startswith("http://"):
  587. server = "http://" + args.server
  588. main(server, args.identityserver, args.username, args.token, args.config)