XmppPlugin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2009, StatusNet, Inc.
  5. *
  6. * Send and receive notices using the XMPP network
  7. *
  8. * PHP version 7
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @category IM
  24. * @package StatusNet
  25. * @author Evan Prodromou <evan@status.net>
  26. * @copyright 2009 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('STATUSNET')) {
  31. // This check helps protect against security problems;
  32. // your code file can't be executed directly from the web.
  33. exit(1);
  34. }
  35. /**
  36. * Plugin for XMPP
  37. *
  38. * @category Plugin
  39. * @package StatusNet
  40. * @author Evan Prodromou <evan@status.net>
  41. * @copyright 2009 StatusNet, Inc.
  42. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  43. * @link http://status.net/
  44. */
  45. class XmppPlugin extends ImPlugin
  46. {
  47. public $server = null;
  48. public $port = 5222;
  49. public $user = 'update';
  50. public $resource = 'gnusocial';
  51. public $encryption = true;
  52. public $password = null;
  53. public $host = null; // only set if != server
  54. public $debug = false; // print extra debug info
  55. public $transport = 'xmpp';
  56. function getDisplayName()
  57. {
  58. // TRANS: Plugin display name.
  59. return _m('XMPP/Jabber');
  60. }
  61. function daemonScreenname()
  62. {
  63. $ret = $this->user . '@' . $this->server;
  64. if ($this->resource) {
  65. return $ret . '/' . $this->resource;
  66. } else {
  67. return $ret;
  68. }
  69. }
  70. function validate($screenname)
  71. {
  72. return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
  73. }
  74. /**
  75. * Checks whether a string is a syntactically valid base Jabber ID (JID).
  76. * A base JID won't include a resource specifier on the end; since we
  77. * take it off when reading input we can't really use them reliably
  78. * to direct outgoing messages yet (sorry guys!)
  79. *
  80. * Note that a bare domain can be a valid JID.
  81. *
  82. * @param string $jid string to check
  83. * @param bool $check_domain whether we should validate that domain...
  84. *
  85. * @return boolean whether the string is a valid JID
  86. */
  87. protected function validateBaseJid($jid, $check_domain = false)
  88. {
  89. try {
  90. $parts = $this->splitJid($jid);
  91. if ($check_domain) {
  92. if (!$this->checkDomain($parts['domain'])) {
  93. return false;
  94. }
  95. }
  96. return ($parts['resource'] === null); // missing; empty ain't kosher
  97. } catch (Exception $e) {
  98. return false;
  99. }
  100. }
  101. /**
  102. * Splits a Jabber ID (JID) into node, domain, and resource portions.
  103. *
  104. * Based on validation routine submitted by:
  105. * @param string $jid string to check
  106. *
  107. * @return array with "node", "domain", and "resource" indices
  108. * @throws Exception if input is not valid
  109. * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact.
  110. *
  111. * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
  112. */
  113. protected function splitJid($jid)
  114. {
  115. $chars = '';
  116. /* the following definitions come from stringprep, Appendix C,
  117. which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */
  118. /* C1.1 ASCII space characters */
  119. $chars .= "\x{20}";
  120. /* C1.2 Non-ASCII space characters */
  121. $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}";
  122. /* C2.1 ASCII control characters */
  123. $chars .= "\x{00}-\x{1f}\x{7f}";
  124. /* C2.2 Non-ASCII control characters */
  125. $chars .= "\x{80}-\x{9f}\x{6dd}\x{70f}\x{180e}\x{200c}\x{200d}\x{2028}\x{2029}\x{2060}-\x{2063}\x{206a}-\x{206f}\x{feff}\x{fff9}-\x{fffc}\x{1d173}-\x{1d17a}";
  126. /* C3 - Private Use */
  127. $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}";
  128. /* C4 - Non-character code points */
  129. $chars .= "\x{fdd0}-\x{fdef}\x{fffe}\x{ffff}\x{1fffe}\x{1ffff}\x{2fffe}\x{2ffff}\x{3fffe}\x{3ffff}\x{4fffe}\x{4ffff}\x{5fffe}\x{5ffff}\x{6fffe}\x{6ffff}\x{7fffe}\x{7ffff}\x{8fffe}\x{8ffff}\x{9fffe}\x{9ffff}\x{afffe}\x{affff}\x{bfffe}\x{bffff}\x{cfffe}\x{cffff}\x{dfffe}\x{dffff}\x{efffe}\x{effff}\x{ffffe}\x{fffff}\x{10fffe}\x{10ffff}";
  130. /* C5 - Surrogate codes */
  131. // We can't use preg_match to check this, fix below
  132. // $chars .= "\x{d800}-\x{dfff}";
  133. /* C6 - Inappropriate for plain text */
  134. $chars .= "\x{fff9}-\x{fffd}";
  135. /* C7 - Inappropriate for canonical representation */
  136. $chars .= "\x{2ff0}-\x{2ffb}";
  137. /* C8 - Change display properties or are deprecated */
  138. $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}";
  139. /* C9 - Tagging characters */
  140. $chars .= "\x{e0001}\x{e0020}-\x{e007f}";
  141. /* Nodeprep forbids some more characters */
  142. $nodeprepchars = $chars;
  143. $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}";
  144. $parts = explode("/", $jid, 2);
  145. if (count($parts) > 1) {
  146. $resource = $parts[1];
  147. // if ($resource == '') then
  148. // Warning: empty resource isn't legit.
  149. // But if we're normalizing, we may as well take it...
  150. } else {
  151. $resource = null;
  152. }
  153. $node = explode("@", $parts[0]);
  154. if ((count($node) > 2) || (count($node) == 0)) {
  155. // TRANS: Exception thrown when using too many @ signs in a Jabber ID.
  156. throw new Exception(_m('Invalid JID: too many @s.'));
  157. } else if (count($node) == 1) {
  158. $domain = $node[0];
  159. $node = null;
  160. } else {
  161. $domain = $node[1];
  162. $node = $node[0];
  163. if ($node == '') {
  164. // TRANS: Exception thrown when using @ sign not followed by a Jabber ID.
  165. throw new Exception(_m('Invalid JID: @ but no node'));
  166. }
  167. }
  168. if ($node !== null) {
  169. // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing
  170. if (strlen($node) > 1023) {
  171. // TRANS: Exception thrown when using too long a Jabber ID (>1023).
  172. throw new Exception(_m('Invalid JID: node too long.'));
  173. }
  174. // C5 - Surrogate codes is ensured by encoding check
  175. if (preg_match("/[" . $nodeprepchars . "]/u", $node) || mb_detect_encoding($node, 'UTF-8', true) != 'UTF-8') {
  176. // TRANS: Exception thrown when using an invalid Jabber ID.
  177. // TRANS: %s is the invalid Jabber ID.
  178. throw new Exception(sprintf(_m('Invalid JID node "%s".'), $node));
  179. }
  180. }
  181. if (strlen($domain) > 1023) {
  182. // TRANS: Exception thrown when using too long a Jabber domain (>1023).
  183. throw new Exception(_m('Invalid JID: domain too long.'));
  184. }
  185. if (!common_valid_domain($domain)) {
  186. // TRANS: Exception thrown when using an invalid Jabber domain name.
  187. // TRANS: %s is the invalid domain name.
  188. throw new Exception(sprintf(_m('Invalid JID domain name "%s".'), $domain));
  189. }
  190. if ($resource !== null) {
  191. if (strlen($resource) > 1023) {
  192. // TRANS: Exception thrown when using too long a resource (>1023).
  193. throw new Exception("Invalid JID: resource too long.");
  194. }
  195. if (preg_match("/[" . $chars . "]/u", $resource)) {
  196. // TRANS: Exception thrown when using an invalid Jabber resource.
  197. // TRANS: %s is the invalid resource.
  198. throw new Exception(sprintf(_m('Invalid JID resource "%s".'), $resource));
  199. }
  200. }
  201. return array('node' => is_null($node) ? null : mb_strtolower($node),
  202. 'domain' => is_null($domain) ? null : mb_strtolower($domain),
  203. 'resource' => $resource);
  204. }
  205. /**
  206. * Check if this domain's got some legit DNS record
  207. * @param $domain
  208. * @return bool
  209. */
  210. protected function checkDomain($domain)
  211. {
  212. if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
  213. return true;
  214. }
  215. if (checkdnsrr($domain, "ANY")) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. /**
  221. * Load related modules when needed
  222. *
  223. * @param string $cls Name of the class to be loaded
  224. *
  225. * @return boolean hook value; true means continue processing, false means stop.
  226. */
  227. function onAutoload($cls)
  228. {
  229. switch ($cls) {
  230. case 'XMPPHP_XMPP':
  231. require_once __DIR__ . '/extlib/XMPPHP/XMPP.php';
  232. return false;
  233. }
  234. return parent::onAutoload($cls);
  235. }
  236. function onStartImDaemonIoManagers(&$classes)
  237. {
  238. parent::onStartImDaemonIoManagers($classes);
  239. $classes[] = new XmppManager($this); // handles pings/reconnects
  240. return true;
  241. }
  242. function sendMessage($screenname, $body)
  243. {
  244. $this->queuedConnection()->message($screenname, $body, 'chat');
  245. }
  246. /**
  247. * Build a queue-proxied XMPP interface object. Any outgoing messages
  248. * will be run back through us for enqueing rather than sent directly.
  249. *
  250. * @return QueuedXMPP
  251. * @throws Exception if server settings are invalid.
  252. */
  253. function queuedConnection()
  254. {
  255. if (!isset($this->server)) {
  256. // TRANS: Exception thrown when the plugin configuration is incorrect.
  257. throw new Exception(_m('You must specify a server in the configuration.'));
  258. }
  259. if (!isset($this->port)) {
  260. // TRANS: Exception thrown when the plugin configuration is incorrect.
  261. throw new Exception(_m('You must specify a port in the configuration.'));
  262. }
  263. if (!isset($this->user)) {
  264. // TRANS: Exception thrown when the plugin configuration is incorrect.
  265. throw new Exception(_m('You must specify a user in the configuration.'));
  266. }
  267. if (!isset($this->password)) {
  268. // TRANS: Exception thrown when the plugin configuration is incorrect.
  269. throw new Exception(_m('You must specify a password in the configuration.'));
  270. }
  271. return new QueuedXMPP($this, $this->host ?
  272. $this->host :
  273. $this->server,
  274. $this->port,
  275. $this->user,
  276. $this->password,
  277. $this->resource,
  278. $this->server,
  279. $this->debug ?
  280. true : false,
  281. $this->debug ?
  282. \XMPPHP\Log::LEVEL_VERBOSE : null
  283. );
  284. }
  285. function sendNotice($screenname, Notice $notice)
  286. {
  287. try {
  288. $msg = $this->formatNotice($notice);
  289. $entry = $this->format_entry($notice);
  290. } catch (Exception $e) {
  291. common_log(LOG_ERR, __METHOD__ . ": Discarding outgoing stanza because of exception: {$e->getMessage()}");
  292. return false; // return value of sendNotice is never actually used as of now
  293. }
  294. $this->queuedConnection()->message($screenname, $msg, 'chat', null, $entry);
  295. return true;
  296. }
  297. /**
  298. * extra information for XMPP messages, as defined by Twitter
  299. *
  300. * @param Notice $notice Notice being sent
  301. *
  302. * @return string Extra information (Atom, HTML, addresses) in string format
  303. */
  304. protected function format_entry(Notice $notice)
  305. {
  306. $profile = $notice->getProfile();
  307. $entry = $notice->asAtomEntry(true, true);
  308. $xs = new XMLStringer();
  309. $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
  310. $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
  311. $xs->element('a', array('href' => $profile->profileurl), $profile->nickname);
  312. try {
  313. $parent = $notice->getParent();
  314. $orig_profile = $parent->getProfile();
  315. $orig_profurl = $orig_profile->getUrl();
  316. $xs->text(" => ");
  317. $xs->element('a', array('href' => $orig_profurl), $orig_profile->nickname);
  318. $xs->text(": ");
  319. } catch (NoParentNoticeException $e) {
  320. $xs->text(": ");
  321. }
  322. // FIXME: Why do we replace \t with ''? is it just to make it pretty? shouldn't whitespace be handled well...?
  323. $xs->raw(str_replace("\t", "", $notice->getRendered()));
  324. $xs->text(" ");
  325. $xs->element('a', array(
  326. 'href' => common_local_url('conversation',
  327. array('id' => $notice->conversation)) . '#notice-' . $notice->id),
  328. // TRANS: Link description to notice in conversation.
  329. // TRANS: %s is a notice ID.
  330. sprintf(_m('[%u]'), $notice->id));
  331. $xs->elementEnd('body');
  332. $xs->elementEnd('html');
  333. $html = $xs->getString();
  334. return $html . ' ' . $entry;
  335. }
  336. function receiveRawMessage($pl)
  337. {
  338. $from = $this->normalize($pl['from']);
  339. if ($pl['type'] != 'chat') {
  340. $this->log(LOG_WARNING, "Ignoring message of type " . $pl['type'] . " from $from: " . $pl['xml']->toString());
  341. return true;
  342. }
  343. if (mb_strlen($pl['body']) == 0) {
  344. $this->log(LOG_WARNING, "Ignoring message with empty body from $from: " . $pl['xml']->toString());
  345. return true;
  346. }
  347. $this->handleIncoming($from, $pl['body']);
  348. return true;
  349. }
  350. /**
  351. * Normalizes a Jabber ID for comparison, dropping the resource component if any.
  352. *
  353. * @param string $jid JID to check
  354. * @return string an equivalent JID in normalized (lowercase) form
  355. */
  356. function normalize($jid)
  357. {
  358. try {
  359. $parts = $this->splitJid($jid);
  360. if ($parts['node'] !== null) {
  361. return $parts['node'] . '@' . $parts['domain'];
  362. } else {
  363. return $parts['domain'];
  364. }
  365. } catch (Exception $e) {
  366. return null;
  367. }
  368. }
  369. /**
  370. * Add XMPP plugin daemon to the list of daemon to start
  371. *
  372. * @param array $daemons the list of daemons to run
  373. *
  374. * @return boolean hook return
  375. */
  376. function onGetValidDaemons(&$daemons)
  377. {
  378. if (isset($this->server) &&
  379. isset($this->port) &&
  380. isset($this->user) &&
  381. isset($this->password)) {
  382. array_push(
  383. $daemons,
  384. INSTALLDIR
  385. . '/scripts/imdaemon.php'
  386. );
  387. }
  388. return true;
  389. }
  390. /**
  391. * Plugin Nodeinfo information
  392. *
  393. * @param array $protocols
  394. * @return bool hook true
  395. */
  396. public function onNodeInfoProtocols(array &$protocols)
  397. {
  398. $protocols[] = "xmpp";
  399. return true;
  400. }
  401. function onPluginVersion(array &$versions)
  402. {
  403. $versions[] = array('name' => 'XMPP',
  404. 'version' => GNUSOCIAL_VERSION,
  405. 'author' => 'Craig Andrews, Evan Prodromou',
  406. 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/XMPP',
  407. 'rawdescription' =>
  408. // TRANS: Plugin description.
  409. _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.'));
  410. return true;
  411. }
  412. /**
  413. * Checks whether a string is a syntactically valid Jabber ID (JID),
  414. * either with or without a resource.
  415. *
  416. * Note that a bare domain can be a valid JID.
  417. *
  418. * @param string $jid string to check
  419. * @param bool $check_domain whether we should validate that domain...
  420. *
  421. * @return boolean whether the string is a valid JID
  422. */
  423. protected function validateFullJid($jid, $check_domain = false)
  424. {
  425. try {
  426. $parts = $this->splitJid($jid);
  427. if ($check_domain) {
  428. if (!$this->checkDomain($parts['domain'])) {
  429. return false;
  430. }
  431. }
  432. return $parts['resource'] !== ''; // missing or present; empty ain't kosher
  433. } catch (Exception $e) {
  434. return false;
  435. }
  436. }
  437. }