private void sendControlRequest(LightstreamerRequest request, RequestListener reqListener, RequestTutor tutor)
        {
            ongoingRequest = new PendingRequest(request, reqListener, tutor);

            wsTransport.sendRequest(protocol, request, new ListenerWrapperAnonymousInnerClass(this, reqListener)
                                    , null, null, 0, 0);
        }
Ejemplo n.º 2
0
        public IActionResult RequestAccess(int id)
        {
            var user = _userManager.GetUserAsync(User).Result;

            var wishList = WishListRepository.Find(id);

            if (wishList.CreatorName == user.Email)
            {
                return(BadRequest("not possible to request access to own wishlist"));
            }
            if (wishList.Subscribers.Any(sub => sub.UserId == user?.Id))
            {
                return(BadRequest("already subscribed to wishlist"));
            }
            if (wishList.PendingRequests.Any(pi => pi.UserId == user?.Id))
            {
                return(BadRequest("access already requested"));
            }

            var request = new PendingRequest
            {
                User     = user,
                WishList = wishList
            };

            wishList.AddRequest(request);

            WishListRepository.Update(wishList);

            return(Ok());
        }
Ejemplo n.º 3
0
        internal static void TransferToImage(Image image, Uri uri)
        {
            SetUriSource(image, null);
            PendingRequest pr = new PendingRequest(image, uri);

            PriorityQueue.AddWorkItem(() =>
            {
                PendingRequest ppr = pr;
                ProcessTransfer(ppr);
            });

            // The original implementation that I created would simply flip the
            // image.Source = new BitmapImage(uri) bit. I've decided not to do
            // that in this newer version where I manage my own set of bytes[].

            if (!_recentQuick.ContainsKey(uri))
            {
                if (_recent.Count == RecentLimit)
                {
                    Uri byebyebye = _recent.Dequeue();
                    _recentQuick.Remove(byebyebye);
                }

                _recentQuick.Add(uri, true);
                _recent.Enqueue(uri);
            }
        }
Ejemplo n.º 4
0
        public async Task <Response> CommitRequest(FlatBufferBuilder fbb,
                                                   RequestData requestDataType,
                                                   int requestDataOffset)
        {
            PendingRequest request = new PendingRequest();

            request.requestId    = nextRequestId++;
            request.responseTask = new TaskCompletionSource <Response>();
            pendingRequests.TryAdd(request.requestId, request);

            int requestOffset =
                Request.CreateRequest(fbb, request.requestId,
                                      requestDataType, requestDataOffset);

            fbb.Finish(requestOffset);

            // Update the placeholder size.
            int bufferOffset = fbb.DataBuffer.Position;
            int bufferLength = fbb.DataBuffer.Length - fbb.DataBuffer.Position;

            fbb.DataBuffer.PutInt(bufferOffset - 4, bufferLength);

            // Send request.
            await socket.SendTaskAsync(fbb.DataBuffer.Data, bufferOffset - 4,
                                       bufferLength + 4, SocketFlags.None);

            // Await response.
            var response = await request.responseTask.Task;

            return(response);
        }
Ejemplo n.º 5
0
        public IActionResult PostAddFriend([FromBody] Friend f)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Model is not valid."));
            }
            if (vinylContext.Friends.SingleOrDefault(e => (e.User1Ref == f.User1Ref) && (e.User2Ref == f.User2Ref)) != null)
            {
                return(Conflict("Alredy exists."));
            }
            vinylContext.Friends.Add(f);
            Friend reverse = new Friend {
                User1Ref = f.User2Ref,
                User2Ref = f.User1Ref
            };
            PendingRequest pr = new PendingRequest
            {
                UserSentRef     = f.User1Ref,
                UserReceavedRef = f.User2Ref
            };

            vinylContext.PendingRequests.Remove(pr);
            vinylContext.Friends.Add(reverse);
            vinylContext.SaveChanges();
            return(Ok());
        }
Ejemplo n.º 6
0
        public Promise <MultiPlayerMessage> SendRequest(MultiPlayerMessage message, TimeSpan?timeout = null)
        {
            try
            {
                message.Sender    = ClientId;
                message.RequestId = Guid.NewGuid().ToString();
                var pendingRequest = new PendingRequest()
                {
                    Id = message.RequestId,
                    ResponseDeferred = Deferred <MultiPlayerMessage> .Create(),
                };

                if (timeout.HasValue)
                {
                    pendingRequest.Timeout = timeout.Value;
                }
                lock (pendingRequests)
                {
                    pendingRequests.Add(message.RequestId, pendingRequest);
                }
                SendMessage(message);
                return(pendingRequest.ResponseDeferred.Promise);
            }
            catch (Exception ex)
            {
                var d = Deferred <MultiPlayerMessage> .Create();

                d.Reject(ex);
                return(d.Promise);
            }
        }
Ejemplo n.º 7
0
        void IMessagingEvents.GetEvents(string msg, object trigger, Queue <Event> buffer)
        {
            var match = regex.Match(msg);

            if (match.Success)
            {
                MessageDirection dir          = match.Groups["dir"].Value == "Incoming" ? MessageDirection.Incoming : MessageDirection.Outgoing;
                MessageType      type         = match.Groups["type"].Value == "request" ? MessageType.Request : MessageType.Response;
                string           requestId    = match.Groups["id"].Value;
                string           requestName  = match.Groups["name"].Value;
                string           rest         = match.Groups["rest"].Value;
                string           remoteSideId = DetectRemoteId(requestName, rest);
                if (type == MessageType.Request)
                {
                    requests[requestId] = new PendingRequest()
                    {
                        RemoteSideId = remoteSideId
                    };
                }
                else if (requests.TryGetValue(requestId, out var pendingRequest))
                {
                    if (remoteSideId == null)
                    {
                        remoteSideId = pendingRequest.RemoteSideId;
                    }
                    requests.Remove(requestId);
                }
                string displayName = MakeDisplayName(requestName, rest);
                buffer.Enqueue(new NetworkMessageEvent(
                                   trigger, displayName, dir, type, "", requestId, null, remoteSideId, GetStatus(rest))
                               .SetTags(GetTags(requestName)));
            }
        }
        /// <summary>
        /// Resolve a whole bunch of IDs.
        /// </summary>
        /// <param name="AgentIds"></param>
        /// <returns></returns>
        public async Task <IEnumerable <MappedIdentity> > MapAgents(IEnumerable <UUID> AgentIds)
        {
            var newRequests = new List <Task <MappedIdentity> >();

            lock (agentCacheLock)
            {
                foreach (var i in AgentIds)
                {
                    MappedIdentity found;
                    if (AgentsByUuid.TryGetValue(i, out found))
                    {
                        newRequests.Add(Task.FromResult(found));
                    }
                    else
                    {
                        var req = new PendingRequest(i);
                        agentRequests.Add(req);
                        newRequests.Add(req.TaskSource.Task);
                    }
                }
            }
            client.Avatars.RequestAvatarNames(AgentIds.ToList());

            return(await Task.WhenAll(newRequests));
        }
        public Task <MappedIdentity> MapAgent(UUID AgentId, string SlName = null)
        {
            MappedIdentity identity;

            lock (agentCacheLock)
            {
                if (AgentsByUuid.TryGetValue(AgentId, out identity))
                {
                    return(Task.FromResult(identity));
                }
            }

            if (SlName != null)
            {
                return(Task.FromResult(MakeAgentIdentity(AgentId, SlName)));
            }

            PendingRequest request;

            lock (agentRequests)
            {
                request = new PendingRequest(AgentId);
                agentRequests.Add(request);
            }
            client.Avatars.RequestAvatarName(AgentId);
            return(request.TaskSource.Task);
        }
