Esempio n. 1
0
 public void ProcessRequest(AdkHttpRequestContext context)
 {
     throw new AdkHttpException
               (AdkHttpStatusCode.ClientError_403_Forbidden,
               "No application configured at this URL (" + context.Request.Url.ToString() +
               ")");
 }
        /**
         * We need to make sure that the url that we are trying to treat as a file
         * lies below the document root of the http server so that people can't grab
         * random files off your computer while this is running.
         */

        public void ProcessRequest(AdkHttpRequestContext context)
        {
            try {
                FileInfo filename =
                    new FileInfo(fVirtualDirectoryServer.MapPath(context.Request.Url));
                if (!filename.FullName.StartsWith(fVirtualDirectoryServer.PhysicalPath))
                {
                    context.Response.Status = AdkHttpStatusCode.ClientError_403_Forbidden;
                }
                else
                {
                    if (!filename.Exists)
                    {
                        if (filename.Extension == "")
                        {
                            context.Response.Status = AdkHttpStatusCode.Redirection_302_Found;
                            string newUrl = context.Request.Url.AbsolutePath + "/";
                            context.Response.Headers["Location"] = newUrl;
                            context.Response.AdditionalInfo      = "<a href=\"" + newUrl + "\">" + newUrl +
                                                                   "</a>";
                            return;
                        }
                        else
                        {
                            throw new FileNotFoundException("File Not Found", filename.FullName);
                        }
                    }
                    string aFileTime =
                        filename.LastWriteTimeUtc.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
                    string aDateTime = context.Request.Headers["If-Modified-Since"];
                    if (aDateTime != null && aFileTime == aDateTime)
                    {
                        context.Response.Status = AdkHttpStatusCode.Redirection_304_Not_Modified;
                    }
                    else
                    {
                        context.Response.ContentType = GetContentType(filename);
                        context.Response.Headers["Last-Modified"] = aFileTime;
                        // Open the file
                        using (
                            FileStream fs =
                                new FileStream(filename.FullName, FileMode.Open, FileAccess.Read)
                            ) {
                            Streams.CopyStream(fs, context.Response.GetResponseStream(), 4096);
                            fs.Close();
                        }
                    }
                }
            }
            catch (FileNotFoundException) {
                context.Response.Status = AdkHttpStatusCode.ClientError_404_Not_Found;
            }
        }
        public static void ProcessRequest(AdkSocketConnection socket,
                                          AdkHttpListener listener)
        {
            AdkHttpRequestContext context = socket.UserData as AdkHttpRequestContext;

            if (context == null)
            {
                AdkHttpConnection conn     = new AdkHttpConnection(socket, listener);
                AdkHttpResponse   response = new AdkHttpResponse(conn);
                AdkHttpRequest    request  = new AdkHttpRequest(conn);
                context = listener.Server.CreateContext(conn, request, response);
            }

            context.Connection.ProcessRequest(context, socket);
        }
