aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Essentials/src/HttpEntity.cs
blob: 64f18ec2d650154077f11da4681aa46a09d5f985 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials
* File: HttpEntity.cs 
*
* HttpEntity.cs is part of VNLib.Plugins.Essentials which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

using VNLib.Net.Http;
using VNLib.Plugins.Essentials.Sessions;
using VNLib.Plugins.Essentials.Extensions;

/*
 * HttpEntity was converted to an object as during profiling
 * it was almost always heap allcated due to async opertaions
 * or other object tracking issues. So to reduce the number of
 * allocations (at the cost of larger objects) basic profiling 
 * showed less GC load and less collections when SessionInfo 
 * remained a value type
 */
#pragma warning disable CA1051 // Do not declare visible instance fields

namespace VNLib.Plugins.Essentials
{
    /// <summary>
    /// A container for an <see cref="HttpEvent"/> with its attached session.
    /// This class cannot be inherited.
    /// </summary>
    public sealed class HttpEntity : IHttpEvent
    {

        /// <summary>
        /// The connection event entity
        /// </summary>
        private readonly IHttpEvent Entity;

        private readonly CancellationTokenSource EventCts;

        public HttpEntity(IHttpEvent entity, IWebProcessor root)
        {
            Entity = entity;
            RequestedRoot = root;
            //Init event cts
            EventCts = new(root.Options.ExecutionTimeout);
          
            //See if the connection is coming from an downstream server
            IsBehindDownStreamServer = root.Options.DownStreamServers.Contains(entity.Server.RemoteEndpoint.Address);
            /*
            * If the connection was behind a trusted downstream server, 
            * we can trust the x-forwarded-for header,
            * otherwise use the remote ep ip address
            */
            TrustedRemoteIp = entity.Server.GetTrustedIp(IsBehindDownStreamServer);
            //Local connection
            IsLocalConnection = entity.Server.LocalEndpoint.Address.IsLocalSubnet(TrustedRemoteIp);
            //Cache value
            IsSecure = entity.Server.IsSecure(IsBehindDownStreamServer);

            //Cache current time
            RequestedTimeUtc = DateTimeOffset.UtcNow;
        }

        private SessionInfo _session;
        internal FileProcessArgs EventArgs;
        internal SessionHandle EventSessionHandle;

        /// <summary>
        /// Internal call to attach a new session to the entity from the 
        /// internal session handle
        /// </summary>
        internal void AttachSession()
        {
            if (EventSessionHandle.IsSet)
            {
                _session = new(EventSessionHandle.SessionData!, Entity.Server, TrustedRemoteIp);
            }
        }

        /// <summary>
        /// Internal call to cleanup any internal resources
        /// </summary>
        internal void Dispose()
        {
            EventCts.Dispose();
        }

        /// <summary>
        /// A token that has a scheduled timeout to signal the cancellation of the entity event
        /// </summary>
        public CancellationToken EventCancellation => EventCts.Token;

        /// <summary>
        /// The session associated with the event
        /// </summary>
        public ref readonly SessionInfo Session => ref _session;

        /// <summary>
        /// A value that indicates if the connecion came from a trusted downstream server
        /// </summary>
        public readonly bool IsBehindDownStreamServer;

        /// <summary>
        /// Determines if the connection came from the local network to the current server
        /// </summary>
        public readonly bool IsLocalConnection;

        /// <summary>
        /// Gets a value that determines if the connection is using tls, locally 
        /// or behind a trusted downstream server that is using tls.
        /// </summary>
        public readonly bool IsSecure;

        /// <summary>
        /// Caches a <see cref="DateTimeOffset"/> that was created when the connection was created.
        /// The approximate current UTC time
        /// </summary>
        public readonly DateTimeOffset RequestedTimeUtc;

        /// <summary>
        /// The connection info object assocated with the entity
        /// </summary>
        public IConnectionInfo Server => Entity.Server;

        /// <summary>
        /// User's ip. If the connection is behind a local proxy, returns the users actual IP. Otherwise returns the connection ip. 
        /// </summary>
        public readonly IPAddress TrustedRemoteIp;

        /// <summary>
        /// The requested web root. Provides additional site information
        /// </summary>
        public readonly IWebProcessor RequestedRoot;

        /// <summary>
        /// If the request has query arguments they are stored in key value format
        /// </summary>
        public IReadOnlyDictionary<string, string> QueryArgs => Entity.QueryArgs;

        /// <summary>
        /// If the request body has form data or url encoded arguments they are stored in key value format
        /// </summary>
        public IReadOnlyDictionary<string, string> RequestArgs => Entity.RequestArgs;

        /// <summary>
        /// Contains all files upladed with current request
        /// </summary>
        public IReadOnlyList<FileUpload> Files => Entity.Files;

        ///<inheritdoc/>
        HttpServer IHttpEvent.OriginServer => Entity.OriginServer;

        /// <summary>
        /// Complete the session and respond to user
        /// </summary>
        /// <param name="code">Status code of operation</param>
        /// <exception cref="InvalidOperationException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void CloseResponse(HttpStatusCode code) => Entity.CloseResponse(code);

        ///<inheritdoc/>
        ///<exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void CloseResponse(HttpStatusCode code, ContentType type, Stream stream)
        {
            Entity.CloseResponse(code, type, stream);
            //Verify content type matches
            if (!Server.Accepts(type))
            {
                throw new ContentTypeUnacceptableException("The client does not accept the content type of the response");
            }
        }

        ///<inheritdoc/>
        ///<exception cref="ContentTypeUnacceptableException"></exception>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void CloseResponse(HttpStatusCode code, ContentType type, IMemoryResponseReader entity)
        {
            //Verify content type matches
            if (!Server.Accepts(type))
            {
                throw new ContentTypeUnacceptableException("The client does not accept the content type of the response");
            }

            Entity.CloseResponse(code, type, entity);
        }

        ///<inheritdoc/>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void DisableCompression() => Entity.DisableCompression();

        /*
         * Do not directly expose dangerous methods, but allow them to be called
         */

        ///<inheritdoc/>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void IHttpEvent.DangerousChangeProtocol(IAlternateProtocol protocolHandler) => Entity.DangerousChangeProtocol(protocolHandler);
    }
}