Ejemplo n.º 10
0
 public IActionResult GetPendingRequests(string user)
 {
     try
     {
         PendingRequest pending = _repo.GetPendingRequests(user);
         if (pending.friend_requests == null)
         {
             return(BadRequest(new AppErrorResponse {
                 status = "failure", reason = "User does not exist"
             }));
         }
         else if (pending.friend_requests.Count() == 0)
         {
             return(NotFound(new AppErrorResponse {
                 status = "failure", reason = "User does not have any requests"
             }));
         }
         else
         {
             return(Ok(pending));
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, ex.Message, ex.InnerException);
         return(BadRequest(new AppErrorResponse()));
     }
 }
Ejemplo n.º 11
0
        public PendingRequest GetPendingRequests(string user)
        {
            PendingRequest pending = new PendingRequest();

            pending.friend_requests = new List <string>();
            using (var factory = new FriendSuggestorContextFactory())
            {
                // Get a context
                using (var context = factory.CreateContext())
                {
                    User u = context.Users.Where(x => x.UserName == user).FirstOrDefault();
                    if (u != null)
                    {
                        pending.friend_requests = (from l in context.FriendsLists
                                                   join r in context.Users
                                                   on l.UserF equals r.UserId
                                                   where l.UserSF == u.UserId && l.IsFriend == false
                                                   select r.UserName).ToList();
                    }
                    else
                    {
                        pending.friend_requests = null;
                    }
                }
            }
            return(pending);
        }
Ejemplo n.º 12
0
        public Task <MultiPlayerMessage> SendRequest(MultiPlayerMessage message, TimeSpan?timeout = null)
        {
            try
            {
                message.Sender    = ClientId;
                message.RequestId = Guid.NewGuid().ToString();
                var pendingRequest = new PendingRequest()
                {
                    Id = message.RequestId,
                    ResponseDeferred = new TaskCompletionSource <MultiPlayerMessage>(),
                };

                if (timeout.HasValue)
                {
                    pendingRequest.Timeout = timeout.Value;
                }
                lock (pendingRequests)
                {
                    pendingRequests.Add(message.RequestId, pendingRequest);
                }
                SendMessage(message);
                return(pendingRequest.ResponseDeferred.Task);
            }
            catch (Exception ex)
            {
                var d = new TaskCompletionSource <MultiPlayerMessage>();
                d.SetException(ex);
                return(d.Task);
            }
        }
Ejemplo n.º 13
0
        internal static void TransferToImage(Image image, Uri uri)
        {
            SetUriSource(image, null);
            PendingRequest pr = new PendingRequest(image, uri);
            PriorityQueue.AddWorkItem(() =>
                {
                    PendingRequest ppr = pr;
                    ProcessTransfer(ppr);
                });

            // The original implementation that I created would simply flip the
            // image.Source = new BitmapImage(uri) bit. I've decided not to do
            // that in this newer version where I manage my own set of bytes[].

            if (!_recentQuick.ContainsKey(uri))
            {
                if (_recent.Count == RecentLimit)
                {
                    Uri byebyebye = _recent.Dequeue();
                    _recentQuick.Remove(byebyebye);
                }

                _recentQuick.Add(uri, true);
                _recent.Enqueue(uri);
            }
        }
Ejemplo n.º 14
0
        private NetStatus OnRequestTimeout(Dispatcher.CallbackArgs args)
        {
            DateTime now = ((TimeoutArgument !)args).now;

            int i = 0;

            while (i != pendingRequests.Count)
            {
                PendingRequest request = (PendingRequest !)pendingRequests[i];
                if (request.expiry < now)
                {
                    DebugPrint("Expiring request");

                    request.callback(request.address,
                                     EthernetAddress.Zero,
                                     request.cookie);
                    pendingRequests.RemoveAt(i);
                    continue;
                }
                i++;
            }

            if (pendingRequests.Count > 0)
            {
                DateTime nextPoll = now + PollPeriod;
                Core.Instance().TheDispatcher.AddCallback(
                    new Dispatcher.Callback(OnRequestTimeout),
                    new TimeoutArgument(nextPoll),
                    (ulong)nextPoll.Ticks
                    );
            }
            return(NetStatus.Code.RT_OK);
        }
Ejemplo n.º 15
0
 private void ProcessPendingRequests()
 {
     PendingRequest rq = null;
     while (m_pendingqueue.DequeueUnblocking(out rq))
     {
         HandleAnswer(rq);
     }
 }
Ejemplo n.º 16
0
        public IHttpActionResult InsertRequest(PendingRequest pendingRequest)
        {
            pendingRequest.Date    = DateTime.Now;
            pendingRequest.Pending = true;

            pendingRequestRepository.Create(pendingRequest);
            return(Ok());
        }
 public PendingRequestResource(PendingRequest pendingRequest)
 {
     this.BookId = pendingRequest.BookId;
     this.Date   = pendingRequest.Date;
     this.User   = pendingRequest.User;
     this.Id     = pendingRequest.Id;
     this.Date   = DateTime.Now;
 }
Ejemplo n.º 18
0
        private static string GetFillRequestMessage(PendingRequest p)
        {
            var fillsRequest = new CBPRO.FillsRequest {
                order_id = p.EntityId
            };

            return(JsonConvert.SerializeObject(fillsRequest).ToString());
        }
