Remote.java 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. public static interface Pairing
  72. {
  73. public void prompt();
  74. public void interrupted(InterruptedException exception);
  75. }
  76. private static final String STORE = "bigscreenbot.keystore";
  77. private static final char[] PASSWORD = "b1GsSC33Nb0T".toCharArray();
  78. private static final char[] NULL = new char[]{};
  79. private static final String TYPE = "_anymote._tcp.local.";
  80. private static final String LOCAL_ALIAS = "anymote-remote";
  81. private static final String REMOTE_ALIAS = "anymote-server-%1$X";
  82. private static class Secret
  83. {
  84. private String secret;
  85. private Thread thread;
  86. public Secret()
  87. {
  88. thread = Thread.currentThread();
  89. }
  90. public synchronized void set(String secret)
  91. {
  92. this.secret = secret;
  93. notify();
  94. }
  95. public synchronized String get() throws InterruptedException
  96. {
  97. while (secret == null)
  98. wait();
  99. return secret;
  100. }
  101. public void interrupt()
  102. {
  103. thread.interrupt();
  104. }
  105. }
  106. static
  107. {
  108. new Fixer();
  109. }
  110. private boolean verbose;
  111. private Settings settings;
  112. private JmDNS mdns;
  113. private KeyStore store;
  114. private SSLSocketFactory factory;
  115. private Map<InetSocketAddress, Secret> secrets = Collections.synchronizedMap(new HashMap<InetSocketAddress, Secret>());
  116. public Remote(boolean verbose, Settings settings) throws UnknownHostException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, GeneralSecurityException
  117. {
  118. this.verbose = verbose;
  119. this.settings = settings;
  120. String interfaze = settings.getProperty("interface");
  121. if (interfaze != null)
  122. mdns = JmDNS.create(InetAddress.getByName(interfaze));
  123. else
  124. mdns = JmDNS.create();
  125. store = KeyStore.getInstance(KeyStore.getDefaultType());
  126. FileInputStream stream = null;
  127. try
  128. {
  129. stream = new FileInputStream(STORE);
  130. store.load(stream, PASSWORD);
  131. }
  132. catch (FileNotFoundException exception)
  133. {
  134. store.load(null, PASSWORD);
  135. }
  136. finally
  137. {
  138. if (stream != null)
  139. stream.close();
  140. }
  141. if (!store.containsAlias(LOCAL_ALIAS))
  142. {
  143. KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
  144. KeyPair pair = generator.generateKeyPair();
  145. X509Certificate certificate = SslUtil.generateX509V3Certificate(pair, "CN=anymote/bigscreenbot/" + System.getProperty("os.name") + "/" + System.getProperty("os.arch") + "/" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName());
  146. store.setKeyEntry(LOCAL_ALIAS, pair.getPrivate(), NULL, new Certificate[]{ certificate });
  147. store();
  148. }
  149. KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  150. factory.init(store, NULL);
  151. this.factory = DummySSLSocketFactory.fromKeyManagers(factory.getKeyManagers());
  152. }
  153. @Override
  154. public void close() throws IOException
  155. {
  156. mdns.close();
  157. }
  158. public List<String> listDevices()
  159. {
  160. List<String> devices = new ArrayList<String>();
  161. for (ServiceInfo info : mdns.list(TYPE))
  162. devices.add(info.getName());
  163. return devices;
  164. }
  165. public boolean startPairDevice(String device, final Pairing pairing) throws MalformedURLException, UnknownHostException, IOException, PoloException
  166. {
  167. SSLSocket socket = (SSLSocket)factory.createSocket();
  168. final InetSocketAddress address = getDevice(device);
  169. socket.connect(address);
  170. PairingContext context = PairingContext.fromSslSocket(socket, false);
  171. ClientPairingSession session = new ClientPairingSession(WireFormat.PROTOCOL_BUFFERS.getWireInterface(context), context, "AnyMote", "Big Screen Bot");
  172. EncodingOption option = new EncodingOption(EncodingOption.EncodingType.ENCODING_HEXADECIMAL, 4);
  173. session.addInputEncoding(option);
  174. session.addOutputEncoding(option);
  175. return session.doPair(new PairingListener()
  176. {
  177. @Override
  178. public void onLogMessage(LogLevel level, String message)
  179. {
  180. if (verbose)
  181. System.out.println(level + ": " + message);
  182. }
  183. @Override
  184. public void onPerformInputDeviceRole(PairingSession session)
  185. {
  186. pairing.prompt();
  187. Secret secret = new Secret(), oldSecret = secrets.put(address, secret);
  188. if (oldSecret != null)
  189. oldSecret.interrupt();
  190. try
  191. {
  192. session.setSecret(session.getEncoder().decodeToBytes(secret.get()));
  193. }
  194. catch (InterruptedException exception)
  195. {
  196. session.teardown();
  197. pairing.interrupted(exception);
  198. }
  199. }
  200. @Override
  201. public void onPerformOutputDeviceRole(PairingSession session, byte[] gamma) throws PoloException
  202. {
  203. throw new PoloException("This should not happen!");
  204. }
  205. @Override
  206. public void onSessionCreated(PairingSession session)
  207. {
  208. if (verbose)
  209. System.out.println(session + " created.");
  210. }
  211. @Override
  212. public void onSessionEnded(PairingSession session)
  213. {
  214. if (verbose)
  215. System.out.println(session + " ended.");
  216. }
  217. });
  218. // TODO: store server certificate
  219. }
  220. public boolean finishPairDevice(String device, String code) throws MalformedURLException
  221. {
  222. Secret secret = secrets.remove(getDevice(device));
  223. if (secret != null)
  224. secret.set(code);
  225. else
  226. return false;
  227. return true;
  228. }
  229. public void fling(String url)
  230. {
  231. }
  232. public void fling(String device, String url)
  233. {
  234. }
  235. private InetSocketAddress getDevice(String device) throws MalformedURLException
  236. {
  237. ServiceInfo info = mdns.getServiceInfo(TYPE, device);
  238. if (info != null)
  239. return new InetSocketAddress(info.getInetAddresses()[0], info.getPort());
  240. else
  241. {
  242. URL url = new URL("http://" + device);
  243. int port = url.getPort();
  244. return new InetSocketAddress(url.getHost(), port == -1 ? 9551 : port);
  245. }
  246. }
  247. private void store() throws FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException
  248. {
  249. FileOutputStream stream = null;
  250. try
  251. {
  252. stream = new FileOutputStream(STORE);
  253. store.store(stream, PASSWORD);
  254. }
  255. finally
  256. {
  257. if (stream != null)
  258. stream.close();
  259. }
  260. }
  261. }
  262. // vim: expandtab