Remote.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. // Remote
  2. //
  3. // Douglas
  4. //
  5. // Remote.java
  6. /* Copyright 2011 Douglas Thrift
  7. *
  8. * This file is part of Big Screen Bot.
  9. *
  10. * Big Screen Bot is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU 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. * Big Screen Bot 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 General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with Big Screen Bot. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package net.douglasthrift.bigscreenbot;
  24. import java.io.Closeable;
  25. import java.io.FileInputStream;
  26. import java.io.FileNotFoundException;
  27. import java.io.FileOutputStream;
  28. import java.io.IOException;
  29. import java.net.InetAddress;
  30. import java.net.InetSocketAddress;
  31. import java.net.MalformedURLException;
  32. import java.net.UnknownHostException;
  33. import java.net.URL;
  34. import java.security.GeneralSecurityException;
  35. import java.security.KeyManagementException;
  36. import java.security.KeyPair;
  37. import java.security.KeyPairGenerator;
  38. import java.security.KeyStore;
  39. import java.security.KeyStoreException;
  40. import java.security.NoSuchAlgorithmException;
  41. import java.security.UnrecoverableKeyException;
  42. import java.security.cert.Certificate;
  43. import java.security.cert.CertificateException;
  44. import java.security.cert.X509Certificate;
  45. import java.util.ArrayList;
  46. import java.util.Collections;
  47. import java.util.HashMap;
  48. import java.util.List;
  49. import java.util.Map;
  50. import javax.jmdns.JmDNS;
  51. import javax.jmdns.ServiceInfo;
  52. import javax.net.ssl.SSLSocket;
  53. import javax.net.ssl.SSLSocketFactory;
  54. import javax.net.ssl.KeyManager;
  55. import javax.net.ssl.KeyManagerFactory;
  56. import com.google.anymote.common.AnymoteFactory;
  57. import com.google.anymote.common.ErrorListener;
  58. import com.google.anymote.device.DeviceAdapter;
  59. import com.google.anymote.device.MessageReceiver;
  60. import com.google.polo.exception.PoloException;
  61. import com.google.polo.pairing.ClientPairingSession;
  62. import com.google.polo.pairing.PairingContext;
  63. import com.google.polo.pairing.PairingListener;
  64. import com.google.polo.pairing.PairingSession;
  65. import com.google.polo.pairing.message.EncodingOption;
  66. import com.google.polo.ssl.DummySSLSocketFactory;
  67. import com.google.polo.ssl.SslUtil;
  68. import com.google.polo.wire.WireFormat;
  69. public class Remote implements Closeable
  70. {
  71. private static final String STORE = "bigscreenbot.keystore";
  72. private static final char[] PASSWORD = "b1GsSC33Nb0T".toCharArray();
  73. private static final char[] NULL = new char[]{};
  74. private static final String TYPE = "_anymote._tcp.local.";
  75. private static final String LOCAL_ALIAS = "anymote-remote";
  76. private static final String REMOTE_ALIAS = "anymote-server-%1$X";
  77. private static class Secret
  78. {
  79. private String secret;
  80. private Thread thread;
  81. public Secret()
  82. {
  83. thread = Thread.currentThread();
  84. }
  85. public synchronized void set(String secret)
  86. {
  87. this.secret = secret;
  88. notify();
  89. }
  90. public synchronized String get() throws InterruptedException
  91. {
  92. while (secret == null)
  93. wait();
  94. return secret;
  95. }
  96. public void interrupt()
  97. {
  98. thread.interrupt();
  99. }
  100. }
  101. static
  102. {
  103. new Fixer();
  104. }
  105. private boolean verbose;
  106. private Settings settings;
  107. private JmDNS mdns;
  108. private KeyStore store;
  109. private SSLSocketFactory factory;
  110. private Map<InetSocketAddress, Secret> secrets = Collections.synchronizedMap(new HashMap<InetSocketAddress, Secret>());
  111. public Remote(boolean verbose, Settings settings) throws UnknownHostException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, GeneralSecurityException
  112. {
  113. this.verbose = verbose;
  114. this.settings = settings;
  115. String interfaze = settings.getProperty("interface");
  116. if (interfaze != null)
  117. mdns = JmDNS.create(InetAddress.getByName(interfaze));
  118. else
  119. mdns = JmDNS.create();
  120. store = KeyStore.getInstance(KeyStore.getDefaultType());
  121. FileInputStream stream = null;
  122. try
  123. {
  124. stream = new FileInputStream(STORE);
  125. store.load(stream, PASSWORD);
  126. }
  127. catch (FileNotFoundException exception)
  128. {
  129. store.load(null, PASSWORD);
  130. }
  131. finally
  132. {
  133. if (stream != null)
  134. stream.close();
  135. }
  136. if (!store.containsAlias(LOCAL_ALIAS))
  137. {
  138. KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  139. KeyPair pair = generator.generateKeyPair();
  140. X509Certificate certificate = SslUtil.generateX509V3Certificate(pair, "CN=anymote/bigscreenbot/" + System.getProperty("os.name") + "/" + System.getProperty("os.arch") + "/" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName());
  141. store.setKeyEntry(LOCAL_ALIAS, pair.getPrivate(), NULL, new Certificate[]{ certificate });
  142. store();
  143. }
  144. KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  145. factory.init(store, NULL);
  146. this.factory = DummySSLSocketFactory.fromKeyManagers(factory.getKeyManagers());
  147. }
  148. @Override
  149. public void close() throws IOException
  150. {
  151. mdns.close();
  152. }
  153. public List<String> listDevices()
  154. {
  155. List<String> devices = new ArrayList<String>();
  156. for (ServiceInfo info : mdns.list(TYPE))
  157. devices.add(info.getName());
  158. return devices;
  159. }
  160. public boolean startPairDevice(String device, final Runnable runnable) throws MalformedURLException, UnknownHostException, IOException, PoloException, KeyStoreException, NoSuchAlgorithmException, CertificateException
  161. {
  162. SSLSocket socket = (SSLSocket)factory.createSocket();
  163. final InetSocketAddress address = getDevice(device);
  164. socket.connect(address);
  165. PairingContext context = PairingContext.fromSslSocket(socket, false);
  166. ClientPairingSession session = new ClientPairingSession(WireFormat.PROTOCOL_BUFFERS.getWireInterface(context), context, "AnyMote", "Big Screen Bot");
  167. EncodingOption option = new EncodingOption(EncodingOption.EncodingType.ENCODING_HEXADECIMAL, 4);
  168. session.addInputEncoding(option);
  169. session.addOutputEncoding(option);
  170. if (session.doPair(new PairingListener()
  171. {
  172. @Override
  173. public void onLogMessage(LogLevel level, String message)
  174. {
  175. if (verbose)
  176. System.out.println(level + ": " + message);
  177. }
  178. @Override
  179. public void onPerformInputDeviceRole(PairingSession session)
  180. {
  181. runnable.run();
  182. Secret secret = new Secret(), oldSecret = secrets.put(address, secret);
  183. if (oldSecret != null)
  184. oldSecret.interrupt();
  185. try
  186. {
  187. session.setSecret(session.getEncoder().decodeToBytes(secret.get()));
  188. }
  189. catch (InterruptedException exception)
  190. {
  191. session.teardown();
  192. }
  193. }
  194. @Override
  195. public void onPerformOutputDeviceRole(PairingSession session, byte[] gamma) throws PoloException
  196. {
  197. throw new PoloException("This should not happen!");
  198. }
  199. @Override
  200. public void onSessionCreated(PairingSession session)
  201. {
  202. if (verbose)
  203. System.out.println(session + " created.");
  204. }
  205. @Override
  206. public void onSessionEnded(PairingSession session)
  207. {
  208. if (verbose)
  209. System.out.println(session + " ended.");
  210. }
  211. }))
  212. {
  213. synchronized (store)
  214. {
  215. Certificate certificate = context.getServerCertificate();
  216. String alias = String.format(REMOTE_ALIAS, certificate.hashCode());
  217. if (store.containsAlias(alias))
  218. store.deleteEntry(alias);
  219. store.setCertificateEntry(alias, certificate);
  220. store();
  221. }
  222. return true;
  223. }
  224. else
  225. return false;
  226. }
  227. public boolean finishPairDevice(String device, String code) throws MalformedURLException
  228. {
  229. Secret secret = secrets.remove(getDevice(device));
  230. if (secret != null)
  231. secret.set(code);
  232. else
  233. return false;
  234. return true;
  235. }
  236. public void fling(String url)
  237. {
  238. }
  239. public void fling(String device, String url)
  240. {
  241. }
  242. private InetSocketAddress getDevice(String device) throws MalformedURLException
  243. {
  244. ServiceInfo info = mdns.getServiceInfo(TYPE, device);
  245. if (info != null)
  246. return new InetSocketAddress(info.getInetAddresses()[0], info.getPort());
  247. else
  248. {
  249. URL url = new URL("http://" + device);
  250. int port = url.getPort();
  251. return new InetSocketAddress(url.getHost(), port == -1 ? 9551 : port);
  252. }
  253. }
  254. private void store() throws FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException
  255. {
  256. FileOutputStream stream = null;
  257. try
  258. {
  259. stream = new FileOutputStream(STORE);
  260. store.store(stream, PASSWORD);
  261. }
  262. finally
  263. {
  264. if (stream != null)
  265. stream.close();
  266. }
  267. }
  268. }
  269. // vim: expandtab