Ejemplo n.º 19
0
        private static async Task <string> MakeFetchRequest(string url)
        {
            Debug.WriteLine("making fetch request, url: [" + url + "]");
            var token = NewToken;
            var req   = _pendingRequests[token] = new PendingRequest(token, url);

            TriggerServerEvent("__sthv__internal:fetchRequest", token, url);
            return(await req.Task);
        }
Ejemplo n.º 20
0
 void ISocketEventListener.OnClose(BaseSocket sock)
 {
     m_sock    = null;
     m_current = null;
     lock (m_lock)
     {
         Monitor.Pulse(m_lock);
     }
 }
Ejemplo n.º 21
0
        private static void Enrich(PendingRequest request)
        {
            if (request == null)
            {
                return;
            }

            request.Resource = DefaultResourceSetRepository.Resources.FirstOrDefault(r => r.Id == request.ResourceId);
        }
Ejemplo n.º 22
0
        private IObservable <IView> PresentLater(object input, Options options)
        {
            // Complete any pending request without fulling it (we only allow a single pending request)
            _pendingRequest?.Subject.OnCompleted();

            // Prepare new pending request
            _pendingRequest = new PendingRequest(input, options);
            return(_pendingRequest.Subject);
        }
Ejemplo n.º 23
0
        private Task <NvimResponse> SendAndReceive(NvimRequest request)
        {
            request.MessageId = _messageIdCounter++;
            var pendingRequest = new PendingRequest();

            _pendingRequests[request.MessageId] = pendingRequest;
            _messageQueue.Add(request);
            return(pendingRequest.GetResponse());
        }
Ejemplo n.º 24
0
 void Server_OnReceiveLine(System.Net.Sockets.Socket socket, string line)
 {
     TCPServer.ClientUser client = Server.Clients[socket.Handle];
     string[] splitChar = { " " };
     string[] args = line.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
     if (client.LinesReceived == 0)
     {
         string method = args[0].ToLower();
         if (args.Length < 2 || (method != "get" && method != "post"))
         {
             //FIXME- add event
             Server.SendLine(socket, (int)HTTPErrorCode.MethodNotAllowed + " method not allowed");
             Server.KillUser(socket.Handle);
         }
         else
         {
             PendingRequest request = new PendingRequest();
             request.Status = ClientStatus.Requesting;
             request.Method = args[0];
             char[] splitPath = { '?' };
             string[] path = args[1].Split(splitPath);
             request.Path = path[0];
             if (path.Length > 0)
             {
                 char[] splitVars = { '&' };
                 char[] splitVal = { '=' };
                 string[] vars = path[1].Split(splitVars);
                 foreach (string v in vars)
                 {
                     string[] keyval = v.Split(splitVal);
                     if (keyval.Length > 0) request.GetVars.Add(keyval[0], keyval[1]);
                     else request.GetVars.Add(keyval[0], "");
                 }
             }
             PendingRequests.Add(socket.Handle, request);
         }
     }
     else if (PendingRequests.ContainsKey(socket.Handle))
     {
         PendingRequest request = PendingRequests[socket.Handle];
         if (args.Length == 0)
         {
             request.Status = ClientStatus.Complete;
             OnHTTPRequest(request.Method, request.Path, request.Host, request.UserAgent, request.ContentType, request.ContentLength, request.GetVars);
         }
         else if (args.Length > 1)
         {
             string param = args[0].ToLower();
             if (param == "host:") request.Host = args[1];
             else if (param == "user-agent:") request.UserAgent = args[1];
             else if (param == "content-type:") request.ContentType = args[1];
             else if (param == "content-length:") int.TryParse(args[1], out request.ContentLength);
         }
         PendingRequests[socket.Handle] = request;
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Close the socket after all pending requests are completed.
        /// </summary>
        public void EnqueueClose()
        {
            PendingRequest req = new PendingRequest(null, null, null, 0, 0, null);

            lock (m_queue)
            {
                m_queue.AddLast(req);
                Monitor.Pulse(m_queue);
            }
        }
Ejemplo n.º 26
0
 private void HandleAnswer(PendingRequest rq)
 {
     byte[] ln = m_connection.ReadLine();
     if (ln == null)
     {
         SetState(State.Terminated, "server closed connection");
         return;
     }
     else if (Protocol.IsCommand("OK", ln))
     {
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Result, id = rq.id, number = rq.number, obj = null });
     }
     else if (Protocol.IsCommand("ERR", ln))
     {
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Failure, id = rq.id, number = rq.number, obj = Protocol.CommandArg("ERR", ln) });
     }
     else if (Protocol.IsCommand("BAD", ln))
     {
         SetState(State.Terminated, "protocol error");
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "protocol error" });
         return;
     }
     else if (Protocol.IsCommand("ANSWER", ln))
     {
         byte[] msg = m_connection.ReadContent();
         if (msg == null)
         {
             SetState(State.Terminated, "server closed connection");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "server closed connection" });
             return;
         }
         ln = m_connection.ReadLine();
         if (msg == null)
         {
             SetState(State.Terminated, "server closed connection");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "server closed connection" });
             return;
         }
         else if (Protocol.IsCommand("OK", ln))
         {
             object answerobj = m_serializer.getResult(msg, rq.answertype);
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Result, id = rq.id, number = rq.number, obj = answerobj });
         }
         else if (Protocol.IsCommand("ERR", ln))
         {
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Failure, id = rq.id, number = rq.number, obj = Protocol.CommandArg("ERR", ln) });
         }
         else if (Protocol.IsCommand("BAD", ln))
         {
             SetState(State.Terminated, "protocol error");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "protocol error" });
             return;
         }
     }
 }
Ejemplo n.º 27
0
        public async Task <string> DownloadString(string url)
        {
            var args = new Dictionary <string, object> {
                { "url", url }
            };
            var argsJson = JsonConvert.SerializeObject(args);
            var id       = API.PerformHttpRequestInternal(argsJson, argsJson.Length);
            var req      = _pendingRequests[id] = new PendingRequest(id);

            return(await req.Task);
        }
