private bool readRequest() { int left = header.ContentLength - header.DataString.Length; int dataLen = 0; if (left > 0) { byte[] data = new byte[left]; try { dataLen = stream.Read(data, 0, left); if (dataLen == 0) { XmlRpcUtil.error("XmlRpcServerConnection::readRequest: Stream was closed"); return(false); } } catch (Exception ex) { XmlRpcUtil.error("XmlRpcServerConnection::readRequest: error while reading the rest of data ({0}).", ex.Message); return(false); } header.Append(Encoding.ASCII.GetString(data, 0, dataLen)); } // Otherwise, parse and dispatch the request XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.DEBUG, "XmlRpcServerConnection::readRequest read {0} bytes.", dataLen); if (!header.ContentComplete) { return(false); } _connectionState = ServerConnectionState.WRITE_RESPONSE; return(true); // Continue monitoring this source }
private bool writeResponse(string request) { string response = server.executeRequest(request); if (response.Length == 0) { XmlRpcUtil.error("XmlRpcServerConnection::writeResponse: empty response."); return(false); } try { MemoryStream memstream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(memstream)) { writer.Write(response); _bytesWritten = response.Length; } try { var buffer = memstream.GetBuffer(); stream.Write(buffer, 0, buffer.Length); } catch (Exception ex) { XmlRpcUtil.error(string.Format("Exception while writing response: {0}", ex.Message)); } } catch (Exception ex) { XmlRpcUtil.error("XmlRpcServerConnection::writeResponse: write error ({0}).", ex.Message); return(false); } /*catch (Exception ex) * { * XmlRpcUtil.error("XmlRpcServerConnection::writeResponse: write error ({0}).", ex.Message); * return false; * }*/ XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.DEBUG, "XmlRpcServerConnection::writeResponse: wrote {0} of {0} bytes.", _bytesWritten, response.Length); // Prepare to read the next request if (_bytesWritten == response.Length) { response = ""; _connectionState = ServerConnectionState.READ_HEADER; } return(_keepAlive); // Continue monitoring this source if true }
internal virtual bool readHeader(ref HTTPHeader header) { // Read available data int dataLen = 0; var stream = getStream(); if (stream == null) { throw new Exception("Could not access network stream"); } byte[] data = new byte[READ_BUFFER_LENGTH]; try { dataLen = stream.Read(data, 0, READ_BUFFER_LENGTH); if (dataLen == 0) { return(false); // If it is disconnect } if (header == null) { header = new HTTPHeader(Encoding.ASCII.GetString(data, 0, dataLen)); if (header.m_headerStatus == HTTPHeader.STATUS.UNINITIALIZED) { return(false); //should only happen if the constructor's invocation of Append did not happen as desired } } else if (header.Append(Encoding.ASCII.GetString(data, 0, dataLen)) == HTTPHeader.STATUS.PARTIAL_HEADER) { return(true); //if we successfully append a piece of the header, return true, but DO NOT change states } } catch (SocketException ex) { XmlRpcUtil.error("XmlRpcServerConnection::readHeader: error while reading header ({0}).", ex.Message); return(false); } catch (Exception ex) { XmlRpcUtil.error("XmlRpcServerConnection::readHeader: error while reading header ({0}).", ex.Message); return(false); } if (header.m_headerStatus != HTTPHeader.STATUS.COMPLETE_HEADER) { return(false); } return(true); }
private bool writeRequest() { if (_bytesWritten == 0) { XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.SPEW, "XmlRpcClient::writeRequest (attempt {0}):\n{1}\n", _sendAttempts + 1, _request); } // Try to write the request try { if (!socket.Connected) { XmlRpcUtil.error("XmlRpcClient::writeRequest not connected"); } MemoryStream memstream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(memstream)) { writer.Write(_request); writer.Flush(); } var stream = socket.GetStream(); try { var buffer = memstream.GetBuffer(); stream.Write(buffer, 0, buffer.Length); stream.Flush(); } catch (Exception ex) { XmlRpcUtil.error(string.Format("Exception while writing request: {0}", ex.Message)); } _bytesWritten = _request.Length; } catch (IOException ex) { XmlRpcUtil.error("Error in XmlRpcClient::writeRequest: write error ({0}).", ex.Message); return(false); } XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.INFO, "XmlRpcClient::writeRequest: wrote {0} of {1} bytes.", _bytesWritten, _request.Length); // Wait for the result if (_bytesWritten == _request.Length) { _connectionState = ConnectionState.READ_HEADER; header = null; } return(true); }
// Parse the method name and the argument values from the request. private string parseRequest(XmlRpcValue parms, string _request) { bool success = true; string methodName = "unknown"; //XmlRpcValue result = null; using (XmlReader reader = XmlReader.Create(new StringReader(_request))) { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(reader); // Parse response xml into result //int offset = 0; XmlNodeList xmlMethodNameList = xmldoc.GetElementsByTagName("methodName"); if (xmlMethodNameList.Count > 0) { XmlNode xmlMethodName = xmlMethodNameList[0]; methodName = xmlMethodName.InnerText; } XmlNodeList xmlParameters = xmldoc.GetElementsByTagName("param"); XmlNodeList xmlFault = xmldoc.GetElementsByTagName("fault"); if (xmlParameters.Count == 0) { XmlRpcUtil.error("Error in XmlRpcServer::parseRequest: Invalid request - no methodResponse. Request:\n{0}", _request); return(null); } parms.SetArray(xmlParameters.Count); for (int i = 0; i < xmlParameters.Count; i++) { var value = new XmlRpcValue(); value.fromXml(xmlParameters[i]["value"]); parms.asArray[i] = value; } if (xmlFault.Count > 0 && parms.fromXml(xmlFault[0])) { XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.WARNING, "Read fault on response for request:\n{0}\nFAULT: {1}", _request, parms.ToString()); } } return(methodName); }
// Possible IO states for the connection // XmlRpcSource interface implementation // Handle server responses. Called by the event dispatcher during execute. public override XmlRpcDispatch.EventType HandleEvent(XmlRpcDispatch.EventType eventType) { if (eventType == XmlRpcDispatch.EventType.Exception) { if (_connectionState == ConnectionState.WRITE_REQUEST && _bytesWritten == 0) { XmlRpcUtil.error("Error in XmlRpcClient::handleEvent: could not connect to server ({0}).", getSocketError()); } else { XmlRpcUtil.error("Error in XmlRpcClient::handleEvent (state {0}): {1}.", _connectionState, getSocketError()); } return(0); } if (_connectionState == ConnectionState.WRITE_REQUEST) { if (!writeRequest()) { return(0); } } if (_connectionState == ConnectionState.READ_HEADER) { if (!readHeader(ref header)) { return(0); } } if (_connectionState == ConnectionState.READ_RESPONSE) { if (!readResponse()) { return(0); } } // This should probably always ask for Exception events too return((_connectionState == ConnectionState.WRITE_REQUEST) ? XmlRpcDispatch.EventType.WritableEvent : XmlRpcDispatch.EventType.ReadableEvent); }
// Accept a client connection request and create a connection to // handle method calls from the client. private void acceptConnection() { bool p = true; // ReSharper disable once CSharpWarnings::CS0665 while (p = listener.Pending()) { try { _disp.AddSource(createConnection(listener.AcceptSocket()), XmlRpcDispatch.EventType.ReadableEvent); XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.WARNING, "XmlRpcServer::acceptConnection: creating a connection"); } catch (SocketException ex) { XmlRpcUtil.error("XmlRpcServer::acceptConnection: Could not accept connection ({0}).", ex.Message); Thread.Sleep(10); } } }
// Connect to the xmlrpc server private bool doConnect() { if (socket == null) { try { socket = new TcpClient(_host, _port); } catch (SocketException ex) { return(false); } } if (!socket.Connected) { close(); XmlRpcUtil.error("Error in XmlRpcClient::doConnect: Could not connect to server ({0}).", getSocketError()); return(false); } return(true); }
private bool readResponse() { int left = header.ContentLength - header.DataString.Length; int dataLen = 0; if (left > 0) { byte[] data = new byte[left]; try { var stream = socket.GetStream(); dataLen = stream.Read(data, 0, left); if (dataLen == 0) { XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.ERROR, "XmlRpcClient::readResponse: Stream was closed"); return(false); } } catch (Exception ex) { XmlRpcUtil.error("XmlRpcClient::readResponse: error while reading the rest of data ({0}).", ex.Message); return(false); } header.Append(Encoding.ASCII.GetString(data, 0, dataLen)); } if (header.ContentComplete) { // Otherwise, parse and dispatch the request XmlRpcUtil.log(XmlRpcUtil.XMLRPC_LOG_LEVEL.INFO, "XmlRpcClient::readResponse read {0} bytes.", _request.Length); _connectionState = ConnectionState.IDLE; return(false); // no need to continue monitoring because we're done reading the response } // Continue monitoring this source return(true); }
// Convert the response xml into a result value private bool parseResponse(XmlRpcValue result, string _response) { bool success = true; //XmlRpcValue result = null; using (XmlReader reader = XmlReader.Create(new StringReader(_response))) { XmlDocument response = new XmlDocument(); response.Load(reader); // Parse response xml into result //int offset = 0; XmlNodeList resp = response.GetElementsByTagName("methodResponse"); XmlNode responseNode = resp[0]; //if (!XmlRpcUtil.findTag(METHODRESPONSE_TAG, _response, out offset)) if (resp.Count == 0) { XmlRpcUtil.error("Error in XmlRpcClient::parseResponse: Invalid response - no methodResponse. Response:\n{0}", _response); return(false); } XmlElement pars = responseNode["params"]; XmlElement fault = responseNode["fault"]; //result = new XmlRpcValue(); if (pars != null) { bool isArray = false; var selection = pars.SelectNodes("param"); if (selection.Count > 1) { result.SetArray(selection.Count); int i = 0; foreach (XmlNode par in selection) { var value = new XmlRpcValue(); value.fromXml(par["value"]); result[i++] = value; } } else if (selection.Count == 1) { result.fromXml(selection[0]["value"]); } else { success = false; } } else if (fault != null && result.fromXml(fault)) { success = false; } else { XmlRpcUtil.error("Error in XmlRpcClient::parseResponse: Invalid response - no param or fault tag. Response:\n{0}", _response); } _response = ""; } return(success); }