List of usage examples for java.net SocketException getMessage
public String getMessage()
From source file:org.zaproxy.zap.extension.ascanrules.CommandInjectionPlugin.java
/** * Tests for injection vulnerabilities with the given payloads. * * @param paramName the name of the parameter that will be used for testing for injection * @param value the value of the parameter that will be used for testing for injection * @param targetCount the number of requests for normal payloads * @param blindTargetCount the number of requests for blind payloads * @param osPayloads the normal payloads * @param blindOsPayloads the blind payloads * @return {@code true} if the vulnerability was found, {@code false} otherwise. *///from ww w . j a va2s. c o m private boolean testCommandInjection(String paramName, String value, int targetCount, int blindTargetCount, Map<String, Pattern> osPayloads, List<String> blindOsPayloads) { // Start testing OS Command Injection patterns // ------------------------------------------ String payload; String paramValue; Iterator<String> it = osPayloads.keySet().iterator(); List<Long> responseTimes = new ArrayList<>(targetCount); long elapsedTime; // ----------------------------------------------- // Check 1: Feedback based OS Command Injection // ----------------------------------------------- // try execution check sending a specific payload // and verifying if it returns back the output inside // the response content // ----------------------------------------------- for (int i = 0; it.hasNext() && (i < targetCount); i++) { payload = it.next(); if (osPayloads.get(payload).matcher(getBaseMsg().getResponseBody().toString()).find()) { continue; // The original matches the detection so continue to next } HttpMessage msg = getNewMsg(); paramValue = value + payload; setParameter(msg, paramName, paramValue); if (log.isDebugEnabled()) { log.debug("Testing [" + paramName + "] = [" + paramValue + "]"); } try { // Send the request and retrieve the response try { sendAndReceive(msg, false); } catch (SocketException ex) { if (log.isDebugEnabled()) log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: " + msg.getRequestHeader().getURI().toString() + "\n The target may have replied with a poorly formed redirect due to our input."); continue; // Something went wrong, move to next payload iteration } elapsedTime = msg.getTimeElapsedMillis(); responseTimes.add(elapsedTime); // Check if the injected content has been evaluated and printed String content = msg.getResponseBody().toString(); Matcher matcher = osPayloads.get(payload).matcher(content); if (matcher.find()) { // We Found IT! // First do logging if (log.isDebugEnabled()) { log.debug("[OS Command Injection Found] on parameter [" + paramName + "] with value [" + paramValue + "]"); } // Now create the alert message this.bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, msg.getRequestHeader().getURI().toString(), paramName, paramValue, null, matcher.group(), msg); // All done. No need to look for vulnerabilities on subsequent // payloads on the same request (to reduce performance impact) return true; } } catch (IOException ex) { // Do not try to internationalise this.. we need an error message in any event.. // if it's in English, it's still better than not having it at all. log.warn("Command Injection vulnerability check failed for parameter [" + paramName + "] and payload [" + payload + "] due to an I/O error", ex); } // Check if the scan has been stopped // if yes dispose resources and exit if (isStop()) { // Dispose all resources // Exit the plugin return false; } } // ----------------------------------------------- // Check 2: Time-based Blind OS Command Injection // ----------------------------------------------- // Check for a sleep shell execution according to // the previous experimented request time execution // It uses deviations and average for the real delay checking... // 7? = 99.9999999997440% of the values // so response time should be less than 7*stdev([normal response times]) // Math reference: http://www.answers.com/topic/standard-deviation // ----------------------------------------------- double deviation = getResponseTimeDeviation(responseTimes); double lowerLimit = (deviation >= 0) ? getResponseTimeAverage(responseTimes) + TIME_STDEV_COEFF * deviation : timeSleepSeconds * 1000; it = blindOsPayloads.iterator(); String timeSleepSecondsStr = String.valueOf(timeSleepSeconds); for (int i = 0; it.hasNext() && (i < blindTargetCount); i++) { HttpMessage msg = getNewMsg(); payload = it.next(); paramValue = value + payload.replace("{0}", timeSleepSecondsStr); setParameter(msg, paramName, paramValue); if (log.isDebugEnabled()) { log.debug("Testing [" + paramName + "] = [" + paramValue + "]"); } try { // Send the request and retrieve the response try { sendAndReceive(msg, false); } catch (SocketException ex) { if (log.isDebugEnabled()) log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: " + msg.getRequestHeader().getURI().toString() + "\n The target may have replied with a poorly formed redirect due to our input."); continue; // Something went wrong, move to next blind iteration } elapsedTime = msg.getTimeElapsedMillis(); // Check if enough time has passed if (elapsedTime >= lowerLimit && elapsedTime > timeSleepSeconds * 1000) { // Probably we've to confirm it launching again the query // But we arise the alert directly with MEDIUM Confidence... // We Found IT! // First do logging if (log.isDebugEnabled()) { log.debug("[Blind OS Command Injection Found] on parameter [" + paramName + "] with value [" + paramValue + "]"); } // Now create the alert message this.bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, msg.getRequestHeader().getURI().toString(), paramName, paramValue, null, null, msg); // All done. No need to look for vulnerabilities on subsequent // payloads on the same request (to reduce performance impact) return true; } } catch (IOException ex) { // Do not try to internationalise this.. we need an error message in any event.. // if it's in English, it's still better than not having it at all. log.warn("Blind Command Injection vulnerability check failed for parameter [" + paramName + "] and payload [" + payload + "] due to an I/O error", ex); } // Check if the scan has been stopped // if yes dispose resources and exit if (isStop()) { // Dispose all resources // Exit the plugin return false; } } return false; }
From source file:org.openhab.binding.globalcache.handler.GlobalCacheHandler.java
@Override public void initialize() { logger.debug("Initializing thing {}", thingID()); try {/*ww w . ja v a 2s .c o m*/ ifAddress = InetAddress.getByName(NetUtil.getLocalIpv4HostAddress()); logger.debug("Handler using address {} on network interface {}", ifAddress.getHostAddress(), NetworkInterface.getByInetAddress(ifAddress).getName()); } catch (SocketException e) { logger.error("Handler got Socket exception creating multicast socket: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } catch (UnknownHostException e) { logger.error("Handler got UnknownHostException getting local IPv4 network interface: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } scheduledFuture = scheduledExecutorService.schedule(commandProcessor, 2, TimeUnit.SECONDS); }
From source file:org.squidy.nodes.TUIO.java
/** * *///ww w. j a v a2 s . c om protected void startOSCServer() { try { oscPortOut = new OSCPortOut(InetAddress.getByName(addressOutgoing), portOutgoing); } catch (SocketException e) { throw new ProcessException(e.getMessage(), e); } catch (UnknownHostException e) { throw new ProcessException(e.getMessage(), e); } try { oscPortIn = new OSCPortIn(portIncoming, endian); } catch (SocketException e) { throw new ProcessException(e.getMessage(), e); } oscPortIn.addListener("/tuio/2Dcur", new OSCListener() { /* (non-Javadoc) * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, com.illposed.osc.OSCMessage[]) */ public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; float x = (Float) arguments[2]; float y = (Float) arguments[3]; float movementVectorX = (Float) arguments[4]; float movementVectorY = (Float) arguments[5]; float motionAcceleration = (Float) arguments[6]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/2Dcur"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); cursors.add(dataPosition2D); } } publish(cursors); } }); oscPortIn.addListener("/tuio/2Dobj", new OSCListener() { /* * (non-Javadoc) * * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, * com.illposed.osc.OSCMessage[]) */ public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> tokens = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; int markerId = (Integer) arguments[2]; float x = (Float) arguments[3]; float y = (Float) arguments[4]; float angle = (Float) arguments[5]; float movementVectorX = (Float) arguments[6]; float movementVectorY = (Float) arguments[7]; float rotationVector = (Float) arguments[8]; float motionAcceleration = (Float) arguments[9]; float rotationAcceleration = (Float) arguments[10]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/2Dobj"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(FIDUCIAL_ID, markerId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(ROTATION_VECTOR_A, rotationVector); dataPosition2D.setAttribute(ANGLE_A, angle); dataPosition2D.setAttribute(ROTATION_ACCELERATION, rotationAcceleration); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); tokenUpdated = true; tokenList.clear(); tokens.add(dataPosition2D); tokenList.add(dataPosition2D); } } publish(tokens); } }); oscPortIn.addListener("/tuio/_sxyXYmaPP", new OSCListener() { public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; float x = (Float) arguments[2]; float y = (Float) arguments[3]; float movementVectorX = (Float) arguments[4]; float movementVectorY = (Float) arguments[5]; float motionAcceleration = (Float) arguments[6]; float angleA = (Float) arguments[6]; float handWidth = (Float) arguments[6]; float handHeight = (Float) arguments[6]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/_sxyXYmaPP"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); dataPosition2D.setAttribute(ANGLE_A, angleA); dataPosition2D.setAttribute(HAND_WIDTH, handWidth); dataPosition2D.setAttribute(HAND_HEIGHT, handHeight); cursors.add(dataPosition2D); } } publish(cursors); } }); oscPortIn.addListener("/tuio/_sxyXYma", new OSCListener() { /* (non-Javadoc) * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, com.illposed.osc.OSCMessage[]) */ public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; float x = (Float) arguments[2]; float y = (Float) arguments[3]; float movementVectorX = (Float) arguments[4]; float movementVectorY = (Float) arguments[5]; float motionAcceleration = (Float) arguments[6]; float angleA = (Float) arguments[7]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/_sxyXYma"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); dataPosition2D.setAttribute(ANGLE_A, angleA); cursors.add(dataPosition2D); } } publish(cursors); } }); oscPortIn.startListening(); }
From source file:org.squidy.nodes.optitrack.TUIO4Optitrack.java
/** * */// w ww . j a va 2 s .c o m protected void startOSCServer() { try { oscPortOut = new OSCPortOut(InetAddress.getByName(addressOutgoing), portOutgoing); } catch (SocketException e) { throw new ProcessException(e.getMessage(), e); } catch (UnknownHostException e) { throw new ProcessException(e.getMessage(), e); } try { oscPortIn = new OSCPortIn(portIncoming, endian); } catch (SocketException e) { throw new ProcessException(e.getMessage(), e); } oscPortIn.addListener("/tuio/2Dcur", new OSCListener() { /* (non-Javadoc) * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, com.illposed.osc.OSCMessage[]) */ public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; float x = (Float) arguments[2]; float y = (Float) arguments[3]; float movementVectorX = (Float) arguments[4]; float movementVectorY = (Float) arguments[5]; float motionAcceleration = (Float) arguments[6]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO4Optitrack.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/2Dcur"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); cursors.add(dataPosition2D); } } publish(cursors); } }); oscPortIn.addListener("/tuio/2Dobj", new OSCListener() { /* * (non-Javadoc) * * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, * com.illposed.osc.OSCMessage[]) */ public void acceptMessages(Date time, OSCMessage[] messages) { List<DataPosition2D> tokens = new ArrayList<DataPosition2D>(1); int fseq = -1; for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("fseq".equals(arguments[0])) { fseq = (Integer) arguments[1]; } } for (OSCMessage message : messages) { Object[] arguments = message.getArguments(); if ("set".equals(arguments[0])) { int sessionId = (Integer) arguments[1]; int markerId = (Integer) arguments[2]; float x = (Float) arguments[3]; float y = (Float) arguments[4]; float angle = (Float) arguments[5]; float movementVectorX = (Float) arguments[6]; float movementVectorY = (Float) arguments[7]; float rotationVector = (Float) arguments[8]; float motionAcceleration = (Float) arguments[9]; float rotationAcceleration = (Float) arguments[10]; DataPosition2D dataPosition2D = new DataPosition2D(TUIO4Optitrack.class, x, y); dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/2Dobj"); dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); dataPosition2D.setAttribute(FIDUCIAL_ID, markerId); dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); dataPosition2D.setAttribute(ROTATION_VECTOR_A, rotationVector); dataPosition2D.setAttribute(ANGLE_A, angle); dataPosition2D.setAttribute(ROTATION_ACCELERATION, rotationAcceleration); dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); tokenUpdated = true; tokenList.clear(); tokens.add(dataPosition2D); tokenList.add(dataPosition2D); } } publish(tokens); } }); // oscPortIn.addListener("/tuio/_sxyXYmaPP", new OSCListener() { // public void acceptMessages(Date time, OSCMessage[] messages) { // // List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); // // int fseq = -1; // for (OSCMessage message : messages) { // Object[] arguments = message.getArguments(); // if ("fseq".equals(arguments[0])) { // fseq = (Integer) arguments[1]; // } // } // // for (OSCMessage message : messages) { // Object[] arguments = message.getArguments(); // // if ("set".equals(arguments[0])) { // // int sessionId = (Integer) arguments[1]; // float x = (Float) arguments[2]; // float y = (Float) arguments[3]; // float movementVectorX = (Float) arguments[4]; // float movementVectorY = (Float) arguments[5]; // float motionAcceleration = (Float) arguments[6]; // float angleA = (Float) arguments[6]; // float handWidth = (Float) arguments[6]; // float handHeight = (Float) arguments[6]; // // DataPosition2D dataPosition2D = new DataPosition2D(TUIO4Optitrack.class, x, y); // dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/_sxyXYmaPP"); // dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); // dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); // dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); // dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); // dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); // dataPosition2D.setAttribute(ANGLE_A, angleA); // dataPosition2D.setAttribute(HAND_WIDTH, handWidth); // dataPosition2D.setAttribute(HAND_HEIGHT, handHeight); // // cursors.add(dataPosition2D); // } // } // // publish(cursors); // } // }); // oscPortIn.addListener("/tuio/_sxyXYma", new OSCListener() { // // /* (non-Javadoc) // * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date, com.illposed.osc.OSCMessage[]) // */ // public void acceptMessages(Date time, OSCMessage[] messages) { // // List<DataPosition2D> cursors = new ArrayList<DataPosition2D>(1); // // int fseq = -1; // for (OSCMessage message : messages) { // Object[] arguments = message.getArguments(); // if ("fseq".equals(arguments[0])) { // fseq = (Integer) arguments[1]; // } // } // // for (OSCMessage message : messages) { // Object[] arguments = message.getArguments(); // // if ("set".equals(arguments[0])) { // // int sessionId = (Integer) arguments[1]; // float x = (Float) arguments[2]; // float y = (Float) arguments[3]; // float movementVectorX = (Float) arguments[4]; // float movementVectorY = (Float) arguments[5]; // float motionAcceleration = (Float) arguments[6]; // float angleA = (Float) arguments[7]; // // DataPosition2D dataPosition2D = new DataPosition2D(TUIO4Optitrack.class, x, y); // dataPosition2D.setAttribute(ORIGIN_ADDRESS, "/tuio/_sxyXYma"); // dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq); // dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId); // dataPosition2D.setAttribute(MOVEMENT_VECTOR_X, movementVectorX); // dataPosition2D.setAttribute(MOVEMENT_VECTOR_Y, movementVectorY); // dataPosition2D.setAttribute(MOTION_ACCELERATION, motionAcceleration); // dataPosition2D.setAttribute(ANGLE_A, angleA); // // cursors.add(dataPosition2D); // } // } // // publish(cursors); // } // }); oscPortIn.startListening(); }
From source file:org.ejbca.ui.web.admin.configuration.EjbcaWebBean.java
/** Perform HTTP connection to the cluster nodes clear-cache Servlet */ private boolean checkHost(String hostname, boolean excludeActiveCryptoTokens) throws IOException { // get http port of remote host, this requires that all cluster nodes uses the same public htt port final int pubport = WebConfiguration.getPublicHttpPort(); final String requestUrl = "http://" + hostname + ":" + pubport + "/ejbca/clearcache?command=clearcaches&excludeactivects=" + excludeActiveCryptoTokens; final URL url = new URL(requestUrl); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (log.isDebugEnabled()) { log.debug("Contacting host with url:" + requestUrl); }// www .ja v a 2s.c om try { final int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return true; } log.info("Failed to clear caches for host: " + hostname + ", responseCode=" + responseCode); } catch (SocketException e) { log.info("Failed to clear caches for host: " + hostname + ", message=" + e.getMessage()); } catch (IOException e) { log.info("Failed to clear caches for host: " + hostname + ", message=" + e.getMessage()); } return false; }
From source file:net.jradius.webservice.WebServiceListener.java
public JRadiusEvent parseRequest(ListenerRequest listenerRequest, ByteBuffer byteBuffer, InputStream inputStream) throws IOException, WebServiceException { DataInputStream reader = new DataInputStream(inputStream); WebServiceRequest request = new WebServiceRequest(); String line = null;/*from w w w .j av a 2 s . co m*/ try { line = reader.readLine(); } catch (SocketException e) { return null; } if (line == null) throw new WebServiceException("Invalid relay request"); StringTokenizer tokens = new StringTokenizer(line); String method = tokens.nextToken(); String uri = tokens.nextToken(); String httpVersion = tokens.nextToken(); if ("GET".equals(method)) request.setMethod(WebServiceRequest.GET); else if ("POST".equals(method)) request.setMethod(WebServiceRequest.POST); else if ("PUT".equals(method)) request.setMethod(WebServiceRequest.PUT); else throw new WebServiceException("Does not handle HTTP request method: " + method); request.setHttpVersion(httpVersion); try { request.setUri(new URI(uri)); } catch (URISyntaxException e) { throw new WebServiceException(e.getMessage()); } Map<String, String> headers = getHeaders(reader); request.setHeaderMap(headers); String clen = headers.get("content-length"); if (clen != null) { request.setContent(getContent(reader, Integer.parseInt(clen))); } return request; }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPClient.java
/*** * Requests to send a file to a remote host, reads the file from an * InputStream, sends the file to the remote host, and closes the * connection. A local UDP socket must first be created by * {@link org.apache.commons.net.DatagramSocketClient#open open()} before * invoking this method. This method will not close the InputStream * containing the file; you must close it after the method invocation. * <p>// w ww . j a v a 2 s . com * @param filename The name the remote server should use when creating * the file on its file system. * @param mode The TFTP mode of the transfer (one of the MODE constants). * @param host The remote host receiving the file. * @param port The port number of the remote TFTP server. * @exception IOException If an I/O error occurs. The nature of the * error will be reported in the message. ***/ public void sendFile(String filename, int mode, InputStream input, InetAddress host, int port) throws IOException { int bytesRead, timeouts, lastBlock, block, hostPort, dataLength, offset; TFTPPacket sent, received = null; TFTPErrorPacket error; TFTPDataPacket data = new TFTPDataPacket(host, port, 0, _sendBuffer, 4, 0); ; TFTPAckPacket ack; beginBufferedOps(); dataLength = lastBlock = hostPort = bytesRead = 0; block = 0; boolean lastAckWait = false; if (mode == TFTP.ASCII_MODE) input = new ToNetASCIIInputStream(input); sent = new TFTPWriteRequestPacket(host, port, filename, mode); _sendPacket: do { bufferedSend(sent); _receivePacket: while (true) { timeouts = 0; while (timeouts < __maxTimeouts) { try { received = bufferedReceive(); break; } catch (SocketException e) { if (++timeouts >= __maxTimeouts) { endBufferedOps(); throw new IOException("Connection timed out."); } continue; } catch (InterruptedIOException e) { if (++timeouts >= __maxTimeouts) { endBufferedOps(); throw new IOException("Connection timed out."); } continue; } catch (TFTPPacketException e) { endBufferedOps(); throw new IOException("Bad packet: " + e.getMessage()); } } // The first time we receive we get the port number and // answering host address (for hosts with multiple IPs) if (lastBlock == 0) { hostPort = received.getPort(); data.setPort(hostPort); if (!host.equals(received.getAddress())) { host = received.getAddress(); data.setAddress(host); sent.setAddress(host); } } // Comply with RFC 783 indication that an error acknowledgement // should be sent to originator if unexpected TID or host. if (host.equals(received.getAddress()) && received.getPort() == hostPort) { switch (received.getType()) { case TFTPPacket.ERROR: error = (TFTPErrorPacket) received; endBufferedOps(); throw new IOException( "Error code " + error.getError() + " received: " + error.getMessage()); case TFTPPacket.ACKNOWLEDGEMENT: ack = (TFTPAckPacket) received; lastBlock = ack.getBlockNumber(); if (lastBlock == block) { ++block; if (lastAckWait) break _sendPacket; else break _receivePacket; } else { discardPackets(); if (lastBlock == (block - 1)) continue _sendPacket; // Resend last acknowledgement. continue _receivePacket; // Start fetching packets again. } //break; default: endBufferedOps(); throw new IOException("Received unexpected packet type."); } } else { error = new TFTPErrorPacket(received.getAddress(), received.getPort(), TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port."); bufferedSend(error); continue _sendPacket; } // We should never get here, but this is a safety to avoid // infinite loop. If only Java had the goto statement. //break; } dataLength = TFTPPacket.SEGMENT_SIZE; offset = 4; while (dataLength > 0 && (bytesRead = input.read(_sendBuffer, offset, dataLength)) > 0) { offset += bytesRead; dataLength -= bytesRead; } data.setBlockNumber(block); data.setData(_sendBuffer, 4, offset - 4); sent = data; } while (dataLength == 0 || lastAckWait); endBufferedOps(); }
From source file:org.openhab.binding.globalcache.internal.handler.GlobalCacheHandler.java
@Override public void initialize() { logger.debug("Initializing thing {}", thingID()); try {//from w ww . j ava2 s . c o m ifAddress = InetAddress.getByName(ipv4Address); logger.debug("Handler using address {} on network interface {}", ifAddress.getHostAddress(), NetworkInterface.getByInetAddress(ifAddress).getName()); } catch (SocketException e) { logger.error("Handler got Socket exception creating multicast socket: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } catch (UnknownHostException e) { logger.error("Handler got UnknownHostException getting local IPv4 network interface: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } scheduledFuture = scheduledExecutorService.schedule(commandProcessor, 2, TimeUnit.SECONDS); }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPClient.java
/*** * Requests a named file from a remote host, writes the * file to an OutputStream, closes the connection, and returns the number * of bytes read. A local UDP socket must first be created by * {@link org.apache.commons.net.DatagramSocketClient#open open()} before * invoking this method. This method will not close the OutputStream * containing the file; you must close it after the method invocation. * <p>/*from w ww . j a va 2 s. c o m*/ * @param filename The name of the file to receive. * @param mode The TFTP mode of the transfer (one of the MODE constants). * @param output The OutputStream to which the file should be written. * @param host The remote host serving the file. * @param port The port number of the remote TFTP server. * @exception IOException If an I/O error occurs. The nature of the * error will be reported in the message. ***/ public int receiveFile(String filename, int mode, OutputStream output, InetAddress host, int port) throws IOException { int bytesRead, timeouts, lastBlock, block, hostPort, dataLength; TFTPPacket sent, received = null; TFTPErrorPacket error; TFTPDataPacket data; TFTPAckPacket ack = new TFTPAckPacket(host, port, 0); beginBufferedOps(); dataLength = lastBlock = hostPort = bytesRead = 0; block = 1; if (mode == TFTP.ASCII_MODE) output = new FromNetASCIIOutputStream(output); sent = new TFTPReadRequestPacket(host, port, filename, mode); _sendPacket: do { bufferedSend(sent); _receivePacket: while (true) { timeouts = 0; while (timeouts < __maxTimeouts) { try { received = bufferedReceive(); break; } catch (SocketException e) { if (++timeouts >= __maxTimeouts) { endBufferedOps(); throw new IOException("Connection timed out."); } continue; } catch (InterruptedIOException e) { if (++timeouts >= __maxTimeouts) { endBufferedOps(); throw new IOException("Connection timed out."); } continue; } catch (TFTPPacketException e) { endBufferedOps(); throw new IOException("Bad packet: " + e.getMessage()); } } // The first time we receive we get the port number and // answering host address (for hosts with multiple IPs) if (lastBlock == 0) { hostPort = received.getPort(); ack.setPort(hostPort); if (!host.equals(received.getAddress())) { host = received.getAddress(); ack.setAddress(host); sent.setAddress(host); } } // Comply with RFC 783 indication that an error acknowledgement // should be sent to originator if unexpected TID or host. if (host.equals(received.getAddress()) && received.getPort() == hostPort) { switch (received.getType()) { case TFTPPacket.ERROR: error = (TFTPErrorPacket) received; endBufferedOps(); throw new IOException( "Error code " + error.getError() + " received: " + error.getMessage()); case TFTPPacket.DATA: data = (TFTPDataPacket) received; dataLength = data.getDataLength(); lastBlock = data.getBlockNumber(); if (lastBlock == block) { try { output.write(data.getData(), data.getDataOffset(), dataLength); } catch (IOException e) { error = new TFTPErrorPacket(host, hostPort, TFTPErrorPacket.OUT_OF_SPACE, "File write failed."); bufferedSend(error); endBufferedOps(); throw e; } ++block; break _receivePacket; } else { discardPackets(); if (lastBlock == (block - 1)) continue _sendPacket; // Resend last acknowledgement. continue _receivePacket; // Start fetching packets again. } //break; default: endBufferedOps(); throw new IOException("Received unexpected packet type."); } } else { error = new TFTPErrorPacket(received.getAddress(), received.getPort(), TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port."); bufferedSend(error); continue _sendPacket; } // We should never get here, but this is a safety to avoid // infinite loop. If only Java had the goto statement. //break; } ack.setBlockNumber(lastBlock); sent = ack; bytesRead += dataLength; } // First data packet less than 512 bytes signals end of stream. while (dataLength == TFTPPacket.SEGMENT_SIZE); bufferedSend(sent); endBufferedOps(); return bytesRead; }
From source file:org.beepcore.beep.transport.tcp.TCPSession.java
private void processNextFrame() { running = true;//from w w w .jav a 2 s .c om if (socket == null) { running = false; return; } try { InputStream is = socket.getInputStream(); while (running) { if (log.isTraceEnabled()) { log.trace("Processing next frame"); } int amountRead; headerBuffer = new byte[Frame.MAX_HEADER_SIZE]; try { do { amountRead = is.read(headerBuffer, 0, MIN_SEQ_HEADER_SIZE); if (amountRead == -1) { throw new SessionAbortedException(); } } while (amountRead == 0); } catch (java.net.SocketException e) { if (running) { throw e; } // socket closed intentionally (session closing) // so just return return; } if (headerBuffer[0] == (byte) MESSAGE_TYPE_SEQ[0]) { processSEQFrame(headerBuffer, amountRead, is); continue; } else { if (processCoreFrame(headerBuffer, amountRead, is) == false) { break; } } } } catch (IOException e) { log.error(e); socket = null; terminate(e.getMessage()); } catch (SessionAbortedException e) { terminate("Session aborted by remote peer."); } catch (Throwable e) { log.error(e); terminate(e.getMessage()); } if (log.isDebugEnabled()) { log.debug("Session listener thread exiting. State = " + TCPSession.this.getState()); } }