source: trunk/CrypP2P/Internal/P2PBase.cs @ 2446

Last change on this file since 2446 was 2446, checked in by Sven Rech, 11 years ago

calling dispose on dht when SystemLeft event occurs

File size: 22.8 KB
Line 
1/*
2   Copyright 2010 Paul Lelgemann and Christian Arnold,
3                  University of Duisburg-Essen
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9       http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16*/
17
18using System;
19using System.Linq;
20using System.Text;
21using System.Threading;
22using Cryptool.PluginBase;
23using Cryptool.Plugins.PeerToPeer.Internal;
24using Gears4Net;
25using PeersAtPlay;
26using PeersAtPlay.Monitoring;
27using PeersAtPlay.P2PLink;
28using PeersAtPlay.P2PLink.SnalNG;
29using PeersAtPlay.P2POverlay;
30using PeersAtPlay.P2POverlay.Bootstrapper;
31using PeersAtPlay.P2POverlay.Bootstrapper.DnsBootstrapper;
32using PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2;
33using PeersAtPlay.P2POverlay.Bootstrapper.LocalMachineBootstrapper;
34using PeersAtPlay.P2POverlay.FullMeshOverlay;
35using PeersAtPlay.P2PStorage.DHT;
36using PeersAtPlay.P2PStorage.FullMeshDHT;
37using PeersAtPlay.PapsClient;
38using PeersAtPlay.Util.Logging;
39using PeersAtPlay.P2POverlay.Chord;
40using PeersAtPlay.P2PStorage.WebDHT;
41using System.Security.Cryptography;
42
43/* TODO:
44 * - Delete UseNatTraversal-Flag and insert CertificateCheck and CertificateSetup
45 * - Testing asynchronous methods incl. EventHandlers
46 */
47
48namespace Cryptool.P2P.Internal
49{
50    /// <summary>
51    ///   Wrapper class to integrate peer@play environment into CrypTool.
52    ///   This class synchronizes asynchronous methods for easier usage in CT2.
53    /// </summary>
54    public class P2PBase
55    {
56        #region Variables
57
58        private AutoResetEvent systemJoined;
59        private readonly AutoResetEvent systemLeft;
60        private IBootstrapper bootstrapper;
61        private IP2PLinkManager linkmanager;
62        private P2POverlay overlay;
63        internal IDHT Dht;
64        internal IVersionedDHT VersionedDht;
65
66        /// <summary>
67        ///   True if system was successfully joined, false if system is COMPLETELY left
68        /// </summary>
69        public bool IsConnected { get; private set; }
70
71        /// <summary>
72        ///   True if the underlying peer to peer system has been fully initialized
73        /// </summary>
74        public bool IsInitialized { get; private set; }
75
76        #endregion
77
78        #region Delegates
79
80        public event P2PMessageReceived OnP2PMessageReceived;
81        public delegate void P2PMessageReceived(PeerId sourceAddr, byte[] data);
82
83        public event SystemJoined OnSystemJoined;
84        public delegate void SystemJoined();
85
86        public event SystemLeft OnSystemLeft;
87        public delegate void SystemLeft();
88
89        #endregion
90
91        public P2PBase()
92        {
93            IsConnected = false;
94            IsInitialized = false;
95
96            systemJoined = new AutoResetEvent(false);
97            systemLeft = new AutoResetEvent(false);
98        }
99
100        #region Basic P2P Methods (Init, Start, Stop)
101
102        /// <summary>
103        ///   Initializes the underlying peer-to-peer system with settings configured in P2PSettings. This step is required in order to be able to establish a connection.
104        /// </summary>
105        public void Initialize()
106        {
107            Scheduler scheduler = new STAScheduler("pap_snal");
108            Scheduler scheduler_2 = new STAScheduler("pap_mysql");
109
110            switch (P2PSettings.Default.LinkManager)
111            {
112                case P2PLinkManagerType.Snal:
113                    LogToMonitor("Init LinkMgr: Using NAT Traversal stuff");
114
115                    // NAT-Traversal stuff needs a different Snal-Version
116                    linkmanager = new Snal(scheduler);
117
118                    var settings = new PeersAtPlay.P2PLink.SnalNG.Settings();
119                    settings.LoadDefaults();
120                    settings.ConnectInternal = true;
121                    settings.LocalReceivingPort = P2PSettings.Default.LocalReceivingPort;
122                    settings.UseLocalAddressDetection = P2PSettings.Default.UseLocalAddressDetection;
123                    settings.NoDelay = false;
124                    settings.ReuseAddress = false;
125                    settings.UseNetworkMonitorServer = true;
126                    settings.CloseConnectionAfterPingTimeout = true;
127
128                    settings.FragmentMessages = true;
129                    settings.FragmentMessageSize = 10*1024;
130
131                    linkmanager.Settings = settings;
132                    linkmanager.ApplicationType = ApplicationType.CrypTool;
133
134                    break;
135                default:
136                    throw new NotImplementedException();
137            }
138
139            switch (P2PSettings.Default.Bootstrapper)
140            {
141                case P2PBootstrapperType.LocalMachineBootstrapper:
142                    // LocalMachineBootstrapper = only local connection (runs only on one machine)
143                    bootstrapper = new LocalMachineBootstrapper();
144                    break;
145                case P2PBootstrapperType.IrcBootstrapper:
146                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.DelaySymmetricResponse = true;
147                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.IncludeSymmetricResponse = false;
148                    PeersAtPlay.P2POverlay.Bootstrapper.IrcBootstrapperV2.Settings.UsePeerCache = false;
149
150                    bootstrapper = new IrcBootstrapper(scheduler);
151                    break;
152                case P2PBootstrapperType.DnsBootstrapper:
153                    bootstrapper = new DnsBootstrapper();
154                    break;
155                default:
156                    throw new NotImplementedException();
157            }
158
159            try
160            {
161                switch (P2PSettings.Default.Architecture)
162                {
163                    case P2PArchitecture.FullMesh:
164                        overlay = new FullMeshOverlay(scheduler);
165                        Dht = new FullMeshDHT(scheduler);
166                        break;
167                    case P2PArchitecture.Chord:
168                        overlay = new ChordNGCore(scheduler);
169                        Dht = (IDHT) overlay;
170                        break;
171                    case P2PArchitecture.Server:
172                        PeersAtPlay.PapsClient.Properties.Settings.Default.ServerHost = P2PSettings.Default.ServerHost;
173                        PeersAtPlay.PapsClient.Properties.Settings.Default.ServerPort = P2PSettings.Default.ServerPort;
174                        bootstrapper = new LocalMachineBootstrapper();
175                        overlay = new PapsClientOverlay();
176                        Dht = new PapsClientDht(scheduler_2);
177                        break;
178                    case P2PArchitecture.WebDHT:
179                        Dht = new WebDHT(scheduler_2);
180                        break;
181                    default:
182                        throw new NotImplementedException();
183                }
184            }
185            catch(Exception e)
186            {
187                P2PManager.GuiLogMessage("Error initializing P2P network: " + e.Message, NotificationLevel.Error);
188                return;
189            }
190
191            if (overlay != null)
192            {
193                overlay.MessageReceived += OverlayMessageReceived;
194            }
195            Dht.SystemJoined += OnDhtSystemJoined;
196            Dht.SystemLeft += OnDhtSystemLeft;
197
198            VersionedDht = (IVersionedDHT) Dht;
199
200            P2PManager.GuiLogMessage("Initializing DHT with world name " + P2PSettings.Default.WorldName,
201                                        NotificationLevel.Info);
202            IsInitialized = true;
203            Dht.Initialize(P2PSettings.Default.PeerName, DecryptString(P2PSettings.Default.Password), P2PSettings.Default.WorldName, overlay,
204                           bootstrapper, linkmanager, null);
205        }
206
207        /// <summary>
208        ///   Starts the P2P System. When the given P2P world doesn't exist yet,
209        ///   inclusive creating the and bootstrapping to the P2P network.
210        ///   In either case joining the P2P world.
211        ///   This synchronized method returns true not before the peer has
212        ///   successfully joined the network (this may take one or two minutes).
213        /// </summary>
214        /// <exception cref = "InvalidOperationException">When the peer-to-peer system has not been initialized.
215        /// After validating the settings, this can be done by calling Initialize().</exception>
216        /// <returns>True, if the peer has completely joined the p2p network</returns>
217        public bool SynchStart()
218        {
219            if (!IsInitialized)
220            {
221                throw new InvalidOperationException("Peer-to-peer is not initialized.");
222            }
223
224            if (IsConnected)
225            {
226                return true;
227            }
228
229            try
230            {
231                Dht.BeginStart(BeginStartEventHandler);
232
233                // Wait for event SystemJoined. When it's invoked, the peer completely joined the P2P system
234                systemJoined.WaitOne();
235                P2PManager.GuiLogMessage("System join process ended.", NotificationLevel.Debug);
236            }
237            catch (Exception e)
238            {
239                e.GetBaseException();
240            }
241
242            return true;
243        }
244
245        private void BeginStartEventHandler(DHTEventArgs eventArgs)
246        {
247            P2PManager.GuiLogMessage("Received DHTEventArgs: " + eventArgs + ", state: " + eventArgs.State, NotificationLevel.Debug);
248        }
249
250        /// <summary>
251        ///   Disconnects from the peer-to-peer system.
252        /// </summary>
253        /// <returns>True, if the peer has completely left the p2p network</returns>
254        public bool SynchStop()
255        {
256            if (Dht == null) return false;
257
258            Dht.BeginStop(null);
259
260            if (IsConnected)
261                systemLeft.WaitOne();
262
263            systemJoined.Reset();
264            systemLeft.Reset();
265
266            return true;
267        }
268
269        #endregion
270
271        #region Peer related method (GetPeerId, Send message to peer)
272
273        /// <summary>
274        ///   Get PeerName of the actual peer
275        /// </summary>
276        /// <param name = "sPeerName">out: additional peer information UserName on LinkManager</param>
277        /// <returns>PeerID as a String</returns>
278        public PeerId GetPeerId(out string sPeerName)
279        {
280            sPeerName = linkmanager.UserName;
281            return new PeerId(overlay.LocalAddress);
282        }
283
284        /// <summary>
285        ///   Construct PeerId object for a specific byte[] id
286        /// </summary>
287        /// <param name = "byteId">overlay address as byte array</param>
288        /// <returns>corresponding PeerId for given byte[] id</returns>
289        public PeerId GetPeerId(byte[] byteId)
290        {
291            LogToMonitor("GetPeerID: Converting byte[] to PeerId-Object");
292            return new PeerId(overlay.GetAddress(byteId));
293        }
294
295        // overlay.LocalAddress = Overlay-Peer-Address/Names
296        public void SendToPeer(byte[] data, byte[] destinationPeer)
297        {
298            // get stack size of the pap use-data and add own use data (for optimizing Stack size)
299            var realStackSize = overlay.GetHeaderSize() + data.Length;
300
301            var stackData = new ByteStack(realStackSize);
302            stackData.Push(data);
303
304            var destinationAddr = overlay.GetAddress(destinationPeer);
305            var overlayMsg = new OverlayMessage(MessageReceiverType.P2PBase, 
306                                                overlay.LocalAddress, destinationAddr, stackData);
307
308            overlay.Send(overlayMsg);
309        }
310
311        private void OverlayMessageReceived(object sender, OverlayMessageEventArgs e)
312        {
313            if (OnP2PMessageReceived == null) return;
314
315            var pid = new PeerId(e.Message.Source);
316            /* You have to fire this event asynchronous, because the main
317                 * thread will be stopped in this wrapper class for synchronizing
318                 * the asynchronous stuff (AutoResetEvent) --> so this could run
319                 * into a deadlock, when you fire this event synchronous (normal Invoke)
320                 * ATTENTION: This could change the invocation order!!! In my case
321                              no problem, but maybe in future cases... */
322
323            // TODO: not safe: The delegate must have only one target
324            // OnP2PMessageReceived.BeginInvoke(pid, e.Message.Data.PopBytes(e.Message.Data.CurrentStackSize), null, null);
325
326            foreach (var del in OnP2PMessageReceived.GetInvocationList())
327            {
328                var data = e.Message.Data.ToArray();
329                if (e.Message.Data.CurrentStackSize != 0)
330                    data = e.Message.Data.PopBytes(e.Message.Data.CurrentStackSize);
331
332                del.DynamicInvoke(pid, data);
333            }
334        }
335
336        #endregion
337
338        #region Event Handling (System Joined, Left and Message Received)
339
340        private void OnDhtSystemJoined(object sender, EventArgs e)
341        {
342            IsConnected = true;
343
344            if (OnSystemJoined != null)
345                OnSystemJoined();
346
347            systemJoined.Set();
348        }
349
350        private void OnDhtSystemLeft(object sender, SystemLeftEventArgs e)
351        {
352            IsConnected = false;
353            IsInitialized = false;
354            Dht.Dispose();
355
356            // Allow new connection to start and check for waiting / blocked tasks
357            // TODO reset running ConnectionWorkers?
358            systemLeft.Set();
359            systemJoined.Set();
360
361            LogToMonitor("CrypP2P left the system.");
362
363            if (OnSystemLeft != null)
364                OnSystemLeft();
365        }
366
367        #endregion
368
369        #region Synchronous Methods + their Callbacks
370
371        /// <summary>
372        ///   Stores a value in the DHT at the given key
373        /// </summary>
374        /// <param name = "key">Key of DHT Entry</param>
375        /// <param name = "value">Value of DHT Entry</param>
376        /// <returns>True, when storing is completed!</returns>
377        public RequestResult SynchStore(string key, string value)
378        {
379            return SynchStore(key, Encoding.UTF8.GetBytes(value));
380        }
381
382        /// <summary>
383        ///   Stores a value in the DHT at the given key
384        /// </summary>
385        /// <param name = "key">Key of DHT Entry</param>
386        /// <param name = "data">Value of DHT Entry</param>
387        /// <returns>True, when storing is completed!</returns>
388        public RequestResult SynchStore(string key, byte[] data)
389        {
390            var autoResetEvent = new AutoResetEvent(false);
391
392            // LogToMonitor("testcrash" + Encoding.UTF8.GetString(new byte[5000]));
393            LogToMonitor("Begin: SynchStore. Key: " + key + ", " + (data != null ? data.Length : 0) + " bytes");
394
395            var requestResult = new RequestResult {WaitHandle = autoResetEvent, Key = key, Data = data};
396            VersionedDht.Store(OnSynchStoreCompleted, key, data, requestResult);
397
398            // blocking till response
399            bool success = autoResetEvent.WaitOne(1000*60*2);
400            if (!success)
401            {
402                P2PManager.GuiLogMessage("Timeout in DHT Operation. Just a quick hack!", NotificationLevel.Warning);
403                if (!IsConnected)
404                    throw new NotConnectedException();
405                else
406                    throw new InvalidOperationException("SynchStore failed for some reason!");
407            }
408            LogToMonitor("End: SynchStore. Key: " + key + ". Status: " + requestResult.Status);
409
410            return requestResult;
411        }
412
413        /// <summary>
414        ///   Callback for a the synchronized store method
415        /// </summary>
416        /// <param name = "storeResult">retrieved data container</param>
417        private static void OnSynchStoreCompleted(StoreResult storeResult)
418        {
419            var requestResult = storeResult.AsyncState as RequestResult;
420            if (requestResult == null)
421            {
422                LogToMonitor("Received OnSynchStoreCompleted, but RequestResult object is missing. Discarding.");
423                return;
424            }
425
426            requestResult.Parse(storeResult);
427
428            // unblock WaitHandle in the synchronous method
429            requestResult.WaitHandle.Set();
430        }
431
432        /// <summary>
433        ///   Get the value of the given DHT Key or null, if it doesn't exist.
434        /// </summary>
435        /// <param name = "key">Key of DHT Entry</param>
436        /// <returns>Value of DHT Entry</returns>
437        public RequestResult SynchRetrieve(string key)
438        {
439            LogToMonitor("Begin: SynchRetrieve. Key: " + key);
440
441            var autoResetEvent = new AutoResetEvent(false);
442            var requestResult = new RequestResult {WaitHandle = autoResetEvent, Key = key};
443
444            Dht.Retrieve(OnSynchRetrieveCompleted, key, requestResult);
445
446            // blocking till response
447            bool success = autoResetEvent.WaitOne(1000 * 60 * 2);
448            if (!success)
449            {
450                P2PManager.GuiLogMessage("Timeout in DHT Operation. Just a quick hack!", NotificationLevel.Warning);
451                if (!IsConnected)
452                    throw new NotConnectedException();
453                else
454                    throw new InvalidOperationException("SynchRetrieve failed for some reason!");
455            }
456
457            LogToMonitor("End: SynchRetrieve. Key: " + key + ". Status: " + requestResult.Status);
458
459            return requestResult;
460        }
461
462        /// <summary>
463        ///   Callback for a the synchronized retrieval method
464        /// </summary>
465        /// <param name = "retrieveResult"></param>
466        private static void OnSynchRetrieveCompleted(RetrieveResult retrieveResult)
467        {
468            var requestResult = retrieveResult.AsyncState as RequestResult;
469            if (requestResult == null)
470            {
471                LogToMonitor("Received OnSynchRetrieveCompleted, but RequestResult object is missing. Discarding.");
472                return;
473            }
474
475            requestResult.Parse(retrieveResult);
476
477            // unblock WaitHandle in the synchronous method
478            requestResult.WaitHandle.Set();
479        }
480
481        /// <summary>
482        ///   Removes a key/value pair out of the DHT
483        /// </summary>
484        /// <param name = "key">Key of the DHT Entry</param>
485        /// <returns>True, when removing is completed!</returns>
486        public RequestResult SynchRemove(string key)
487        {
488            LogToMonitor("Begin SynchRemove. Key: " + key);
489
490            var autoResetEvent = new AutoResetEvent(false);
491            var requestResult = new RequestResult { WaitHandle = autoResetEvent, Key = key };
492            VersionedDht.Remove(OnSynchRemoveCompleted, key, requestResult);
493
494            // blocking till response
495            bool success = autoResetEvent.WaitOne(1000 * 60 * 2);
496            if (!success)
497            {
498                P2PManager.GuiLogMessage("Timeout in DHT Operation. Just a quick hack!", NotificationLevel.Warning);
499                if (!IsConnected)
500                    throw new NotConnectedException();
501                else
502                    throw new InvalidOperationException("SynchRemove failed for some reason!");
503            }
504
505            LogToMonitor("End: SynchRemove. Key: " + key + ". Status: " + requestResult.Status);
506
507            return requestResult;
508        }
509
510        /// <summary>
511        ///   Callback for a the synchronized remove method
512        /// </summary>
513        /// <param name = "removeResult"></param>
514        private static void OnSynchRemoveCompleted(RemoveResult removeResult)
515        {
516            var requestResult = removeResult.AsyncState as RequestResult;
517            if (requestResult == null)
518            {
519                LogToMonitor("Received OnSynchRemoveCompleted, but RequestResult object is missing. Discarding.");
520                return;
521            }
522
523            requestResult.Parse(removeResult);
524
525            // unblock WaitHandle in the synchronous method
526            requestResult.WaitHandle.Set();
527        }
528
529        #endregion
530
531        #region Statistic Methods
532
533        public long TotalBytesSentOnAllLinks()
534        {
535            return (long) linkmanager.GetAllLinkInformation().Sum(linkInformation => linkInformation.TotalBytesSent);
536        }
537
538        public long TotalBytesReceivedOnAllLinks()
539        {
540            return (long) linkmanager.GetAllLinkInformation().Sum(linkInformation => linkInformation.TotalBytesReceived);
541        }
542
543        #endregion
544
545        #region Log facility
546
547        /// <summary>
548        ///   To log the internal state in the Monitoring Software of P@play
549        /// </summary>
550        public void LogInternalState()
551        {
552            if (Dht != null)
553            {
554                Dht.LogInternalState();
555            }
556        }
557
558        private static void LogToMonitor(string sTextToLog)
559        {
560            if (P2PSettings.Default.Log2Monitor)
561                Log.Debug(sTextToLog);
562        }
563
564        /// <summary>
565        /// Encrypts the given string using the current windows user password and converts
566        /// this to a base64 string
567        /// </summary>
568        /// <param name="s"></param>
569        /// <returns>encrypted base64 string</returns>
570        public static string EncryptString(string s)
571        {
572            byte[] bytes = Encoding.Unicode.GetBytes(s);
573            byte[] encBytes = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
574            return Convert.ToBase64String(encBytes);
575        }
576
577        /// <summary>
578        /// Decrypts the given base64 string using the current windows user password
579        /// </summary>
580        /// <param name="s"></param>
581        /// <returns>decrypted string</returns>
582        public static string DecryptString(string s)
583        {
584            if (string.IsNullOrEmpty(s))
585            {
586                return "";
587            }
588            try
589            {
590                byte[] encBytes = Convert.FromBase64String(s);
591                byte[] bytes = ProtectedData.Unprotect(encBytes, null, DataProtectionScope.CurrentUser);
592                return Encoding.Unicode.GetString(bytes);
593            }
594            catch (Exception)
595            {
596                return "";
597            }
598        }
599
600
601        #endregion
602    }
603}
Note: See TracBrowser for help on using the repository browser.