Ejemplo n.º 28
0
        private static void ProcessTransfer(PendingRequest pendingRequest)
        {
            if (pendingRequest == null || pendingRequest.Uri == null)
            {
                return;
            }

            try
            {
                if (pendingRequest.Uri.IsAbsoluteUri)
                {
                    _iso.GetItem(pendingRequest.Uri, (img, exc, stat) =>
                    {
                        if (stat == IsoStoreCache.ItemCacheStatus.Hit)
                        {
                            var ms = new MemoryStream(img);
                            var pc = new PendingCompletion(pendingRequest.Image, pendingRequest.Uri, ms);
                            PriorityQueue.AddUiWorkItem(() =>
                            {
                                HandleCompletion(pc);
                            });
                        }
                        else
                        {
                            // Download from network
                            var webRequest = HttpWebRequest.CreateHttp(pendingRequest.Uri);
                            webRequest.AllowReadStreamBuffering = true;     // Don't want to block this thread or the UI thread on network access
                            webRequest.BeginGetResponse(HandleGetResponseResult, new ResponseState(webRequest, pendingRequest.Image, pendingRequest.Uri));
                        }
                    });
                }
                else
                {
                    // Load from application (must have "Build Action"="Content")
                    var originalUriString = pendingRequest.Uri.OriginalString;
                    // Trim leading '/' to avoid problems
                    var resourceStreamUri = originalUriString.StartsWith("/", StringComparison.Ordinal) ? new Uri(originalUriString.TrimStart('/'), UriKind.Relative) : pendingRequest.Uri;
                    // Enqueue resource stream for completion
                    var streamResourceInfo = Application.GetResourceStream(resourceStreamUri);
                    if (null != streamResourceInfo)
                    {
                        var pc = new PendingCompletion(pendingRequest.Image, pendingRequest.Uri, streamResourceInfo.Stream);
                        PriorityQueue.AddUiWorkItem(() =>
                        {
                            HandleCompletion(pc);
                        });
                    }
                }
            }
            catch (NullReferenceException)
            {
                // Trying to address user-found bugs here.
            }
        }
