/** * Handle an exception - construct a sip reply and send it back to the caller. * * @param ex The exception thrown at us by our application. */ public void handleException(SIPServerException ex) { // Return a parse error message to the client on the other end // if he is still alive. // ex.printStackTrace(); int rc = ex.getRC(); Request request = (Request) ex.getSIPMessage(); Response response; String msgString = ex.getMessage(); if (rc != 0) { response = request.createResponse(rc, msgString); // messageFormatter.newResponse(rc,request,msgString); try { sendMessage(response); } catch (IOException ioex) { ServerLog.logException(ioex); } } else { // Assume that the message has already been formatted. try { sendMessage(msgString); } catch (IOException ioex) { ServerLog.logException(ioex); } } }
public void testA() { Hashtable<String, String> initialLineDict = new Hashtable<String, String>(); Hashtable<String, String> headLinesDict = new Hashtable<String, String>(); MyResponseBuffer buf = new MyResponseBuffer(); request = new MyHttpServletRequest(initialLineDict, headLinesDict, buf); assertTrue(true); ServerLog serverLog1 = ServerLog.getInstance("testServerLog.txt"); ServerLog serverLog2 = ServerLog.getInstance("testServerLog2.txt"); assertEquals("testServerLog.txt", serverLog2.serverLogName); assertEquals(serverLog1, serverLog2); }
/** * Return a formatted message to the client. We try to re-connect with the peer on the other end * if possible. * * @param msg Message to send. * @throws IOException If there is an error sending the message */ public void sendMessage(Message sipMessage) throws IOException { if (sipMessage == null) throw new NullPointerException("null arg!"); byte[] msg = sipMessage.encodeAsBytes(); long time = System.currentTimeMillis(); this.sendMessage(msg, true); if (ServerLog.needsLogging(ServerLog.TRACE_MESSAGES)) logMessage(sipMessage, peerAddress, peerPort, time); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); if (jjNumber.isDigit(jjTools.getParameter(request, "maxSize"))) { maxSize = Long.parseLong(jjTools.getParameter(request, "maxSize")); } response.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); name = name == null ? "" : name; response.setContentType("text/plain"); super.init(getServletConfig()); // response.setContentType("text/plain"); PrintWriter out = response.getWriter(); // out.println(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // fileItemFactory.setSizeThreshold(1024 * 1024); //1 MB try { ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { /* * Field */ // out.println("Field Name=" + item.getFieldName() + ", Value=" + // item.getString()); data.put(item.getFieldName(), item.getString()); } else { /* * File */ File folderAddress = new File(request.getServletContext().getRealPath(Save_Folder_Name)); // "/" + String extension = ""; String nameWithoutExtension = item.getName(); if (item.getName().lastIndexOf(".") > -1) { extension = item.getName().substring(item.getName().lastIndexOf(".")); nameWithoutExtension = item.getName() .substring( item.getName().lastIndexOf("\\") + 1, item.getName().lastIndexOf(".")); } folderAddress.mkdirs(); nameWithoutExtension = "P"; File file = new File( folderAddress + "/" + nameWithoutExtension.toLowerCase() + jjNumber.getRandom(10) + extension.toLowerCase()); String i = "0000000000"; while (file.exists()) { i = jjNumber.getRandom(10); file = new File( folderAddress + "/" + nameWithoutExtension.toLowerCase() + i + extension.toLowerCase()); } if (!name.equals("")) { file = new File(folderAddress + "/" + name); } // out.println("File Name=" + item.getName() // + ", Field Name=" + item.getFieldName() // + ", Content type=" + item.getContentType() // + ", File Size=" + item.getSize() // + ", Save Address=" + file); // out.println(file); // String urlPath = // request.getRequestURL().toString().replace("Upload2", "Upload") + "/" + // file.getName().replace("\\", "/"); // out.println("<html><head><meta http-equiv='Content-Type' // content='text/html; charset=utf-8'></head><body><input type='text' name='T1' size='58' // value='" + urlPath + "'></body></html>"); data.put(item.getFieldName(), file.getAbsolutePath()); if (!file.getName().toLowerCase().endsWith(".exe")) { item.write(file); } long size = file.length(); ServerLog.Print("?>>>>>>" + file + " - Size:" + size); if (size > maxSize) { file.delete(); out.print("big"); } else { out.print( file.getName() .replace(" ", "%20") .replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", "")); ServerLog.Print("Write pic in: " + file + " size:" + file.length()); String name2 = file.getName().substring(0, file.getName().lastIndexOf(".")); String extension2 = file.getName() .substring(file.getName().lastIndexOf(".") + 1, file.getName().length()); File file2 = new File(file.getParent() + "/" + name2 + "_small." + extension2); if (extension2.toLowerCase().equals("jpg") || extension2.toLowerCase().equals("png") || extension2.toLowerCase().equals("gif")) { jjPicture.doChangeSizeOfPic(file, file2, 250); } } } } } catch (Exception ex) { Server.ErrorHandler(ex); } out.flush(); out.close(); }
/** * Gets invoked by the parser as a callback on successful message parsing (i.e. no parser errors). * * @param sipMessage Mesage to process (this calls the application for processing the message). */ public void processMessage(Message sipMessage) { if (!stack.isAlive()) { if (LogWriter.needsLogging) LogWriter.logMessage( LogWriter.TRACE_DEBUG, "MsgChannel " + this + " is dropping message as the stack is closing"); return; // drop messages when closing, avoid Exceptions } try { if (LogWriter.needsLogging) LogWriter.logMessage( "[TCPMessageChannel]-> Processing incoming message: " + sipMessage.getFirstLine()); if (sipMessage.getFromHeader() == null || sipMessage.getTo() == null || sipMessage.getCallId() == null || sipMessage.getCSeqHeader() == null || sipMessage.getViaHeaders() == null) { String badmsg = sipMessage.encode(); if (LogWriter.needsLogging) { ServerLog.logMessage("bad message " + badmsg); ServerLog.logMessage(">>> Dropped Bad Msg"); } stack.logBadMessage(badmsg); return; } ViaList viaList = sipMessage.getViaHeaders(); // For a request // first via header tells where the message is coming from. // For response, this has already been recorded in the outgoing // message. if (sipMessage instanceof Request) { ViaHeader v = (ViaHeader) viaList.first(); if (v.hasPort()) { viaPort = v.getPort(); } else { viaPort = SIPMessageStack.DEFAULT_PORT; } this.peerProtocol = v.getTransport(); try { if (peerPort == -1) peerPort = mySock.getPort(); this.peerAddress = mySock.getAddress(); // Log this because it happens when the remote host identifies // as a FQDN but this is not resolvable to an IP by the OS. // S40 doesn't have DNS settings, for instance, so if the APN // is not able to resolve all the addresses of the SIP/IMS core, // this problem will appear. if (peerAddress == null && LogWriter.needsLogging) LogWriter.logMessage( LogWriter.TRACE_EXCEPTION, "WARNING! Socket.getAddress() returned 'null'!!!"); // Be warned, the host comparison may fail if socket.getAddress() // returns a domain name as the Via Host will be a numeric IP. // FIXME: No idea. Doing a DNS lookup or reverse DNS lookup // can be misleading because they can be non-matching, that is, // DNS(peerAddressName) != ReverseDNS(peerAddressIP) if (v.hasParameter(ViaHeader.RPORT) || !v.getHost().equals(this.peerAddress)) { if (LogWriter.needsLogging) LogWriter.logMessage( LogWriter.TRACE_MESSAGES, "WARNING! \"Received\" parameter " + "has been temporarily disabled. Response will be sent to topmost Via Host: " + v.getHost()); this.peerAddress = v.getHost(); // if (LogWriter.needsLogging) // LogWriter.logMessage(LogWriter.TRACE_MESSAGES, "Adding // \"received\" parameter" + // " to incoming request with value: " + peerAddress + // " because it doesn't match the Via host " + v.getHost()); // v.setParameter(ViaHeader.RECEIVED, this.peerAddress); } if (v.hasParameter(ViaHeader.RPORT)) v.setParameter(ViaHeader.RPORT, Integer.toString(this.peerPort)); /* * If socket is invalid, close it because it is useless and dangerous. * Also if we ran out of slots for new sockets, as this could prevent * incoming connections from being accepted. */ if (mySock.getAddress() == null || (stack.maxConnections != -1 && tcpMessageProcessor.getNumConnections() >= stack.maxConnections)) { stack.ioHandler.disposeSocket(mySock, myClientInputStream, myClientOutputStream); mySock = null; myClientInputStream = null; myClientOutputStream = null; if (stack.maxConnections != -1) { synchronized (tcpMessageProcessor) { tcpMessageProcessor.decreaseNumConnections(); tcpMessageProcessor.notify(); } } } // reuse socket even for outgoing requests else if (!this.isCached) { ((TCPMessageProcessor) this.messageProcessor).cacheMessageChannel(this); String key = "TCP" + ":" + stack.ioHandler.makeKey(peerAddress, peerPort); stack.ioHandler.putSocket(key, mySock, myClientOutputStream, myClientInputStream); } } catch (IOException e) { e.printStackTrace(); } } // System.out.println("receiver address = " + receiverAddress); // For each part of the request header, fetch it and process it long receptionTime = System.currentTimeMillis(); if (sipMessage instanceof Request) { // This is a request - process the request. Request sipRequest = (Request) sipMessage; // Create a new sever side request processor for this // message and let it handle the rest. if (LogWriter.needsLogging) { LogWriter.logMessage("----Processing Message---"); } // TODO: check maximum size of request SIPServerRequestInterface sipServerRequest = stack.newSIPServerRequest(sipRequest, this); if (sipServerRequest != null) { try { sipServerRequest.processRequest(sipRequest, this); ServerLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), false, receptionTime); } catch (SIPServerException ex) { ServerLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), ex.getMessage(), false, receptionTime); handleException(ex); } } else { if (LogWriter.needsLogging) LogWriter.logMessage("Dropping request -- null sipServerRequest"); } } else { // This is a response message - process it. Response sipResponse = (Response) sipMessage; // TODO: check maximum size of the response SIPServerResponseInterface sipServerResponse = stack.newSIPServerResponse(sipResponse, this); if (LogWriter.needsLogging) LogWriter.logMessage("got a response interface " + sipServerResponse); try { // Responses with no ClienTransaction associated will not be processed // as they may cause a NPE in the EventScanner thread. if (sipServerResponse != null) sipServerResponse.processResponse(sipResponse, this); else { if (LogWriter.needsLogging) { LogWriter.logMessage("null sipServerResponse!"); } } } catch (SIPServerException ex) { // An error occured processing the message -- just log it. ServerLog.logMessage( sipMessage, getPeerAddress().toString() + ":" + getPeerPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), ex.getMessage(), false, receptionTime); // Ignore errors while processing responses?? } } } catch (Exception ee) { if (stack.isAlive()) { throw new RuntimeException(ee.getClass() + ":" + ee.getMessage()); } // else ignore exceptions } finally { // this.tcpMessageProcessor.useCount --; } }
/** * Actually process the parsed SIP message. * * @param sipMessage */ public void processMessage(Message sipMessage) { if (sipMessage instanceof Request) { Request sipRequest = (Request) sipMessage; // This is a request - process it. SIPServerRequestInterface sipServerRequest = stack.newSIPServerRequest(sipRequest, this); // Drop it if there is no request returned if (sipServerRequest == null) { if (LogWriter.needsLogging) { LogWriter.logMessage("Null request interface returned"); } return; } try { if (LogWriter.needsLogging) LogWriter.logMessage( "About to process " + sipRequest.getFirstLine() + "/" + sipServerRequest); sipServerRequest.processRequest(sipRequest, this); if (LogWriter.needsLogging) LogWriter.logMessage( "Done processing " + sipRequest.getFirstLine() + "/" + sipServerRequest); // So far so good -- we will commit this message if // all processing is OK. if (ServerLog.needsLogging(ServerLog.TRACE_MESSAGES)) { if (sipServerRequest.getProcessingInfo() == null) { ServerLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), false, new Long(receptionTime).toString()); } else { ServerLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), sipServerRequest.getProcessingInfo(), false, new Long(receptionTime).toString()); } } } catch (SIPServerException ex) { if (ServerLog.needsLogging(ServerLog.TRACE_MESSAGES)) { ServerLog.logMessage( sipMessage, sipRequest.getViaHost() + ":" + sipRequest.getViaPort(), stack.getHostAddress() + ":" + stack.getPort(this.getTransport()), ex.getMessage(), false, new Long(receptionTime).toString()); } handleException(ex); } } else { // Handle a SIP Response message. Response sipResponse = (Response) sipMessage; SIPServerResponseInterface sipServerResponse = stack.newSIPServerResponse(sipResponse, this); try { if (sipServerResponse != null) { sipServerResponse.processResponse(sipResponse, this); // Normal processing of message. } else { if (LogWriter.needsLogging) { LogWriter.logMessage("null sipServerResponse!"); } } } catch (SIPServerException ex) { if (ServerLog.needsLogging(ServerLog.TRACE_MESSAGES)) { this.logResponse(sipResponse, receptionTime, ex.getMessage() + "-- Dropped!"); } ServerLog.logException(ex); } } }