Changeset 971


Ignore:
Timestamp:
Dec 8, 2009, 3:31:08 PM (12 years ago)
Author:
arnold
Message:

Beta Version of Distributed KeySearcher with P2PManager und P2PWorker.

Location:
trunk/CrypPlugins
Files:
21 added
3 deleted
13 edited

Legend:

Unmodified
Added
Removed
  • trunk/CrypPlugins/KeySearcher/KeyPattern.cs

    r959 r971  
    152152                        {
    153153                            if (i - 1 - begin == 1)
    154                                 res += values[begin] + values[i - 1];
     154                                res += values[begin] + "" + values[i - 1];
    155155                            else
    156156                                res += values[begin] + "-" + values[i - 1];
     
    198198        private string pattern;
    199199        private ArrayList wildcardList;
     200        /// <summary>
     201        /// Property for the WildCardKey. Could return null, if the KeyPattern isn't initialized correctly.
     202        /// </summary>
    200203        public string WildcardKey
    201204        {
     
    395398            int pcount = 0;
    396399            int wccount = 0;
    397             while (pcount < pattern.Length)
    398             {
    399                 if (pattern[pcount] != '[')
    400                     res += pattern[pcount];
    401                 else
    402                 {
    403                     res += ((Wildcard)wildcardList[wccount++]).getRepresentationString();
    404                     while (pattern[++pcount] != ']') ;
    405                 }
    406                 pcount++;
    407             }
    408             return res;
     400
     401            // error handling
     402            if (wildcardList != null)
     403            {
     404                while (pcount < pattern.Length)
     405                {
     406                    if (pattern[pcount] != '[')
     407                        res += pattern[pcount];
     408                    else
     409                    {
     410                        res += ((Wildcard)wildcardList[wccount++]).getRepresentationString();
     411                        while (pattern[++pcount] != ']') ;
     412                    }
     413                    pcount++;
     414                }
     415                return res;
     416            }
     417            else
     418                return null;
    409419        }
    410420
     
    579589        public override string ToString()
    580590        {
    581             return "Type: KeySearcher.KeyPattern. WildcardKey: '" + this.WildcardKey + "', Pattern: '" + this.pattern + "'";
     591            if(this.WildcardKey != null)
     592                return "Type: KeySearcher.KeyPattern. WildcardKey: '" + this.WildcardKey + "', Pattern: '" + this.pattern + "'";
     593            else
     594                return "Type: KeySearcher.KeyPattern. KeyPattern isn't initialized correctly, Pattern: '" + this.pattern + "'";
    582595        }
    583596
     
    629642            if (wildcardKey != null && this.pattern != null)
    630643            {
    631                 // TODO: implement testPattern-method
    632                 //if (testPattern(pattern) && testKey(key))
    633644                if (testWildcardKey(wildcardKey))
    634645                {
     
    670681
    671682            // test extracted pattern and wildcardKey!
    672             // TODO: implement testPattern-method
    673             //if (testPattern(pattern_temp) && testKey(wildcardKey_temp))
    674683            if (testWildcardKey(wildcardKey_temp))
    675684            {
  • trunk/CrypPlugins/KeySearcher/KeySearcher.cs

    r959 r971  
    393393            if (sender == null || costMaster == null)
    394394                return;
     395            if (!Pattern.testWildcardKey(settings.Key))
     396            {
     397                GuiLogMessage("Wrong key pattern!", NotificationLevel.Error);
     398                return;
     399            }
     400            Pattern.WildcardKey = settings.Key;
    395401            bruteforcePattern(Pattern, sender);
    396402        }
    397403
     404        // modified by Christian Arnold 2009.12.07 - return type LinkedList (top10List)
    398405        // main entry point to the KeySearcher
    399         private void bruteforcePattern(KeyPattern pattern, IControlEncryption sender)
     406        private LinkedList<ValueKey> bruteforcePattern(KeyPattern pattern, IControlEncryption sender)
    400407        {
    401408            int maxInList = 10;
     
    407414            {
    408415                GuiLogMessage("Wrong key pattern!", NotificationLevel.Error);
    409                 return;
     416                return null;
    410417            }
    411418
     
    419426            {
    420427                GuiLogMessage("Bytes used not valid: " + ex.Message, NotificationLevel.Error);
    421                 return;
    422             }
    423 
    424             pattern.WildcardKey = settings.Key;
     428                return null;
     429            }
     430
    425431            BigInteger size = pattern.size();
    426432            KeyPattern[] patterns = splitPatternForThreads(pattern);
     
    460466                    int id = -1;
    461467                    for (int i = 0; i < patterns.Length; i++)
    462                         if (keysleft[i] > max)
     468                        if (keysleft[i] != null && keysleft[i] > max)
    463469                        {
    464470                            max = keysleft[i];
     
    488494            if (!stop)
    489495                ProgressChanged(1, 1);
     496
     497            return costList;
    490498        }
    491499
     
    691699        }
    692700
    693         // modified by Arnie - 2009.12.02
     701        // set to protected by Christian Arnold - 2009.12.06
    694702        protected virtual void onStatusChanged(IControl sender, bool readyForExecution)
    695703        {
     
    699707            }
    700708        }
     709
     710
     711        // added by Arnie - 2009.12.07
     712        public delegate void BruteforcingEnded(LinkedList<ValueKey> top10List);
     713        /// <summary>
     714        /// This event gets thrown after Bruteforcing had ended. This is no evidence, that bruteforcing was successful.
     715        /// But when the returned List is filled, we have (at least a part) of the possible best keys
     716        /// </summary>
     717        public event BruteforcingEnded OnBruteforcingEnded;
    701718
    702719        // added by Arnie -2009.12.02
     
    706723            ControlMaster = encryptControl;
    707724            CostMaster = costControl;
    708             bruteforcePattern(pattern, encryptControl);
     725            LinkedList<ValueKey> lstRet = bruteforcePattern(pattern, encryptControl);
     726            if(OnBruteforcingEnded != null)
     727                OnBruteforcingEnded(lstRet);
    709728        }
    710729
     
    726745        }
    727746
     747        // modified by Christian Arnold - 2009.12.07 (to public)
    728748        /// <summary>
    729749        /// used for delivering the results from the worker threads to the main thread:
    730750        /// </summary>
    731         private struct ValueKey
     751        public struct ValueKey
    732752        {
    733753            public double value;
  • trunk/CrypPlugins/PeerToPeerBase/IP2PControl.cs

    r872 r971  
    8383        bool DHTremove(string sKey);
    8484
     85        bool PeerStarted();
     86
    8587        PeerId GetPeerID(out string sPeerName);
    8688        //byte[] GetPeerID(out string sPeerName);
  • trunk/CrypPlugins/PeerToPeerBase/P2PPeer.cs

    r872 r971  
    307307        #endregion
    308308
     309        public bool PeerStarted()
     310        {
     311            return this.p2pPeer.PeerStarted;
     312        }
     313
    309314        /// <summary>
    310315        /// workaround method. If the PAP functions are used, but the PAP system isn't
  • trunk/CrypPlugins/PeerToPeerBase/PeerToPeerBase.cs

    r928 r971  
    644644        }
    645645
     646       
     647
     648        public override string ToString()
     649        {
     650            return this.stringId;
     651        }
     652
     653        public byte[] ToByteArray()
     654        {
     655            return this.byteId;
     656        }
     657
    646658        // not used at present...
    647659        public bool Equals(PeerId otherPeerId)
     
    652664                return false;
    653665        }
    654 
    655         public string ToString()
    656         {
    657             return this.stringId;
    658         }
    659 
    660         public byte[] ToByteArray()
    661         {
    662             return this.byteId;
    663         }
    664666    }
    665667}
  • trunk/CrypPlugins/PeerToPeerBase/PeerToPeerBase.csproj

    r836 r971  
    9999  </ItemGroup>
    100100  <ItemGroup>
     101    <Compile Include="DebugToFile.cs" />
    101102    <Compile Include="IP2PControl.cs" />
    102103    <Compile Include="P2PPeerSettings.cs" />
  • trunk/CrypPlugins/PeerToPeerManager/P2PManager.cs

    r928 r971  
    3737    /// </summary>
    3838    [Author("Christian Arnold", "arnold@cryptool.org", "Uni Duisburg-Essen", "http://www.uni-due.de")]
    39     [PluginInfo(false, "P2P_Manager", "Creates a new Manager-Peer", "", "PeerToPeerManager/ct2_p2p_pub_medium.png")]
     39    [PluginInfo(false, "P2P_Manager", "Creates a new Manager-Peer", "", "PeerToPeerManager/manager_medium_neutral.png", "PeerToPeerManager/manager_medium_working.png", "PeerToPeerManager/manager_medium_finished.png")]
    4040    public class P2PManager : IInput
    4141    {
     
    5656            {
    5757                pattern = value;
    58                 if ((settings.Key == null) || ((settings.Key != null) && !pattern.testKey(settings.Key)))
    59                     settings.Key = pattern.giveWildcardKey();
     58                if ((settings.Key == null) || ((settings.Key != null) && !pattern.testWildcardKey(settings.Key)))
     59                    settings.Key = pattern.giveInputPattern();
    6060            }
    6161        }
     
    167167            this.settings.PropertyChanged += new PropertyChangedEventHandler(settings_PropertyChanged);
    168168            this.settings.TaskPaneAttributeChanged += new TaskPaneAttributeChangedHandler(settings_TaskPaneAttributeChanged);
     169            this.settings.OnPluginStatusChanged += new StatusChangedEventHandler(settings_OnPluginStatusChanged);
     170        }
     171
     172        void settings_OnPluginStatusChanged(IPlugin sender, StatusEventArgs args)
     173        {
     174            if (OnPluginStatusChanged != null)
     175                OnPluginStatusChanged(this, args);
    169176        }
    170177
     
    239246        public void Stop()
    240247        {
    241             if(this.p2pManager != null)
     248
     249            if (this.p2pManager != null && this.p2pManager.Started)
     250            {
    242251                this.p2pManager.Stop(PubSubMessageType.Unregister);
     252                this.settings.MngStatusChanged(P2PManagerSettings.MngStatus.Neutral);
     253            }
    243254        }
    244255
     
    266277                this.p2pManager = new P2PManagerBase(this.P2PControl);
    267278                this.p2pManager.OnGuiMessage += new P2PPublisherBase.GuiMessage(p2pManager_OnGuiMessage);
     279                this.p2pManager.OnFinishedDistributingPatterns += new P2PManagerBase.FinishedDistributingPatterns(p2pManager_OnFinishedDistributingPatterns);
    268280                //this.p2pManager.Start(this.settings.TopicName, (long)this.settings.SendAliveMessageInterval);
    269281            }
     282        }
     283
     284        void p2pManager_OnFinishedDistributingPatterns(List<object> lstTopList)
     285        {
     286            // TODO: display received TopList
     287            this.settings.MngStatusChanged(P2PManagerSettings.MngStatus.Finished);
    270288        }
    271289
     
    294312            /*Begin Testspace*/
    295313            string pattern = iControlEncryption.getKeyPattern();
     314            GuiLogMessage("string pattern = Encrypt.GetKeyPattern() = '" + pattern + "'", NotificationLevel.Debug);
    296315            KeyPattern kp = new KeyPattern(pattern);
    297             kp.initKeyIteration("30-30-30-30-30-30-30-30-30-30-30-30-30-**-**-**");
     316            int len = pattern.ToString().Length;
     317
     318            if(len == 271) //AES
     319                kp.WildcardKey = "30-30-30-30-30-30-30-30-30-30-30-30-30-**-**-**";
     320            else if(len == 135) //DES
     321                kp.WildcardKey = "30-30-30-30-30-**-**-**";
     322            else
     323                throw(new Exception("Encryption Type not supported"));
     324
     325            GuiLogMessage("KeyPattern kp = new KeyPattern(pattern) = GetKey '" + kp.getKey() + "'", NotificationLevel.Debug);
    298326
    299327            this.p2pManager.StartManager(this.settings.TopicName, (long)this.settings.SendAliveMessageInterval, kp);
     328
     329            this.settings.MngStatusChanged(P2PManagerSettings.MngStatus.Working);
    300330            /*End Testspace*/
    301331        }
  • trunk/CrypPlugins/PeerToPeerManager/P2PManagerBase.cs

    r928 r971  
    88using KeySearcher;
    99using Cryptool.PluginBase.Miscellaneous;
     10using System.IO;
    1011
    1112/*bearbeitung
    1213 * TODO:
    1314 * - Order the results when they arrived as a message! (MessageReceived method)
     15 * - Fire event, when all Pattern were distributed and ALL there results had arrived
    1416 */
    1517
     
    1820    public class P2PManagerBase : P2PPublisherBase
    1921    {
     22        public delegate void FinishedDistributingPatterns(List<object> lstTopList);
     23        public event FinishedDistributingPatterns OnFinishedDistributingPatterns;
     24
    2025        #region Variables
    2126
     
    2732        }
    2833
    29         private BigInteger keyPatternPartSize = 10000;
     34        // 10.000 = 2048 Keys bei AES; 100.000 = 256 Keys bei AES; 400.000 = 64 Keys bei AES; 1.000.000 = xx Keys bei AES
     35        private BigInteger keyPatternPartSize = 1000000;
    3036        /// <summary>
    3137        /// Declare in how many parts the key space will be split
     
    6066        /// </summary>
    6167        Dictionary<KeyPattern, string> patternResults;
     68        /// <summary>
     69        /// When a working peer sends the information message "Solution Found" the
     70        /// actual worked Pattern gets stored with the PeerId, so we can detect the
     71        /// following received serialized result list. Delete entry after receiving
     72        /// the result list!!!
     73        /// </summary>
     74        Dictionary<string, KeyPattern> solutionFound;
    6275
    6376        #endregion
     
    6881            this.allocatedPatterns = new Dictionary<string, KeyPattern>();
    6982            this.patternResults = new Dictionary<KeyPattern, string>();
     83            this.solutionFound = new Dictionary<string, KeyPattern>();
    7084        }
    7185
     
    7589
    7690            if (msgType != PubSubMessageType.NULL)
    77                 // base class handles all administration cases (register, alive, unregister, ping, pong, ...)
    78                 base.MessageReceived(sourceAddr, sData);
     91                // before the worker send the result list, it sends a SolutionFound Message
     92                if (msgType == PubSubMessageType.Solution)
     93                {
     94                    // if solutionFound sending peer isn't already in the solutionFound list, but had been allocated to a pattern
     95                    if (!this.solutionFound.ContainsKey(sourceAddr.stringId) && this.allocatedPatterns.ContainsKey(sourceAddr.stringId))
     96                    {
     97                        GuiLogging("Solution found message received from '" + sourceAddr.stringId + "'", NotificationLevel.Info);
     98                        this.solutionFound.Add(sourceAddr.stringId, this.allocatedPatterns[sourceAddr.stringId]);
     99                    }
     100                }
     101                else
     102                    // base class handles all administration cases (register, alive, unregister, ping, pong, ...)
     103                    base.MessageReceived(sourceAddr, sData);
    79104            else
    80105            {
    81106                // if sending peer is in the allocatedPatterns Dict, its an (intermediate) result
    82                 if (this.allocatedPatterns.ContainsKey(sourceAddr.stringId))
    83                 {
     107                if (this.allocatedPatterns.ContainsKey(sourceAddr.stringId) && this.solutionFound.ContainsKey(sourceAddr.stringId))
     108                {
     109                    GuiLogging("Result from worker '" + sourceAddr.stringId + "' received. Data: " + sData, NotificationLevel.Debug);
     110
    84111                    KeyPattern actualPattern = this.allocatedPatterns[sourceAddr.stringId];
     112
     113                    LinkedList<KeySearcher.KeySearcher.ValueKey> lstResults = DeserializeKeySearcherResult(sData);
     114                   
     115                    GuiLogging("Result for Pattern '" + actualPattern.WildcardKey + "' was deserialized. Value: '" + lstResults.First.Value,NotificationLevel.Debug);
     116
    85117                    // if patternResult already contains a result for this pattern, compare the results
    86118                    // and take the better one
     
    89121                        // TODO: compare results and take the better one
    90122                        this.patternResults[actualPattern] = sData;
     123                        GuiLogging("New result for the same pattern (" + actualPattern.WildcardKey + ") received. So it was updated.", NotificationLevel.Debug);
    91124                    }
    92125                    else
    93126                    {
    94127                        this.patternResults.Add(actualPattern, sData);
     128                        GuiLogging("Received FIRST result for the pattern '" + actualPattern.WildcardKey + "'",NotificationLevel.Debug);
    95129                    }
    96                     GuiLogging("(Intermediate) result found for pattern: '" + actualPattern.ToString() + "'. Result: '" + sData + "'", NotificationLevel.Debug);
     130                    // TODO: Compare, actualize and display top 10 list of all results received from the different workers
     131                    // ActualizeTopList(DeserializeKeySearcherResult(sData));
     132
     133                    KeySearcher.KeySearcher.ValueKey firstResult = lstResults.First();
     134
     135                    // result was processed, so peer must be removed from solution list
     136                    this.solutionFound.Remove(sourceAddr.stringId);
     137
     138                    GuiLogging("(Intermediate) result found for pattern: '" + actualPattern.ToString() + "'. Result: '" + firstResult.key + "' with Coefficient: " + firstResult.value.ToString(), NotificationLevel.Info);
    97139                }
    98140                else
     
    101143                }
    102144            }
     145        }
     146
     147        /*
     148         * serialization information: 3 fields per data set in the following order:
     149         * 1) value (double)
     150         * 2) key (string)
     151         * 3) decryption (byte[])
     152         */
     153        private string seperator = "#;#";
     154        private string dataSetSeperator = "|**|";
     155        private LinkedList<KeySearcher.KeySearcher.ValueKey> DeserializeKeySearcherResult(string sSerializedResult)
     156        {
     157            LinkedList<KeySearcher.KeySearcher.ValueKey> lstRet = new LinkedList<KeySearcher.KeySearcher.ValueKey>();
     158            string[] serveralDataSets = sSerializedResult.Split(dataSetSeperator.ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
     159            for (int i = 0; i < serveralDataSets.Length; i++)
     160            {
     161                string[] severalFieldsInDataSet = serveralDataSets[i].Split(seperator.ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
     162                if(severalFieldsInDataSet.Length != 3)
     163                    return null;
     164                // build ValueKey from splitted string
     165                KeySearcher.KeySearcher.ValueKey valKey = new KeySearcher.KeySearcher.ValueKey();
     166                valKey.value = Convert.ToDouble(severalFieldsInDataSet[0]);
     167                valKey.key = severalFieldsInDataSet[1];
     168                valKey.decryption = UTF8Encoding.UTF8.GetBytes(severalFieldsInDataSet[2]);
     169                // add builded ValueKey to list
     170                lstRet.AddLast(valKey);
     171            }
     172            return lstRet;
    103173        }
    104174
     
    106176        private void peerManagement_OnFreeWorkersAvailable()
    107177        {
    108             DispersePatterns();
     178            if (DispersePatterns() == 0)
     179            {
     180                int result = 0;
     181                while (!this.ManagerStarted && result == 0)
     182                {
     183                    result = DispersePatterns();
     184                }
     185            }
    109186        }
    110187
     
    139216                if (iCycle <= iFreePatternAmount)
    140217                {
    141                     KeyPattern actualPattern = this.leftKeyPatterns.Dequeue();
    142                     this.allocatedPatterns.Add(subscriber.stringId, actualPattern);
     218                    KeyPattern actualKeyPattern = this.leftKeyPatterns.Dequeue();
     219                    this.allocatedPatterns.Add(subscriber.stringId, actualKeyPattern);
    143220                    // send job (Keyspace) to the actual worker peer
    144                     this.p2pControl.SendToPeer(actualPattern.ToString(), subscriber.byteId);
     221                    this.p2pControl.SendToPeer(actualKeyPattern.SerializeToString(), subscriber.byteId);
    145222                    // set free worker to busy in the peerManagement class
    146223                    ((WorkersManagement)this.peerManagement).SetFreeWorkerToBusy(subscriber);
     
    151228                {
    152229                    // no more patterns to disperse, so leave foreach
     230                    // TODO: inform all workers that no more patterns must be bruteforced, they only have to finish the last assigned Patterns
     231                    ((WorkersManagement)this.peerManagement).OnFreeWorkersAvailable -= peerManagement_OnFreeWorkersAvailable;
    153232                    break;
    154233                }
     
    183262            foreach (KeyPattern keyPatternPart in arrKeyPatternPool)
    184263            {
     264               
    185265                this.leftKeyPatterns.Enqueue(keyPatternPart);
    186266            }
     267           
     268            /* ************************************** */
     269            /* Only for debugging reasons - to delete */     
     270            StreamWriter debugWriter = DebugToFile.GetDebugStreamWriter();
     271            int i = 0;
     272            foreach (KeyPattern patternPart in this.leftKeyPatterns.ToList<KeyPattern>())
     273            {
     274                debugWriter.WriteLine(i + "\t" + patternPart.ToString());
     275                i++;
     276            }
     277            debugWriter.Dispose();
     278
     279            /* Only for debugging reasons - to delete */
     280            /* ************************************** */
     281           
    187282
    188283            this.ManagerStarted = true;
  • trunk/CrypPlugins/PeerToPeerManager/P2PManagerSettings.cs

    r928 r971  
    1616        private bool hasChanges = false;
    1717        private P2PManager p2pManager;
    18         //private KeySearcher.KeySearcher keysearcher;
     18        //private KeySearcher keysearcher;
    1919
    2020        #region ISettings Members
     
    4343                TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer("BtnRegister", Visibility.Visible)));
    4444            }
     45            ChangePluginIcon(MngStatus.Neutral);
    4546        }
    4647
     
    137138
    138139        #endregion
     140
     141        #region PlugIn-Icon status Stuff
     142
     143        // Index depends on icon-position in P2PManager-Class properties
     144        public enum MngStatus
     145        {
     146            Neutral = 0,
     147            Working = 1,
     148            Finished = 2
     149            //Error = 3
     150        }
     151
     152        /// <summary>
     153        /// Changes icon of P2PManager and visibility of the control buttons in settings
     154        /// </summary>
     155        /// <param name="peerStat"></param>
     156        public void MngStatusChanged(MngStatus mngStat)
     157        {
     158            ChangePluginIcon(mngStat);
     159        }
     160
     161        public event StatusChangedEventHandler OnPluginStatusChanged;
     162        private void ChangePluginIcon(MngStatus mngStatus)
     163        {
     164            if (OnPluginStatusChanged != null)
     165                OnPluginStatusChanged(null, new StatusEventArgs(StatusChangedMode.ImageUpdate, (int)mngStatus));
     166        }
     167
     168        #endregion
    139169    }
    140170}
  • trunk/CrypPlugins/PeerToPeerManager/PeerToPeerManager.csproj

    r928 r971  
    8080  </ItemGroup>
    8181  <ItemGroup>
    82     <Resource Include="ct2_p2p_pub_medium.png" />
     82    <Resource Include="manager_medium_finished.png" />
     83    <Resource Include="manager_medium_neutral.png" />
     84    <Resource Include="manager_medium_working.png" />
    8385  </ItemGroup>
    8486  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  • trunk/CrypPlugins/PeerToPeerPublisher/P2PPublisherBase.cs

    r928 r971  
    135135            GuiLogging("Unregister messages were sent to " + i.ToString() + " subscribers!", NotificationLevel.Info);
    136136
    137             //Still an error in dhtRemove... so at present ignored...
    138             if (this.p2pControl != null)
     137            //Still an error in dhtRemove... so at present ignored... - partially freezing the workspace forever...
     138            /*
     139             * if someone wants to call the Stop-method, but the peer is already down,
     140             * this will run into a problem (CrypWin.exe lives on), because of the
     141             * necessary workaround in P2PPeerMaster (Initializes Peer, if it isn't
     142             * initialized yet). This workaround was necessary, because of the gradual
     143             * execution of the PlugIns, so that the case could occur, that the Peer isn't
     144             * initialized by the PlugIn-method, but its Master-PlugIns want to use its
     145             * functions right now
     146             */
     147            if (this.p2pControl != null && this.p2pControl.PeerStarted())
    139148            {
    140149
  • trunk/CrypPlugins/PeerToPeerSubscriber/P2PSubscriber.cs

    r872 r971  
    124124                if (this.p2pSubscriber != null)
    125125                {
    126                     this.p2pSubscriber.Stop();
     126                    this.p2pSubscriber.Stop(PubSubMessageType.Unregister);
    127127                    GuiLogMessage("Subscriber unregistered from Publisher!", NotificationLevel.Info);
    128128                }
     
    141141                if (this.p2pSubscriber != null)
    142142                {
    143                     this.p2pSubscriber.SolutionFound();
     143                    this.p2pSubscriber.SolutionFound("");
    144144                    GuiLogMessage("Solution found message sent to Publisher.", NotificationLevel.Info);
    145145                }
     
    185185        {
    186186            if(this.p2pSubscriber != null)
    187                 this.p2pSubscriber.Stop();
     187                this.p2pSubscriber.Stop(PubSubMessageType.Stop);
    188188        }
    189189
  • trunk/CrypPlugins/PeerToPeerSubscriber/P2PSubscriberBase.cs

    r928 r971  
    2323        public delegate void TextArrivedFromPublisher(string sData, PeerId pid);
    2424        public event TextArrivedFromPublisher OnTextArrivedFromPublisher;
     25        public delegate void ReceivedStopFromPublisher(PubSubMessageType stopType, string sData);
     26        /// <summary>
     27        /// fired when Manager sent "stop" message to the worker.
     28        /// </summary>
     29        public event ReceivedStopFromPublisher OnReceivedStopMessageFromPublisher;
    2530
    2631        #region Variables
     
    8590        /* BEGIN: Only for experimental cases */
    8691
    87         public void SolutionFound()
     92        public void SolutionFound(string sSolutionData)
    8893        {
    8994            SendMessage(actualPublisher, PubSubMessageType.Solution);
     95            this.p2pControl.SendToPeer(sSolutionData, actualPublisher.byteId);
    9096        }
    9197        /* END: Only for experimental cases */
     
    129135            if (sourceAddr.stringId != actualPublisher.stringId)
    130136            {
    131                 OnGuiMessage("RECEIVED message from third party peer (not the publisher!): " + sData.Trim() + ", ID: " + sourceAddr.stringId, NotificationLevel.Info);
     137                GuiLogging("RECEIVED message from third party peer (not the publisher!): " + sData.Trim() + ", ID: " + sourceAddr.stringId, NotificationLevel.Info);
    132138                return;
    133139            }
     
    138144            {
    139145                case PubSubMessageType.RegisteringAccepted:
    140                     OnGuiMessage("REGISTERING ACCEPTED received from publisher!", NotificationLevel.Info);
     146                    GuiLogging("REGISTERING ACCEPTED received from publisher!", NotificationLevel.Info);
    141147                    if (this.timeoutForPublishersRegAccept != null)
    142148                    {
     
    147153                case PubSubMessageType.Ping:
    148154                    SendMessage(sourceAddr, PubSubMessageType.Pong);
    149                     OnGuiMessage("REPLIED to a ping message from " + sourceAddr, NotificationLevel.Info);
     155                    GuiLogging("REPLIED to a ping message from " + sourceAddr, NotificationLevel.Info);
    150156                    break;
    151157                case PubSubMessageType.Register:
    152158                case PubSubMessageType.Unregister:
    153                     OnGuiMessage(msgType.ToString().ToUpper() + " received from PUBLISHER.", NotificationLevel.Warning);
     159                    GuiLogging(msgType.ToString().ToUpper() + " received from PUBLISHER.", NotificationLevel.Warning);
    154160                    // continuously try to get a unregister and than re-register with publisher
    155                     Stop();
     161                    Stop(msgType);
    156162                    Register(this.sTopic,this.checkPublishersAvailability, this.publisherReplyTimespan);
    157163                    break;
    158164                case PubSubMessageType.Solution:
    159                     Stop();
    160                     OnGuiMessage("Another Subscriber had found the solution!", NotificationLevel.Info);
     165                    Stop(msgType);
     166                    GuiLogging("Another Subscriber had found the solution!", NotificationLevel.Info);
    161167                    break;
    162168                case PubSubMessageType.Stop:
    163                     Stop();
    164                     OnGuiMessage("STOP received from publisher. Subscriber is stopped!", NotificationLevel.Warning);
     169                    Stop(msgType);
     170                    GuiLogging("STOP received from publisher. Subscriber is stopped!", NotificationLevel.Warning);
    165171                    break;
    166172                case PubSubMessageType.Pong:
     
    172178                    break;
    173179                // if the received Data couldn't be casted to enum,
    174                 // it must be text-data
     180                // it must be some data
    175181                case PubSubMessageType.NULL:
    176                     OnGuiMessage("RECEIVED: Message from '" + sourceAddr.stringId
    177                     + "' with data: '" + sData + "'", NotificationLevel.Info);
    178 
    179                     if (OnTextArrivedFromPublisher != null)
    180                         OnTextArrivedFromPublisher(sData, sourceAddr);
     182                    // functionality swapped for better inheritance
     183                    HandleIncomingData(sourceAddr, sData);
    181184
    182185                    break;
     
    186189                    break;
    187190            }
     191        }
     192
     193        /// <summary>
     194        /// Incoming data will be printed in the information field and the OnTextArrivedEvent will be thrown
     195        /// </summary>
     196        /// <param name="senderId"></param>
     197        /// <param name="sData"></param>
     198        protected virtual void HandleIncomingData(PeerId senderId, string sData)
     199        {
     200            GuiLogging("RECEIVED: Message from '" + senderId.stringId
     201                    + "' with data: '" + sData + "'", NotificationLevel.Info);
     202
     203            if (OnTextArrivedFromPublisher != null)
     204                OnTextArrivedFromPublisher(sData, senderId);
    188205        }
    189206
     
    209226                    break;
    210227                case PubSubMessageType.Solution:
    211                     Stop();
     228                    // when i send Solution to the Stop method, we will run into a recursive loop between SendMessage and Stop!
     229                    Stop(PubSubMessageType.NULL);
    212230                    break;
    213231                default:
    214                     OnGuiMessage("No Message sent, because MessageType wasn't supported: " + msgType.ToString(), NotificationLevel.Warning);
     232                    GuiLogging("No Message sent, because MessageType wasn't supported: " + msgType.ToString(), NotificationLevel.Warning);
    215233                    return;
    216234            }
     
    219237            // don't show every single alive message
    220238            if (msgType != PubSubMessageType.Alive)
    221                 OnGuiMessage(msgType.ToString() + " message sent to Publisher", NotificationLevel.Info);
     239                GuiLogging(msgType.ToString() + " message sent to Publisher", NotificationLevel.Info);
    222240        }
    223241
     
    232250                SendMessage(pubId, PubSubMessageType.Register);
    233251            else
    234                 OnGuiMessage("No publisher for registering found.", NotificationLevel.Info);
     252                GuiLogging("No publisher for registering found.", NotificationLevel.Info);
    235253        }
    236254
     
    258276            if (byteISettings == null)
    259277            {
    260                 OnGuiMessage("Can't find settings from Publisher for the Subscriber.", NotificationLevel.Error);
     278                GuiLogging("Can't find settings from Publisher for the Subscriber.", NotificationLevel.Error);
    261279                return null;
    262280            }
     
    264282
    265283            string sPubId = this.p2pControl.ConvertIdToString(bytePubId);
    266             OnGuiMessage("RECEIVED: Publishers' peer name '" + sPubId + "', Alive-Msg-Interval: " + sendAliveMessageInterval / 1000 + " sec!", NotificationLevel.Info);
     284            GuiLogging("RECEIVED: Publishers' peer name '" + sPubId + "', Alive-Msg-Interval: " + sendAliveMessageInterval / 1000 + " sec!", NotificationLevel.Info);
    267285
    268286            pid = new PeerId(sPubId, bytePubId);
     
    289307            if (newPubId == null)
    290308            {
    291                 OnGuiMessage("Publisher wasn't found in DHT or settings didn't stored on the right way.", NotificationLevel.Warning);
     309                GuiLogging("Publisher wasn't found in DHT or settings didn't stored on the right way.", NotificationLevel.Warning);
    292310                return;
    293311            }
     
    295313            {
    296314                //Handle case, when publisher changed or isn't active at present (don't reply on response)
    297                 OnGuiMessage("CHANGED: Publisher from '" + actualPublisher.stringId
     315                GuiLogging("CHANGED: Publisher from '" + actualPublisher.stringId
    298316                    + "' to '" + newPubId.stringId + "'!", NotificationLevel.Info);
    299317                actualPublisher = newPubId;
     
    319337        private void OnTimeoutRegisteringAccepted(object state)
    320338        {
    321             OnGuiMessage("TIMEOUT: Waiting for registering accepted message from publisher!", NotificationLevel.Warning);
     339            GuiLogging("TIMEOUT: Waiting for registering accepted message from publisher!", NotificationLevel.Warning);
    322340            // TODO: anything
    323341        }
     
    329347        private void OnTimeoutPublishersPong(object state)
    330348        {
    331             OnGuiMessage("Publisher didn't answer on Ping in the given time span!", NotificationLevel.Warning);
     349            GuiLogging("Publisher didn't answer on Ping in the given time span!", NotificationLevel.Warning);
    332350            timeoutForPublishersPong.Dispose();
    333351            timeoutForPublishersPong = null;
     
    341359        /// unregister message will be send to the publisher
    342360        /// </summary>
    343         public void Stop()
     361        public void Stop(PubSubMessageType msgType)
    344362        {
    345363            this.bolStopped = true;
    346             if (actualPublisher != null)
    347                 SendMessage(actualPublisher, PubSubMessageType.Unregister);
     364            if (actualPublisher != null && msgType != PubSubMessageType.NULL)
     365                SendMessage(actualPublisher, msgType);
    348366
    349367            #region stopping all timers, if they are still active
     
    377395            this.Started = false;
    378396        }
     397
     398        protected void GuiLogging(string sText, NotificationLevel notLev)
     399        {
     400            if (OnGuiMessage != null)
     401                OnGuiMessage(sText, notLev);
     402        }
    379403    }
    380404}
Note: See TracChangeset for help on using the changeset viewer.