Ejemplo n.º 29
0
        public Task Start(Action <NanoListenerTransaction> transactionCallback, Action <NanoResult> errorCallback)
        {
            return(Task.Run(
                       async() =>
            {
                while (true)
                {
                    try
                    {
                        await Task.Delay(this.Interval);
                        PendingRequest pendingRequest = new PendingRequest();
                        pendingRequest.Account = this.Account;
                        pendingRequest.Count = this.Count.ToString();
                        NanoResult <PendingResponse> pendingResult = await this.Nano.SendAsync <PendingResponse>(pendingRequest);
                        if (pendingResult.IsError())
                        {
                            errorCallback?.Invoke(pendingResult);
                        }

                        BlocksInfoRequest blocksInfoRequest = new BlocksInfoRequest();
                        blocksInfoRequest.Hashes = pendingResult.Response.Blocks;
                        NanoResult <BlocksInfoResponse> blocksInfoResult = await this.Nano.SendAsync <BlocksInfoResponse>(blocksInfoRequest);
                        if (blocksInfoResult.IsError())
                        {
                            errorCallback?.Invoke(blocksInfoResult);
                        }

                        if (blocksInfoResult.Response.Blocks != null)
                        {
                            foreach ((string key, BlockInfo block) in blocksInfoResult.Response.Blocks)
                            {
                                lock (this.knownHashes)
                                {
                                    if (this.knownHashes.Contains(key))
                                    {
                                        continue;
                                    }

                                    if (block.Confirmed == "true")
                                    {
                                        this.knownHashes.Add(key);
                                        transactionCallback?.Invoke(new NanoListenerTransaction(key, block));
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        // Do Nothing (For Now)
                    }
                }
            }));
        }
Ejemplo n.º 30
0
        public async Task AddPendingRequest(string id)
        {
            var model = new PendingRequest()
            {
                CustomerId = id,
                IssusOpend = true
            };

            this.AuroraLineDbContext.PendingRequests.Add(model);

            await this.AuroraLineDbContext.SaveChangesAsync();
        }
Ejemplo n.º 31
0
        public async Task <UserResponse> AcceptRequest(string username, string friendUsername)
        {
            var user = await context.RegisteredUsers
                       .Include(i => i.MyFriends)
                       .Include(i => i.MyPendingRequests)
                       .FirstOrDefaultAsync(i => i.Username.ToLower().Equals(username.ToLower()));

            if (user == null)
            {
                return(new UserResponse("User with username: "******" does not exist."));
            }
            var friend = await context.RegisteredUsers
                         .Include(i => i.MyFriends)
                         .FirstOrDefaultAsync(i => i.Username.ToLower().Equals(friendUsername.ToLower()));

            if (friend == null)
            {
                return(new UserResponse("User with username: "******" hasn't sent friend request."));
            }
            PendingRequest temp = null;

            foreach (var a in user.MyPendingRequests)
            {
                if (a.RequestSenderUsername.ToLower() == friendUsername.ToLower())
                {
                    var friend1 = new Friend();
                    var friend2 = new Friend();
                    friend1.FriendLastName = user.LastName;
                    friend1.FriendName     = user.Name;
                    friend1.FriendUsername = user.Username;

                    friend2.FriendUsername = friend.Username;
                    friend2.FriendName     = friend.Name;
                    friend2.FriendLastName = friend.LastName;

                    user.MyFriends.Add(friend2);
                    friend.MyFriends.Add(friend1);

                    temp = a;
                    break;
                }
            }

            if (temp != null)
            {
                user.MyPendingRequests.Remove(temp);
                return(new UserResponse(user));
            }
            else
            {
                return(new UserResponse("No friend request found."));
            }
        }
Ejemplo n.º 32
0
        public Task <bool> Update(PendingRequest pendingRequest)
        {
            var record = _pendingRequestLst.FirstOrDefault(p => p.Id == pendingRequest.Id);

            if (record == null)
            {
                return(Task.FromResult(false));
            }

            record.IsConfirmed = pendingRequest.IsConfirmed;
            return(Task.FromResult(true));
        }
Ejemplo n.º 33
0
        public ResponseMessage QueueAndWait(RequestMessage request)
        {
            var pending = new PendingRequest(request, log);

            lock (sync)
            {
                queue.Add(pending);
                inProgress.Add(request.Id, pending);
                hasItems.Set();
            }

            pending.WaitUntilComplete();

            lock (sync)
            {
                inProgress.Remove(request.Id);
            }

            return pending.Response;
        }
        public Task<MappedIdentity> MapAgent(string IrcNick)
        {
            MappedIdentity identity;
            lock (agentCacheLock)
            {
                if (AgentsByIrcNick.TryGetValue(IrcNick, out identity))
                {
                    return Task.FromResult(identity);
                }
            }

            string slName = IrcNick.Replace('.', ' ');
            PendingRequest request;
            lock (agentRequests)
            {
                request = new PendingRequest(slName);
                agentRequests.Add(request);
            }
            client.Avatars.RequestAvatarNameSearch(slName, UUID.Random());
            return request.TaskSource.Task;
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Creates a new pending request for the current session.
        /// </summary>
        /// <param name="landingUrl">The landing page of the SignResponse</param>
        /// <param name="language">The language of the e-contract.be pages, <c>null</c> for the default language</param>
        /// <param name="properties">Additional properties (location, role, visibility info, ...) for the signature request</param>
        /// <param name="authorization">The optional authorization that the signer must match too to be authorized</param>
        /// <returns>The base64 encoded PendingRequest, to be used as value for the "PendingRequest"-input</returns>
        public string GeneratePendingRequest(Uri landingUrl, string language, SignatureRequestProperties properties, Authorization authorization)
        {
            if (landingUrl == null) throw new ArgumentNullException("landingUrl");

            //Prepare browser post message (to return)
            var pendingRequest = new PendingRequest();
            pendingRequest.OptionalInputs = new OptionalInputs();
            pendingRequest.OptionalInputs.AdditionalProfile = "urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing";
            pendingRequest.OptionalInputs.ResponseID = this.ServerId;
            pendingRequest.OptionalInputs.MessageID = new AttributedURIType();
            pendingRequest.OptionalInputs.MessageID.Value = this.ClientId;
            pendingRequest.OptionalInputs.Timestamp = new TimestampType();
            pendingRequest.OptionalInputs.Timestamp.Created = new AttributedDateTime();
            pendingRequest.OptionalInputs.Timestamp.Created.Value = DateTime.UtcNow;
            pendingRequest.OptionalInputs.Timestamp.Expires = new AttributedDateTime();
            pendingRequest.OptionalInputs.Timestamp.Expires.Value = DateTime.UtcNow.AddMinutes(10);
            pendingRequest.OptionalInputs.ReplyTo = new EndpointReferenceType();
            pendingRequest.OptionalInputs.ReplyTo.Address = new AttributedURIType();
            pendingRequest.OptionalInputs.ReplyTo.Address.Value = landingUrl.AbsoluteUri;
            pendingRequest.OptionalInputs.ReturnSignerIdentity = new ReturnSignerIdentity();
            pendingRequest.OptionalInputs.Language = string.IsNullOrEmpty(language) ? null : language;

            if (properties != null && (!string.IsNullOrEmpty(properties.SignerRole)
                    || !string.IsNullOrEmpty(properties.SignatureProductionPlace)
                    || properties.VisibleSignature != null))
            {
                var items = new List<VisibleSignatureItemType>();
                PixelVisibleSignaturePositionType pixelVisibleSignaturePosition = null;

                if (!string.IsNullOrEmpty(properties.SignerRole))
                {
                    var stringItem = new ItemValueStringType();
                    stringItem.ItemValue = properties.SignerRole;

                    var item = new VisibleSignatureItemType();
                    item.ItemName = ItemNameEnum.SignatureReason;
                    item.ItemValue = stringItem;
                    items.Add(item);
                }
                if (!string.IsNullOrEmpty(properties.SignatureProductionPlace))
                {
                    var stringItem = new ItemValueStringType();
                    stringItem.ItemValue = properties.SignatureProductionPlace;

                    var item = new VisibleSignatureItemType();
                    item.ItemName = ItemNameEnum.SignatureProductionPlace;
                    item.ItemValue = stringItem;
                    items.Add(item);
                }
                if (properties.VisibleSignature != null)
                {
                    var photoProp = properties.VisibleSignature as ImageVisibleSignature;
                    if (photoProp != null)
                    {
                        var uriItem = new ItemValueURIType();
                        uriItem.ItemValue = photoProp.ValueUri;

                        var item = new VisibleSignatureItemType();
                        item.ItemName = ItemNameEnum.SignerImage;
                        item.ItemValue = uriItem;
                        items.Add(item);

                        var customText = photoProp.CustomText;
                        if (!string.IsNullOrEmpty(customText))
                        {
                            var customTextItem = new VisibleSignatureItemType();
                            customTextItem.ItemName = ItemNameEnum.CustomText;
                            var customTextItemValue = new ItemValueStringType();
                            customTextItemValue.ItemValue = customText;
                            customTextItem.ItemValue = customTextItemValue;
                            items.Add(customTextItem);
                        }
                    }
                    else
                    {
                        throw new ArgumentException("The type of VisibleSignatureProperties (field of SignatureRequestProperties) is unsupported", "properties");
                    }

                    pixelVisibleSignaturePosition = new PixelVisibleSignaturePositionType();
                    pixelVisibleSignaturePosition.PageNumber = properties.VisibleSignature.Page;
                    pixelVisibleSignaturePosition.x = properties.VisibleSignature.X;
                    pixelVisibleSignaturePosition.y = properties.VisibleSignature.Y;
                }

                pendingRequest.OptionalInputs.VisibleSignatureConfiguration = new VisibleSignatureConfigurationType();
                pendingRequest.OptionalInputs.VisibleSignatureConfiguration.VisibleSignaturePolicy = VisibleSignaturePolicyType.DocumentSubmissionPolicy;
                pendingRequest.OptionalInputs.VisibleSignatureConfiguration.VisibleSignatureItemsConfiguration = new VisibleSignatureItemsConfigurationType();
                pendingRequest.OptionalInputs.VisibleSignatureConfiguration.VisibleSignatureItemsConfiguration.VisibleSignatureItem = items.ToArray<VisibleSignatureItemType>();
                pendingRequest.OptionalInputs.VisibleSignatureConfiguration.VisibleSignaturePosition = pixelVisibleSignaturePosition;
            }

            if (authorization != null)
            {
                pendingRequest.OptionalInputs.Policy = authorization.getPolicy();
            }

            //Prepare Sign
            var pendingRequestXml = new XmlDocument();
            pendingRequestXml.PreserveWhitespace = true;
            if (null == requestSerializer)
            {
                requestSerializer = new XmlSerializer(typeof(PendingRequest), "urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:1.0");
            }
            using (var pendingRequestWriter = pendingRequestXml.CreateNavigator().AppendChild())
            {
                requestSerializer.Serialize(pendingRequestWriter, pendingRequest);
            }

            var signedXml = new SignedXml(pendingRequestXml);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigHMACSHA1Url;
            var docRef = new Reference("");
            docRef.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
            docRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            docRef.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(docRef);

            //Add Key Info
            var keyRefXml = new XmlDocument();
            keyRefXml.PreserveWhitespace = true;
            if (null == tRefSerializer)
            {
                tRefSerializer = new XmlSerializer(typeof(SecurityTokenReferenceType), null, new Type[0], new XmlRootAttribute("SecurityTokenReference"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            }
            using (var keyRefXmlWriter = keyRefXml.CreateNavigator().AppendChild())
            {
                tRefSerializer.Serialize(keyRefXmlWriter, this.KeyReference);
            }
            signedXml.KeyInfo = new KeyInfo();
            signedXml.KeyInfo.AddClause(new KeyInfoNode(keyRefXml.DocumentElement));

            //Compute signature
            signedXml.ComputeSignature(new HMACSHA1(this.KeyValue));

            //Append signature to document
            var nsmgr = new XmlNamespaceManager(pendingRequestXml.NameTable);
            nsmgr.AddNamespace("async", "urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:1.0");
            nsmgr.AddNamespace("dss", "urn:oasis:names:tc:dss:1.0:core:schema");
            pendingRequestXml.SelectSingleNode("/async:PendingRequest/dss:OptionalInputs", nsmgr).AppendChild(signedXml.GetXml());

            //Serialize and encode
            var stream = new MemoryStream();
            pendingRequestXml.Save(stream);
            return Convert.ToBase64String(stream.ToArray());
        }
Ejemplo n.º 36
0
    public async Task<Response> CommitRequest(FlatBufferBuilder fbb,
                                              RequestData requestDataType,
                                              int requestDataOffset) {
      PendingRequest request = new PendingRequest();
      request.requestId = nextRequestId++;
      request.responseTask = new TaskCompletionSource<Response>();
      pendingRequests.TryAdd(request.requestId, request);

      int requestOffset =
          Request.CreateRequest(fbb, request.requestId,
                                requestDataType, requestDataOffset);
      fbb.Finish(requestOffset);

      // Update the placeholder size.
      int bufferOffset = fbb.DataBuffer.Position;
      int bufferLength = fbb.DataBuffer.Length - fbb.DataBuffer.Position;
      fbb.DataBuffer.PutInt(bufferOffset - 4, bufferLength);

      // Send request.
      await socket.SendTaskAsync(fbb.DataBuffer.Data, bufferOffset - 4,
                                 bufferLength + 4, SocketFlags.None);

      // Await response.
      var response = await request.responseTask.Task;

      return response;
    }
Ejemplo n.º 37
0
 private void HandleAnswer(PendingRequest rq)
 {
     byte[] ln = m_connection.ReadLine();
     if (ln == null)
     {
         SetState(State.Terminated, "server closed connection");
         return;
     }
     else if (Protocol.IsCommand("OK", ln))
     {
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Result, id = rq.id, number = rq.number, obj = null });
     }
     else if (Protocol.IsCommand("ERR", ln))
     {
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Failure, id = rq.id, number = rq.number, obj = Protocol.CommandArg("ERR", ln) });
     }
     else if (Protocol.IsCommand("BAD", ln))
     {
         SetState(State.Terminated, "protocol error");
         m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "protocol error" });
         return;
     }
     else if (Protocol.IsCommand("ANSWER", ln))
     {
         byte[] msg = m_connection.ReadContent();
         if (msg == null)
         {
             SetState(State.Terminated, "server closed connection");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "server closed connection" });
             return;
         }
         ln = m_connection.ReadLine();
         if (msg == null)
         {
             SetState(State.Terminated, "server closed connection");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "server closed connection" });
             return;
         }
         else if (Protocol.IsCommand("OK", ln))
         {
             object answerobj = m_serializer.getResult(msg, rq.answertype);
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Result, id = rq.id, number = rq.number, obj = answerobj });
         }
         else if (Protocol.IsCommand("ERR", ln))
         {
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Failure, id = rq.id, number = rq.number, obj = Protocol.CommandArg("ERR", ln) });
         }
         else if (Protocol.IsCommand("BAD", ln))
         {
             SetState(State.Terminated, "protocol error");
             m_answerCallback(new Answer { msgtype = Answer.MsgType.Error, id = rq.id, number = rq.number, obj = "protocol error" });
             return;
         }
     }
 }
