Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / PithosAccount.cs @ 255f5f86

History | View | Annotate | Download (10.3 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PithosAccount.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42

    
43
// </copyright>
44
// -----------------------------------------------------------------------
45

    
46
using System.IO;
47
using Pithos.Network;
48
using log4net;
49

    
50
namespace Pithos.Client.WPF
51
{
52
    using System;
53
    using System.Collections.Generic;
54
    using System.Linq;
55
    using System.Text;
56
    using System.Net;
57
    using System.Threading.Tasks;
58
    using System.Diagnostics.Contracts;
59
    using System.Diagnostics;
60
    using System.Net.Sockets;
61

    
62
    /// <summary>
63
    /// TODO: Update summary.
64
    /// </summary>
65
    /// <summary>
66
    /// Retrieves an account name and token from PITHOS
67
    /// </summary>
68
    public static class PithosAccount
69
    {
70
        private static readonly ILog Log = LogManager.GetLogger(typeof(PithosAccount));
71

    
72
        /// <summary>
73
        /// Asynchronously retrieves PITHOS credentials
74
        /// </summary>
75
        /// <param name="loginUrl">URL to retrieve the account info from PITHOS. Must end with =</param>
76
        /// <returns>The credentials wrapped in a Task</returns>
77
        public static Task<NetworkCredential> RetrieveCredentials(string loginUrl)
78
        {
79
            Contract.Requires(Uri.IsWellFormedUriString(loginUrl, UriKind.Absolute));
80

    
81
            if (!Uri.IsWellFormedUriString(loginUrl, UriKind.Absolute))
82
                throw new ArgumentException("The pithosSite parameter must be a valid absolute URL", "loginUrl");
83
            
84
            int port = GetFreePort();
85
            
86
            //TODO:Force logout here to take care of existing cookies
87

    
88

    
89
            var listenerUrl = String.Format("http://127.0.0.1:{0}/", port);
90

    
91
            
92

    
93
            var receiveCredentials = ListenForRedirectAsync(port);
94

    
95
            var uriBuilder=new UriBuilder(loginUrl);                       
96
            uriBuilder.Query="next=" + listenerUrl;
97

    
98
            var retrieveUri = uriBuilder.Uri;
99
            Log.InfoFormat("[RETRIEVE] Open Browser at {0}", retrieveUri);
100
            Process.Start(retrieveUri.ToString());
101

    
102
            return receiveCredentials;
103
        }
104

    
105
/*
106
        private static async Task<NetworkCredential> ListenHttpForRedirectAsync(string listenerUrl)
107
        {
108
            using (var listener = new HttpListener())
109
            {
110
                listener.Prefixes.Add(listenerUrl);
111

    
112
                Log.InfoFormat("[RETRIEVE] Listening at {0}", listenerUrl);
113

    
114

    
115
                try
116
                {
117
                    listener.Start();
118

    
119
                    var context = await listener.GetContextAsync()
120
                                            .WithTimeout(TimeSpan.FromMinutes(5));
121

    
122
                    var request = context.Request;
123
                    Log.InfoFormat("[RETRIEVE] Got Connection {0}", request.RawUrl);
124

    
125
                    var query = request.QueryString;
126
                    var userName = query["user"];
127
                    var token = query["token"];
128
                    if (String.IsNullOrWhiteSpace(userName) ||
129
                        String.IsNullOrWhiteSpace(token))
130
                    {
131
                        Respond(context, "Failure", "The server did not return a username or token");
132
                        Log.ErrorFormat("[RETRIEVE] No credentials returned by server");
133
                        throw new Exception("The server did not return a username or token");
134
                    }
135
                    else
136
                    {
137
                        Log.InfoFormat("[RETRIEVE] Credentials retrieved user:{0} token:{1}", userName, token);
138
                        Respond(context, "Authenticated", "Got It");
139

    
140
                        return new NetworkCredential(userName, token);
141
                    }
142
                }
143
                catch (Exception exc)
144
                {
145
                    Log.Error("[RETRIEVE][ERROR] Receive connection {0}", exc);
146
                    throw;
147
                }
148
            }
149
        }
150
*/
151

    
152
        private static async Task<NetworkCredential> ListenForRedirectAsync(int port)
153
        {
154
            var listener = new TcpListener(IPAddress.Any, port);            
155
            Log.InfoFormat("[RETRIEVE] Listening at {0}", port);
156

    
157
            try
158
            {
159
                listener.Start();
160

    
161
                using (var client = await listener.AcceptTcpClientAsync()
162
                                        .WithTimeout(TimeSpan.FromMinutes(5)))
163
                {
164
                    using (var stream = client.GetStream())
165
                    using (var reader=new StreamReader(stream))
166
                    {
167
                        var request = await reader.ReadLineAsync();
168
                        //BUG
169
                        //TODO: Add proper warnings here if the content is empty, don't just throw an exception
170
                        //This may be a common occurence 
171

    
172
                        if (String.IsNullOrWhiteSpace(request))
173
                            throw new PithosException("The server did send any information");
174
                        Log.InfoFormat("[RETRIEVE] Got Connection {0}", request);
175

    
176

    
177
                        var items = ParseResponse(request);
178

    
179
                        var userName = items["user"];
180
                        var token = items["token"];
181
                        if (String.IsNullOrWhiteSpace(userName) ||
182
                            String.IsNullOrWhiteSpace(token))
183
                        {
184
                            Respond(stream, "Failure", "The server did not return a username or token");
185
                            Log.ErrorFormat("[RETRIEVE] No credentials returned by server");
186
                            throw new PithosException("The server did not return a username or token");
187
                        }
188
                        else
189
                        {
190
                            Log.InfoFormat("[RETRIEVE] Credentials retrieved user:{0} token:{1}", userName, token);
191
                            Respond(stream, "Authenticated", "Got It");                            
192
                        }
193
                        return new NetworkCredential(userName, token);
194
                    }
195
                }
196
            }
197
            catch (Exception exc)
198
            {
199
                Log.Error("[RETRIEVE][ERROR] Receive connection {0}", exc);
200
                throw new PithosException("An error occured while retrieving credentials",exc);
201
            }
202
        }
203

    
204
        private static Dictionary<string, string> ParseResponse(string request)
205
        {
206
            var parts = request.Split(' ');
207
            var query = parts[1].TrimStart('/', '?');
208

    
209
            var items = query.Split('&')
210
                .Select(pair => pair.Split('='))
211
                .ToDictionary(arr => arr[0].ToLower(), arr => Uri.UnescapeDataString(arr[1]));
212
            return items;
213
        }
214

    
215

    
216
        private static void Respond(HttpListenerContext context,string title,string message)
217
        {
218
            var response = context.Response;
219
            var html = String.Format("<html><head><title>{0}</title></head><body><h1>{1}</h1></body></html>", title, message);
220
            var outBuffer = Encoding.UTF8.GetBytes(html);
221
            response.ContentLength64 = outBuffer.Length;
222
            using (var stream = response.OutputStream)
223
            {
224
                stream.Write(outBuffer, 0, outBuffer.Length);
225
            }
226

    
227
            Log.InfoFormat("[RETRIEVE] Responded");
228
        }
229

    
230
        private static void Respond(Stream stream,string title,string message)
231
        {
232
            
233
            var html = String.Format("<html><head><title>{0}</title></head><body><h1>{1}</h1></body></html>", title, message);
234
            
235
            var response = new StringBuilder();
236
            response.AppendLine("HTTP/1.1 200 OK");
237
            response.AppendFormat("Content-Length: {0}\n", html.Length);
238
            response.AppendLine("Server: Microsoft-HTTPAPI/2.0");
239
            response.AppendFormat("Date: {0}\n\n", DateTime.UtcNow);
240
            response.AppendLine(html);
241

    
242
            var outBuffer=Encoding.UTF8.GetBytes(response.ToString());
243
            
244
            stream.Write(outBuffer, 0, outBuffer.Length);
245

    
246
            Log.InfoFormat("[RETRIEVE] Responded");
247
        }
248

    
249
       
250
        /// <summary>
251
        /// Locates a free local port 
252
        /// </summary>
253
        /// <returns>A free port</returns>
254
        /// <remarks>The method starts and stops a TcpListener on port 0 to locate a free port.</remarks>
255
        public static int GetFreePort()
256
        {
257
            //The TcpListener will locate a free port             
258
            var listener = new TcpListener(IPAddress.Any, 0);
259
            listener.Start();
260
            var port = ((IPEndPoint)listener.LocalEndpoint).Port;
261
            listener.Stop();
262
            return port;
263
        }
264
    }
265
}