Esempio n. 4
0
 public void ProcessRequest(AdkHttpRequestContext context)
 {
     context.Response.Headers.Add(OK_HEADER, OK_VALUE);
     context.Response.Write("OK");
 }
        private void ProcessRequest( AdkHttpRequestContext context,
                                     AdkSocketConnection socket )
        {
            int aStart = Environment.TickCount;

            bool keepAlive = true;
            AdkHttpRequest request = context.Request;
            AdkHttpResponse response = context.Response;
            try {
                context.Request.Receive( socket );
                if ( !context.Request.ReceiveComplete ) {
                    socket.UserData = context;
                    return;
                }
                else {
                    IAdkHttpHandler handler = fListener.GetHandlerForContext( request );
                    handler.ProcessRequest( context );
                }
            }

            catch ( AdkHttpException httpEx ) {
                _logError( httpEx );
                response.Clear();
                response.Status = httpEx.HttpExceptionCode;
                if ( (int) httpEx.HttpExceptionCode > 499 ) {
                    keepAlive = false;
                }
                response.AdditionalInfo = httpEx.GetType().FullName + " - " + httpEx.Message + " - " +
                                          httpEx.StackTrace;
            }
            catch ( Exception ex ) {
                keepAlive = false;
                _logError( ex );
                // TODO : Implement more verbose error output ( internalexceptions and such )
                response.Clear();
                response.Status = AdkHttpStatusCode.ServerError_500_Internal_Server_Error;
                response.AdditionalInfo = ex.GetType().FullName + " - " + ex.Message + " - " +
                                          ex.StackTrace;
            }

            // Clear out the context state because we are done with this request and the socket
            // may remain open for the next request
            socket.UserData = null;

            if ( socket.Connected ) {
                if ( keepAlive ) {
                    keepAlive = ShouldKeepAlive( context.Request );
                }
                context.Response.Headers.Add( "X-Powered-By", fListener.Server.Name );
                // Write the Response
                context.Response.AsyncFinishRequest( socket, context.Request, keepAlive );

                if ( (Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0 &&
                     fListener.Server.Log.IsDebugEnabled ) {
                    fListener.Server.Log.Info
                        ( string.Format
                              ( "Processed Request for {0}:{1} ( {2} ) in {3} milliseconds",
                                this.ClientEndPoint.Address, this.ClientEndPoint.Port,
                                context.Request.Path, (Environment.TickCount - aStart).ToString() ) );
                }
                if ( !keepAlive ) {
                    socket.Close();
                }
            }
        }
Esempio n. 6
0
        public void ProcessRequest(AdkHttpRequestContext context)
        {
            if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
            {
                Zone.Log.Debug
                    ("Received push message from " + context.Request.RemoteAddress + " (" +
                    context.Request.Url.Scheme + ")");
            }

            SIF_Ack           ack    = null;
            SifMessagePayload parsed = null;

            //Check request length and type
            if (!SifIOFormatter.IsValidContentLength(context.Request.ContentLength))
            {
                throw new AdkHttpException
                          (AdkHttpStatusCode.ClientError_400_Bad_Request,
                          "Content length Must be greater than zero");
            }

            if (!SifIOFormatter.IsValidContentMediaType(context.Request.ContentType))
            {
                throw new AdkHttpException(AdkHttpStatusCode.ClientError_415_Unsupported_Media_Type,
                                           "Content header does not support the specified media type: " + context.Request.ContentType);
            }

            //  Read raw content
            Stream        requestStream = context.Request.GetRequestStream();
            StringBuilder requestXml    = null;

            // If we need to convert the request stream to a string for either logging or messaging, do so
            if ((Adk.Debug & AdkDebugFlags.Message_Content) != 0)
            {
                requestXml = ConvertRequestToString(requestStream);
                Zone.Log.Debug
                    ("Received " + context.Request.ContentLength + " bytes:\r\n" +
                    requestXml.ToString());
            }

            TextReader requestReader = new StreamReader(requestStream, SifIOFormatter.ENCODING);

            Exception parseEx   = null;
            bool      reparse   = false;
            bool      cancelled = false;
            int       reparsed  = 0;

            do
            {
                try {
                    parseEx = null;

                    //  Parse content
                    parsed  = (SifMessagePayload)CreateParser().Parse(requestReader, Zone);
                    reparse = false;
                    parsed.LogRecv(Zone.Log);
                }
                catch (AdkParsingException adke) {
                    parseEx = adke;
                }
                catch (Exception ex) {
                    parseEx = ex;
                }

                //
                //	Notify listeners...
                //
                //	If we're asked to reparse the message, do so but do not notify
                //	listeners the second time around.
                //
                if (reparsed == 0)
                {
                    ICollection <IMessagingListener> msgList = MessageDispatcher.GetMessagingListeners(Zone);
                    if (msgList.Count > 0)
                    {
                        // Convert the stream to a string builder
                        if (requestXml == null)
                        {
                            requestXml = ConvertRequestToString(requestStream);
                        }

                        //	Determine message type before parsing
                        foreach (IMessagingListener listener in msgList)
                        {
                            try {
                                SifMessageType pload =
                                    Adk.Dtd.GetElementType(parsed.ElementDef.Name);
                                MessagingReturnCode code =
                                    listener.OnMessageReceived(pload, requestXml);
                                switch (code)
                                {
                                case MessagingReturnCode.Discard:
                                    cancelled = true;
                                    break;

                                case MessagingReturnCode.Reparse:
                                    requestReader = new StringReader(requestXml.ToString());
                                    reparse       = true;
                                    break;
                                }
                            }
                            catch (AdkException adke) {
                                parseEx = adke;
                            }
                        }
                    }
                }

                if (cancelled)
                {
                    return;
                }

                reparsed++;
            }while (reparse);

            if (parseEx != null)
            {
                //  TODO: Handle the case where SIF_OriginalSourceId and SIF_OriginalMsgId
                //  are not available because parsing failed. See SIFInfra
                //  Resolution #157.
                if (parseEx is SifException && parsed != null)
                {
                    //  Specific SIF error already provided to us by SIFParser
                    ack = parsed.AckError((SifException)parseEx);
                }
                else
                {
                    String errorMessage = null;
                    if (parseEx is AdkException)
                    {
                        errorMessage = parseEx.Message;
                    }
                    else
                    {
                        // Unchecked Throwable
                        errorMessage = "Could not parse message";
                    }

                    if (parsed == null)
                    {
                        SifException sifError = null;
                        if (parseEx is SifException)
                        {
                            sifError = (SifException)parseEx;
                        }
                        else
                        {
                            sifError = new SifException(
                                SifErrorCategoryCode.Xml,
                                SifErrorCodes.XML_GENERIC_ERROR_1,
                                "Could not parse message",
                                parseEx.ToString(),
                                this.Zone,
                                parseEx);
                        }
                        if (requestXml == null)
                        {
                            requestXml = ConvertRequestToString(requestStream);
                        }
                        ack = SIFPrimitives.ackError(
                            requestXml.ToString( ),
                            sifError,
                            this.Zone);
                    }
                    else
                    {
                        ack = parsed.AckError(
                            SifErrorCategoryCode.Generic,
                            SifErrorCodes.GENERIC_GENERIC_ERROR_1,
                            errorMessage,
                            parseEx.ToString());
                    }
                }

                if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
                {
                    Zone.Log.Warn
                        ("Failed to parse push message from zone \"" + Zone + "\": " + parseEx);
                }

                if (ack != null)
                {
                    //  Ack messages in the same version of SIF as the original message
                    if (parsed != null)
                    {
                        ack.SifVersion = parsed.SifVersion;
                    }
                    AckPush(ack, context.Response);
                }
                else
                {
                    //  If we couldn't build a SIF_Ack, returning an HTTP 500 is
                    //  probably the best we can do to let the server know that
                    //  we didn't get the message. Note this should cause the ZIS
                    //  to resend the message, which could result in a deadlock
                    //  condition. The administrator would need to manually remove
                    //  the offending message from the agent's queue.

                    if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
                    {
                        Zone.Log.Debug
                            ("Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)");
                    }
                    throw new AdkHttpException
                              (AdkHttpStatusCode.ServerError_500_Internal_Server_Error,
                              "Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)");
                }

                return;
            }

            //  Check SourceId to see if it matches this agent's SourceId
            String destId = parsed.DestinationId;

            if (destId != null && !destId.Equals(Zone.Agent.Id))
            {
                Zone.Log.Warn
                    ("Received push message for DestinationId \"" + destId +
                    "\", but agent is registered as \"" + Zone.Agent.Id + "\"");

                ack = parsed.AckError
                      (
                    SifErrorCategoryCode.Transport,
                    SifErrorCodes.WIRE_GENERIC_ERROR_1,
                    "Message not intended for this agent (SourceId of agent does not match DestinationId of message)",
                    "Message intended for \"" + destId + "\" but this agent is registered as \"" +
                    Zone.Agent.Id + "\"");

                AckPush(ack, context.Response);

                return;
            }

            //  Convert content to SIF message object and dispatch it
            ack = ProcessPush(parsed);

            //  Send SIF_Ack reply
            AckPush(ack, context.Response);
        }
        private void ProcessRequest(AdkHttpRequestContext context,
                                    AdkSocketConnection socket)
        {
            int aStart = Environment.TickCount;

            bool            keepAlive = true;
            AdkHttpRequest  request   = context.Request;
            AdkHttpResponse response  = context.Response;

            try {
                context.Request.Receive(socket);
                if (!context.Request.ReceiveComplete)
                {
                    socket.UserData = context;
                    return;
                }
                else
                {
                    IAdkHttpHandler handler = fListener.GetHandlerForContext(request);
                    handler.ProcessRequest(context);
                }
            }

            catch (AdkHttpException httpEx) {
                _logError(httpEx);
                response.Clear();
                response.Status = httpEx.HttpExceptionCode;
                if ((int)httpEx.HttpExceptionCode > 499)
                {
                    keepAlive = false;
                }
                response.AdditionalInfo = httpEx.GetType().FullName + " - " + httpEx.Message + " - " +
                                          httpEx.StackTrace;
            }
            catch (Exception ex) {
                keepAlive = false;
                _logError(ex);
                // TODO : Implement more verbose error output ( internalexceptions and such )
                response.Clear();
                response.Status         = AdkHttpStatusCode.ServerError_500_Internal_Server_Error;
                response.AdditionalInfo = ex.GetType().FullName + " - " + ex.Message + " - " +
                                          ex.StackTrace;
            }

            // Clear out the context state because we are done with this request and the socket
            // may remain open for the next request
            socket.UserData = null;

            if (socket.Connected)
            {
                if (keepAlive)
                {
                    keepAlive = ShouldKeepAlive(context.Request);
                }
                context.Response.Headers.Add("X-Powered-By", fListener.Server.Name);
                // Write the Response
                context.Response.AsyncFinishRequest(socket, context.Request, keepAlive);

                if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0 &&
                    fListener.Server.Log.IsDebugEnabled)
                {
                    fListener.Server.Log.Info
                        (string.Format
                            ("Processed Request for {0}:{1} ( {2} ) in {3} milliseconds",
                            this.ClientEndPoint.Address, this.ClientEndPoint.Port,
                            context.Request.Path, (Environment.TickCount - aStart).ToString()));
                }
                if (!keepAlive)
                {
                    socket.Close();
                }
            }
        }
