List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java
public void accept(MsgContext ep) throws IOException { if (sSocket == null) { return;// w w w . ja va2s . c om } synchronized (this) { while (paused) { try { wait(); } catch (InterruptedException ie) { //Ignore, since can't happen } } } Socket s = sSocket.accept(); ep.setNote(socketNote, s); if (LoggerUtils.getLogger().isLoggable(Level.FINEST)) { LoggerUtils.getLogger().log(Level.FINEST, "Accepted socket " + s); } try { setSocketOptions(s); } catch (SocketException sex) { LoggerUtils.getLogger().log(Level.FINEST, "Error initializing Socket Options", sex); } requestCount++; InputStream is = new BufferedInputStream(s.getInputStream()); OutputStream os; if (bufferSize > 0) { os = new BufferedOutputStream(s.getOutputStream(), bufferSize); } else { os = s.getOutputStream(); } ep.setNote(isNote, is); ep.setNote(osNote, os); ep.setControl(tp); }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
/** * Completes the OAuth 1.0a authorization steps with SoundCloud, assuming the consumer application * can use a local port to receive the verification code. * /*from w ww . j a v a 2s . c o m*/ * <p>The function acts as a minimal HTTP server and will listen on the port specified in the * <code>url</code> (or the default HTTP port, if no port is specified in the <code>url</code>). It will provide the * specified <code>response</code> when it receives a request for the path specified in the <code>url</code>, and * assuming the request includes the verification code, terminate successfully. * To all other requests it will respond with a <code>Not Found</code> error, and continue listening. * * <p>The following example assumes the consumer application is running on the client's computer / device. * Hence, it uses a local URL ("http://localhost:8088/") to receive the verification code callback. The function * will listen on specified port 8088 to receive the callback.</p> * * <pre> * {@code * soundcloudapi.authorizeUsingUrl * ( * "http://localhost:8088/", * "Thank you for authorizing", * new AuthorizationURLOpener() * { * public void openAuthorizationURL(String authorizationURL) * { * System.out.println("Please visit " + authorizationURL); * } * } * ); * } * </pre> * * @param url - a callback URL via which the user can provide the verification code. * @param response - a response given back to the user when they allow access and get redirected to the callback URL. * @param URLOpener - an AuthorizationURLOpener which can open the authorization URL to the user when needed. * * @return true if the process is completed successfully, false if the process was canceled via <code>cancelAuthorizeUsingUrl</code>. * * @throws OAuthCommunicationException * @throws OAuthExpectationFailedException * @throws OAuthNotAuthorizedException * @throws OAuthMessageSignerException * @throws IOException * @since 0.9.1 * @see #cancelAuthorizeUsingUrl() */ public boolean authorizeUsingUrl(final String url, final String response, final AuthorizationURLOpener URLOpener) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { mCancelAuthorization = false; unauthorize(); URLOpener.openAuthorizationURL(obtainRequestToken(url)); URL parsedUrl = new URL(url); int port = parsedUrl.getPort(); if (port == -1) port = parsedUrl.getDefaultPort(); ServerSocket server = null; String verificationCode = null; try { server = new ServerSocket(port); server.setSoTimeout(500); while (verificationCode == null) { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { try { socket = server.accept(); } catch (java.io.InterruptedIOException e) { if (mCancelAuthorization) { unauthorize(); return false; } else continue; } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String requestedUrl = in.readLine().split("\\s+")[1]; URL parsedRequestedUrl = new URL("http://localhost" + requestedUrl); out = new PrintWriter(socket.getOutputStream(), true); if (!parsedRequestedUrl.getPath().equals(parsedUrl.getPath())) out.print("HTTP/1.1 404 Not Found"); else { out.print("HTTP/1.1 200 OK\n\n" + response); for (String parameter : parsedRequestedUrl.getQuery().split("&")) { String[] keyValue = parameter.split("="); if (keyValue[0].equals("oauth_verifier")) verificationCode = keyValue[1]; } if (verificationCode == null) // problem - why didn't we get a verification code? verificationCode = ""; } out.flush(); } finally { closeQuietly(in); closeQuietly(out); closeQuietly(socket); } } } finally { closeQuietly(server); } if (verificationCode.length() > 0) { obtainAccessToken(verificationCode); return true; } else return false; }
From source file:org.apache.hadoop.hive.llap.LlapBaseInputFormat.java
@SuppressWarnings("unchecked") @Override/*from ww w .ja v a 2s .co m*/ public RecordReader<NullWritable, V> getRecordReader(InputSplit split, JobConf job, Reporter reporter) throws IOException { LlapInputSplit llapSplit = (LlapInputSplit) split; // Set conf to use LLAP user rather than current user for LLAP Zk registry. HiveConf.setVar(job, HiveConf.ConfVars.LLAP_ZK_REGISTRY_USER, llapSplit.getLlapUser()); SubmitWorkInfo submitWorkInfo = SubmitWorkInfo.fromBytes(llapSplit.getPlanBytes()); ServiceInstance serviceInstance = getServiceInstance(job, llapSplit); String host = serviceInstance.getHost(); int llapSubmitPort = serviceInstance.getRpcPort(); LOG.info("Found service instance for host " + host + " with rpc port " + llapSubmitPort + " and outputformat port " + serviceInstance.getOutputFormatPort()); byte[] llapTokenBytes = llapSplit.getTokenBytes(); Token<LlapTokenIdentifier> llapToken = null; if (llapTokenBytes != null) { DataInputBuffer in = new DataInputBuffer(); in.reset(llapTokenBytes, 0, llapTokenBytes.length); llapToken = new Token<LlapTokenIdentifier>(); llapToken.readFields(in); } LlapRecordReaderTaskUmbilicalExternalResponder umbilicalResponder = new LlapRecordReaderTaskUmbilicalExternalResponder(); LlapTaskUmbilicalExternalClient llapClient = new LlapTaskUmbilicalExternalClient(job, submitWorkInfo.getTokenIdentifier(), submitWorkInfo.getToken(), umbilicalResponder, llapToken); int attemptNum = 0; // Use task attempt number from conf if provided TaskAttemptID taskAttemptId = TaskAttemptID.forName(job.get(MRJobConfig.TASK_ATTEMPT_ID)); if (taskAttemptId != null) { attemptNum = taskAttemptId.getId(); if (LOG.isDebugEnabled()) { LOG.debug("Setting attempt number to " + attemptNum + " from task attempt ID in conf: " + job.get(MRJobConfig.TASK_ATTEMPT_ID)); } } SubmitWorkRequestProto request = constructSubmitWorkRequestProto(submitWorkInfo, llapSplit.getSplitNum(), attemptNum, llapClient.getAddress(), submitWorkInfo.getToken(), llapSplit.getFragmentBytes(), llapSplit.getFragmentBytesSignature(), job); llapClient.submitWork(request, host, llapSubmitPort); Socket socket = new Socket(host, serviceInstance.getOutputFormatPort()); LOG.debug("Socket connected"); SignableVertexSpec vertex = SignableVertexSpec.parseFrom(submitWorkInfo.getVertexBinary()); String fragmentId = Converters.createTaskAttemptId(vertex.getQueryIdentifier(), vertex.getVertexIndex(), request.getFragmentNumber(), request.getAttemptNumber()).toString(); OutputStream socketStream = socket.getOutputStream(); LlapOutputSocketInitMessage.Builder builder = LlapOutputSocketInitMessage.newBuilder() .setFragmentId(fragmentId); if (llapSplit.getTokenBytes() != null) { builder.setToken(ByteString.copyFrom(llapSplit.getTokenBytes())); } builder.build().writeDelimitedTo(socketStream); socketStream.flush(); LOG.info("Registered id: " + fragmentId); @SuppressWarnings("rawtypes") LlapBaseRecordReader recordReader = new LlapBaseRecordReader(socket.getInputStream(), llapSplit.getSchema(), Text.class, job, llapClient, (java.io.Closeable) socket); umbilicalResponder.setRecordReader(recordReader); return recordReader; }
From source file:android.core.SSLSocketTest.java
/** * Does a number of HTTPS requests on some host and consumes the response. * We don't use the HttpsUrlConnection class, but do this on our own * with the SSLSocket class. This gives us a chance to test the basic * behavior of SSL./*from w w w. ja v a 2s. c om*/ * * @param host The host name the request is being sent to. * @param port The port the request is being sent to. * @param path The path being requested (e.g. "/index.html"). * @param outerLoop The number of times we reconnect and do the request. * @param innerLoop The number of times we do the request for each * connection (using HTTP keep-alive). * @param delay The delay after each request (in seconds). * @throws IOException When a problem occurs. */ private void fetch(SSLSocketFactory socketFactory, String host, int port, boolean secure, String path, int outerLoop, int innerLoop, int delay, int timeout) throws IOException { InetSocketAddress address = new InetSocketAddress(host, port); for (int i = 0; i < outerLoop; i++) { // Connect to the remote host Socket socket = secure ? socketFactory.createSocket() : new Socket(); if (timeout >= 0) { socket.setKeepAlive(true); socket.setSoTimeout(timeout * 1000); } socket.connect(address); // Get the streams OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output); try { DataInputStream input = new DataInputStream(socket.getInputStream()); try { for (int j = 0; j < innerLoop; j++) { android.util.Log.d("SSLSocketTest", "GET https://" + host + path + " HTTP/1.1"); // Send a request writer.println("GET https://" + host + path + " HTTP/1.1\r"); writer.println("Host: " + host + "\r"); writer.println("Connection: " + (j == innerLoop - 1 ? "Close" : "Keep-Alive") + "\r"); writer.println("\r"); writer.flush(); int length = -1; boolean chunked = false; String line = input.readLine(); if (line == null) { throw new IOException("No response from server"); // android.util.Log.d("SSLSocketTest", "No response from server"); } // Consume the headers, check content length and encoding type while (line != null && line.length() != 0) { // System.out.println(line); int dot = line.indexOf(':'); if (dot != -1) { String key = line.substring(0, dot).trim(); String value = line.substring(dot + 1).trim(); if ("Content-Length".equalsIgnoreCase(key)) { length = Integer.valueOf(value); } else if ("Transfer-Encoding".equalsIgnoreCase(key)) { chunked = "Chunked".equalsIgnoreCase(value); } } line = input.readLine(); } assertTrue("Need either content length or chunked encoding", length != -1 || chunked); // Consume the content itself if (chunked) { length = Integer.parseInt(input.readLine(), 16); while (length != 0) { byte[] buffer = new byte[length]; input.readFully(buffer); input.readLine(); length = Integer.parseInt(input.readLine(), 16); } input.readLine(); } else { byte[] buffer = new byte[length]; input.readFully(buffer); } // Sleep for the given number of seconds try { Thread.sleep(delay * 1000); } catch (InterruptedException ex) { // Shut up! } } } finally { input.close(); } } finally { writer.close(); } // Close the connection socket.close(); } }
From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java
protected void performCommand(Environment env, ProjectService service, String projectId, String path, String requestPath, RequestHeadersSupport headers) throws CommandException { String internalProxyUri = service.computeInternalProxyBaseUri(false); if (internalProxyUri == null) { throw new IllegalStateException(); }/*from w ww .j a va 2s.co m*/ URI targetUri; try { if (!internalProxyUri.endsWith("/")) { internalProxyUri += "/"; } internalProxyUri += getName() + '/' + path; targetUri = new URI(internalProxyUri); } catch (URISyntaxException e) { throw new RuntimeException(e); } String host = targetUri.getHost(); int port = targetUri.getPort(); if (port < 0) { port = 80; } if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) { throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported"); } HeaderGroup headerGroup = computeHeaders(targetUri); for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) { for (String value : headerEntry.getValue()) { headerGroup.addHeader(new Header(headerEntry.getKey(), value)); } } getLogger().info("Proxying " + getName() + " to " + targetUri); try { Socket socket = socketFactory.openConnection(host, port); try { // initiate an HTTP request with Transfer-Encoding: chunked OutputStream proxyOut = socket.getOutputStream(); emitHttpRequestLine(proxyOut, targetUri); emitHeaders(proxyOut, headerGroup); proxyOut.flush(); List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3); FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut); tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true)); // start these pipes ExecutorService executor = Executors.newFixedThreadPool(tasks.size()); try { for (Callable<Void> task : tasks) { executor.submit(task); } InputStream proxyInput = socket.getInputStream(); try { readHttpResponse(proxyInput); MultiplexingInputStream input = new MultiplexingInputStream( new ChunkedInputStream(proxyInput)); for (;;) { PacketType packetType = input.getPacketType(); if (packetType == null) { break; } int length = input.getPacketLength(); processData(input, packetType, length); } } finally { try { executor.shutdown(); executor.awaitTermination(1000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } } } finally { executor.shutdownNow(); try { executor.awaitTermination(3000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } Thread.interrupted(); try { // attempt to close the chunked output, since this will make us a well-behaved client // by sending the closing chunk. chunkedRequestOut.close(); } catch (Throwable t) { // ignore } } } finally { socket.close(); } } catch (ConnectException e) { getLogger().error(e.getMessage(), e); throw new CommandException(-1, "Service temporarily unavailable"); } catch (IOException e) { getLogger().warn(e.getMessage(), e); throw new CommandException(-1, e.getMessage()); } }
From source file:com.mulesoft.agent.monitoring.publisher.ZabbixMonitorPublisher.java
@Override public boolean flush(@NotNull Collection<List<Metric>> listOfMetrics) { Socket zabbixConnection = null; OutputStream out = null;//ww w . j a v a2 s. co m BufferedReader in = null; try { for (List<Metric> metrics : listOfMetrics) { for (Metric metric : metrics) { zabbixConnection = new Socket(zabbixServer, zabbixPort); StringBuilder message = new StringBuilder(); message.append(MESSAGE_START); message.append(host); message.append(MESSAGE_MIDDLE_LEFT); message.append(metric.getName().replaceAll("\\s", "").replace(":", "")); message.append(MESSAGE_MIDDLE_RIGHT); message.append(metric.getValue()); message.append(MESSAGE_END); String s = message.toString(); byte[] chars = s.getBytes(); int length = chars.length; out = zabbixConnection.getOutputStream(); out.write(new byte[] { 'Z', 'B', 'X', 'D', '\1', (byte) (length & 0xFF), (byte) ((length >> 8) & 0x00FF), (byte) ((length >> 16) & 0x0000FF), (byte) ((length >> 24) & 0x000000FF), '\0', '\0', '\0', '\0' }); out.write(chars); out.flush(); in = new BufferedReader(new InputStreamReader(zabbixConnection.getInputStream())); LOGGER.debug("Message sent to Zabbix: " + message.toString()); } } } catch (IOException e) { LOGGER.warn("Failed to establish connection to Zabbix", e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (zabbixConnection != null) { zabbixConnection.close(); } } catch (IOException e) { } } return true; }
From source file:game.Clue.ClueGameUI.java
private void sendMsgToServer(Socket clientSocket, String msg) { try {// w w w .j av a2 s .c o m PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); out.println(msg); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java
private Thread newListenerThread(final Socket socket) { // Launch a new thread to read from the socket return new Thread(new Runnable() { @Override/*from w w w . j av a 2s . c om*/ public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { LogUtils.LOGD(TAG, "Starting socket listener thread..."); // We're going to read from the socket. This will be a blocking call and // it will keep on going until disconnect() is called on this object. // Note: Mind the objects used here: we use createParser because it doesn't // close the socket after ObjectMapper.readTree. JsonParser jsonParser = objectMapper.getFactory().createParser(socket.getInputStream()); ObjectNode jsonResponse; while ((jsonResponse = objectMapper.readTree(jsonParser)) != null) { LogUtils.LOGD(TAG, "Read from socket: " + jsonResponse.toString()); // LogUtils.LOGD_FULL(TAG, "Read from socket: " + jsonResponse.toString()); handleTcpResponse(jsonResponse); } } catch (JsonProcessingException e) { LogUtils.LOGW(TAG, "Got an exception while parsing JSON response.", e); callErrorCallback(null, new ApiException(ApiException.INVALID_JSON_RESPONSE_FROM_HOST, e)); } catch (IOException e) { LogUtils.LOGW(TAG, "Error reading from socket.", e); disconnect(); callErrorCallback(null, new ApiException(ApiException.IO_EXCEPTION_WHILE_READING_RESPONSE, e)); } } }); }
From source file:com.raddle.tools.ClipboardTransferMain.java
private void initGUI() { try {// w w w. j a v a 2s .c o m { this.setTitle("\u8fdc\u7a0b\u526a\u5207\u677f"); getContentPane().setLayout(null); { remoteClipGetBtn = new JButton(); getContentPane().add(remoteClipGetBtn); remoteClipGetBtn.setText("\u83b7\u5f97\u8fdc\u7a0b\u526a\u5207\u677f"); remoteClipGetBtn.setBounds(12, 22, 151, 29); remoteClipGetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { doInSocket(new SocketCallback() { @Override public Object connected(Socket socket) throws Exception { if (!isProcessing) { isProcessing = true; try { ClipCommand cmd = new ClipCommand(); cmd.setCmdCode(ClipCommand.CMD_GET_CLIP); updateMessage("??"); // ?? ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); out.writeObject(cmd); // ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); ClipResult result = (ClipResult) in.readObject(); if (result.isSuccess()) { setLocalClipboard(result); StringBuilder sb = new StringBuilder(); for (DataFlavor dataFlavor : result.getClipdata().keySet()) { sb.append("\n"); sb.append(dataFlavor.getPrimaryType()).append("/") .append(dataFlavor.getSubType()); } updateMessage("??? " + sb); } else { updateMessage("?:" + result.getMessage()); } in.close(); out.close(); } catch (Exception e) { updateMessage("?:" + e.getMessage()); } finally { isProcessing = false; } } return null; } }); } }); } { remoteClipSetBtn = new JButton(); getContentPane().add(remoteClipSetBtn); remoteClipSetBtn.setText("\u8bbe\u7f6e\u8fdc\u7a0b\u526a\u5207\u677f"); remoteClipSetBtn.setBounds(181, 22, 159, 29); remoteClipSetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setRemoteClipboard(true); } }); } { serverLeb = new JLabel(); getContentPane().add(serverLeb); serverLeb.setText("\u8fdc\u7a0b\u670d\u52a1\u5668\u5730\u5740(IP:PORT)"); serverLeb.setBounds(12, 63, 162, 17); } { serverAddrTxt = new JTextField(); getContentPane().add(serverAddrTxt); serverAddrTxt.setBounds(169, 58, 186, 27); } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); jLabel1.setText("\u6d88\u606f\uff1a"); jLabel1.setBounds(12, 97, 48, 24); } { jLabel2 = new JLabel(); getContentPane().add(jLabel2); jLabel2.setText("\u672c\u5730\u526a\u5207\u677f\u670d\u52a1"); jLabel2.setBounds(12, 297, 91, 20); } { clipServerStartBtn = new JButton(); getContentPane().add(clipServerStartBtn); clipServerStartBtn.setText("\u542f\u52a8"); clipServerStartBtn.setBounds(12, 329, 79, 29); clipServerStartBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { startServer(); } }); } { clipServerStopBtn = new JButton(); getContentPane().add(clipServerStopBtn); clipServerStopBtn.setText("\u505c\u6b62"); clipServerStopBtn.setBounds(103, 329, 81, 29); clipServerStopBtn.setEnabled(false); clipServerStopBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { shutdown(); } }); } { jLabel3 = new JLabel(); getContentPane().add(jLabel3); jLabel3.setText("\u7aef\u53e3\uff1a"); jLabel3.setBounds(196, 335, 44, 17); } { portTxt = new JTextField(); getContentPane().add(portTxt); portTxt.setText("11221"); portTxt.setBounds(252, 330, 88, 27); } { modifyClipChk = new JCheckBox(); getContentPane().add(modifyClipChk); modifyClipChk.setText("\u5141\u8bb8\u8fdc\u7a0b\u4fee\u6539\u526a\u5207\u677f"); modifyClipChk.setBounds(12, 377, 172, 22); } { clearBtn = new JButton(); getContentPane().add(clearBtn); clearBtn.setText("\u6e05\u7a7a\u672c\u5730\u7cfb\u7edf\u526a\u5207\u677f"); clearBtn.setBounds(196, 374, 159, 29); clearBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(null); sysc.setContents(tText, null); } }); } { autoChk = new JCheckBox(); autoChk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m.setEnabled(autoChk.isSelected()); } }); getContentPane().add(autoChk); autoChk.setText("\u81ea\u52a8\u8bbe\u7f6e\u8fdc\u7a0b\u526a\u5207\u677f"); autoChk.setBounds(12, 405, 172, 22); } } JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(55, 97, 542, 199); getContentPane().add(scrollPane); { messageArea = new JTextArea(); scrollPane.setViewportView(messageArea); } this.setSize(611, 465); { } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.piusvelte.taplock.server.ConnectionThread.java
@SuppressWarnings("unchecked") @Override//from www . ja va2s. co m public void run() { TapLockServer.writeLog("ConnectionThread started"); // retrieve the local Bluetooth device object // setup the server to listen for connection try { local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); // String url = "btspp://localhost:" + mRemoteAuthServerUUID.toString() + ";master=false;encrypt=false;authenticate=false;name=" + sSPD; String url = "btspp://localhost:" + sTapLockUUID.toString() + ";name=" + sSPD; notifier = (StreamConnectionNotifier) Connector.open(url); } catch (Exception e) { // no bluetooth present TapLockServer.writeLog("notifier init: " + e.getMessage()); TapLockServer.shutdown(); return; } JSONParser jsonParser = new JSONParser(); while (notifier != null) { TapLockServer.writeLog("waiting for connection..."); try { btConnection = notifier.acceptAndOpen(); } catch (IOException e) { TapLockServer.writeLog("notifier.acceptAndOpen: " + e.getMessage()); btConnection = null; } if (btConnection != null) { TapLockServer.writeLog("new connection..."); try { btInStream = btConnection.openInputStream(); btOutStream = btConnection.openOutputStream(); } catch (IOException e) { TapLockServer.writeLog("inStream and outStream open: " + e.getMessage()); } if ((btInStream != null) && (btOutStream != null)) { // send the challenge String challenge = Long.toString(System.currentTimeMillis()); TapLockServer.writeLog("init challenge: " + challenge); JSONObject responseJObj = new JSONObject(); responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge); String responseStr = responseJObj.toJSONString(); try { btOutStream.write(responseStr.getBytes()); } catch (IOException e) { TapLockServer.writeLog("outStream.write: " + e.getMessage()); } // prepare to receive data byte[] btBuffer = new byte[1024]; int btReadBytes = -1; try { btReadBytes = btInStream.read(btBuffer); } catch (IOException e) { TapLockServer.writeLog("inStream.read: " + e.getMessage()); } while (btReadBytes != -1) { responseJObj.clear(); String requestStr = new String(btBuffer, 0, btReadBytes); TapLockServer.writeLog("request: " + requestStr); JSONObject requestJObj = null; try { requestJObj = (JSONObject) jsonParser.parse(requestStr); } catch (ParseException e) { TapLockServer.writeLog("jsonParser.parse: " + e.getMessage()); } if (requestJObj != null) { if ((requestJObj != null) && requestJObj.containsKey(TapLockServer.PARAM_ACTION) && requestJObj.containsKey(TapLockServer.PARAM_HMAC)) { String requestAction = (String) requestJObj.get(TapLockServer.PARAM_ACTION); TapLockServer.writeLog("action: " + requestAction); String requestPassphrase = (String) requestJObj.get(TapLockServer.PARAM_PASSPHRASE); if (requestPassphrase == null) requestPassphrase = ""; String requestHMAC = (String) requestJObj.get(TapLockServer.PARAM_HMAC); String validHMAC = null; try { validHMAC = TapLockServer.getHashString(challenge + TapLockServer.sPassphrase + requestAction + requestPassphrase); } catch (NoSuchAlgorithmException e) { TapLockServer.writeLog("getHashString: " + e.getMessage()); } catch (UnsupportedEncodingException e) { TapLockServer.writeLog("getHashString: " + e.getMessage()); } if (requestHMAC.equals(validHMAC)) { if (TapLockServer.ACTION_PASSPHRASE.equals(requestAction)) TapLockServer.setPassphrase(requestPassphrase); else { if (TapLockServer.OS == TapLockServer.OS_WIN) { if (TapLockServer.ACTION_LOCK.equals(requestAction)) runCommand("rundll32.exe user32.dll, LockWorkStation"); else { // either unlock or toggle String password = ""; Properties prop = new Properties(); try { prop.load(new FileInputStream(TapLockServer.sProperties)); if (prop.containsKey(TapLockServer.sPasswordKey)) password = TapLockServer.decryptString( prop.getProperty(TapLockServer.sPasswordKey)); } catch (FileNotFoundException e) { TapLockServer.writeLog("prop load: " + e.getMessage()); } catch (IOException e) { TapLockServer.writeLog("prop load: " + e.getMessage()); } Socket cpSocket = null; try { cpSocket = new Socket(TapLockServer.S_LOCALHOST, TapLockServer.SERVER_PORT); } catch (UnknownHostException e) { TapLockServer.writeLog("socket: " + e.getMessage()); } catch (IOException e) { TapLockServer.writeLog("socket: " + e.getMessage()); } if (cpSocket != null) { InputStream cpInStream = null; OutputStream cpOutStream = null; try { cpInStream = cpSocket.getInputStream(); cpOutStream = cpSocket.getOutputStream(); } catch (IOException e) { TapLockServer.writeLog("in/out stream: " + e.getMessage()); } if ((cpInStream != null) && (cpOutStream != null)) { // get the version byte[] cpBuffer = new byte[1]; int cpReadBytes = -1; try { cpReadBytes = cpInStream.read(cpBuffer); } catch (IOException e) { TapLockServer .writeLog("instream read: " + e.getMessage()); } if (cpReadBytes != -1) { TapLockServer.writeLog("credential provider version: " + new String(cpBuffer, 0, cpReadBytes)); // pack the credentials byte[] usernameBytes = System.getProperty("user.name") .getBytes(Charset.forName("UTF-8")); byte[] passwordBytes = password .getBytes(Charset.forName("UTF-8")); byte[] credentialsBuf = new byte[TapLockServer.S_CREDBUF]; for (int i = 0, l = usernameBytes.length; (i < l) && (i < TapLockServer.S_USERBUF); i++) credentialsBuf[i] = usernameBytes[i]; for (int i = 0, l = passwordBytes.length; (i < l) && (i < TapLockServer.S_PASSBUF); i++) credentialsBuf[i + TapLockServer.S_USERBUF] = passwordBytes[i]; try { cpOutStream.write(credentialsBuf); } catch (IOException e) { TapLockServer.writeLog( "cpOutStream write: " + e.getMessage()); } cpReadBytes = -1; try { cpReadBytes = cpInStream.read(credentialsBuf); } catch (IOException e) { TapLockServer.writeLog( "cpInStream read: " + e.getMessage()); } // the socket should return "0" if no errors if (cpReadBytes != -1) { String cpResult = new String(credentialsBuf, 0, cpReadBytes); TapLockServer.writeLog( "credential provider result: " + cpResult); if (!TapLockServer.CREDENTIAL_PROVIDER_SUCCESS .equals(cpResult)) responseJObj.put(TapLockServer.PARAM_ERROR, "Authentication error, is the Windows password set in Tap Lock Server?"); } try { cpOutStream.close(); } catch (IOException e) { TapLockServer.writeLog( "output close: " + e.getMessage()); } try { cpInStream.close(); } catch (IOException e) { TapLockServer .writeLog("in close: " + e.getMessage()); } try { cpSocket.close(); } catch (IOException e) { TapLockServer.writeLog( "socket close: " + e.getMessage()); } } } } else runCommand("rundll32.exe user32.dll, LockWorkStation"); } } else if (TapLockServer.OS == TapLockServer.OS_NIX) { if (TapLockServer.ACTION_TOGGLE.equals(requestAction)) requestAction = TapLockServer.getToggleAction(); String command = null; if (TapLockServer.ACTION_LOCK.equals(requestAction)) command = "gnome-screensaver-command -a"; else if (TapLockServer.ACTION_UNLOCK.equals(requestAction)) command = "gnome-screensaver-command -d"; if (command != null) runCommand(command); } } } else { TapLockServer.writeLog("authentication failed"); responseJObj.put(TapLockServer.PARAM_ERROR, "authentication failed"); } } else { TapLockServer.writeLog("invalid request"); responseJObj.put(TapLockServer.PARAM_ERROR, "invalid request"); } } else { TapLockServer.writeLog("failed to parse request"); responseJObj.put(TapLockServer.PARAM_ERROR, "failed to parse request"); } // send the new challenge challenge = Long.toString(System.currentTimeMillis()); TapLockServer.writeLog("next challenge: " + challenge); responseJObj.put(TapLockServer.PARAM_CHALLENGE, challenge); responseStr = responseJObj.toJSONString(); try { btOutStream.write(responseStr.getBytes()); } catch (IOException e) { TapLockServer.writeLog("outStream.write: " + e.getMessage()); } try { btReadBytes = btInStream.read(btBuffer); } catch (IOException e) { TapLockServer.writeLog("inStream.read: " + e.getMessage()); } } if (btInStream != null) { try { btInStream.close(); } catch (IOException e) { TapLockServer.writeLog("inStream.close: " + e.getMessage()); } } if (btOutStream != null) { try { btOutStream.close(); } catch (IOException e) { TapLockServer.writeLog("outStream.close: " + e.getMessage()); } } } if (btConnection != null) { try { btConnection.close(); } catch (IOException e) { TapLockServer.writeLog("connection.close: " + e.getMessage()); } btConnection = null; } } } }