Ejemplo n.º 38
0
        private static void ProcessTransfer(PendingRequest pendingRequest)
        {
            if (pendingRequest == null || pendingRequest.Uri == null)
            {
                return;
            }

            try
            {
                if (pendingRequest.Uri.IsAbsoluteUri)
                {
                    _iso.GetItem(pendingRequest.Uri, (img, exc, stat) =>
                        {
                            if (stat == IsoStoreCache.ItemCacheStatus.Hit)
                            {
                                var ms = new MemoryStream(img);
                                var pc = new PendingCompletion(pendingRequest.Image, pendingRequest.Uri, ms);
                                PriorityQueue.AddUiWorkItem(() =>
                                {
                                    HandleCompletion(pc);
                                });
                            }
                            else
                            {
                                // Download from network
                                var webRequest = HttpWebRequest.CreateHttp(pendingRequest.Uri);
                                webRequest.AllowReadStreamBuffering = true; // Don't want to block this thread or the UI thread on network access
                                webRequest.BeginGetResponse(HandleGetResponseResult, new ResponseState(webRequest, pendingRequest.Image, pendingRequest.Uri));
                            }
                        });
                }
                else
                {
                    // Load from application (must have "Build Action"="Content")
                    var originalUriString = pendingRequest.Uri.OriginalString;
                    // Trim leading '/' to avoid problems
                    var resourceStreamUri = originalUriString.StartsWith("/", StringComparison.Ordinal) ? new Uri(originalUriString.TrimStart('/'), UriKind.Relative) : pendingRequest.Uri;
                    // Enqueue resource stream for completion
                    var streamResourceInfo = Application.GetResourceStream(resourceStreamUri);
                    if (null != streamResourceInfo)
                    {
                        var pc = new PendingCompletion(pendingRequest.Image, pendingRequest.Uri, streamResourceInfo.Stream);
                        PriorityQueue.AddUiWorkItem(() =>
                            {
                                HandleCompletion(pc);
                            });
                    }
                }
            }
            catch (NullReferenceException)
            {
                // Trying to address user-found bugs here.
            }
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Close the socket after all pending requests are completed.
 /// </summary>
 public void EnqueueClose()
 {
     PendingRequest req = new PendingRequest(null, null, null, 0, 0, null);
     lock (m_queue)
     {
         m_queue.AddLast(req);
         Monitor.Pulse(m_queue);
     }
 }
Ejemplo n.º 40
0
 private void Done()
 {
     m_state = ParseState.START;
     m_current = null;
     Debug.WriteLine("HTTP Socket " + m_name + " done");
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Execute an HTTP request.
        /// </summary>
        /// <param name="method">The HTTP method verb.  E.g. "GET", "POST", etc.</param>
        /// <param name="URL">The URL to request.  MUST be for the same host as the first request.</param>
        /// <param name="body">Any data to post with the request</param>
        /// <param name="offset">The offset into body from which to start</param>
        /// <param name="len">The number of bytes to read from body, starting at offset</param>
        /// <param name="contentType">The MIME type of the supplied body</param>
        public void Execute(string method, Uri URL, byte[] body, int offset, int len, string contentType)
        {
            Debug.Assert(!this.IsPending);

            PendingRequest req = new PendingRequest(method, URL, body, offset, len, contentType);
            if (m_host == null)
                m_host = req.URI.Host;
            else if (m_host != req.URI.Host)
                throw new InvalidOperationException("All requests must got to same host: " + m_host);

            // connect if not yet connected
            if (req.Method != null)
            {
                lock (m_lock)
                {
                    if (!Connected)
                    {
                        Connect(req.URI);

                        Monitor.Wait(m_lock, (int)(m_connectRetrySec * 1000));
                        if (!m_keepRunning)
                            return;

                        Debug.Assert(Connected);
                        Debug.Assert(!IsPending);
                    }
                }
            }
            Send(req);
        }
        /// <summary>
        /// Resolve a whole bunch of IDs.
        /// </summary>
        /// <param name="AgentIds"></param>
        /// <returns></returns>
        public async Task<IEnumerable<MappedIdentity>> MapAgents(IEnumerable<UUID> AgentIds)
        {
            var newRequests = new List<Task<MappedIdentity>>();
            lock (agentCacheLock)
            {
                foreach (var i in AgentIds)
                {
                    MappedIdentity found;
                    if (AgentsByUuid.TryGetValue(i, out found))
                    {
                        newRequests.Add(Task.FromResult(found));
                    }
                    else
                    {
                        var req = new PendingRequest(i);
                        agentRequests.Add(req);
                        newRequests.Add(req.TaskSource.Task);
                    }
                }
            }
            client.Avatars.RequestAvatarNames(AgentIds.ToList());

            return await Task.WhenAll(newRequests);
        }
Ejemplo n.º 43
0
        void ISocketEventListener.OnConnect(BaseSocket sock)
        {
            m_errorCount = 0;

            m_listener.OnConnect(null);
            lock (m_queue)
            {
                // push back.
                if (m_current != null)
                {
                    m_queue.AddFirst(m_current);
                    m_current = null;
                }
                Monitor.Pulse(m_queue);
            }
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Submits a request on the channel
 /// </summary>
 /// <param name="request">
 /// The request message to submit
 /// </param>
 /// <param name="timeout">
 /// The timeout for the submit operation
 /// </param>
 /// <param name="callback">
 /// Asynchronous completion delegate
 /// </param>
 /// <param name="state">
 /// Asynchronous completion delegate parameter
 /// </param>
 /// <returns>
 /// The asynchronous completion token
 /// </returns>
 public override IAsyncResult BeginRequest(
     Message request,
     TimeSpan timeout,
     AsyncCallback callback,
     Object state)
 {
     Boolean isOneWay = (request.Headers.ReplyTo == null);
      // prepare the request message for submission
      this.RemoteAddress.ApplyTo(request);
      if (request.Headers.MessageId == null)
     request.Headers.MessageId = new System.Xml.UniqueId();
      // abort any pending timed-out requests
      FlushTimeouts();
      // register the two-way request in the pending request map
      AsyncResult async = null;
      if (!isOneWay)
      {
     DateTime now = DateTime.UtcNow;
     PendingRequest context = new PendingRequest()
     {
        Result = async = new AsyncResult(callback, state, timeout),
        Expiration = (timeout < DateTime.MaxValue - now) ?
           DateTime.UtcNow + timeout :
           DateTime.MaxValue
     };
     lock (base.ThisLock)
        this.requestMap.Add(request.Headers.MessageId, context);
      }
      // submit the request start an async receive
      try
      {
     try
     {
        // send the request message on the socket
        using (ManagedBuffer requestBuffer = this.Codec.Encode(request))
           this.socket.Send(requestBuffer);
        // start a receiver if none is running
        if (!isOneWay)
           if (Interlocked.Increment(ref this.pending) == 1)
              BeginReceive();
        // if no response is expected, complete the request sync
        return (isOneWay) ? new SyncResult(callback, state) : (IAsyncResult)async;
     }
     catch (ObjectDisposedException)
     {
        // if the socket was disposed, then the other side of the
        // channel closed, so close this side
        // we must throw here to force the WCF dispatcher to shut down
        // the channel; otherwise, it will continue to call us
        if (base.State == CommunicationState.Opened)
           base.Close();
        throw new CommunicationObjectFaultedException();
     }
      }
      catch
      {
     // if an error occurred, remove the pending request context
     if (!isOneWay)
        lock (base.ThisLock)
           this.requestMap.Remove(request.Headers.MessageId);
     throw;
      }
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Execute an HTTP request.
 /// </summary>
 /// <param name="method">The HTTP method verb.  E.g. "GET", "POST", etc.</param>
 /// <param name="URL">The URL to request.  MUST be for the same host as the first request.</param>
 /// <param name="body">Any data to post with the request</param>
 /// <param name="offset">The offset into body from which to start</param>
 /// <param name="len">The number of bytes to read from body, starting at offset</param>
 /// <param name="contentType">The MIME type of the supplied body</param>
 public void Execute(string method, Uri URL, byte[] body, int offset, int len, string contentType)
 {
     lock (m_queue)
     {
         PendingRequest req = new PendingRequest(method, URL, body, offset, len, contentType);
         if (m_host == null)
             m_host = req.URI.Host;
         else if (m_host != req.URI.Host)
             throw new InvalidOperationException("All requests must got to same host: " + m_host);
         m_queue.AddLast(req);
         Monitor.Pulse(m_queue);
     }
 }
        public Task<MappedIdentity> MapAgent(UUID AgentId, string SlName = null)
        {
            MappedIdentity identity;
            lock (agentCacheLock)
            {
                if (AgentsByUuid.TryGetValue(AgentId, out identity))
                {
                    return Task.FromResult(identity);
                }
            }

            if(SlName != null)
            {
                return Task.FromResult(MakeAgentIdentity(AgentId, SlName));
            }

            PendingRequest request;
            lock(agentRequests)
            {
                request = new PendingRequest(AgentId);
                agentRequests.Add(request);
            }
            client.Avatars.RequestAvatarName(AgentId);
            return request.TaskSource.Task;
        }
Ejemplo n.º 47
0
        private void Send(PendingRequest req)
        {
            m_current = req;

            // Try to get it big enough that we don't have to allocate, without going overboard.
            MemoryStream ms = new MemoryStream(req.Length + 256);
            WriteString(ms, req.Method);
            WriteString(ms, " ");
            if (m_proxyURI == null)
                WriteString(ms, req.URI.PathAndQuery);
            else
                WriteString(ms, req.URI.ToString());
            ms.Write(SP_HTTP11_CRLF, 0, SP_HTTP11_CRLF.Length);

            WebHeaderCollection coll = new WebHeaderCollection {{HttpRequestHeader.Host, req.URI.Host}};
            if (req.ContentType != null)
                coll.Add(HttpRequestHeader.ContentType, req.ContentType);
            if (m_proxyCredentials != null)
            {
                byte[] creds = Encoding.ASCII.GetBytes(m_proxyCredentials.UserName + ":" + m_proxyCredentials.Password);
                coll.Add("Proxy-Authorization", "Basic " + Convert.ToBase64String(creds));
            }
            coll.Add("X-JN-Name", m_name);
            coll.Add(HttpRequestHeader.Date, string.Format("{0:r}", DateTime.Now));
            coll.Add(HttpRequestHeader.ContentLength, req.Length.ToString());

            byte[] headers = coll.ToByteArray();
            ms.Write(headers, 0, headers.Length);

            ms.Write(req.Body, req.Offset, req.Length);

            byte[] buf = ms.ToArray();

            m_sock.Write(buf);
            m_sock.RequestRead();
        }
Ejemplo n.º 48
0
        bool ISocketEventListener.OnRead(BaseSocket sock, byte[] buf, int offset, int length)
        {
            Debug.WriteLine("IN HTTP: " + ENC.GetString(buf, offset, length));
            int i = offset;
            string header = null;
            int last = offset + length;

            while (i < last)
            {
                // HTTP/1.1 200 OK
                // Header: value
                // Header: value
                //
                // Content
                switch (m_state)
                {
                    case ParseState.START:
                        if (!ParseAt(buf, ref i, last, HTTP11_SP, 0))
                            goto ERROR;
                        m_state = ParseState.RESPONSE;
                        break;
                    case ParseState.RESPONSE:
                        string code = ParseTo(buf, ref i, last, SPACE);
                        if (code == null)
                            goto ERROR;

                        if (code != "200")
                        {
                            Debug.WriteLine("Non-OK response from server (" + code + ").  STOP!");
                            goto ERROR;
                        }

                        try
                        {
                            // I know this can never fail.  it's here for when we
                            // implement redirects and the like.
                            m_current.Code = int.Parse(code);
                        }
                        catch (Exception)
                        {
                            Debug.WriteLine("invalid response code");
                            goto ERROR;
                        }

                        m_state = ParseState.RESPONSE_TEXT;
                        break;
                    case ParseState.RESPONSE_TEXT:
                        m_current.ResponseText = ParseTo(buf, ref i, last, CRLF);
                        if (m_current.ResponseText == null)
                            goto ERROR;
                        m_state = ParseState.HEADER_NAME;
                        break;
                    case ParseState.HEADER_NAME:
                        if (ParseAt(buf, ref i, last, CRLF, 0))
                        {
                            m_state = ParseState.BODY_START;
                            break;
                        }
                        header = ParseTo(buf, ref i, last, COL_SP);
                        if (header == null)
                            goto ERROR;
                        m_state = ParseState.HEADER_VALUE;
                        break;
                    case ParseState.HEADER_VALUE:
                        string val = ParseTo(buf, ref i, last, CRLF);
                        if (val == null)
                            goto ERROR;
                        m_current.Headers.Add(header, val);
                        m_state = ParseState.HEADER_NAME;
                        break;
                    case ParseState.BODY_START:
                        // if we have the whole response, which is typical in XEP-124, then return it all at
                        // once, without creating a MemoryStream.
                        int len = m_current.ContentLength;
                        if (len == -1)
                            goto ERROR;
                        if (i + len <= last)
                        {
                            m_current = null;
                            m_state = ParseState.START;
                            if (!m_listener.OnRead(null, buf, i, len))
                            {
                                Close();
                                return false;
                            }
                            lock (m_queue)
                            {
                                Monitor.Pulse(m_queue);
                            }
                            return false;
                        }

                        // We got a partial response.  We're going to have to wait until OnRead is called
                        // again before we can pass a full response upstream.  Hold on to the pieces in a
                        // MemoryStream.
                        m_current.Response = new MemoryStream(len);
                        m_current.Response.Write(buf, i, last - i);
                        m_state = ParseState.BODY_CONTINUE;
                        return true;
                    case ParseState.BODY_CONTINUE:
                        m_current.Response.Write(buf, i, last - i);
                        if (m_current.Response.Length == m_current.Response.Capacity)
                        {
                            PendingRequest req = m_current;
                            m_current = null;
                            m_state = ParseState.START;

                            byte[] resp = req.Response.ToArray();
                            if (!m_listener.OnRead(null, resp, 0, resp.Length))
                            {
                                Close();
                                return false;
                            }

                            lock (m_queue)
                            {
                                Monitor.Pulse(m_queue);
                            }
                            return false;
                        }
                        return true;
                    default:
                        break;
                }
            }
            return true;

            ERROR:
            m_listener.OnError(null, new ProtocolViolationException("Error parsing HTTP response"));
            Close();
            return false;
        }
Ejemplo n.º 49
0
 void ISocketEventListener.OnClose(BaseSocket sock)
 {
     m_sock = null;
     m_current = null;
     lock (m_lock)
     {
         Monitor.Pulse(m_lock);
     }
 }