Esempio n. 8
0
 public void ProcessRequest( AdkHttpRequestContext context )
 {
     throw new AdkHttpException
         ( AdkHttpStatusCode.ClientError_403_Forbidden,
           "No application configured at this URL (" + context.Request.Url.ToString() +
           ")" );
 }
        public void ProcessRequest( AdkHttpRequestContext context )
        {
            if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
                Zone.Log.Debug
                    ( "Received push message from " + context.Request.RemoteAddress + " (" +
                      context.Request.Url.Scheme + ")" );
            }

            SIF_Ack ack = null;
            SifMessagePayload parsed = null;

            //Check request length and type
            if (!SifIOFormatter.IsValidContentLength(context.Request.ContentLength)) {
                throw new AdkHttpException
                    ( AdkHttpStatusCode.ClientError_400_Bad_Request,
                      "Content length Must be greater than zero" );
            }

            if (!SifIOFormatter.IsValidContentMediaType(context.Request.ContentType)) {
                throw new AdkHttpException(AdkHttpStatusCode.ClientError_415_Unsupported_Media_Type,
                    "Content header does not support the specified media type: " + context.Request.ContentType);
            }

            //  Read raw content
            Stream requestStream = context.Request.GetRequestStream();
            StringBuilder requestXml = null;

            // If we need to convert the request stream to a string for either logging or messaging, do so
            if ( (Adk.Debug & AdkDebugFlags.Message_Content) != 0 ) {
                requestXml = ConvertRequestToString( requestStream );
                Zone.Log.Debug
                    ( "Received " + context.Request.ContentLength + " bytes:\r\n" +
                      requestXml.ToString() );
            }

            TextReader requestReader = new StreamReader( requestStream, SifIOFormatter.ENCODING );

            Exception parseEx = null;
            bool reparse = false;
            bool cancelled = false;
            int reparsed = 0;

            do {
                try {
                    parseEx = null;

                    //  Parse content
                    parsed = (SifMessagePayload) CreateParser().Parse( requestReader, Zone );
                    reparse = false;
                    parsed.LogRecv( Zone.Log );
                }
                catch ( AdkParsingException adke ) {
                    parseEx = adke;
                }
                catch ( Exception ex ) {
                    parseEx = ex;
                }

                //
                //	Notify listeners...
                //
                //	If we're asked to reparse the message, do so but do not notify
                //	listeners the second time around.
                //
                if ( reparsed == 0 ) {
                   ICollection<IMessagingListener> msgList = MessageDispatcher.GetMessagingListeners(Zone);
                    if ( msgList.Count > 0 ) {
                        // Convert the stream to a string builder
                        if ( requestXml == null ) {
                            requestXml = ConvertRequestToString( requestStream );
                        }

                        //	Determine message type before parsing
                        foreach ( IMessagingListener listener in msgList ) {
                            try {
                                SifMessageType pload =
                                    Adk.Dtd.GetElementType( parsed.ElementDef.Name );
                                MessagingReturnCode code =
                                    listener.OnMessageReceived( pload, requestXml );
                                switch ( code ) {
                                    case MessagingReturnCode.Discard:
                                        cancelled = true;
                                        break;

                                    case MessagingReturnCode.Reparse:
                                        requestReader = new StringReader( requestXml.ToString() );
                                        reparse = true;
                                        break;
                                }
                            }
                            catch ( AdkException adke ) {
                                parseEx = adke;
                            }
                        }
                    }
                }

                if ( cancelled ) {
                    return;
                }

                reparsed++;
            }
            while ( reparse );

            if ( parseEx != null ) {
                //  TODO: Handle the case where SIF_OriginalSourceId and SIF_OriginalMsgId
                //  are not available because parsing failed. See SIFInfra
                //  Resolution #157.
                if( parseEx is SifException && parsed != null )
                {
                    //  Specific SIF error already provided to us by SIFParser
                    ack = parsed.AckError( (SifException)parseEx );
                }
                else{
                    String errorMessage = null;
                    if( parseEx is AdkException )
                    {
                        errorMessage = parseEx.Message;
                    } else {
                        // Unchecked Throwable
                        errorMessage = "Could not parse message";
                    }

                    if( parsed == null )
                    {
                        SifException sifError = null;
                        if( parseEx is SifException ){
                            sifError = (SifException) parseEx;

                        }else {
                            sifError = new SifException(
                                SifErrorCategoryCode.Xml,
                                SifErrorCodes.XML_GENERIC_ERROR_1,
                                "Could not parse message",
                                parseEx.ToString(),
                                this.Zone,
                                parseEx );
                        }
                        if( requestXml == null )
                        {
                            requestXml = ConvertRequestToString( requestStream );
                        }
                        ack = SIFPrimitives.ackError(
                                requestXml.ToString( ),
                                sifError,
                                this.Zone );
                    }
                    else
                    {
                        ack = parsed.AckError(
                            SifErrorCategoryCode.Generic,
                            SifErrorCodes.GENERIC_GENERIC_ERROR_1,
                            errorMessage,
                            parseEx.ToString() );
                    }

                }

                if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
                    Zone.Log.Warn
                        ( "Failed to parse push message from zone \"" + Zone + "\": " + parseEx );
                }

                if ( ack != null ) {
                    //  Ack messages in the same version of SIF as the original message
                    if ( parsed != null ) {
                        ack.SifVersion = parsed.SifVersion;
                    }
                    AckPush( ack, context.Response );
                }
                else {
                    //  If we couldn't build a SIF_Ack, returning an HTTP 500 is
                    //  probably the best we can do to let the server know that
                    //  we didn't get the message. Note this should cause the ZIS
                    //  to resend the message, which could result in a deadlock
                    //  condition. The administrator would need to manually remove
                    //  the offending message from the agent's queue.

                    if ( (Adk.Debug & AdkDebugFlags.Messaging) != 0 ) {
                        Zone.Log.Debug
                            ( "Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)" );
                    }
                    throw new AdkHttpException
                        ( AdkHttpStatusCode.ServerError_500_Internal_Server_Error,
                          "Could not generate SIF_Ack for failed push message (returning HTTP/1.1 500)" );
                }

                return;
            }

            //  Check SourceId to see if it matches this agent's SourceId
            String destId = parsed.DestinationId;
            if ( destId != null && !destId.Equals( Zone.Agent.Id ) ) {
                Zone.Log.Warn
                    ( "Received push message for DestinationId \"" + destId +
                      "\", but agent is registered as \"" + Zone.Agent.Id + "\"" );

                ack = parsed.AckError
                    (
                    SifErrorCategoryCode.Transport,
                    SifErrorCodes.WIRE_GENERIC_ERROR_1,
                    "Message not intended for this agent (SourceId of agent does not match DestinationId of message)",
                    "Message intended for \"" + destId + "\" but this agent is registered as \"" +
                    Zone.Agent.Id + "\"" );

                AckPush( ack, context.Response );

                return;
            }

            //  Convert content to SIF message object and dispatch it
            ack = ProcessPush( parsed );

            //  Send SIF_Ack reply
            AckPush( ack, context.Response );
        }