public void Receive(byte[] data, IHeaders headers, IMessageCallback callback)
        {
            var envelope = new Envelope(data, headers, callback);
            Received.Add(envelope);

            envelope.Callback.MarkSuccessful();
        }
示例#2
0
        private static void AddGeneralProperties(IHeaders props, XmlElement item)
        {
            string prop;
              var ownerDocument = item.OwnerDocument;
              if (ownerDocument == null) {
            throw new ArgumentNullException(nameof(item));
              }
              if (props.TryGetValue("DateO", out prop)) {
            var e = ownerDocument.CreateElement("dc", "date", NS_DC);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Genre", out prop)) {
            var e = ownerDocument.CreateElement("upnp", "genre", NS_UPNP);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Description", out prop)) {
            var e = ownerDocument.CreateElement("dc", "description", NS_DC);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Artist", out prop)) {
            var e = ownerDocument.CreateElement("upnp", "artist", NS_UPNP);
            e.SetAttribute("role", "AlbumArtist");
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Performer", out prop)) {
            var e = ownerDocument.CreateElement("upnp", "artist", NS_UPNP);
            e.SetAttribute("role", "Performer");
            e.InnerText = prop;
            item.AppendChild(e);
            e = ownerDocument.CreateElement("dc", "creator", NS_DC);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Album", out prop)) {
            var e = ownerDocument.CreateElement("upnp", "album", NS_UPNP);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Track", out prop)) {
            var e = ownerDocument.CreateElement(
              "upnp", "originalTrackNumber", NS_UPNP);
            e.InnerText = prop;
            item.AppendChild(e);
              }
              if (props.TryGetValue("Creator", out prop)) {
            var e = ownerDocument.CreateElement("dc", "creator", NS_DC);
            e.InnerText = prop;
            item.AppendChild(e);
              }

              if (props.TryGetValue("Director", out prop)) {
            var e = ownerDocument.CreateElement("upnp", "director", NS_UPNP);
            e.InnerText = prop;
            item.AppendChild(e);
              }
        }
 public void Send(byte[] data, IHeaders headers)
 {
     var payload = new MessagePayload {Data = data, Headers = headers.ToNameValues()};
     var scope = _queueManager.BeginTransactionalScope();
     scope.Send(Address, payload);
     scope.Commit();
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueProducerConfiguration" /> class.
        /// </summary>
        /// <param name="transportConfiguration">The transport configuration.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="additionalConfiguration">The additional configuration.</param>
        /// <param name="timeConfiguration">The time configuration.</param>
        public QueueProducerConfiguration(TransportConfigurationSend transportConfiguration, 
            IHeaders headers, 
            IConfiguration additionalConfiguration,
            BaseTimeConfiguration timeConfiguration)
            : base(transportConfiguration, headers, additionalConfiguration, timeConfiguration)
        {

        }
示例#5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisHeaders" /> class.
 /// </summary>
 /// <param name="messageContextDataFactory">The message context data factory.</param>
 /// <param name="headers">The headers.</param>
 public RedisHeaders(IMessageContextDataFactory messageContextDataFactory,
     IHeaders headers)
 {
     Guard.NotNull(() => messageContextDataFactory, messageContextDataFactory);
     Guard.NotNull(() => headers, headers);
     Headers = headers;
     IncreaseQueueDelay = messageContextDataFactory.Create("IncreaseQueueDelay", new RedisQueueDelay(TimeSpan.Zero));
     CorelationId = messageContextDataFactory.Create<RedisQueueCorrelationIdSerialized>("CorelationId", null);
 }
示例#6
0
        // TODO -- do routing slip tracking later
        public Envelope(IHeaders headers)
        {
            Headers = headers;

            if (CorrelationId.IsEmpty())
            {
                CorrelationId = Guid.NewGuid().ToString();
            }
        }
示例#7
0
 internal static SQLiteCommand CreateMetaDataRecord(TimeSpan? delay, TimeSpan expiration, SQLiteConnection connection,
     IMessage message, IAdditionalMessageData data, TableNameHelper tableNameHelper, 
     IHeaders headers, SqLiteMessageQueueTransportOptions options, IGetTime getTime)
 {
     var command = new SQLiteCommand(connection);
     BuildMetaCommand(command, tableNameHelper, headers,
         data, message, 0, options, delay, expiration, getTime.GetCurrentUtcDate());
     return command;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="QueueRpcConfiguration" /> class.
 /// </summary>
 /// <param name="transportConfigurationReceive">The transport configuration receive.</param>
 /// <param name="transportConfigurationSend">The transport configuration send.</param>
 /// <param name="messageExpirationConfiguration">The message expiration configuration.</param>
 /// <param name="headers">The headers.</param>
 public QueueRpcConfiguration(TransportConfigurationReceive transportConfigurationReceive, 
     TransportConfigurationSend transportConfigurationSend, 
     IMessageExpirationConfiguration messageExpirationConfiguration, 
     IHeaders headers)
     : base(transportConfigurationSend, transportConfigurationReceive, headers)
 {
     Guard.NotNull(() => messageExpirationConfiguration, messageExpirationConfiguration);
     MessageExpiration = messageExpirationConfiguration;
 }
        public void Send(byte[] data, IHeaders headers)
        {
            var envelope = new EnvelopeToken
            {
                Data = data,
                Headers = headers
            };

            _queue.Enqueue(envelope);
        }
 public HttpRequestAuthParameters(IHeaders headers, IPEndPoint endPoint)
 {
     if (headers != null) {
     headers.TryGetValue("User-Agent", out _userAgent);
       }
       if (endPoint != null) {
     _address = endPoint.Address;
     _mac = IP.GetMAC(_address);
       }
 }
示例#11
0
 public bool Authorize(IHeaders headers, IPEndPoint endPoint, string mac)
 {
     var addr = endPoint?.Address;
       if (addr == null) {
     return false;
       }
       var rv = ips.ContainsKey(addr);
       DebugFormat(!rv ? "Rejecting {0}. Not in IP whitelist" : "Accepted {0} via IP whitelist", addr);
       return rv;
 }
示例#12
0
        public bool Authorize(IHeaders headers, IPEndPoint endPoint, string mac)
        {
            if (string.IsNullOrEmpty(mac)) {
            return false;
              }

              var rv = macs.ContainsKey(mac);
              DebugFormat(!rv ? "Rejecting {0}. Not in MAC whitelist" : "Accepted {0} via MAC whitelist", mac);
              return rv;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueConfigurationRpc" /> class.
        /// </summary>
        /// <param name="transportConfigurationSend">The transport configuration send.</param>
        /// <param name="transportConfigurationReceive">The transport configuration receive.</param>
        /// <param name="headerNames">The header names.</param>
        public QueueConfigurationRpc(TransportConfigurationSend transportConfigurationSend, 
            TransportConfigurationReceive transportConfigurationReceive,
            IHeaders headerNames)
        {
            Guard.NotNull(() => transportConfigurationSend, transportConfigurationSend);
            Guard.NotNull(() => transportConfigurationReceive, transportConfigurationReceive);
            Guard.NotNull(() => headerNames, headerNames);

            TransportConfigurationSend = transportConfigurationSend;
            TransportConfigurationReceive = transportConfigurationReceive;
            HeaderNames = headerNames;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ReceiveMessagesDecorator" /> class.
 /// </summary>
 /// <param name="metrics">The metrics factory.</param>
 /// <param name="headers">The headers.</param>
 /// <param name="getTime">The get time.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="connectionInformation">The connection information.</param>
 public ReceiveMessagesDecorator(IMetrics metrics,
     IHeaders headers,
     IGetTimeFactory getTime,
     IReceiveMessages handler,
     IConnectionInformation connectionInformation)
 {
     var name = handler.GetType().Name;
     _meter = metrics.Meter($"{connectionInformation.QueueName}.{name}.ReceiveMessageMeter", Units.Items);
     _waitTimer = metrics.Timer($"{connectionInformation.QueueName}.{name}.WaitForDeQueueMeter", Units.None);
     _handler = handler;
     _getTime = getTime;
     _headers = headers;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueConfigurationSend" /> class.
        /// </summary>
        /// <param name="transportConfiguration">The transport configuration.</param>
        /// <param name="headerNames">The header names.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="timeConfiguration">The time configuration.</param>
        public QueueConfigurationSend(TransportConfigurationSend transportConfiguration, 
            IHeaders headerNames,
            IConfiguration configuration,
            BaseTimeConfiguration timeConfiguration)
        {
            Guard.NotNull(() => transportConfiguration, transportConfiguration);
            Guard.NotNull(() => headerNames, headerNames);
            Guard.NotNull(() => configuration, configuration);
            Guard.NotNull(() => timeConfiguration, timeConfiguration);

            TransportConfiguration = transportConfiguration;
            HeaderNames = headerNames;
            AdditionalConfiguration = configuration;
            TimeConfiguration = timeConfiguration;
        }
示例#16
0
        public MessageDeQueue(IHeaders headers,
             IMessageFactory messageFactory,
             IReceivedMessageFactory receivedMessageFactory,
             ICompositeSerialization serialization)
        {
            Guard.NotNull(() => serialization, serialization);
            Guard.NotNull(() => headers, headers);
            Guard.NotNull(() => messageFactory, messageFactory);
            Guard.NotNull(() => receivedMessageFactory, receivedMessageFactory);

            _messageFactory = messageFactory;
            _headers = headers;
            _serialization = serialization;
            _receivedMessageFactory = receivedMessageFactory;
        }
示例#17
0
        public void Receive(byte[] data, IHeaders headers, IMessageCallback callback)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (headers == null) throw new ArgumentNullException("headers");
            if (callback == null) throw new ArgumentNullException("callback");

            var envelope = new Envelope(data, headers, callback)
            {
                ReceivedAt = _address
            };

            envelope.ContentType = envelope.ContentType ?? _node.DefaultContentType ?? _graph.DefaultContentType;

            _pipeline.Receive(envelope);
        }
示例#18
0
        public bool Authorize(IHeaders headers, IPEndPoint ep, string mac)
        {
            if (string.IsNullOrEmpty(mac)) {
            return false;
              }

              var rv = macs.ContainsKey(mac);
              if (!rv) {
            DebugFormat("Rejecting {0}. Not in MAC whitelist", mac ?? "<UNKNOWN>");
              }
              else {
            DebugFormat("Accepted {0} via MAC whitelist", mac);
              }
              return rv;
        }
        public void Send(byte[] data, IHeaders headers)
        {
            var messagePayload = new MessagePayload
            {
                Data = data,
                Headers = headers.ToNameValues()
            };

            var sendingScope = _queueManager.BeginTransactionalScope();
            var id = sendingScope.Send(_address, messagePayload);

            // TODO -- do we grab this?

            //data.CorrelationId = id.MessageIdentifier;
            sendingScope.Commit();
        }
示例#20
0
 public bool Authorize(IHeaders headers, IPEndPoint endPoint, string mac)
 {
     if (headers == null) {
     throw new ArgumentNullException(nameof(headers));
       }
       string ua;
       if (!headers.TryGetValue("User-Agent", out ua)) {
     return false;
       }
       if (string.IsNullOrEmpty(ua)) {
     return false;
       }
       var rv = userAgents.ContainsKey(ua);
       DebugFormat(!rv ? "Rejecting {0}. Not in User-Agent whitelist" : "Accepted {0} via User-Agent whitelist", ua);
       return rv;
 }
        public void Send(byte[] data, IHeaders headers)
        {
            var messagePayload = new MessagePayload
            {
                Data = data,
                Headers = headers.ToNameValues()
            };
            //TODO Maybe expose something to modify transport specific payloads?
            messagePayload.TranslateHeaders();

            var sendingScope = _queueManager.BeginTransactionalScope();
            var id = sendingScope.Send(_address, messagePayload);

            // TODO -- do we grab this?

            //data.CorrelationId = id.MessageIdentifier;
            sendingScope.Commit();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkerNotification" /> class.
        /// </summary>
        /// <param name="headerNames">The header names.</param>
        /// <param name="cancelWork">The cancel work.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="log">The log.</param>
        /// <param name="metrics">The metrics factory.</param>
        public WorkerNotification(IHeaders headerNames,
            IQueueCancelWork cancelWork,
            TransportConfigurationReceive configuration,
            ILogFactory log,
            IMetrics metrics)
        {
            Guard.NotNull(() => headerNames, headerNames);
            Guard.NotNull(() => cancelWork, cancelWork);
            Guard.NotNull(() => configuration, configuration);
            Guard.NotNull(() => log, log);
            Guard.NotNull(() => metrics, metrics);

            HeaderNames = headerNames;
            WorkerStopping = cancelWork;
            TransportSupportsRollback = configuration.MessageRollbackSupported;
            Log = log.Create();
            Metrics = metrics;
        }
示例#23
0
 public bool Authorize(IHeaders headers, IPEndPoint ep, string mac)
 {
     if (methods.Count == 0) {
     return true;
       }
       try {
     foreach (var m in methods) {
       if (m.Authorize(headers, ep, mac)) {
     return true;
       }
     }
     return false;
       }
       catch (Exception ex) {
     Error("Failed to authorize", ex);
     return false;
       }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="QueueConsumerConfiguration" /> class.
        /// </summary>
        /// <param name="transportConfiguration">The transport configuration.</param>
        /// <param name="workerConfiguration">The worker configuration.</param>
        /// <param name="heartBeatConfiguration">The heart beat configuration.</param>
        /// <param name="messageExpirationConfiguration">The message expiration configuration.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="additionalConfiguration">The additional configuration.</param>
        /// <param name="timeConfiguration">The time configuration.</param>
        public QueueConsumerConfiguration(TransportConfigurationReceive transportConfiguration, 
            IWorkerConfiguration workerConfiguration, 
            IHeartBeatConfiguration heartBeatConfiguration, 
            IMessageExpirationConfiguration messageExpirationConfiguration, 
            IHeaders headers,
            IConfiguration additionalConfiguration,
            BaseTimeConfiguration timeConfiguration)
            : base(transportConfiguration, headers, additionalConfiguration, timeConfiguration)
        {
            Guard.NotNull(() => workerConfiguration, workerConfiguration);
            Guard.NotNull(() => heartBeatConfiguration, heartBeatConfiguration);
            Guard.NotNull(() => messageExpirationConfiguration, messageExpirationConfiguration);

            Worker = workerConfiguration;
            HeartBeat = heartBeatConfiguration;
            MessageExpiration = messageExpirationConfiguration;
            _routes = new List<string>();
        }
示例#25
0
 public bool Authorize(IHeaders headers, IPEndPoint ep, string mac)
 {
     if (ep == null) {
     return false;
       }
       var addr = ep.Address;
       if (addr == null) {
     return false;
       }
       var rv = ips.ContainsKey(addr);
       if (!rv) {
     DebugFormat("Rejecting {0}. Not in IP whitelist", addr);
       }
       else {
     DebugFormat("Accepted {0} via IP whitelist", addr);
       }
       return rv;
 }
示例#26
0
        internal static void BuildMetaCommand(NpgsqlCommand command, 
            TableNameHelper tableNameHelper,
            IHeaders headers,
            IAdditionalMessageData data,
            IMessage message,
            long id,
            PostgreSqlMessageQueueTransportOptions options,
            TimeSpan? delay, 
            TimeSpan expiration,
            DateTime currentDateTime)
        {
            var sbMeta = new StringBuilder();
            sbMeta.AppendLine("Insert into " + tableNameHelper.MetaDataName);
            sbMeta.Append("(QueueID, CorrelationID, QueuedDateTime ");

            //add configurable columns - queue
            options.AddBuiltInColumns(sbMeta);

            AddHeaderColumns(sbMeta, message, headers);

            //close the column list
            sbMeta.AppendLine(") ");

            //add standard values that are always present
            sbMeta.Append("VALUES (");
            sbMeta.Append("@QueueID, @CorrelationID, now() at time zone 'utc' ");

            //add the values for built in fields
            options.AddBuiltInColumnValues(delay, expiration, currentDateTime, sbMeta);

            AddHeaderValues(sbMeta, message, headers);

            sbMeta.Append(")"); //close the VALUES 

            command.CommandText = sbMeta.ToString();

            options.AddBuiltInColumnsParams(command, data);
            AddHeaderColumnParams(command, message, headers);

            command.Parameters.Add("@QueueID", NpgsqlDbType.Bigint, 8).Value = id;
            command.Parameters.Add("@CorrelationID", NpgsqlDbType.Uuid, 16).Value = data.CorrelationId.Id.Value;

        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisQueueReceiveMessages" /> class.
        /// </summary>
        /// <param name="workSubFactory">The work sub factory.</param>
        /// <param name="receiveMessage">The receive message.</param>
        /// <param name="handleMessage">The handle message.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="cancelWork">The cancel work.</param>
        /// <param name="receiveMessageAsync">The receive message asynchronous.</param>
        public RedisQueueReceiveMessages(IRedisQueueWorkSubFactory workSubFactory,
            IQueryHandler<ReceiveMessageQuery, RedisMessage> receiveMessage, 
            HandleMessage handleMessage, 
            IHeaders headers,
            IQueueCancelWork cancelWork, IQueryHandler<ReceiveMessageQueryAsync, Task<RedisMessage>> receiveMessageAsync)
        {
            Guard.NotNull(() => workSubFactory, workSubFactory);
            Guard.NotNull(() => receiveMessage, receiveMessage);
            Guard.NotNull(() => handleMessage, handleMessage);
            Guard.NotNull(() => headers, headers);
            Guard.NotNull(() => cancelWork, cancelWork);
            Guard.NotNull(() => receiveMessageAsync, receiveMessageAsync);

            _receiveMessage = receiveMessage;
            _handleMessage = handleMessage;
            _headers = headers;
            _cancelWork = cancelWork;
            _receiveMessageAsync = receiveMessageAsync;
            _workSubFactory = workSubFactory;
        }
 public static TimeSpan GetExpiration(SendMessageCommand commandSend, 
     IHeaders headers)
 {
     //there are three possible locations for a message expiration. The user data and the header / internal headers
     //grab it from the internal header
     var expiration = commandSend.MessageToSend.GetInternalHeader(headers.StandardHeaders.RpcTimeout).Timeout;
     //if the header value is zero, check the message expiration
     if (expiration == TimeSpan.Zero)
     {
         //try the message header
         expiration = commandSend.MessageToSend.GetHeader(headers.StandardHeaders.RpcTimeout).Timeout;
     }
     //if the header value is zero, check the message expiration
     if (expiration == TimeSpan.Zero && commandSend.MessageData.GetExpiration().HasValue)
     {
         // ReSharper disable once PossibleInvalidOperationException
         expiration = commandSend.MessageData.GetExpiration().Value;
     }
     return expiration;
 }
示例#29
0
        internal static SQLiteCommand GetMainCommand(SendMessageCommand commandSend, 
            SQLiteConnection connection,
            SqLiteCommandStringCache commandCache,
            IHeaders headers,
            ICompositeSerialization serializer)
        {
            var command = connection.CreateCommand();
            command.CommandText = commandCache.GetCommand(SqLiteCommandStringTypes.InsertMessageBody);
            var serialization =
                serializer.Serializer.MessageToBytes(new MessageBody { Body = commandSend.MessageToSend.Body });

            command.Parameters.Add("@body", DbType.Binary, -1);
            command.Parameters["@body"].Value = serialization.Output;

            commandSend.MessageToSend.SetHeader(headers.StandardHeaders.MessageInterceptorGraph,
                serialization.Graph);

            command.Parameters.Add("@headers", DbType.Binary, -1);
            command.Parameters["@headers"].Value =
                serializer.InternalSerializer.ConvertToBytes(commandSend.MessageToSend.Headers);
            return command;
        }
示例#30
0
        internal static void BuildStatusCommand(SQLiteCommand command,
            TableNameHelper tableNameHelper,
            IHeaders headers,
            IAdditionalMessageData data,
            IMessage message,
            long id,
            SqLiteMessageQueueTransportOptions options,
            DateTime currentDateTime)
        {
            var builder = new StringBuilder();
            builder.AppendLine("Insert into " + tableNameHelper.StatusName);
            builder.Append("(QueueID, Status, CorrelationID ");

            //add configurable columns - user
            AddUserColumns(builder, data);

            //close the column list
            builder.AppendLine(") ");

            //add standard values that are always present
            builder.Append("VALUES (");
            builder.Append($"@QueueID, {Convert.ToInt32(QueueStatuses.Waiting)}, @CorrelationID");

            //add configurable column value - user
            AddUserColumnsValues(builder, data);

            builder.Append(")"); //close the VALUES 

            command.CommandText = builder.ToString();

            options.AddBuiltInColumnsParams(command, data, null, TimeSpan.Zero, currentDateTime);

            command.Parameters.Add("@QueueID", DbType.Int64, 8).Value = id;
            command.Parameters.Add("@CorrelationID", DbType.StringFixedLength, 38).Value = data.CorrelationId.Id.Value.ToString();

            //add configurable column command params - user
            AddUserColumnsParams(command, data);
            AddHeaderColumnParams(command, message, headers);
        }
示例#31
0
        internal static void BuildStatusCommand(NpgsqlCommand command,
                                                TableNameHelper tableNameHelper,
                                                IHeaders headers,
                                                IAdditionalMessageData data,
                                                IMessage message,
                                                long id,
                                                PostgreSqlMessageQueueTransportOptions options)
        {
            var builder = new StringBuilder();

            builder.AppendLine("Insert into " + tableNameHelper.StatusName);
            builder.Append("(QueueID, Status, CorrelationID ");

            //add configurable columns - user
            AddUserColumns(builder, data);

            //close the column list
            builder.AppendLine(") ");

            //add standard values that are always present
            builder.Append("VALUES (");
            builder.Append($"@QueueID, {Convert.ToInt32(QueueStatuses.Waiting)}, @CorrelationID");

            //add configurable column value - user
            AddUserColumnsValues(builder, data);

            builder.Append(")"); //close the VALUES

            command.CommandText = builder.ToString();

            options.AddBuiltInColumnsParams(command, data);

            command.Parameters.Add("@QueueID", NpgsqlDbType.Bigint, 8).Value      = id;
            command.Parameters.Add("@CorrelationID", NpgsqlDbType.Uuid, 16).Value = data.CorrelationId.Id.Value;

            //add configurable column command params - user
            AddUserColumnsParams(command, data);
        }
示例#32
0
        /// <summary>
        /// Loads html page by http get request
        /// </summary>
        /// <param name="uri">URL of page for loading</param>
        /// <param name="headers">Http headers</param>
        /// <returns>AngleSharp.IDocument</returns>
        public virtual async Task <IDocument> LoadPage(Uri uri, IHeaders headers)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            var requester = new HttpRequester();

            requester.Headers["User-Agent"] = headers.UserAgent;
            requester.Headers["Accept"]     = headers.Accept;

            var config = Configuration.Default
                         .WithDefaultLoader(requesters: new IRequester[] { requester })
                         .WithJavaScript()
                         .WithCss();

            return(await BrowsingContext.New(config).OpenAsync(uri.ToString()));
        }
        internal static void BuildMetaCommand(SqlCommand command,
                                              ITableNameHelper tableNameHelper,
                                              IHeaders headers,
                                              IAdditionalMessageData data,
                                              IMessage message,
                                              long id,
                                              SqlServerMessageQueueTransportOptions options,
                                              TimeSpan?delay,
                                              TimeSpan expiration)
        {
            var sbMeta = new StringBuilder();

            sbMeta.AppendLine("Insert into " + tableNameHelper.MetaDataName);
            sbMeta.Append("(QueueID, CorrelationID, QueuedDateTime ");

            //add configurable columns - queue
            options.AddBuiltInColumns(sbMeta);

            //close the column list
            sbMeta.AppendLine(") ");

            //add standard values that are always present
            sbMeta.Append("VALUES (");
            sbMeta.Append("@QueueID, @CorrelationID, GetUTCDate() ");

            //add the values for built in fields
            options.AddBuiltInColumnValues(delay, expiration, sbMeta);

            sbMeta.Append(")"); //close the VALUES

            command.CommandText = sbMeta.ToString();

            options.AddBuiltInColumnsParams(command, data);

            command.Parameters.Add("@QueueID", SqlDbType.BigInt, 8).Value = id;
            command.Parameters.Add("@CorrelationID", SqlDbType.UniqueIdentifier, 16).Value = data.CorrelationId.Id.Value;
        }
示例#34
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SendMessageCommandHandler" /> class.
        /// </summary>
        /// <param name="tableNameHelper">The table name helper.</param>
        /// <param name="serializer">The serializer.</param>
        /// <param name="optionsFactory">The options factory.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="commandCache">The command cache.</param>
        /// <param name="configurationSend">The configuration send.</param>
        /// <param name="getTimeFactory">The get time factory.</param>
        /// <param name="dbFactory">The database factory.</param>
        /// <param name="sendJobStatus">The send job status.</param>
        /// <param name="jobExistsHandler">The job exists handler.</param>
        /// <param name="jobSchedulerMetaData">The job scheduler meta data.</param>
        /// <param name="databaseExists">The database exists.</param>
        public SendMessageCommandHandler(TableNameHelper tableNameHelper,
                                         ICompositeSerialization serializer,
                                         ISqLiteMessageQueueTransportOptionsFactory optionsFactory,
                                         IHeaders headers,
                                         IDbCommandStringCache commandCache,
                                         TransportConfigurationSend configurationSend,
                                         IGetTimeFactory getTimeFactory,
                                         IDbFactory dbFactory,
                                         ICommandHandler <SetJobLastKnownEventCommand <IDbConnection, IDbTransaction> > sendJobStatus, RelationalDatabase.IQueryHandler <DoesJobExistQuery <IDbConnection, IDbTransaction>, QueueStatuses> jobExistsHandler,
                                         IJobSchedulerMetaData jobSchedulerMetaData,
                                         DatabaseExists databaseExists)
        {
            Guard.NotNull(() => tableNameHelper, tableNameHelper);
            Guard.NotNull(() => serializer, serializer);
            Guard.NotNull(() => optionsFactory, optionsFactory);
            Guard.NotNull(() => headers, headers);
            Guard.NotNull(() => commandCache, commandCache);
            Guard.NotNull(() => configurationSend, configurationSend);
            Guard.NotNull(() => getTimeFactory, getTimeFactory);
            Guard.NotNull(() => sendJobStatus, sendJobStatus);
            Guard.NotNull(() => jobExistsHandler, jobExistsHandler);
            Guard.NotNull(() => databaseExists, databaseExists);
            Guard.NotNull(() => dbFactory, dbFactory);

            _tableNameHelper      = tableNameHelper;
            _serializer           = serializer;
            _options              = new Lazy <SqLiteMessageQueueTransportOptions>(optionsFactory.Create);
            _headers              = headers;
            _commandCache         = commandCache;
            _configurationSend    = configurationSend;
            _getTime              = getTimeFactory.Create();
            _dbFactory            = dbFactory;
            _sendJobStatus        = sendJobStatus;
            _jobExistsHandler     = jobExistsHandler;
            _jobSchedulerMetaData = jobSchedulerMetaData;
            _databaseExists       = databaseExists;
        }
示例#35
0
        public bool Authorize(IHeaders headers, IPEndPoint endPoint, string mac)
        {
            if (endPoint == null)
            {
                return(false);
            }
            var addr = endPoint.Address;

            if (addr == null)
            {
                return(false);
            }
            var rv = ips.ContainsKey(addr);

            if (!rv)
            {
                DebugFormat("Rejecting {0}. Not in IP whitelist", addr);
            }
            else
            {
                DebugFormat("Accepted {0} via IP whitelist", addr);
            }
            return(rv);
        }
示例#36
0
        public void Receive(byte[] data, IHeaders headers, IMessageCallback callback)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            var envelope = new Envelope(data, headers, callback)
            {
                ReceivedAt = _address
            };

            envelope.ContentType = envelope.ContentType ?? _node.DefaultContentType ?? _graph.DefaultContentType;

            _pipeline.Receive(envelope);
        }
示例#37
0
        internal override IDictionary <string, string> GetSignature(HttpRequest request, HttpContext context, IHeaders iheaders)
        {
            CommonUtil.AddHeader(request, iheaders.ContentSha256Header(), ContentSha256);
            IDictionary <string, string> tempDict = new Dictionary <string, string>();

            foreach (KeyValuePair <string, string> entry in request.Headers)
            {
                if (string.IsNullOrEmpty(entry.Key))
                {
                    continue;
                }
                tempDict.Add(entry.Key.Trim().ToLower(), entry.Value);
            }

            List <string> signedHeadersList = V4Signer.GetSignedHeaderList(tempDict);
            string        signedHeaders     = V4Signer.GetSignedHeaders(signedHeadersList);

            IDictionary <string, string> dateDict = V4Signer.GetLongDateAndShortDate(request, iheaders);

            string signature = GetTemporarySignature(request, context, iheaders, dateDict, signedHeaders, tempDict, signedHeadersList, ContentSha256);

            IDictionary <string, string> ret = new Dictionary <string, string>();

            ret.Add("Signature", signature);
            ret.Add("ShortDate", dateDict["ShortDate"]);
            ret.Add("SignedHeaders", signedHeaders);
            return(ret);
        }
示例#38
0
        private IEnumerable <KeyValuePair <string, string> > HandleBrowse(
            IRequest request, IHeaders sparams)
        {
            var key = Prefix + sparams.HeaderBlock;
            AttributeCollection rv;

            if (soapCache.TryGetValue(key, out rv))
            {
                return(rv);
            }

            var id   = sparams["ObjectID"];
            var flag = sparams["BrowseFlag"];

            var requested = 20;
            var provided  = 0;
            var start     = 0;

            try
            {
                if (int.TryParse(sparams["RequestedCount"], out requested) &&
                    requested <= 0)
                {
                    requested = 20;
                }
                if (int.TryParse(sparams["StartingIndex"], out start) && start <= 0)
                {
                    start = 0;
                }
            }
            catch (Exception ex)
            {
                Debug("Not all params provided", ex);
            }

            var root = GetItem(id) as IMediaFolder;

            if (root == null)
            {
                throw new ArgumentException("Invalid id");
            }
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);

            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);
            didl.SetAttribute("xmlns:sec", NS_SEC);
            result.AppendChild(didl);

            if (flag == "BrowseMetadata")
            {
                Browse_AddFolder(result, root);
                provided++;
            }
            else
            {
                provided = BrowseFolder_AddItems(
                    request, result, root, start, requested);
            }

            var resXML = result.OuterXml;

            rv = new AttributeCollection
            {
                { "Result", resXML },
                { "NumberReturned", provided.ToString() },
                { "TotalMatches", root.ChildCount.ToString() },
                { "UpdateID", systemID.ToString() }
            };
            soapCache[key] = rv;
            return(rv);
        }
示例#39
0
        private static void AddGeneralProperties(IHeaders props, XmlElement item)
        {
            string prop;
            var    ownerDocument = item.OwnerDocument;

            if (ownerDocument == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            if (props.TryGetValue("DateO", out prop))
            {
                var e = ownerDocument.CreateElement("dc", "date", NS_DC);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Genre", out prop))
            {
                var e = ownerDocument.CreateElement("upnp", "genre", NS_UPNP);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Description", out prop))
            {
                var e = ownerDocument.CreateElement("dc", "description", NS_DC);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Artist", out prop))
            {
                var e = ownerDocument.CreateElement("upnp", "artist", NS_UPNP);
                e.SetAttribute("role", "AlbumArtist");
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Performer", out prop))
            {
                var e = ownerDocument.CreateElement("upnp", "artist", NS_UPNP);
                e.SetAttribute("role", "Performer");
                e.InnerText = prop;
                item.AppendChild(e);
                e           = ownerDocument.CreateElement("dc", "creator", NS_DC);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Album", out prop))
            {
                var e = ownerDocument.CreateElement("upnp", "album", NS_UPNP);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Track", out prop))
            {
                var e = ownerDocument.CreateElement(
                    "upnp", "originalTrackNumber", NS_UPNP);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Creator", out prop))
            {
                var e = ownerDocument.CreateElement("dc", "creator", NS_DC);
                e.InnerText = prop;
                item.AppendChild(e);
            }

            if (props.TryGetValue("Director", out prop))
            {
                var e = ownerDocument.CreateElement("upnp", "director", NS_UPNP);
                e.InnerText = prop;
                item.AppendChild(e);
            }
        }
示例#40
0
 public IHeaders <TKey, TValue> Add(IHeaders <TKey, TValue> headers)
 {
     throw ReadOnlyException;
 }
示例#41
0
        private CreateTemporarySignatureResponse CreateTemporarySignature(HttpRequest httpRequest, long expires, IHeaders iheaders)
        {
            DateTime dt1970       = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string   expiresValue = ((DateTime.UtcNow.Ticks - dt1970.Ticks) / 10000000 + expires).ToString();

            httpRequest.Headers[Constants.CommonHeaders.Date] = expiresValue;

            HttpContext context = new HttpContext(this.sp, this.ObsConfig);

            IDictionary <string, string> SinerReturn = this.httpClient.GetSigner(new HttpContext(this.sp, this.ObsConfig)).GetSignature(httpRequest, context, iheaders);

            string signature = CommonUtil.UrlEncode(SinerReturn["Signature"]);

            CreateTemporarySignatureResponse response = new CreateTemporarySignatureResponse();

            response.SignUrl = this.ObsConfig.Endpoint.StartsWith("https", StringComparison.OrdinalIgnoreCase) ?
                               "https://" : "http://";

            response.SignUrl += httpRequest.GetHost(this.ObsConfig.Endpoint);

            if (this.ObsConfig.PathStyle && !string.IsNullOrEmpty(httpRequest.BucketName))
            {
                response.SignUrl += "/" + CommonUtil.UrlEncode(httpRequest.BucketName);
            }

            if (!string.IsNullOrEmpty(httpRequest.ObjectKey))
            {
                response.SignUrl += "/" + CommonUtil.UrlEncode(httpRequest.ObjectKey, null, "/");
            }

            string accessKeyIdPrefix = this.ObsConfig.AuthType == AuthTypeEnum.OBS ? "AccessKeyId=" : "AWSAccessKeyId=";

            response.SignUrl += "?" + accessKeyIdPrefix + this.sp.Ak + "&Expires=" + expiresValue;

            foreach (KeyValuePair <string, string> entry in httpRequest.Params)
            {
                response.SignUrl += "&";
                response.SignUrl += CommonUtil.UrlEncode(entry.Key);
                response.SignUrl += "=";
                response.SignUrl += CommonUtil.UrlEncode(entry.Value);
            }

            response.SignUrl += "&Signature=" + signature;

            foreach (KeyValuePair <string, string> entry in httpRequest.Headers)
            {
                if (!entry.Key.Equals(Constants.CommonHeaders.Date))
                {
                    response.ActualSignedRequestHeaders.Add(entry.Key, entry.Value);
                }
            }

            return(response);
        }
示例#42
0
 public ContentHeader(IHeaders headers)
 {
     this.headers = headers;
 }
 public new static IConvertor GetInstance(IHeaders iheaders)
 {
     return(new ObsConvertor(iheaders));
 }
        internal override IDictionary <string, string> GetSignature(HttpRequest request, HttpContext context, IHeaders iheaders)
        {
            StringBuilder stringToSign = new StringBuilder();

            stringToSign.Append(request.Method.ToString()).Append("\n");

            string dateHeader        = Constants.CommonHeaders.Date.ToLower();
            string contentTypeHeader = Constants.CommonHeaders.ContentType.ToLower();
            string contentMd5Header  = Constants.CommonHeaders.ContentMd5.ToLower();
            string headerPrefix      = iheaders.HeaderPrefix();
            string headerMetaPrefix  = iheaders.HeaderMetaPrefix();

            IDictionary <string, string> tempDict = new Dictionary <string, string>();

            if (request.Headers.Count > 0)
            {
                foreach (KeyValuePair <string, string> entry in request.Headers)
                {
                    if (string.IsNullOrEmpty(entry.Key))
                    {
                        continue;
                    }

                    string key = entry.Key.Trim().ToLower();
                    if (key.StartsWith(headerPrefix) || key.Equals(contentTypeHeader) || key.Equals(contentMd5Header))
                    {
                        tempDict.Add(key, entry.Value);
                    }
                }
            }

            if (request.Headers.ContainsKey(dateHeader))
            {
                tempDict.Add(dateHeader, request.Headers[dateHeader]);
            }
            else
            {
                tempDict.Add(dateHeader, "");
            }

            if (!tempDict.ContainsKey(contentMd5Header))
            {
                tempDict.Add(contentMd5Header, "");
            }

            if (!tempDict.ContainsKey(contentTypeHeader))
            {
                tempDict.Add(contentTypeHeader, "");
            }

            List <KeyValuePair <string, string> > kvlist = new List <KeyValuePair <string, string> >(tempDict);

            tempDict.Clear();

            kvlist.Sort(delegate(KeyValuePair <string, string> x, KeyValuePair <string, string> y)
            {
                return(string.Compare(x.Key, y.Key, StringComparison.Ordinal));
            });

            foreach (KeyValuePair <string, string> kv in kvlist)
            {
                if (kv.Key.StartsWith(headerMetaPrefix))
                {
                    stringToSign.Append(kv.Key).Append(":").Append(kv.Value.Trim());
                }
                else if (kv.Key.StartsWith(headerPrefix))
                {
                    stringToSign.Append(kv.Key).Append(":").Append(kv.Value);
                }
                else
                {
                    stringToSign.Append(kv.Value);
                }
                stringToSign.Append("\n");
            }

            kvlist.Clear();

            stringToSign.Append("/");
            if (!string.IsNullOrEmpty(request.BucketName))
            {
                stringToSign.Append(CommonUtil.UrlEncode(request.BucketName));

                if (!request.PathStyle)
                {
                    stringToSign.Append("/");
                }

                if (!string.IsNullOrEmpty(request.ObjectKey))
                {
                    if (request.PathStyle)
                    {
                        stringToSign.Append("/");
                    }
                    stringToSign.Append(CommonUtil.UrlEncode(request.ObjectKey, null, "/"));
                }
            }

            if (request.Params.Count > 0)
            {
                foreach (KeyValuePair <string, string> entry in request.Params)
                {
                    if (string.IsNullOrEmpty(entry.Key))
                    {
                        continue;
                    }
                    if (Constants.AllowedResourceParameters.Contains(entry.Key.ToLower()) || entry.Key.ToLower().StartsWith(iheaders.HeaderPrefix()))
                    {
                        tempDict.Add(entry.Key, entry.Value);
                    }
                }
            }

            kvlist = new List <KeyValuePair <string, string> >(tempDict);

            tempDict.Clear();

            kvlist.Sort(delegate(KeyValuePair <string, string> x, KeyValuePair <string, string> y)
            {
                return(string.Compare(x.Key, y.Key, StringComparison.Ordinal));
            });
            if (kvlist.Count > 0)
            {
                bool isFirst = true;
                foreach (KeyValuePair <string, string> kv in kvlist)
                {
                    if (isFirst)
                    {
                        stringToSign.Append("?");
                        isFirst = false;
                    }
                    else
                    {
                        stringToSign.Append("&");
                    }
                    stringToSign.Append(kv.Key);
                    if (kv.Value != null)
                    {
                        stringToSign.Append("=").Append(kv.Value);
                    }
                }
            }

            if (LoggerMgr.IsDebugEnabled)
            {
                LoggerMgr.Debug("StringToSign: ******");
            }

            IDictionary <string, string> ret = new Dictionary <string, string>();

            ret.Add("Signature", Convert.ToBase64String(CommonUtil.HmacSha1(context.SecurityProvider.Sk, stringToSign.ToString())));

            return(ret);
        }
 public void Send(byte[] data, IHeaders headers)
 {
     _queueManager.Send(data, headers, Address);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SendMessageCommandHandlerAsyncDecorator"/> class.
 /// </summary>
 /// <param name="handler">The handler.</param>
 /// <param name="tracer">The tracer.</param>
 /// <param name="headers">The headers.</param>
 /// <param name="connectionInformation">The connection information.</param>
 public SendMessageCommandHandlerAsyncDecorator(ICommandHandlerWithOutputAsync <SendMessageCommand, int> handler, ActivitySource tracer, IHeaders headers, IConnectionInformation connectionInformation)
 {
     _handler = handler;
     _tracer  = tracer;
     _headers = headers;
     _connectionInformation = connectionInformation;
 }
示例#47
0
        public static void ParseObsWebServiceResponse(HttpResponse httpResponse, ObsWebServiceResponse response, IHeaders iheaders)
        {
            response.StatusCode = httpResponse.StatusCode;
            if (httpResponse.Headers.ContainsKey(iheaders.RequestIdHeader()))
            {
                response.RequestId = httpResponse.Headers[iheaders.RequestIdHeader()];
            }
            if (httpResponse.Headers.ContainsKey(Constants.CommonHeaders.ContentLength))
            {
                response.ContentLength = Convert.ToInt64(httpResponse.Headers[Constants.CommonHeaders.ContentLength]);
            }

            foreach (KeyValuePair <string, string> header in httpResponse.Headers)
            {
                string key = header.Key;
                if (key.StartsWith(iheaders.HeaderMetaPrefix()))
                {
                    key = key.Substring(iheaders.HeaderMetaPrefix().Length);
                }
                else if (key.StartsWith(iheaders.HeaderPrefix()))
                {
                    key = key.Substring(iheaders.HeaderPrefix().Length);
                }
                else if (key.StartsWith(Constants.ObsHeaderMetaPrefix))
                {
                    key = key.Substring(Constants.ObsHeaderMetaPrefix.Length);
                }
                else if (key.StartsWith(Constants.ObsHeaderPrefix))
                {
                    key = key.Substring(Constants.ObsHeaderPrefix.Length);
                }
                response.Headers.Add(key, header.Value);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public HeadersDictionary(IHeaders headers)
 {
     this.headers = headers;
 }
示例#49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AddStandardMessageHeaders"/> class.
 /// </summary>
 /// <param name="headers">The headers.</param>
 /// <param name="getFirstMessageDeliveryTime">The get first message delivery time.</param>
 public AddStandardMessageHeaders(IHeaders headers,
                                  IGetFirstMessageDeliveryTime getFirstMessageDeliveryTime)
 {
     _headers = headers;
     _getFirstMessageDeliveryTime = getFirstMessageDeliveryTime;
 }
示例#50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageHandlerAsyncDecorator"/> class.
 /// </summary>
 /// <param name="handler">The handler.</param>
 /// <param name="tracer">The tracer.</param>
 /// <param name="headers">The headers.</param>
 public MessageHandlerAsyncDecorator(IMessageHandlerAsync handler, ITracer tracer, IHeaders headers)
 {
     _handler = handler;
     _tracer  = tracer;
     _headers = headers;
 }
 protected ObsConvertor(IHeaders iheaders) : base(iheaders)
 {
 }
示例#52
0
        private CreateTemporarySignatureResponse CreateV4TemporarySignature(HttpRequest httpRequest, long expires, IHeaders iheaders)
        {
            IDictionary <string, string> dateDict = V4Signer.GetLongDateAndShortDate(httpRequest, iheaders);
            string host = httpRequest.GetHost(this.ObsConfig.Endpoint);

            CommonUtil.AddHeader(httpRequest, Constants.CommonHeaders.Host, host);

            IDictionary <string, string> tempDict = new Dictionary <string, string>();

            foreach (KeyValuePair <string, string> entry in httpRequest.Headers)
            {
                if (string.IsNullOrEmpty(entry.Key))
                {
                    continue;
                }
                tempDict.Add(entry.Key.Trim().ToLower(), entry.Value);
            }

            List <string> signedHeadersList = V4Signer.GetSignedHeaderList(tempDict);
            string        signedHeaders     = V4Signer.GetSignedHeaders(signedHeadersList);

            CommonUtil.AddParam(httpRequest, "X-Amz-Algorithm", V4Signer.Algorithm);
            CommonUtil.AddParam(httpRequest, "X-Amz-Credential", this.sp.Ak + "/" + dateDict["ShortDate"] + V4Signer.ScopeSuffix);
            CommonUtil.AddParam(httpRequest, "X-Amz-Date", dateDict["LongDate"]);
            CommonUtil.AddParam(httpRequest, "X-Amz-Expires", expires.ToString());
            CommonUtil.AddParam(httpRequest, "X-Amz-SignedHeaders", signedHeaders);

            HttpContext context   = new HttpContext(this.sp, this.ObsConfig);
            string      signature = CommonUtil.UrlEncode(V4Signer.GetTemporarySignature(httpRequest, context, iheaders, dateDict, signedHeaders, tempDict, signedHeadersList, null));

            CreateTemporarySignatureResponse response = new CreateTemporarySignatureResponse();

            response.SignUrl = this.ObsConfig.Endpoint.StartsWith("https", StringComparison.OrdinalIgnoreCase) ?
                               "https://" : "http://";

            response.SignUrl += host;

            if (this.ObsConfig.PathStyle && !string.IsNullOrEmpty(httpRequest.BucketName))
            {
                response.SignUrl += "/" + CommonUtil.UrlEncode(httpRequest.BucketName);
            }

            if (!string.IsNullOrEmpty(httpRequest.ObjectKey))
            {
                response.SignUrl += "/" + CommonUtil.UrlEncode(httpRequest.ObjectKey, null, "/");
            }

            bool isFirst = true;

            foreach (KeyValuePair <string, string> entry in httpRequest.Params)
            {
                if (isFirst)
                {
                    response.SignUrl += "?";
                    isFirst           = false;
                }
                else
                {
                    response.SignUrl += "&";
                }
                response.SignUrl += CommonUtil.UrlEncode(entry.Key);
                response.SignUrl += "=";
                response.SignUrl += CommonUtil.UrlEncode(entry.Value);
            }

            if (!string.IsNullOrEmpty(this.sp.Token))
            {
                response.SignUrl += "&" + iheaders.SecurityTokenHeader() + "=" + this.sp.Token;
            }
            response.SignUrl += "&X-Amz-Signature=" + signature;

            foreach (KeyValuePair <string, string> entry in httpRequest.Headers)
            {
                if (!entry.Key.Equals(Constants.CommonHeaders.Date))
                {
                    response.ActualSignedRequestHeaders.Add(entry.Key, entry.Value);
                }
            }

            return(response);
        }
示例#53
0
 public Envelope(byte[] data, IHeaders headers, IMessageCallback callback) : this(headers)
 {
     Data     = data;
     Callback = callback;
 }
示例#54
0
 public void Send(byte[] data, IHeaders headers)
 {
 }
示例#55
0
        internal static IDictionary <string, string> GetLongDateAndShortDate(HttpRequest request, IHeaders iheaders)
        {
            string longDate;

            if (request.Headers.ContainsKey(iheaders.DateHeader()))
            {
                longDate = request.Headers[iheaders.DateHeader()];
            }
            else if (request.Headers.ContainsKey(Constants.CommonHeaders.Date))
            {
                longDate =
                    DateTime.ParseExact(request.Headers[Constants.CommonHeaders.Date], Constants.RFC822DateFormat, Constants.CultureInfo)
                    .ToString(Constants.LongDateFormat, Constants.CultureInfo);
            }
            else
            {
                longDate = DateTime.UtcNow.ToString(Constants.LongDateFormat, Constants.CultureInfo);
            }

            string shortDate = longDate.Substring(0, longDate.IndexOf("T"));
            IDictionary <string, string> tempDict = new Dictionary <string, string>();

            tempDict.Add("LongDate", longDate);
            tempDict.Add("ShortDate", shortDate);
            return(tempDict);
        }
示例#56
0
 public new static IParser GetInstance(IHeaders iheaders)
 {
     return(new ObsParser(iheaders));
 }
示例#57
0
        /// <summary>
        /// Generate parameters for a temporary authentication request.
        /// </summary>
        /// <param name="request">Request parameters</param>
        /// <returns>Response</returns>
        public CreateTemporarySignatureResponse CreateTemporarySignature(CreateTemporarySignatureRequest request)
        {
            HttpRequest httpRequest = new HttpRequest();

            httpRequest.PathStyle  = this.ObsConfig.PathStyle;
            httpRequest.BucketName = request.BucketName;
            httpRequest.ObjectKey  = request.ObjectKey;
            httpRequest.Method     = request.Method;

            IHeaders iheaders = this.httpClient.GetIHeaders(new HttpContext(this.sp, this.ObsConfig));

            if (!string.IsNullOrEmpty(this.sp.Token) && !request.Parameters.ContainsKey(iheaders.SecurityTokenHeader()))
            {
                request.Parameters.Add(iheaders.SecurityTokenHeader(), this.sp.Token.Trim());
            }

            foreach (KeyValuePair <string, string> entry in request.Headers)
            {
                CommonUtil.AddHeader(httpRequest, entry.Key, entry.Value);
            }

            foreach (KeyValuePair <string, string> entry in request.Parameters)
            {
                CommonUtil.AddParam(httpRequest, entry.Key, entry.Value);
            }

            if (request.SubResource.HasValue)
            {
                SubResourceEnum value = request.SubResource.Value;
                if (value == SubResourceEnum.StoragePolicy && this.ObsConfig.AuthType == AuthTypeEnum.OBS)
                {
                    value = SubResourceEnum.StorageClass;
                }
                else if (value == SubResourceEnum.StorageClass && this.ObsConfig.AuthType != AuthTypeEnum.OBS)
                {
                    value = SubResourceEnum.StoragePolicy;
                }

                CommonUtil.AddParam(httpRequest, EnumAdaptor.GetStringValue(value), null);
            }

            foreach (KeyValuePair <string, string> entry in request.Metadata.KeyValuePairs)
            {
                if (string.IsNullOrEmpty(entry.Key))
                {
                    continue;
                }
                string _key = entry.Key;
                if (!entry.Key.StartsWith(iheaders.HeaderMetaPrefix(), StringComparison.OrdinalIgnoreCase) && !entry.Key.StartsWith(Constants.ObsHeaderMetaPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    _key = iheaders.HeaderMetaPrefix() + _key;
                }
                CommonUtil.AddHeader(httpRequest, _key, entry.Value);
            }

            long expires = 300;

            if (request.Expires.HasValue && request.Expires.Value > 0)
            {
                expires = request.Expires.Value;
            }

            return(this.ObsConfig.AuthType == AuthTypeEnum.V4 ? this.CreateV4TemporarySignature(httpRequest, expires, iheaders) : this.CreateTemporarySignature(httpRequest, expires, iheaders));
        }
示例#58
0
        internal static string GetTemporarySignature(HttpRequest request, HttpContext context, IHeaders iheaders, IDictionary <string, string> dateDict, string signedHeaders,
                                                     IDictionary <string, string> headerDict, List <string> signedHeaderList, string payload)
        {
            StringBuilder canonicalRequest = new StringBuilder();

            canonicalRequest.Append(request.Method).Append("\n");

            // Canonical URI
            canonicalRequest.Append("/");
            if (!string.IsNullOrEmpty(request.BucketName))
            {
                if (request.PathStyle)
                {
                    canonicalRequest.Append(CommonUtil.UrlEncode(request.BucketName));
                }

                if (!string.IsNullOrEmpty(request.ObjectKey))
                {
                    if (request.PathStyle)
                    {
                        canonicalRequest.Append("/");
                    }
                    canonicalRequest.Append(CommonUtil.UrlEncode(request.ObjectKey, null, "/"));
                }
            }

            canonicalRequest.Append("\n");

            //CanonicalQueryString
            IDictionary <string, string> tempDict = new Dictionary <string, string>();

            foreach (KeyValuePair <string, string> entry in request.Params)
            {
                if (string.IsNullOrEmpty(entry.Key))
                {
                    continue;
                }
                tempDict.Add(entry.Key, entry.Value);
            }

            List <KeyValuePair <string, string> > kvlist = new List <KeyValuePair <string, string> >(tempDict);

            tempDict.Clear();

            kvlist.Sort(delegate(KeyValuePair <string, string> x, KeyValuePair <string, string> y)
            {
                return(string.Compare(x.Key, y.Key, StringComparison.Ordinal));
            });

            canonicalRequest.Append(CommonUtil.ConvertParamsToCanonicalQueryString(kvlist));

            canonicalRequest.Append("\n");

            if (headerDict == null)
            {
                // Canonical Headers
                headerDict = new Dictionary <string, string>();
                foreach (KeyValuePair <string, string> entry in request.Headers)
                {
                    if (string.IsNullOrEmpty(entry.Key))
                    {
                        continue;
                    }
                    headerDict.Add(entry.Key.Trim().ToLower(), entry.Value);
                }
            }

            foreach (string key in signedHeaderList)
            {
                canonicalRequest.Append(key).Append(":").Append(headerDict[key]).Append("\n");
            }

            canonicalRequest.Append("\n");

            // SignedHeaders
            canonicalRequest.Append(signedHeaders);
            canonicalRequest.Append("\n");

            // Hashed Payload
            canonicalRequest.Append(string.IsNullOrEmpty(payload)? UnsignedPayload : payload);

            if (LoggerMgr.IsDebugEnabled)
            {
                LoggerMgr.Debug("CanonicalRequest:" + canonicalRequest);
            }

            StringBuilder stringToSign = new StringBuilder(Algorithm).Append("\n")
                                         .Append(dateDict["LongDate"]).Append("\n")
                                         .Append(dateDict["ShortDate"]).Append(ScopeSuffix).Append("\n")
                                         .Append(CommonUtil.HexSha256(canonicalRequest.ToString()));

            if (LoggerMgr.IsDebugEnabled)
            {
                LoggerMgr.Debug("StringToSign:" + stringToSign.ToString());
            }

            return(CaculateSignature(stringToSign.ToString(), dateDict["ShortDate"], context.SecurityProvider.Sk));
        }
 internal HttpAuthorizationEventArgs(IHeaders headers,
                                     IPEndPoint remoteEndpoint)
 {
     Headers        = headers;
     RemoteEndpoint = remoteEndpoint;
 }
示例#60
0
 private ObsParser(IHeaders iheaders) : base(iheaders)
 {
 }