Ejemplo n.º 1
0
        private void _handleHandshakeRequest(BaseClient sender, RequestReceivedEventArgs e)
        {
            if (handshakeStep == 0)
                using (var br = new BinaryReader(e.Response.RequestPayloadStream, Encoding.UTF8))
                {
                    int vma = br.ReadInt32();
                    int vmi = br.ReadInt32();

                    if (ProtocolVersion.Major != vma || ProtocolVersion.Minor != vmi)
                        _CheckIfStopped(new NotSupportedException("vProto Protocol Version mismatch."));
                    else
                    {
                        handshakeStep = 1;

                        using (var str = new MemoryStream())
                        using (BinaryWriter bw = new BinaryWriter(str, Encoding.UTF8))
                        {
                            bw.Write(ProtocolVersion.Major);
                            bw.Write(ProtocolVersion.Minor);

                            bw.Flush();

                            e.Response.SetPayload(str, SeekOrigin.Begin).Send();
                        }
                    }
                }
            else if (handshakeStep == 1)
                using (var br = new BinaryReader(e.Response.RequestPayloadStream, Encoding.UTF8))
                {
                    this._id = br.ReadInt32();

                    int peers_cnt = br.ReadInt32();
                    int[] peers = null;

                    if (peers_cnt != -1)
                    {
                        peers = new int[peers_cnt];

                        for (int i = peers_cnt - 1; i >= 0; i--)
                            peers[i] = br.ReadInt32();
                    }

                    lock (_peers_lock)
                    {
                        _peers = new List<int>(peers);

                        if (peers != null)
                            for (int i = 0; i < _peers_queued_temp.Count; i++)
                                if (!_peers.Contains(_peers_queued_temp[i]))
                                    _peers.Add(_peers_queued_temp[i]);

                        _peers_queued_temp = null;
                    }

                    _FinishHandhake();

                    e.Response.Send();
                }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Executes the handlers for a specified request type.
        /// </summary>
        /// <param name="key">The request type.</param>
        /// <param name="client">Client on which to execute handler; provided in event delegate.</param>
        /// <param name="e">Desired event arguments.</param>
        public void ExecuteHandler(short key, BaseClient client, RequestReceivedEventArgs e)
        {
            ClientEventHandler<RequestReceivedEventArgs> value;

            if (TryGetValue(key, out value))
            {
                value.Invoke(client, e);
            }
        }
        /// <summary>
        /// Invoked on receipt of a request from the other side.
        /// </summary>
        /// <param name="pack">Package detailing request data.</param>
        protected virtual void OnInternalRequestReceived(Package pack)
        {
            var res = new Response(this, pack.Header.IDTop, pack.Header.IDBottom, pack.Payload, new TimeSpan(0, 0, 0, 0, pack.Header.RequestTimeout * 10), DateTime.Now) { isInternal = pack.Header.Type == PackageType.InternalRequest };

            if (pack.Header.Type == PackageType.InternalRequest)
            {
                PendingInternalResponses.Add(res);

                var e = new RequestReceivedEventArgs(res);

                InternalRequestHandlers.ExecuteHandler(pack.Header.IDBottom, this, e);
            }
            else
            {
                PendingResponses.Add(res);

                var e = new RequestReceivedEventArgs(res);

                OnRequestReceived(e);
                RequestHandlers.ExecuteHandler(pack.Header.IDBottom, this, e);
            }
        }
Ejemplo n.º 4
0
 public Task HandleRequest(object sender, RequestReceivedEventArgs args)
 {
     return(_requestHandler.HandleRequest(sender, args));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Extracts the parameters from the query string portion of the URL.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private Parameters ExtractParameters(RequestReceivedEventArgs args)
        {
            var result = new Parameters()
            {
                ReportType            = QueryString(args, "rep", true),
                FromRow               = QueryInt(args, "fromrow", -1),
                ToRow                 = QueryInt(args, "torow", -1),
                SortField1            = QueryString(args, "sort1", false),
                SortField2            = QueryString(args, "sort2", false),
                SortAscending1        = QueryString(args, "sort1dir", true) != "DESC",
                SortAscending2        = QueryString(args, "sort2dir", true) != "DESC",
                UseAlternateCallsigns = QueryBool(args, "altCall", false),
            };

            foreach (string name in args.QueryString)
            {
                var caselessName = name.ToUpper();
                if (caselessName.StartsWith("CALL-"))
                {
                    result.Callsign = DecodeStringFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("COU-"))
                {
                    result.Country = DecodeStringFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("DATE-"))
                {
                    result.Date = DecodeDateRangeFilter(result.Date, name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("FALT-"))
                {
                    result.FirstAltitude = DecodeIntRangeFilter(result.FirstAltitude, name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("ICAO-"))
                {
                    result.Icao = DecodeStringFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("EMG-"))
                {
                    result.IsEmergency = DecodeBoolFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("LALT-"))
                {
                    result.LastAltitude = DecodeIntRangeFilter(result.LastAltitude, name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("OP-"))
                {
                    result.Operator = DecodeStringFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("REG-"))
                {
                    result.Registration = DecodeStringFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("MIL-"))
                {
                    result.IsMilitary = DecodeBoolFilter(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("WTC-"))
                {
                    result.WakeTurbulenceCategory = DecodeEnumFilter <WakeTurbulenceCategory>(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("SPC-"))
                {
                    result.Species = DecodeEnumFilter <Species>(name, args.QueryString[name]);
                }
                else if (caselessName.StartsWith("TYP-"))
                {
                    result.Type = DecodeStringFilter(name, args.QueryString[name]);
                }
            }
            if (result.Date != null)
            {
                result.Date.NormaliseRange();
            }

            return(result);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Returns the double? value associated with the name or null if there is no value.
 /// </summary>
 /// <param name="args"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 protected double?QueryNDouble(RequestReceivedEventArgs args, string name)
 {
     return(QueryNDouble(QueryString(args, name, false)));
 }
Ejemplo n.º 7
0
 /// <summary>
 /// When overridden by a derivee this examines the args to see whether the request can be handled by the object and then,
 /// if it can, it supplies content for the request.
 /// </summary>
 /// <param name="server"></param>
 /// <param name="args"></param>
 /// <returns>True if the request was handled by the object, false if it was not.</returns>
 protected abstract bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args);
Ejemplo n.º 8
0
        private void TranscribeDatabaseRecordsToJson(List <BaseStationFlight> dbFlights, List <ReportFlightJson> jsonFlights, List <ReportAircraftJson> jsonAircraft, List <ReportAirportJson> jsonAirports, List <ReportRouteJson> jsonRoutes, RequestReceivedEventArgs args, Parameters parameters)
        {
            var aircraftIdMap = new Dictionary <int, int>();
            var airportMap    = new Dictionary <string, int>();
            var routeMap      = new Dictionary <string, int>();

            int rowNumber = parameters.FromRow < 1 ? 1 : parameters.FromRow + 1;

            foreach (var dbFlight in dbFlights)
            {
                var jsonFlight = AddReportFlightJson(dbFlight, jsonFlights, ref rowNumber);

                if (jsonAircraft != null)
                {
                    var dbAircraft = dbFlight.Aircraft;
                    if (dbAircraft == null)
                    {
                        jsonFlight.AircraftIndex = jsonAircraft.Count;
                        jsonAircraft.Add(new ReportAircraftJson()
                        {
                            IsUnknown = true
                        });
                    }
                    else
                    {
                        int aircraftIndex;
                        if (!aircraftIdMap.TryGetValue(dbAircraft.AircraftID, out aircraftIndex))
                        {
                            aircraftIndex = jsonAircraft.Count;
                            aircraftIdMap.Add(dbAircraft.AircraftID, aircraftIndex);
                            jsonAircraft.Add(CreateReportAircraftJson(dbAircraft, args));
                        }
                        jsonFlight.AircraftIndex = aircraftIndex;
                    }
                }

                int routeIndex = -1;
                if (!String.IsNullOrEmpty(dbFlight.Callsign) && !routeMap.TryGetValue(dbFlight.Callsign, out routeIndex))
                {
                    var operatorCode = dbFlight.Aircraft != null ? dbFlight.Aircraft.OperatorFlagCode : null;
                    foreach (var routeCallsign in _CallsignParser.GetAllRouteCallsigns(dbFlight.Callsign, operatorCode))
                    {
                        var sdmRoute = StandingDataManager.FindRoute(routeCallsign);
                        if (sdmRoute == null)
                        {
                            routeIndex = -1;
                        }
                        else
                        {
                            var jsonRoute = new ReportRouteJson()
                            {
                                FromIndex = BuildAirportJson(sdmRoute.From, airportMap, jsonAirports),
                                ToIndex   = BuildAirportJson(sdmRoute.To, airportMap, jsonAirports),
                            };
                            foreach (var stopover in sdmRoute.Stopovers)
                            {
                                int index = BuildAirportJson(stopover, airportMap, jsonAirports);
                                if (index != -1)
                                {
                                    jsonRoute.StopoversIndex.Add(index);
                                }
                            }

                            routeIndex = jsonRoutes.Count;
                            jsonRoutes.Add(jsonRoute);
                            routeMap.Add(dbFlight.Callsign, routeIndex);

                            break;
                        }
                    }
                }
                jsonFlight.RouteIndex = routeIndex;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Raised by the provider when a new request is received from the user.
        /// </summary>
        /// <param name="asyncResult"></param>
        private void GetContextHandler(IAsyncResult asyncResult)
        {
            if (Provider.IsListening)
            {
                bool     providerIsStable = true;
                IContext context          = null;

                try {
                    context = Provider.EndGetContext(asyncResult);
                } catch (HttpListenerException ex) {
                    // These are just discarded, they're usually disconnections by the user made before we can process the request
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                } catch (ObjectDisposedException ex) {
                    // These are usually thrown during program shutdown, after the provider has gone away but while requests are outstanding
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    providerIsStable = false;
                } catch (Exception ex) {
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    OnExceptionCaught(new EventArgs <Exception>(ex));
                    providerIsStable = false;
                }

                try {
                    if (providerIsStable)
                    {
                        Provider.BeginGetContext(GetContextHandler);
                    }
                } catch (HttpListenerException ex) {
                    // These can be thrown if the server is taken offline between the EndGetContext above and this BeginGetContext
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    context = null;
                } catch (ObjectDisposedException ex) {
                    // These are usually thrown during program shutdown for the same reasons that EndGetContext can throw them
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    context = null;
                } catch (InvalidOperationException ex) {
                    // These are thrown when the provider is taken offline between the check above for Provider.IsListening and
                    // the call to BeginGetContext
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    context = null;
                } catch (Exception ex) {
                    Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    OnExceptionCaught(new EventArgs <Exception>(ex));
                    context = null;
                }

                if (context != null)
                {
                    try {
                        var requestArgs = new RequestReceivedEventArgs(context.Request, context.Response, Root);
                        if (Authenticated(context))
                        {
                            var startTime = Provider.UtcNow;
                            OnBeforeRequestReceived(requestArgs);
                            OnRequestReceived(requestArgs);
                            OnAfterRequestReceived(requestArgs);

                            if (!requestArgs.Handled)
                            {
                                context.Response.StatusCode = HttpStatusCode.NotFound;
                            }

                            var fullClientAddress = String.Format("{0}:{1}", requestArgs.ClientAddress, context.Request.RemoteEndPoint.Port);
                            var responseArgs      = new ResponseSentEventArgs(requestArgs.PathAndFile, fullClientAddress, requestArgs.ClientAddress,
                                                                              context.Response.ContentLength, requestArgs.Classification, context.Request,
                                                                              (int)context.Response.StatusCode, (int)(Provider.UtcNow - startTime).TotalMilliseconds);
                            OnResponseSent(responseArgs);
                        }
                    } catch (HttpListenerException ex) {
                        // These are usually thrown when the browser disconnects while the event handler tries to send data to it. You can get a lot
                        // of these, we just discard them to prevent them spamming logs or the display with messages we can't do anything about.
                        Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    } catch (Exception ex) {
                        Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                        OnExceptionCaught(new EventArgs <Exception>(ex));
                    }

                    try {
                        context.Response.OutputStream.Close();
                    } catch (Exception ex) {
                        // We can get a lot of exceptions from closing the stream if the client browser has disconnected, it's exception spam.
                        Debug.WriteLine(String.Format("WebServer.GetContextHandler caught exception {0}", ex.ToString()));
                    }
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles a potential request for a JSON file.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="responder"></param>
        /// <returns></returns>
        public bool ProcessJsonRequest(RequestReceivedEventArgs args, IResponder responder)
        {
            var result = false;

            var mappedView = FindMappedView(args);

            if (mappedView != null)
            {
                mappedView.LastContactUtc = DateTime.UtcNow;

                var normalisedFile = NormaliseString(args.File);
                if (normalisedFile == NormaliseString(ViewHeartbeatMethod))
                {
                    result = true;
                }
                else if (normalisedFile == NormaliseString(GetDeferredResponseMethod))
                {
                    ProcessRequestForDeferredResponse(args, responder);
                    result = true;
                }
                else
                {
                    ExposedMethod exposedMethod;
                    if (mappedView.ExposedMethods.TryGetValue(normalisedFile, out exposedMethod))
                    {
                        var response = new JsonResponse();

                        try {
                            var parameters = MapParameters(exposedMethod, args);

                            if (!exposedMethod.WebAdminMethod.DeferExecution)
                            {
                                response.Response = exposedMethod.MethodInfo.Invoke(mappedView.View, parameters);
                            }
                            else
                            {
                                var deferredMethod = new DeferredMethod(args.UniqueId, mappedView, exposedMethod, parameters);
                                lock (_SyncLock) {
                                    var newMethods = CollectionHelper.ShallowCopy(_DeferredMethods);
                                    newMethods.Add(deferredMethod.RequestId, deferredMethod);
                                    _DeferredMethods = newMethods;
                                }

                                response.Response = new DeferredExecutionResult()
                                {
                                    JobId = deferredMethod.JobId,
                                };
                            }
                        } catch (Exception ex) {
                            try {
                                var log = Factory.Singleton.ResolveSingleton <ILog>();
                                log.WriteLine("Caught exception during processing of request for {0}: {1}", args.Request.RawUrl, ex);
                            } catch {}
                            response.Exception = ex.Message;
                            response.Response  = null;
                        }

                        var jsonText = JsonConvert.SerializeObject(response);
                        responder.SendText(args.Request, args.Response, jsonText, Encoding.UTF8, MimeType.Json, cacheSeconds: 0);

                        result = true;
                    }
                }
            }

            return(result);
        }
        private void ProcessSetColorRequest(RequestReceivedEventArgs e, BlinkStickDeviceSettings ledSettings)
        {
            RgbColor color    = RgbColor.Black();
            int      channel  = 0;
            int      firstLed = 0;
            int      lastLed  = 0;

            for (int i = 0; i < e.Context.Request.QueryString.AllKeys.Length; i++)
            {
                string key   = e.Context.Request.QueryString.AllKeys[i].ToLower();
                string value = e.Context.Request.QueryString.GetValues(i)[0];

                if (key == "channel")
                {
                    try
                    {
                        channel = Convert.ToInt32(value);
                        if (channel < 0 || channel > 2)
                        {
                            throw new Exception("not within range of 0..2");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid channel parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "firstled")
                {
                    try
                    {
                        firstLed = Convert.ToInt32(value);
                        if (firstLed < 0 || firstLed > 63)
                        {
                            throw new Exception("not within range of 0..63");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid ledStart parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "lastled")
                {
                    try
                    {
                        lastLed = Convert.ToInt32(value);
                        if (lastLed < 0 || lastLed > 63)
                        {
                            throw new Exception("not within range of 0..63");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid ledEnd parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "color")
                {
                    try
                    {
                        color = RgbColor.FromString(value);
                    }
                    catch
                    {
                        try
                        {
                            color = RgbColor.FromString("#" + value);
                        }
                        catch
                        {
                            server.SendResponseJson(422, new ErrorResponse()
                            {
                                error = "Invalid color parameter"
                            }, e.Context.Response);
                            e.Handled = true;
                            return;
                        }
                    }
                }
            }

            try
            {
                Pattern pattern = new Pattern();
                pattern.Animations.Add(new Animation());
                pattern.Animations[0].AnimationType = AnimationTypeEnum.SetColor;
                pattern.Animations[0].DelaySetColor = 0;
                pattern.Animations[0].Color         = color;
                OnPatternSend(channel, (byte)firstLed, (byte)lastLed, ledSettings, pattern, 1, 0);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Failed to send color {0}", ex);
            }
            server.SendResponseJson(200, null, e.Context.Response);

            e.Handled = true;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Extracts information about the required image from the URL.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private ImageRequest ExtractImageRequest(RequestReceivedEventArgs args)
        {
            bool isValid = true;

            ImageRequest result = new ImageRequest()
            {
                ImageName = Path.GetFileNameWithoutExtension(args.File).ToUpper(),
            };

            switch (Path.GetExtension(args.File).ToUpper())
            {
            case ".PNG":    result.ImageFormat = ImageFormat.Png; break;

            case ".GIF":    result.ImageFormat = ImageFormat.Gif; break;

            case ".BMP":    result.ImageFormat = ImageFormat.Bmp; break;

            default:        isValid = false; break;
            }

            foreach (var pathPart in args.PathParts)
            {
                var caselessPart = pathPart.ToUpper();
                if (caselessPart.StartsWith("ALT-"))
                {
                    result.ShowAltitudeStalk = true;
                }
                if (caselessPart.StartsWith("ROTATE-"))
                {
                    result.RotateDegrees = ParseDouble(pathPart.Substring(7), 0.0, 359.99);
                }
                else if (caselessPart.StartsWith("HGHT-"))
                {
                    result.Height = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("WDTH-"))
                {
                    result.Width = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("CENX-"))
                {
                    result.CentreX = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("FILE-"))
                {
                    result.File = pathPart.Substring(5).Replace("\\", "");
                }
                else if (caselessPart.StartsWith("SIZE-"))
                {
                    result.Size = ParseStandardSize(pathPart.Substring(5));
                }
                else if (caselessPart == "HIDPI")
                {
                    result.IsHighDpi = true;
                }
                else if (caselessPart == "LEFT")
                {
                    result.CentreImageHorizontally = false;
                }
                else if (caselessPart == "TOP")
                {
                    result.CentreImageVertically = false;
                }
                else if (caselessPart == "NO-CACHE")
                {
                    result.NoCache = !args.IsInternetRequest;
                }
                else if (caselessPart.StartsWith("WEB") && isValid)
                {
                    var pathAndFileName = new StringBuilder("/images/");
                    var hyphenPosn      = pathPart.IndexOf('-');
                    if (hyphenPosn != -1)
                    {
                        var folder = pathPart.Substring(hyphenPosn + 1).Replace("\\", "/").Trim();
                        if (folder.Length > 0)
                        {
                            pathAndFileName.AppendFormat("{0}{1}", folder, folder[folder.Length - 1] == '/' ? "" : "/");
                        }
                    }
                    pathAndFileName.Append(Path.GetFileName(args.File));
                    result.WebSiteFileName = pathAndFileName.ToString();
                }
                else if (caselessPart.StartsWith("PL"))
                {
                    var hyphenPosn = caselessPart.IndexOf('-');
                    if (hyphenPosn >= 2)
                    {
                        var rowText = caselessPart.Substring(2, hyphenPosn - 2);
                        int row;
                        if (int.TryParse(rowText, out row) && row >= 1 && row <= 9)
                        {
                            --row;
                            while (result.TextLines.Count <= row)
                            {
                                result.TextLines.Add(null);
                            }
                            result.TextLines[row] = pathPart.Substring(hyphenPosn + 1);
                        }
                    }
                }
            }

            return(isValid ? result : null);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Fills either of the stock image or temporary image parameters with the initial image to use (before any alterations are made).
        /// </summary>
        /// <param name="imageRequest"></param>
        /// <param name="args"></param>
        /// <param name="stockImage"></param>
        /// <param name="tempImage"></param>
        /// <returns></returns>
        private bool BuildInitialImage(ImageRequest imageRequest, RequestReceivedEventArgs args, ref Image stockImage, ref Image tempImage)
        {
            bool result = true;

            if (imageRequest.WebSiteFileName != null)
            {
                // This will return a clone, we don't have to clone it. We are responsible for destroying the image.
                stockImage = ImageFileManager.LoadFromWebSite(_WebSite, imageRequest.WebSiteFileName, !imageRequest.NoCache);
            }
            else
            {
                switch (imageRequest.ImageName)
                {
                case "AIRPLANE":                stockImage = Images.Clone_Marker_Airplane(); break;

                case "AIRPLANESELECTED":        stockImage = Images.Clone_Marker_AirplaneSelected(); break;

                case "BLANK":                   tempImage = _Graphics.CreateBlankImage(imageRequest.Width.GetValueOrDefault(), imageRequest.Height.GetValueOrDefault()); break;

                case "CHEVRONBLUECIRCLE":       stockImage = Images.Clone_ChevronBlueCircle(); break;

                case "CHEVRONGREENCIRCLE":      stockImage = Images.Clone_ChevronGreenCircle(); break;

                case "CHEVRONREDCIRCLE":        stockImage = Images.Clone_ChevronRedCircle(); break;

                case "CLOSESLIDER":             stockImage = Images.Clone_CloseSlider(); break;

                case "COMPASS":                 stockImage = Images.Clone_Compass(); break;

                case "CORNER-TL":               stockImage = Images.Clone_Corner_TopLeft(); break;

                case "CORNER-TR":               stockImage = Images.Clone_Corner_TopRight(); break;

                case "CORNER-BL":               stockImage = Images.Clone_Corner_BottomLeft(); break;

                case "CORNER-BR":               stockImage = Images.Clone_Corner_BottomRight(); break;

                case "CROSSHAIR":               stockImage = Images.Clone_Crosshair(); break;

                case "GOTOCURRENTLOCATION":     stockImage = Images.Clone_GotoCurrentLocation(); break;

                case "GROUNDVEHICLE":           stockImage = Images.Clone_FollowMe(); break;

                case "GROUNDVEHICLESELECTED":   stockImage = Images.Clone_FollowMe(); break;

                case "HEADING":                 stockImage = Images.Clone_SmallPlaneNorth(); break;

                case "HIDELIST":                stockImage = Images.Clone_HideList(); break;

                case "IPHONEBACKBUTTON":        stockImage = Images.Clone_IPhoneBackButton(); break;

                case "IPHONEBLUEBUTTON":        stockImage = Images.Clone_IPhoneBlueButton(); break;

                case "IPHONECHEVRON":           stockImage = Images.Clone_IPhoneChevron(); break;

                case "IPHONEGRAYBUTTON":        stockImage = Images.Clone_IPhoneGrayButton(); break;

                case "IPHONEICON":              stockImage = Images.Clone_IPhoneIcon(); break;

                case "IPHONELISTGROUP":         stockImage = Images.Clone_IPhoneListGroup(); break;

                case "IPHONEONOFF":             stockImage = Images.Clone_IPhoneOnOff(); break;

                case "IPHONEPINSTRIPES":        stockImage = Images.Clone_IPhonePinstripes(); break;

                case "IPHONESELECTEDTICK":      stockImage = Images.Clone_IPhoneSelectedTick(); break;

                case "IPHONESELECTION":         stockImage = Images.Clone_IPhoneSelection(); break;

                case "IPHONESPLASH":            tempImage = _Graphics.CreateIPhoneSplash(args.WebSite, args.IsIPad, args.PathParts); break;

                case "IPHONETOOLBAR":           stockImage = Images.Clone_IPhoneToolbar(); break;

                case "IPHONETOOLBUTTON":        stockImage = Images.Clone_IPhoneToolButton(); break;

                case "IPHONEWHITEBUTTON":       stockImage = Images.Clone_IPhoneWhiteButton(); break;

                case "MINUS":                   stockImage = Images.Clone_Collapse(); break;

                case "MOVINGMAPCHECKED":        stockImage = Images.Clone_MovingMapChecked(); break;

                case "MOVINGMAPUNCHECKED":      stockImage = Images.Clone_MovingMapUnchecked(); break;

                case "OPENSLIDER":              stockImage = Images.Clone_OpenSlider(); break;

                case "OPFLAG":                  tempImage = CreateLogoImage(imageRequest.File, _OperatorFlagFolder); break;

                case "PICTURE":                 tempImage = CreateAirplanePicture(imageRequest.File, imageRequest.Size, args.IsInternetRequest, imageRequest.Width, imageRequest.Height); imageRequest.Width = imageRequest.Height = null; break;

                case "PLUS":                    stockImage = Images.Clone_Expand(); break;

                case "ROWHEADER":               stockImage = Images.Clone_RowHeader(); break;

                case "ROWHEADERSELECTED":       stockImage = Images.Clone_RowHeaderSelected(); break;

                case "SHOWLIST":                stockImage = Images.Clone_ShowList(); break;

                case "TESTSQUARE":              stockImage = Images.Clone_TestSquare(); break;

                case "TOWER":                   stockImage = Images.Clone_Tower(); break;

                case "TOWERSELECTED":           stockImage = Images.Clone_Tower(); break;

                case "TRANSPARENT-25":          stockImage = Images.Clone_Transparent_25(); break;

                case "TRANSPARENT-50":          stockImage = Images.Clone_Transparent_50(); break;

                case "TYPE":                    tempImage = CreateLogoImage(imageRequest.File, _SilhouetteFolder); break;

                case "VOLUME0":                 stockImage = Images.Clone_Volume0(); break;

                case "VOLUME25":                stockImage = Images.Clone_Volume25(); break;

                case "VOLUME50":                stockImage = Images.Clone_Volume50(); break;

                case "VOLUME75":                stockImage = Images.Clone_Volume75(); break;

                case "VOLUME100":               stockImage = Images.Clone_Volume100(); break;

                case "VOLUMEDOWN":              stockImage = Images.Clone_VolumeDown(); break;

                case "VOLUMEMUTE":              stockImage = Images.Clone_VolumeMute(); break;

                case "VOLUMEUP":                stockImage = Images.Clone_VolumeUp(); break;

                case "YOUAREHERE":              stockImage = Images.Clone_BlueBall(); break;

                default:                        result = false; break;
                }
            }

            if (result)
            {
                result = stockImage != null || tempImage != null;
            }

            return(result);
        }
Ejemplo n.º 14
0
 private void ApiRequestReceivEventHandler(object sender, RequestReceivedEventArgs requestReceivedEventArgs)
 {
     _requestsReceived.Add(requestReceivedEventArgs);
 }
 public Task HandleRequest(object sender, RequestReceivedEventArgs args)
 {
     Request?.Invoke(sender, args);
     return(Task.CompletedTask);
 }
        private void ProcessPlayPatternRequest(RequestReceivedEventArgs e, BlinkStickDeviceSettings ledSettings)
        {
            Pattern pattern  = new Pattern();
            int     channel  = 0;
            int     ledStart = 0;
            int     ledEnd   = 0;

            for (int i = 0; i < e.Context.Request.QueryString.AllKeys.Length; i++)
            {
                string key   = e.Context.Request.QueryString.AllKeys[i].ToLower();
                string value = e.Context.Request.QueryString.GetValues(i)[0];

                if (key == "channel")
                {
                    try
                    {
                        channel = Convert.ToInt32(value);
                        if (channel < 0 || channel > 2)
                        {
                            throw new Exception("not within range of 0..2");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid channel parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "firstled")
                {
                    try
                    {
                        ledStart = Convert.ToInt32(value);
                        if (ledStart < 0 || ledStart > 63)
                        {
                            throw new Exception("not within range of 0..63");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid ledStart parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "lastled")
                {
                    try
                    {
                        ledEnd = Convert.ToInt32(value);
                        if (ledEnd < 0 || ledEnd > 63)
                        {
                            throw new Exception("not within range of 0..63");
                        }
                    }
                    catch (Exception ex)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Invalid ledEnd parameter: {0}", ex.Message)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
                else if (key == "pattern")
                {
                    pattern = DataModel.FindPatternByName(value);

                    if (pattern == null)
                    {
                        server.SendResponseJson(422, new ErrorResponse()
                        {
                            error = String.Format("Pattern {0} not found", value)
                        }, e.Context.Response);
                        e.Handled = true;
                        return;
                    }
                }
            }

            if (pattern == null)
            {
                server.SendResponseJson(422, new ErrorResponse()
                {
                    error = "Missing pattern parameter"
                }, e.Context.Response);
                e.Handled = true;
                return;
            }

            try
            {
                OnPatternSend(channel, (byte)ledStart, (byte)ledEnd, ledSettings, pattern, 1, 0);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Failed to send color {0}", ex);
            }
            server.SendResponseJson(200, null, e.Context.Response);

            e.Handled = true;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Authenticates the request from the browser.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requestArgs"></param>
        /// <returns></returns>
        private bool Authenticated(IContext context, RequestReceivedEventArgs requestArgs)
        {
            bool result = false;

            var authenticationScheme = AuthenticationScheme;
            var isAdministratorPath  = IsAdministratorPath(requestArgs);

            if (isAdministratorPath)
            {
                authenticationScheme = AuthenticationSchemes.Basic;
            }

            switch (authenticationScheme)
            {
            case AuthenticationSchemes.None:
            case AuthenticationSchemes.Anonymous:
                if (isAdministratorPath)
                {
                    throw new InvalidOperationException("Anonymous access to administrator paths is not supported");
                }
                result = true;
                break;

            case AuthenticationSchemes.Basic:
                bool useCache = CacheCredentials;
                if (useCache && context.BasicUserName != null)
                {
                    CachedCredential cachedCredential;
                    if (_AuthenticatedUserCache.TryGetValue(context.BasicUserName, out cachedCredential))
                    {
                        result = context.BasicPassword == cachedCredential.Password;
                        if (result)
                        {
                            result = !isAdministratorPath || cachedCredential.IsAdministrator;
                        }
                    }
                }

                if (!result)
                {
                    var args = new AuthenticationRequiredEventArgs(context.BasicUserName, context.BasicPassword);
                    OnAuthenticationRequired(args);
                    result = args.IsAuthenticated && (!isAdministratorPath || args.IsAdministrator);
                    if (result)
                    {
                        if (useCache && args.User != null)
                        {
                            var cachedCredential = new CachedCredential()
                            {
                                IsAdministrator = args.IsAdministrator,
                                Password        = context.BasicPassword,
                            };
                            _AuthenticatedUserCache.Add(context.BasicUserName, cachedCredential);
                        }
                    }
                    else
                    {
                        var failedLogin     = _FailedLoginAttempts.GetAndRefreshOrCreate(context.Request.RemoteEndPoint.Address, (unused) => new FailedLogin());
                        var sameCredentials = context.BasicUserName == failedLogin.User && context.BasicPassword == failedLogin.Password;
                        failedLogin.User     = context.BasicUserName;
                        failedLogin.Password = context.BasicPassword;
                        if (!sameCredentials)
                        {
                            if (failedLogin.Attempts < int.MaxValue)
                            {
                                ++failedLogin.Attempts;
                            }
                            if (failedLogin.Attempts > 2)
                            {
                                var pauseMilliseconds = (Math.Min(failedLogin.Attempts, 14) - 2) * 5000;
                                Thread.Sleep(pauseMilliseconds);
                            }
                        }

                        context.Response.StatusCode = HttpStatusCode.Unauthorized;
                        context.Response.AddHeader("WWW-Authenticate", String.Format(@"Basic Realm=""{0}""", Provider.ListenerRealm));
                    }
                }

                if (result)
                {
                    requestArgs.UserName = context.BasicUserName;
                }

                break;

            default:
                throw new NotImplementedException();
            }

            return(result);
        }
        /// <summary>
        /// Request handler.
        /// </summary>
        /// <param name="sender">The serveragent object.</param>
        /// <param name="eventArgs">Request parameters.</param>
        public virtual void OnRequest(object sender, RequestReceivedEventArgs eventArgs)
        {
            Request request          = eventArgs.Request;
            bool    requestIsAllowed = false;
            bool    addedToAllowList = false;
            string  fromUserAtHost;
            string  toUserAtHost;

            Header header = request.AllHeaders.FindFirst(Header.StandardHeaderType.From);

            fromUserAtHost = Utils.UriParser.GetUserAtHost(header.Value);
            header         = request.AllHeaders.FindFirst(Header.StandardHeaderType.To);
            toUserAtHost   = Utils.UriParser.GetUserAtHost(header.Value);

            //
            // Check the request origin and carry out the appropriate action.
            //

            AuthenticationInfo authenticationInfo = (AuthenticationInfo)request.AuthenticationInfo;

            if (authenticationInfo.Origin == AuthenticationInfo.MessageOrigin.NetworkExternal)
            {
                //
                // Get the From domain.
                //

                string fromDomain = Utils.UriParser.GetHost(fromUserAtHost).ToLower();

                //
                // See if this domain has been validated already.
                //


                lock (this.SyncRoot) {
                    if (allowList.Contains(fromDomain))
                    {
                        //
                        // This is a validated domain. It can show up here if we
                        // added this in another thread and this has not been picked up
                        // in SPL.
                        //

                        requestIsAllowed = true;
                    }
                }

                if (!requestIsAllowed)
                {
                    LogEntry logEntry = new LogEntry(fromUserAtHost, toUserAtHost, fromDomain);
                    lock (externalEdgeLog.SyncRoot) {
                        externalEdgeLog.Log(logEntry);
                    }
                }
            }
            else
            {
                // We should have only internal here - the SPL script should not be
                // dispatching the other cases here.
                Debug.Assert(authenticationInfo.Origin == AuthenticationInfo.MessageOrigin.NetworkInternal);

                //
                // Get the To domain.
                //

                string toDomain = Utils.UriParser.GetHost(toUserAtHost).ToLower();

                //
                // See if this domain has been validated already.
                //

                lock (this.SyncRoot) {
                    if (allowList.Contains(toDomain))
                    {
                        //
                        // This is a validated domain. It can show up here if we
                        // added this in another thread and this has not been picked up
                        // in SPL.
                        //

                        requestIsAllowed = true;
                    }
                    else
                    {
                        //
                        // Policy implementation. Put action to be carried out for unknown
                        // internal domains here.
                        //

                        //
                        // Check whether we are allowed to add this entry automatically.
                        //

                        if (config.ActionForUnknownDomainFromInternalEdge == Config.ActionAutoAdd)
                        {
                            if (currentDomains + 1 < config.MaxDomainsInEnhancedAllowList)
                            {
                                allowList.Add(toDomain, null);
                                currentDomains  += 1;
                                addedToAllowList = true;
                                requestIsAllowed = true;
                            }
                            else
                            {
                                RaiseConfigFileFullEvent();
                            }
                        }
                    }
                }

                if (addedToAllowList)
                {
                    //
                    // This entry was added to the global allow list and hence we need to add
                    // this to the SPL script flat file.
                    //

                    try {
                        InternalAppendDomainToEnhancedAllowListFile(toDomain);
                    } catch (Exception e) {
                        // Failed to open or write to allow list.
                        lock (this.SyncRoot) {
                            allowList.Remove(toDomain);
                            currentDomains  -= 1;
                            addedToAllowList = false;
                            requestIsAllowed = false;
                        }

                        RaiseConfigFileWriteFailureEvent(e.Message);
                    }

                    if (addedToAllowList)
                    {
                        //
                        // Log that we added this entry as well.
                        //

                        LogEntry logEntry = new AllowListLogEntry(fromUserAtHost, toUserAtHost, toDomain);
                        lock (internalEdgeLog.SyncRoot) {
                            internalEdgeLog.Log(logEntry);
                        }
                    }
                }

                if (!requestIsAllowed)
                {
                    LogEntry logEntry = new LogEntry(fromUserAtHost, toUserAtHost, toDomain);
                    lock (internalEdgeLog.SyncRoot) {
                        internalEdgeLog.Log(logEntry);
                    }
                }
            }

            if (requestIsAllowed)
            {
                //
                // Mark the request as simple proxy. This will turn on
                // performance optimizations that would otherwise be not
                // possible.
                //

                request.SimpleProxy = true;
                eventArgs.ServerTransaction.EnableForking = false;


                ClientTransaction ct = eventArgs.ServerTransaction.CreateBranch();
                ct.SendRequest(request);
            }
            else
            {
                Response localResponse = request.CreateResponse(403);
                eventArgs.ServerTransaction.SendResponse(localResponse);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// See base class docs.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args)
        {
            var requestFile = GetRequestFile(args.PathParts, args.File);

            var result = requestFile != null && !String.IsNullOrEmpty(requestFile.FileName) && File.Exists(requestFile.FileName);

            if (result)
            {
                var normalisedRequestPath = NormaliseRequestPath(args.PathAndFile);
                var extension             = Path.GetExtension(requestFile.FileName);
                var isProtected           = requestFile.Root.IsProtectedContent;

                var checksumEntry = isProtected ? requestFile.Root.FindChecksum(normalisedRequestPath, requestPathIsNormalised: true) : null;
                result = !isProtected || checksumEntry != null;
                if (result)
                {
                    var isHtml = ".html".Equals(extension, StringComparison.OrdinalIgnoreCase) || ".htm".Equals(extension, StringComparison.OrdinalIgnoreCase);

                    if (isProtected && !requestFile.Root.TestChecksum(checksumEntry, requestFile.FileName))
                    {
                        Factory.Singleton.Resolve <ILog>().Singleton.WriteLine("Will not serve {0}, it has failed the checksum test", args.PathAndFile);
                        if (!isHtml)
                        {
                            args.Response.StatusCode = HttpStatusCode.BadRequest;
                        }
                        else
                        {
                            Responder.SendText(args.Request, args.Response, "<HTML><HEAD><TITLE>No</TITLE></HEAD><BODY>VRS will not serve content that has been tampered with. Install the custom content plugin if you want to alter the site's files.</BODY></HTML>", Encoding.UTF8, MimeType.Html);
                            args.Classification = ContentClassification.Html;
                        }
                    }
                    else
                    {
                        if (isHtml)
                        {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                var textContentArgs = new TextContentEventArgs(args.Request, args.PathAndFile, r.Content, r.Encoding);
                                _WebSite.OnHtmlLoadedFromFile(textContentArgs);
                                r.Content = textContentArgs.Content;

                                _WebSite.InjectHtmlContent(args.PathAndFile, r);
                                _WebSite.BundleHtml(args.PathAndFile, r);
                            });
                        }
                        else if (".js".Equals(extension, StringComparison.OrdinalIgnoreCase))
                        {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                _WebSite.InjectIntoJavaScript(args.PathAndFile, r);
                                _WebSite.MinifyJavaScript(r);
                            });
                        }
                        else if (".css".Equals(extension, StringComparison.OrdinalIgnoreCase))
                        {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                _WebSite.MinifyCss(r);
                            });
                        }
                        else
                        {
                            args.Response.MimeType = MimeType.GetForExtension(extension);

                            var enableCompression = true;
                            if (args.Response.MimeType == MimeType.IconImage)
                            {
                                enableCompression = false;
                            }
                            else if (args.Response.MimeType.StartsWith("image/"))
                            {
                                enableCompression = false;
                            }

                            if (enableCompression)
                            {
                                args.Response.EnableCompression(args.Request);
                            }
                            args.Response.ContentLength = new FileInfo(requestFile.FileName).Length;
                            args.Classification         = MimeType.GetContentClassification(args.Response.MimeType);
                            args.Response.StatusCode    = HttpStatusCode.OK;
                            using (var fileStream = new FileStream(requestFile.FileName, FileMode.Open, FileAccess.Read)) {
                                StreamHelper.CopyStream(fileStream, args.Response.OutputStream, 4096);
                            }
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates the JSON representation of an aircraft.
        /// </summary>
        /// <param name="aircraft"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private ReportAircraftJson CreateReportAircraftJson(BaseStationAircraft aircraft, RequestReceivedEventArgs args)
        {
            var result = new ReportAircraftJson()
            {
                AircraftClass    = aircraft.AircraftClass,
                AircraftId       = aircraft.AircraftID,
                CofACategory     = aircraft.CofACategory,
                CofAExpiry       = aircraft.CofAExpiry,
                Country          = aircraft.Country,
                CurrentRegDate   = aircraft.CurrentRegDate,
                DeRegDate        = aircraft.DeRegDate,
                FirstRegDate     = aircraft.FirstRegDate,
                GenericName      = aircraft.GenericName,
                IcaoTypeCode     = aircraft.ICAOTypeCode,
                InfoUrl          = aircraft.InfoUrl,
                Interested       = aircraft.Interested,
                Manufacturer     = aircraft.Manufacturer,
                Icao             = aircraft.ModeS,
                ModeSCountry     = aircraft.ModeSCountry,
                MTOW             = aircraft.MTOW,
                OperatorFlagCode = aircraft.OperatorFlagCode,
                OwnershipStatus  = aircraft.OwnershipStatus,
                PictureUrl1      = aircraft.PictureUrl1,
                PictureUrl2      = aircraft.PictureUrl2,
                PictureUrl3      = aircraft.PictureUrl3,
                PopularName      = aircraft.PopularName,
                PreviousId       = aircraft.PreviousID,
                Registration     = aircraft.Registration,
                RegisteredOwners = aircraft.RegisteredOwners,
                SerialNumber     = aircraft.SerialNo,
                Status           = aircraft.Status,
                TotalHours       = aircraft.TotalHours,
                Type             = aircraft.Type,
                Notes            = aircraft.UserNotes,
                YearBuilt        = aircraft.YearBuilt,
            };

            if (!args.IsInternetRequest || _InternetClientCanSeePictures)
            {
                try {
                    var pictureDetails = _PictureManager.FindPicture(_PictureFolderCache, aircraft.ModeS, aircraft.Registration);
                    if (pictureDetails != null)
                    {
                        result.HasPicture    = true;
                        result.PictureWidth  = pictureDetails.Width;
                        result.PictureHeight = pictureDetails.Height;
                    }
                } catch (Exception ex) {
                    try {
                        var log = Factory.Singleton.Resolve <ILog>().Singleton;
                        log.WriteLine("Caught exception when fetching picture for {0}/{1} for a report: {2}", aircraft.ModeS, aircraft.Registration, ex.ToString());
                    } catch {
                    }
                }
            }

            var aircraftType = String.IsNullOrEmpty(aircraft.ICAOTypeCode) ? null : StandingDataManager.FindAircraftType(aircraft.ICAOTypeCode);

            if (aircraftType != null)
            {
                result.WakeTurbulenceCategory = (int)aircraftType.WakeTurbulenceCategory;
                result.Engines         = aircraftType.Engines;
                result.EngineType      = (int)aircraftType.EngineType;
                result.EnginePlacement = (int)aircraftType.EnginePlacement;
                result.Species         = (int)aircraftType.Species;
            }

            var codeBlock = String.IsNullOrEmpty(aircraft.ModeS) ? null : StandingDataManager.FindCodeBlock(aircraft.ModeS);

            if (codeBlock != null)
            {
                result.Military = codeBlock.IsMilitary;
            }

            return(result);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Raises the RequestReceived event.
        /// </summary>
        /// <param name="e">Desired event arguments.</param>
        protected virtual void OnRequestReceived(RequestReceivedEventArgs e)
        {
            ClientEventHandler<RequestReceivedEventArgs> handler = RequestReceived;

            if (handler != null)
            {
                handler(this, e);
            }
        }
        /// <summary>
        /// This function receives SIP requests, updates
        /// session state variables, and proxies the request
        /// to the default request uri
        /// </summary>
        /// <remarks>
        /// The request handler's name must be the name of the
        /// function that is given in the SPL Dispatch function
        /// for SIP requests.
        /// </remarks>
        /// <param name="sender">not used</param>
        /// <param name="e">the request state</param>
        public void RequestHandler(object sender, RequestReceivedEventArgs e)
        {
            /* If this is a SIP INVITE, then create an entry
             *  in the session state table for this call-id.
             *  A session is established, when an ACK for this
             *  call-id is received.
             */
            Request request = e.Request;

            if (request.StandardMethod == Request.StandardMethodType.Invite)
            {
                ///extract the call-id and create session state
                Header callIdHeader = request.AllHeaders.FindFirst("Call-ID");

                if (callIdHeader != null)
                {
                    Session newSession = new Session();
                    newSession.State  = Session.States.Initializing;
                    newSession.CallId = callIdHeader.Value;
                    lock (sessionStateTable.SyncRoot) {
                        sessionStateTable[callIdHeader.Value] = newSession;
                    }
                }
            }
            else if (request.StandardMethod == Request.StandardMethodType.Ack)
            {
                ///extract the call-id and update session state, ignore errors
                Header callIdHeader = request.AllHeaders.FindFirst("Call-ID");

                if (callIdHeader != null)
                {
                    Session session = sessionStateTable[callIdHeader.Value] as Session;
                    if (session != null)
                    {
                        session.State = Session.States.Established;
                        statistics.Update(true /* new session */);
                    }
                }
            }

            ///update other counters
            statistics.Update(request.StandardMethod);

            Header fromHeader = request.AllHeaders.FindFirst("From");
            Header toHeader   = request.AllHeaders.FindFirst("To");


            statistics.Update(SipUriParser.GetUserAtHost(fromHeader.Value));
            statistics.Update(SipUriParser.GetUserAtHost(toHeader.Value));

            ///notify the state change
            this.StateChangeListeners(e);

            ///We will not be forking, and marking this explicitly
            ///allows ServerAgent to optimize message proxying.
            e.ServerTransaction.EnableForking = false;

            ///we are done with state management, proxy
            ClientTransaction ct = e.ServerTransaction.CreateBranch();

            if (SimpleProxy)
            {
                // Setting SimpleProxy to true will turn on performance
                // optimizations during message proxying.
                request.SimpleProxy = true;
            }

            ///Add a header if requested by user.
            if (AddHeader)
            {
                Header h = new Header(SipSnoopHeaderName, SipSnoopHeaderValue);
                request.AllHeaders.Add(h);
            }

            ///Modify To header if requested by user by adding a parameter.
            if (ModifyToHeader)
            {
                NameValueCollection toParamColl = toHeader.Parameters;
                toParamColl.Set(SipSnoopParamName, SipSnoopParamValue);
                toHeader.Parameters = toParamColl;
            }

            ct.SendRequest(e.Request);

            return;
        }
Ejemplo n.º 23
0
 internal void OnRequestReceived(RequestReceivedEventArgs args)
 {
     EventHelper.RaiseQuickly(RequestReceived, this, args);
 }
Ejemplo n.º 24
0
        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args)
        {
            bool result = false;

            if (args.PathAndFile.StartsWith("/Images/", StringComparison.OrdinalIgnoreCase))
            {
                var imageRequest = ExtractImageRequest(args);
                result = imageRequest != null;

                // Stock image is an image from the resource file. We don't need to dispose of it, it can be reused
                // Temp image is an image we have either built from scratch or built by modifying a stock image. It is only
                // good for this request and needs to be disposed of when we're done with it.
                Image stockImage = null;
                Image tempImage  = null;

                if (result)
                {
                    if (_ForceSingleThreadAccess)
                    {
                        Monitor.Enter(_ForceSingleThreadAccessLock);
                    }
                    try {
                        result = BuildInitialImage(imageRequest, args, ref stockImage, ref tempImage);
                        if (result)
                        {
                            var addTextLines = imageRequest.HasTextLines && (!args.IsInternetRequest || _InternetClientCanShowText);
                            if (imageRequest.RotateDegrees > 0.0)
                            {
                                tempImage = UseImage(tempImage, RotateImage(tempImage ?? stockImage, imageRequest.RotateDegrees.Value));
                            }
                            if (imageRequest.Width != null)
                            {
                                tempImage = UseImage(tempImage, WidenImage(tempImage ?? stockImage, imageRequest.Width.Value, imageRequest.CentreImageHorizontally));
                            }
                            if (imageRequest.ShowAltitudeStalk)
                            {
                                tempImage = UseImage(tempImage, AddAltitudeStalk(tempImage ?? stockImage, imageRequest.Height.GetValueOrDefault(), imageRequest.CentreX.GetValueOrDefault()));
                            }
                            else if (imageRequest.Height != null)
                            {
                                tempImage = UseImage(tempImage, HeightenImage(tempImage ?? stockImage, imageRequest.Height.Value, imageRequest.CentreImageVertically));
                            }
                            if (addTextLines)
                            {
                                tempImage = UseImage(tempImage, AddTextLines(tempImage ?? stockImage, imageRequest.TextLines, true));
                            }
                        }

                        if (result)
                        {
                            Responder.SendImage(args.Response, tempImage ?? stockImage, imageRequest.ImageFormat);
                            args.Classification = ContentClassification.Image;
                        }
                    } finally {
                        if (tempImage != null)
                        {
                            tempImage.Dispose();
                        }
                        if (_ForceSingleThreadAccess)
                        {
                            Monitor.Exit(_ForceSingleThreadAccessLock);
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Handles the request for content by a server.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private void Server_RequestReceived(object sender, RequestReceivedEventArgs args)
 {
     RequestContent(args);
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Extracts information about the required image from the URL.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        private ImageRequest ExtractImageRequest(RequestReceivedEventArgs args)
        {
            bool isValid = true;

            ImageRequest result = new ImageRequest()
            {
                ImageName = Path.GetFileNameWithoutExtension(args.File).ToUpper(),
            };

            switch (Path.GetExtension(args.File).ToUpper())
            {
            case ".PNG":    result.ImageFormat = ImageFormat.Png; break;

            case ".GIF":    result.ImageFormat = ImageFormat.Gif; break;

            case ".BMP":    result.ImageFormat = ImageFormat.Bmp; break;

            default:        isValid = false; break;
            }

            foreach (var pathPart in args.PathParts)
            {
                var caselessPart = pathPart.ToUpper();
                if (caselessPart.StartsWith("ALT-"))
                {
                    result.ShowAltitudeStalk = true;
                }
                if (caselessPart.StartsWith("ROTATE-"))
                {
                    result.RotateDegrees = ParseDouble(pathPart.Substring(7), 0.0, 359.99);
                }
                else if (caselessPart.StartsWith("HGHT-"))
                {
                    result.Height = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("WDTH-"))
                {
                    result.Width = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("CENX-"))
                {
                    result.CentreX = ParseInt(pathPart.Substring(5), 0, 4096);
                }
                else if (caselessPart.StartsWith("FILE-"))
                {
                    result.File = pathPart.Substring(5).Replace("\\", "");
                }
                else if (caselessPart.StartsWith("SIZE-"))
                {
                    result.Size = ParseStandardSize(pathPart.Substring(5));
                }
                else if (caselessPart.StartsWith("PL1-"))
                {
                    result.TextLines[0] = pathPart.Substring(4);
                }
                else if (caselessPart.StartsWith("PL2-"))
                {
                    result.TextLines[1] = pathPart.Substring(4);
                }
                else if (caselessPart.StartsWith("PL3-"))
                {
                    result.TextLines[2] = pathPart.Substring(4);
                }
            }

            switch (result.ImageName)
            {
            case "AIRPLANE":
            case "AIRPLANESELECTED":    result.CentreImageVertically = false; break;
            }

            return(isValid ? result : null);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Returns the date (formatted as yyyy-MM-dd) passed as a query string parameter or null if either the date is not present or is invalid.
 /// </summary>
 /// <param name="args"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 protected DateTime?QueryNDateTime(RequestReceivedEventArgs args, string name)
 {
     return(QueryNDateTime(QueryString(args, name, false)));
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Fills either of the stock image or temporary image parameters with the initial image to use (before any alterations are made).
        /// </summary>
        /// <param name="imageRequest"></param>
        /// <param name="args"></param>
        /// <param name="stockImage"></param>
        /// <param name="tempImage"></param>
        /// <returns></returns>
        private bool BuildInitialImage(ImageRequest imageRequest, RequestReceivedEventArgs args, ref Image stockImage, ref Image tempImage)
        {
            bool result = true;

            switch (imageRequest.ImageName)
            {
            case "AIRPLANE":                stockImage = Images.Marker_Airplane; break;

            case "AIRPLANESELECTED":        stockImage = Images.Marker_AirplaneSelected; break;

            case "BLANK":                   tempImage = CreateBlankImage(imageRequest.Width.GetValueOrDefault(), imageRequest.Height.GetValueOrDefault()); break;

            case "CHEVRONBLUECIRCLE":       stockImage = Images.ChevronBlueCircle; break;

            case "CHEVRONGREENCIRCLE":      stockImage = Images.ChevronGreenCircle; break;

            case "CHEVRONREDCIRCLE":        stockImage = Images.ChevronRedCircle; break;

            case "CLOSESLIDER":             stockImage = Images.CloseSlider; break;

            case "COMPASS":                 stockImage = Images.Compass; break;

            case "CORNER-TL":               stockImage = Images.Corner_TopLeft; break;

            case "CORNER-TR":               stockImage = Images.Corner_TopRight; break;

            case "CORNER-BL":               stockImage = Images.Corner_BottomLeft; break;

            case "CORNER-BR":               stockImage = Images.Corner_BottomRight; break;

            case "CROSSHAIR":               stockImage = Images.Crosshair; break;

            case "GOTOCURRENTLOCATION":     stockImage = Images.GotoCurrentLocation; break;

            case "HEADING":                 stockImage = Images.SmallPlaneNorth; break;

            case "HIDELIST":                stockImage = Images.HideList; break;

            case "IPHONEBACKBUTTON":        stockImage = Images.IPhoneBackButton; break;

            case "IPHONEBLUEBUTTON":        stockImage = Images.IPhoneBlueButton; break;

            case "IPHONECHEVRON":           stockImage = Images.IPhoneChevron; break;

            case "IPHONEGRAYBUTTON":        stockImage = Images.IPhoneGrayButton; break;

            case "IPHONEICON":              stockImage = Images.IPhoneIcon; break;

            case "IPHONELISTGROUP":         stockImage = Images.IPhoneListGroup; break;

            case "IPHONEONOFF":             stockImage = Images.IPhoneOnOff; break;

            case "IPHONEPINSTRIPES":        stockImage = Images.IPhonePinstripes; break;

            case "IPHONESELECTEDTICK":      stockImage = Images.IPhoneSelectedTick; break;

            case "IPHONESELECTION":         stockImage = Images.IPhoneSelection; break;

            case "IPHONESPLASH":            tempImage = CreateIPhoneSplash(args.WebSite, args.IsIPad, args.PathParts); break;

            case "IPHONETOOLBAR":           stockImage = Images.IPhoneToolbar; break;

            case "IPHONETOOLBUTTON":        stockImage = Images.IPhoneToolButton; break;

            case "IPHONEWHITEBUTTON":       stockImage = Images.IPhoneWhiteButton; break;

            case "MINUS":                   stockImage = Images.Collapse; break;

            case "MOVINGMAPCHECKED":        stockImage = Images.MovingMapChecked; break;

            case "MOVINGMAPUNCHECKED":      stockImage = Images.MovingMapUnchecked; break;

            case "OPENSLIDER":              stockImage = Images.OpenSlider; break;

            case "OPFLAG":                  tempImage = CreateLogoImage(imageRequest.File, _OperatorFlagFolder); break;

            case "PICTURE":                 tempImage = CreateAirplanePicture(imageRequest.File, imageRequest.Size, args.IsInternetRequest); break;

            case "PLUS":                    stockImage = Images.Expand; break;

            case "ROWHEADER":               stockImage = Images.RowHeader; break;

            case "ROWHEADERSELECTED":       stockImage = Images.RowHeaderSelected; break;

            case "SHOWLIST":                stockImage = Images.ShowList; break;

            case "TESTSQUARE":              stockImage = Images.TestSquare; break;

            case "TRANSPARENT-25":          stockImage = Images.Transparent_25; break;

            case "TRANSPARENT-50":          stockImage = Images.Transparent_50; break;

            case "TYPE":                    tempImage = CreateLogoImage(imageRequest.File, _SilhouetteFolder); break;

            case "VOLUME0":                 stockImage = Images.Volume0; break;

            case "VOLUME25":                stockImage = Images.Volume25; break;

            case "VOLUME50":                stockImage = Images.Volume50; break;

            case "VOLUME75":                stockImage = Images.Volume75; break;

            case "VOLUME100":               stockImage = Images.Volume100; break;

            case "VOLUMEDOWN":              stockImage = Images.VolumeDown; break;

            case "VOLUMEMUTE":              stockImage = Images.VolumeMute; break;

            case "VOLUMEUP":                stockImage = Images.VolumeUp; break;

            case "YOUAREHERE":              stockImage = Images.BlueBall; break;

            default:                        result = false; break;
            }

            if (result)
            {
                result = stockImage != null || tempImage != null;
            }

            return(result);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Returns the int? value associated with the name or null if there is no value.
 /// </summary>
 /// <param name="args"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 protected int?QueryNInt(RequestReceivedEventArgs args, string name)
 {
     return(QueryNInt(QueryString(args, name, false)));
 }
Ejemplo n.º 30
0
 private void Server_RequestReceived(object sender, RequestReceivedEventArgs e)
 {
     _httpLogger.LogInformation($"Incoming request: {e.Request.Path}");
 }
Ejemplo n.º 31
0
        private async Task <ResponsePacket> OnHostGame(object sender, RequestReceivedEventArgs args)
        {
            var gsResp = await _server.Request(args.Request, _gameServerUserId);

            return(new ResponsePacket(args.Request, gsResp.Data));
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Raises <see cref="BeforeRequestReceived"/>.
 /// </summary>
 /// <param name="args"></param>
 private void OnBeforeRequestReceived(RequestReceivedEventArgs args)
 {
     EventHelper.RaiseQuickly(BeforeRequestReceived, this, args);
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Raises <see cref="AfterRequestReceived"/>.
 /// </summary>
 /// <param name="args"></param>
 private void OnAfterRequestReceived(RequestReceivedEventArgs args)
 {
     EventHelper.RaiseQuickly(AfterRequestReceived, this, args);
 }
Ejemplo n.º 34
0
        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args)
        {
            bool result = false;

            if (args.PathAndFile.Equals("/ReportRows.json", StringComparison.OrdinalIgnoreCase) && (_InternetClientCanRunReports || !args.IsInternetRequest))
            {
                result = true;

                ReportRowsJson json      = null;
                var            startTime = Provider.UtcNow;

                Type expectedJsonType = ExpectedJsonType(args);

                try {
                    var parameters = ExtractParameters(args);

                    LimitDatesWhenNoStrongCriteriaPresent(parameters, args.IsInternetRequest);
                    if (parameters.Date != null && parameters.Date.UpperValue != null)
                    {
                        if (parameters.Date.UpperValue.Value.Year != 9999)
                        {
                            parameters.Date.UpperValue = parameters.Date.UpperValue.Value.AddDays(1).AddMilliseconds(-1);
                        }
                    }

                    switch (parameters.ReportType)
                    {
                    case "DATE":    json = CreateManyAircraftReport(args, parameters); break;

                    case "ICAO":    json = CreateSingleAircraftReport(args, parameters, true); break;

                    case "REG":     json = CreateSingleAircraftReport(args, parameters, false); break;

                    default:        throw new NotImplementedException();
                    }

                    if (json != null)
                    {
                        json.GroupBy = parameters.SortField1 ?? parameters.SortField2 ?? "";
                    }
                } catch (Exception ex) {
                    Debug.WriteLine(String.Format("ReportRowsJsonPage.DoHandleRequest caught exception {0}", ex.ToString()));
                    ILog log = Factory.Singleton.Resolve <ILog>().Singleton;
                    log.WriteLine("An exception was encountered during the processing of a report: {0}", ex.ToString());
                    if (json == null)
                    {
                        json = (ReportRowsJson)Activator.CreateInstance(expectedJsonType);
                    }
                    json.ErrorText = String.Format("An exception was encounted during the processing of the report, see log for full details: {0}", ex.Message);
                }

                if (json == null)
                {
                    json = (ReportRowsJson)Activator.CreateInstance(expectedJsonType);
                }
                json.ProcessingTime         = String.Format("{0:N3}", (Provider.UtcNow - startTime).TotalSeconds);
                json.OperatorFlagsAvailable = _ShowOperatorFlags;
                json.SilhouettesAvailable   = _ShowSilhouettes;
                Responder.SendJson(args.Request, args.Response, json, null, null);
                args.Classification = ContentClassification.Json;
            }

            return(result);
        }