Exemple #1
0
        private void LoadHeaderFile(string path, OpStorage storage, bool reload, bool working)
        {
            try
            {
                if (!File.Exists(path))
                    return;

                bool cached = Network.Routing.InCacheArea(storage.UserID);
                bool local = false;

                byte[] key = working ? LocalFileKey : storage.File.Header.FileKey;

                using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                {
                    PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                    G2Header header = null;

                    ulong currentUID = 0;

                    while (stream.ReadPacket(ref header))
                    {
                        if (!working && header.Name == StoragePacket.Root)
                        {
                            StorageRoot packet = StorageRoot.Decode(header);

                            local = Core.UserID == storage.UserID ||
                                    GetHigherRegion(Core.UserID, packet.ProjectID).Contains(storage.UserID) ||
                                    Trust.GetDownlinkIDs(Core.UserID, packet.ProjectID, 1).Contains(storage.UserID);
                        }

                        if (header.Name == StoragePacket.File)
                        {
                            StorageFile packet = StorageFile.Decode(header);

                            if (packet == null)
                                continue;

                            bool historyFile = true;
                            if (packet.UID != currentUID)
                            {
                                historyFile = false;
                                currentUID = packet.UID;
                            }

                            OpFile file = null;
                            if (!FileMap.SafeTryGetValue(packet.HashID, out file))
                            {
                                file = new OpFile(packet);
                                FileMap.SafeAdd(packet.HashID, file);
                            }

                            InternalFileMap.SafeAdd(packet.InternalHashID, file);

                            if (!reload)
                                file.References++;

                            if (!working) // if one ref is public, then whole file is marked public
                                file.Working = false;

                            if (packet.HashID == 0 || packet.InternalHash == null)
                            {
                                Debug.Assert(false);
                                continue;
                            }

                            string filepath = GetFilePath(packet.HashID);
                            file.Downloaded = File.Exists(filepath);

                            if (Loading && file.Downloaded && !ReferencedPaths.Contains(filepath))
                                ReferencedPaths.Add(filepath);

                            if (!file.Downloaded)
                            {
                                // if in local range only store latest
                                if (local && !historyFile)
                                    DownloadFile(storage.UserID, packet);

                                // if storage is in cache range, download all files
                                else if (Network.Established && cached)
                                    DownloadFile(storage.UserID, packet);
                            }

                            // on link update, if in local range, get latest files
                            // (handled by location update, when it sees a new version of storage component is available)
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Exemple #2
0
        public static InvitePackage OpenInvite(byte[] decrypted, G2Protocol protocol)
        {
            // if we get down here, opening invite was success

            MemoryStream mem = new MemoryStream(decrypted);
            PacketStream stream = new PacketStream(mem, protocol, FileAccess.Read);

            InvitePackage package = new InvitePackage();

            G2Header root = null;
            while (stream.ReadPacket(ref root))
            {
                if (root.Name == InvitePacket.Info)
                    package.Info = OneWayInvite.Decode(root);

                if (root.Name == InvitePacket.Contact)
                    package.Contacts.Add(DhtContact.ReadPacket(root));

                if (root.Name == InvitePacket.WebCache)
                    package.Caches.Add(WebCache.Decode(root));
            }

            return package;
        }
Exemple #3
0
 // ensure that key/name associations persist between runs, done so remote people dont change their name and try to play with
 // us, once we make an association with a key, we change that name on our terms, also prevents key spoofing with dupe
 // user ids
 public void SaveKeyIndex(PacketStream stream)
 {
     NameMap.LockReading(() =>
     {
         foreach (ulong user in KeyMap.Keys)
             if (NameMap.ContainsKey(user))
             {
                 Debug.Assert(NameMap[user] != null);
                 if (NameMap[user] != null)
                     stream.WritePacket(new UserInfo() { Name = NameMap[user], Key = KeyMap[user] });
             }
     });
 }
Exemple #4
0
        private void LoadUplinkReqs()
        {
            try
            {
                string path = LinkPath + Path.DirectorySeparatorChar + Utilities.CryptFilename(Core, "uplinks");

                if (!File.Exists(path))
                    return;

                using (IVCryptoStream crypto = IVCryptoStream.Load(path, LocalFileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                        if (root.Name == DataPacket.SignedData)
                        {
                            SignedData signed = SignedData.Decode(root);
                            G2Header embedded = new G2Header(signed.Data);

                            // figure out data contained
                            if (G2Protocol.ReadPacket(embedded))
                                if (embedded.Name == TrustPacket.UplinkReq)
                                    Process_UplinkReq(null, signed, UplinkRequest.Decode(embedded));
                        }
                }
            }
            catch (Exception ex)
            {
                Network.UpdateLog("Link", "Error loading links " + ex.Message);
            }
        }
Exemple #5
0
        private void Cache_FileAquired(OpVersionedFile file)
        {
            if (file.UserID != Network.Local.UserID)
                return;

            // only we can open the buddly list stored on the network
            byte[] key = Core.User.Settings.KeyPair.Decrypt(file.Header.FileKey, false);

            using (TaggedStream tagged = new TaggedStream(Cache.GetFilePath(file.Header), Network.Protocol))
            using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, key))
            {
                BuddyList.SafeClear();

                PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                G2Header root = null;

                while (stream.ReadPacket(ref root))
                    if (root.Name == BuddyPacket.Buddy)
                    {
                        OpBuddy buddy = OpBuddy.Decode(root);
                        ulong id = Utilities.KeytoID(buddy.Key);

                        Core.IndexKey(id, ref buddy.Key);
                        Core.IndexName(id, buddy.Name);

                        if(buddy.Ignored)
                            IgnoreList.SafeAdd(id, buddy);
                        else
                            BuddyList.SafeAdd(id, buddy);
                    }
            }

            Core.RunInGuiThread(GuiUpdate);
        }
Exemple #6
0
        private void RescanDiff(ulong id)
        {
            /*
             * see if uid exists in rescan map
            if file
                add to changes
            if folder
                add temp if uid doesnt exist
                set inTarget[uid], add further uids if recurse set
             */

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
                return;

            string path = Storages.GetFilePath(storage);

            if (!File.Exists(path))
                return;

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    ulong remoteUID = 0;
                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

                    List<ulong> Recursing = new List<ulong>();

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.Root)
                        {
                            StorageRoot root = StorageRoot.Decode(header);

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                // if new UID
                                if (remoteUID == folder.UID)
                                    continue;

                                remoteUID = folder.UID;

                                if (RescanFolderMap.ContainsKey(remoteUID))
                                    if (RescanFolderMap[remoteUID].Recurse)
                                        Recursing.Add(remoteUID);

                                if (Recursing.Count > 0 || RescanFolderMap.ContainsKey(remoteUID))
                                {
                                    bool added = false;

                                    while (!added)
                                    {
                                        if (currentFolder.Details.UID == folder.ParentUID)
                                        {
                                            // if folder exists with UID
                                            if (currentFolder.Folders.ContainsKey(remoteUID))
                                                currentFolder = currentFolder.Folders[remoteUID];

                                            // else add folder as temp, mark as changed
                                            else
                                                currentFolder = currentFolder.AddFolderInfo(folder, true);

                                            // diff file properties, if different, add as change
                                            if (currentFolder.Temp || Storages.ItemDiff(currentFolder.Details, folder) != StorageActions.None)
                                            {
                                                currentFolder.Changes[id] = folder;
                                                currentFolder.UpdateOverlay();
                                            }

                                            added = true;
                                        }
                                        else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        {
                                            // if current folder id equals recurse marker stop recursing
                                            if (Recursing.Contains(currentFolder.Details.UID))
                                                Recursing.Remove(currentFolder.Details.UID);

                                            currentFolder = (FolderNode)currentFolder.Parent;
                                        }
                                        else
                                            break;
                                    }
                                }
                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile file = StorageFile.Decode(header);

                                // if new UID
                                if (remoteUID == file.UID)
                                    continue;

                                remoteUID = file.UID;

                                if (Recursing.Count > 0 /*|| RescanFileMap.ContainsKey(remoteUID)*/)
                                {
                                    FileItem currentFile = null;

                                    // if file exists with UID
                                    if (currentFolder.Files.ContainsKey(remoteUID))
                                        currentFile = currentFolder.Files[remoteUID];

                                    // else add file as temp, mark as changed
                                    else
                                        currentFile = currentFolder.AddFileInfo(file, true);

                                    //crit check if file is integrated

                                    if (currentFile.Temp || Storages.ItemDiff(currentFile.Details, file) != StorageActions.None)
                                        currentFile.Changes[id] = file;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
Exemple #7
0
        public void SaveLocal()
        {
            if (Core.InvokeRequired)
            {
                Core.RunInCoreAsync(() => SaveLocal());
                return;
            }

            try
            {
                // create new link file in temp dir
                string tempPath = Core.GetTempPath();
                byte[] key = Utilities.GenerateKey(Core.StrongRndGen, 256);
                using (IVCryptoStream stream = IVCryptoStream.Save(tempPath, key))
                {
                    // project packets
                    foreach (OpLink link in LocalTrust.Links.Values)
                        if (link.Active)
                        {
                            ProjectData project = new ProjectData();
                            project.ID = link.Project;
                            project.Name = GetProjectName(link.Project);

                            if (link.Project == 0)
                                project.UserName = Core.User.Settings.UserName;

                            byte[] packet = SignedData.Encode(Network.Protocol, Core.User.Settings.KeyPair, project);
                            stream.Write(packet, 0, packet.Length);

                            // uplinks
                            if (link.Uplink != null)
                            {
                                LinkData data = new LinkData(link.Project, link.Uplink.Trust.File.Key);
                                packet = SignedData.Encode(Network.Protocol, Core.User.Settings.KeyPair, data);
                                stream.Write(packet, 0, packet.Length);
                            }

                            // downlinks
                            foreach (OpLink downlink in link.Downlinks)
                                if (link.Confirmed.Contains(downlink.UserID))
                                {
                                    string title;
                                    link.Titles.TryGetValue(downlink.UserID, out title);

                                    LinkData data = new LinkData(link.Project, downlink.Trust.File.Key, title);
                                    packet = SignedData.Encode(Network.Protocol, Core.User.Settings.KeyPair, data);
                                    stream.Write(packet, 0, packet.Length);
                                }
                        }

                    PacketStream streamEx = new PacketStream(stream, Network.Protocol, FileAccess.Write);

                    // save top 5 web caches
                    foreach (WebCache cache in Network.Cache.GetLastSeen(5))
                        streamEx.WritePacket(new WebCache(cache, TrustPacket.WebCache));

                    // save inheritable settings only if they can be inherited
                    if (IsInheritNode(Core.UserID))
                    {
                        if (Core.User.OpIcon != null)
                            streamEx.WritePacket(new IconPacket(TrustPacket.Icon, Core.User.OpIcon));

                        if (Core.User.OpSplash != null)
                        {
                            MemoryStream splash = new MemoryStream();
                            Core.User.OpSplash.Save(splash, ImageFormat.Jpeg);
                            LargeDataPacket.Write(streamEx, TrustPacket.Splash, splash.ToArray());
                        }
                    }

                    stream.WriteByte(0); // signal last packet
                    stream.FlushFinalBlock();
                }

                OpVersionedFile file = Cache.UpdateLocal(tempPath, key, null);

                Store.PublishDirect(GetLocsAbove(), Core.UserID, ServiceID, DataTypeFile, file.SignedHeader);

                SaveUplinkReqs();
            }
            catch (Exception ex)
            {
                Network.UpdateLog("LinkControl", "Error updating local " + ex.Message);
            }
        }
Exemple #8
0
        public UpdateInfo ReadUpdateInfo()
        {
            if (!File.Exists(BootstrapPath))
                return null;

            try
            {
                using (IVCryptoStream crypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey))
                {
                    PacketStream stream = new PacketStream(crypto, new G2Protocol(), FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                        if (root.Name == IdentityPacket.Update)
                            return UpdateInfo.Decode(root);
                }
            }
            catch { }

            return null;
        }
Exemple #9
0
        public void Save(OpCore core)
        {
            Debug.Assert(core.Network.IsLookup);

            try
            {
                var serializer = new XmlSerializer(typeof(PortsConfig));

                using (var writer = new StreamWriter(PortsConfigPath))
                    serializer.Serialize(writer, Ports);
            }
            catch { }

            if (core.Sim != null)
                return;

            try
            {
                // Attach to crypto stream and write file
                using (IVCryptoStream crypto = IVCryptoStream.Save(BootstrapPath, BootstrapKey))
                {
                    PacketStream stream = new PacketStream(crypto, core.Network.Protocol, FileAccess.Write);

                    if(core.Context.SignedUpdate != null)
                        stream.WritePacket(core.Context.SignedUpdate);

                    core.Network.Cache.SaveIPs(stream);
                    core.Network.Cache.SaveWeb(stream);
                }
            }

            catch (Exception ex)
            {
                core.Network.UpdateLog("Exception", "LookupSettings::Save " + ex.Message);
            }
        }
Exemple #10
0
        public void SaveWeb(PacketStream stream)
        {
            // randomize
            List<WebCache> source = new List<WebCache>(WebCaches);
            List<WebCache> randomized = new List<WebCache>();

            while (source.Count > 0)
            {
                WebCache pick = source[Core.RndGen.Next(source.Count)];
                randomized.Add(pick);
                source.Remove(pick);
            }

            foreach (WebCache cache in randomized)
                stream.WritePacket(cache);
        }
Exemple #11
0
        public void Load(DhtNetwork network)
        {
            // if the user has multiple ops, the lookup network is setup with the same settings
            // so it is easy to find and predictable for other's bootstrapping
            // we put it in local settings so we safe-guard these settings from moving to other computers
            // and having dupe dht lookup ids on the network
            try
            {
                var serializer = new XmlSerializer(typeof(PortsConfig));

                using (var reader = new StreamReader(PortsConfigPath))
                    Ports = (PortsConfig)serializer.Deserialize(reader);
            }
            catch
            {
                Ports = new PortsConfig();
            }

            if (Ports.UserID == 0 || network.Core.Sim != null)
                Ports.UserID = Utilities.StrongRandUInt64(network.Core.StrongRndGen);

            // keep tcp/udp the same by default
            if (Ports.Tcp == 0 || network.Core.Sim != null)
                Ports.Tcp = (ushort)network.Core.RndGen.Next(3000, 15000);

            if (Ports.Udp == 0 || network.Core.Sim != null)
                Ports.Udp = Ports.Tcp;

            // dont want instances saving and loading same lookup file
            if (network.Core.Sim == null && File.Exists(BootstrapPath))
            {
                try
                {
                    using (IVCryptoStream crypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey))
                    {
                        PacketStream stream = new PacketStream(crypto, network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == IdentityPacket.LookupCachedIP)
                                network.Cache.AddSavedContact(CachedIP.Decode(root));

                            if (root.Name == IdentityPacket.LookupCachedWeb)
                                network.Cache.AddWebCache(WebCache.Decode(root));
                        }
                    }
                }
                catch (Exception ex)
                {
                    network.UpdateLog("Exception", "LookupSettings::Load " + ex.Message);
                }
            }
        }
Exemple #12
0
        public void SaveIPs(PacketStream stream)
        {
            byte type = Network.IsLookup ? IdentityPacket.LookupCachedIP : IdentityPacket.OpCachedIP;

            foreach (var contact in BootstrapContacts.Values)
                stream.WritePacket(new CachedIP(type, contact, true));

            lock (IPs)
                foreach (var contact in IPs)
                    if (contact.TunnelClient == null)
                        stream.WritePacket(new CachedIP(type, contact, false));
        }
Exemple #13
0
        public void SaveLocal(uint project)
        {
            try
            {
                string tempPath = Core.GetTempPath();
                byte[] key = Utilities.GenerateKey(Core.StrongRndGen, 256);

                using (IVCryptoStream stream = IVCryptoStream.Save(tempPath, key))
                {
                    // write loaded projects
                    WorkingStorage working = null;
                    if (Working.ContainsKey(project))
                        working = Working[project];

                    if (working != null)
                    {
                        Protocol.WriteToFile(new StorageRoot(working.ProjectID), stream);
                        working.WriteWorkingFile(stream, working.RootFolder, true);

                        working.Modified = false;

                        try { File.Delete(GetWorkingPath(project)); }
                        catch { }

                    }

                    // open old file and copy entries, except for working
                    OpStorage local = GetStorage(Core.UserID);

                    if (local != null)
                    {
                        string oldPath = GetFilePath(local);

                        if (File.Exists(oldPath))
                        {
                            using (TaggedStream file = new TaggedStream(oldPath, Network.Protocol))
                            using (IVCryptoStream crypto = IVCryptoStream.Load(file, local.File.Header.FileKey))
                            {

                                PacketStream oldStream = new PacketStream(crypto, Protocol, FileAccess.Read);
                                bool write = false;
                                G2Header g2header = null;

                                while (oldStream.ReadPacket(ref g2header))
                                {
                                    if (g2header.Name == StoragePacket.Root)
                                    {
                                        StorageRoot root = StorageRoot.Decode(g2header);

                                        write = (root.ProjectID != project);
                                    }

                                    //copy packet right to new file
                                    if (write) //crit test
                                        stream.Write(g2header.Data, g2header.PacketPos, g2header.PacketSize);
                                }
                            }
                        }
                    }

                    stream.WriteByte(0); // signal last packet

                    stream.FlushFinalBlock();
                }

                SavingLocal = true; // prevents auto-integrate from re-calling saveLocal
                OpVersionedFile vfile = Cache.UpdateLocal(tempPath, key, BitConverter.GetBytes(Core.TimeNow.ToUniversalTime().ToBinary()));
                SavingLocal = false;

                Store.PublishDirect(Core.Trust.GetLocsAbove(), Core.UserID, ServiceID, FileTypeCache, vfile.SignedHeader);
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error updating local " + ex.Message);
            }

            if (StorageUpdate != null)
                Core.RunInGuiThread(StorageUpdate, GetStorage(Core.UserID));
        }
Exemple #14
0
        private void UnloadHeaderFile(string path, byte[] key)
        {
            try
            {
                if (!File.Exists(path))
                    return;

                using (TaggedStream filex = new TaggedStream(path, Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                {
                    PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                    G2Header header = null;

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.File)
                        {
                            StorageFile packet = StorageFile.Decode(header);

                            if (packet == null)
                                continue;

                            OpFile commonFile = null;
                            if (!FileMap.SafeTryGetValue(packet.HashID, out commonFile))
                                continue;

                            commonFile.DeRef();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Exemple #15
0
        public void LoadHeader(ulong id)
        {
            try
            {
                string path = GetTargetDir(id) + Path.DirectorySeparatorChar + Utilities.CryptFilename(Core, "headers" + id.ToString());

                if (!File.Exists(path))
                    return;

                using (IVCryptoStream crypto = IVCryptoStream.Load(path, LocalFileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                        if (root.Name == DataPacket.SignedData)
                        {
                            SignedData signed = SignedData.Decode(root);
                            G2Header embedded = new G2Header(signed.Data);

                            // figure out data contained
                            if (G2Protocol.ReadPacket(embedded))
                                if (embedded.Name == BoardPacket.PostHeader)
                                    Process_PostHeader(null, signed, PostHeader.Decode(embedded));
                        }
                }
            }
            catch(Exception ex)
            {
                Network.UpdateLog("Board", "Could not load header " + id.ToString() + ": " + ex.Message);
            }
        }
Exemple #16
0
        public void WriteUpdateInfo(OpCore core)
        {
            // non lookup core, embedding update packet
            Debug.Assert(!core.Network.IsLookup);

            string temp = Path.Combine(StartupPath, "temp.dat");

            try
            {
                using (IVCryptoStream inCrypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey))
                using (IVCryptoStream outCrypto = IVCryptoStream.Save(temp, BootstrapKey))
                {
                    byte[] update = core.Context.SignedUpdate.Encode(core.Network.Protocol);
                    outCrypto.Write(update, 0, update.Length);

                    PacketStream inStream = new PacketStream(inCrypto, core.Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (inStream.ReadPacket(ref root))
                        if (root.Name != IdentityPacket.Update)
                            outCrypto.Write(root.Data, root.PacketPos, root.PacketSize);
                }

                File.Copy(temp, BootstrapPath, true);
                File.Delete(temp);
            }

            catch (Exception ex)
            {
                core.Network.UpdateLog("Exception", "WriteUpdateInfo::" + ex.Message);
            }
        }
Exemple #17
0
        private void LoadHeader(string path, byte[] key)
        {
            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, key))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.Root)
                        {
                            StorageRoot root = StorageRoot.Decode(header);

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        // show archived if selected, only add top uid, not copies

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                bool added = false;

                                while (!added)
                                {
                                    if (currentFolder.Details.UID == folder.ParentUID)
                                    {
                                        currentFolder = currentFolder.AddFolderInfo(folder, false);

                                        // re-select on re-load
                                        if (SelectedFolder != null && currentFolder.Details.UID == SelectedFolder.Details.UID)
                                        {
                                            currentFolder.Selected = true;
                                            SelectedFolder = currentFolder;
                                        }

                                        added = true;
                                    }
                                    else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        currentFolder = (FolderNode)currentFolder.Parent;
                                    else
                                        break;
                                }

                                if (!added)
                                {
                                    Debug.Assert(false);
                                    throw new Exception("Error loading CFS");
                                }
                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile file = StorageFile.Decode(header);

                                currentFolder.AddFileInfo(file, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading files " + ex.Message);
            }
        }
Exemple #18
0
        public void Load(LoadModeType loadMode)
        {
            RijndaelManaged Password = new RijndaelManaged();
            Password.Key = PasswordKey;

            byte[] iv = new byte[16];
            byte[] salt = new byte[4];

            OpCore lookup = null;
            if (Core != null)
                lookup = Core.Context.Lookup;

            try
            {
                using (TaggedStream file = new TaggedStream(ProfilePath, Protocol, ProcessSplash)) // tagged with splash
                {
                    // first 16 bytes IV, next 4 bytes is salt
                    file.Read(iv, 0, 16);
                    file.Read(salt, 0, 4);
                    Password.IV = iv;

                    using (CryptoStream crypto = new CryptoStream(file, Password.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                        G2Header root = null;
                        while (stream.ReadPacket(ref root))
                        {
                            if (loadMode == LoadModeType.Settings)
                            {
                                if (root.Name == IdentityPacket.OperationSettings)
                                    Settings = SettingsPacket.Decode(root);

                                if (root.Name == IdentityPacket.UserInfo && Core != null &&
                                    (Core.Sim == null || !Core.Sim.Internet.FreshStart))
                                    Core.IndexInfo(UserInfo.Decode(root));

                                // save icon to identity file because only root node saves icon/splash to link file
                                // to minimize link file size, but allow user to set custom icon/splash if there are not overrides
                                if (root.Name == IdentityPacket.Icon)
                                    OpIcon = IconPacket.Decode(root).OpIcon;
                            }

                            if (lookup != null && (loadMode == LoadModeType.AllCaches || loadMode == LoadModeType.LookupCache))
                            {
                                if (root.Name == IdentityPacket.LookupCachedIP)
                                    lookup.Network.Cache.AddSavedContact(CachedIP.Decode(root));

                                if (root.Name == IdentityPacket.LookupCachedWeb)
                                    lookup.Network.Cache.AddWebCache(WebCache.Decode(root));
                            }

                            if (loadMode == LoadModeType.AllCaches)
                            {
                                if (root.Name == IdentityPacket.OpCachedIP)
                                    Core.Network.Cache.AddSavedContact(CachedIP.Decode(root));

                                if (root.Name == IdentityPacket.OpCachedWeb)
                                    Core.Network.Cache.AddWebCache(WebCache.Decode(root));
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
Exemple #19
0
        private void ApplyDiff(ulong id)
        {
            // change log - who / not

            // read file uid

                // if exists locally
                    // if integrated mark as so
                    // else mark as changed, run history diff, and use last note

                // if doesnt exist
                    // add file as a temp
                    // user does - add to storage, to add it

                // if remote doesnt have any record of local file, ignore

            ChangeCount[id] = 0;

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
            {
                FailedDiffs.Add(id);
                return;
            }

            string path = Storages.GetFilePath(storage);

            if (!File.Exists(path))
            {
                FailedDiffs.Add(id);
                return;
            }

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Storages.Protocol, FileAccess.Read);

                    ulong remoteUID = 0;
                    FolderNode currentFolder = RootFolder;
                    bool readingProject = false;

                    G2Header header = null;

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.Root)
                        {
                            StorageRoot root = StorageRoot.Decode(header);

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                // if new UID
                                if (remoteUID == folder.UID)
                                    continue;

                                remoteUID = folder.UID;

                                // check scope
                                bool ignore = false;
                                if (folder.Scope.Count > 0 && !Trust.IsInScope(folder.Scope, UserID, ProjectID))
                                    ignore = true;

                                bool added = false;

                                while (!added)
                                {
                                    if (currentFolder.Details.UID == folder.ParentUID)
                                    {
                                        // if folder exists with UID
                                        if (currentFolder.Folders.ContainsKey(remoteUID))
                                            currentFolder = currentFolder.Folders[remoteUID];

                                        // else add folder as temp, mark as changed
                                        else
                                        {
                                            if (ignore) // temp so traverse works, but not saved in structure
                                            {
                                                currentFolder = new FolderNode(this, folder, currentFolder, false);
                                                break;
                                            }
                                            else
                                                currentFolder = currentFolder.AddFolderInfo(folder, true);
                                        }

                                        bool found = false;

                                        currentFolder.Archived.LockReading(delegate()
                                        {
                                            foreach (StorageFolder archive in currentFolder.Archived)
                                                if (Storages.ItemDiff(archive, folder) == StorageActions.None)
                                                    if (archive.Date == folder.Date)
                                                    {
                                                        found = true;
                                                        break;
                                                    }
                                        });

                                        if (!found)
                                        {
                                            currentFolder.Changes[id] = folder;
                                            currentFolder.UpdateOverlay();
                                        }

                                        // diff file properties, if different, add as change
                                        /*if (currentFolder.Temp || Storages.ItemDiff(currentFolder.Details, folder) != StorageActions.None)
                                        {
                                            currentFolder.Changes[id] = folder;
                                            currentFolder.UpdateOverlay();
                                        }*/

                                        added = true;
                                    }
                                    else if (currentFolder.Parent.GetType() == typeof(FolderNode))
                                        currentFolder = (FolderNode)currentFolder.Parent;
                                    else
                                        break;
                                }
                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile file = StorageFile.Decode(header);

                                // if new UID
                                if (remoteUID == file.UID)
                                    continue;

                                remoteUID = file.UID;

                                // check scope
                                if (file.Scope.Count > 0 && !Trust.IsInScope(file.Scope, UserID, ProjectID))
                                    continue;

                                FileItem currentFile = null;

                                // if file exists with UID
                                if (currentFolder.Files.ContainsKey(remoteUID))
                                    currentFile = currentFolder.Files[remoteUID];

                                // else add file as temp, mark as changed
                                else
                                    currentFile = currentFolder.AddFileInfo(file, true);

                                // if file is integrated, still add, so that reject functions

                                // true if file doesnt exist in local file history
                                // if it does exist and file is newer than latest, true

                                bool found = false;

                                currentFile.Archived.LockReading(delegate()
                                {
                                    foreach (StorageFile archive in currentFile.Archived)
                                        if (Storages.ItemDiff(archive, file) == StorageActions.None)
                                            if (archive.Date == file.Date)
                                            {
                                                found = true;
                                                break;
                                            }
                                });

                                if (!found)
                                    currentFile.Changes[id] = file;
                            }
                        }
                    }
                }
            }
            catch
            {
                FailedDiffs.Add(id);
            }
        }
Exemple #20
0
        public void Save()
        {
            if (Core != null && Core.InvokeRequired)
            {
                Debug.Assert(false);
                Core.RunInCoreAsync(() => Save());
                return;
            }

            string backupPath = ProfilePath.Replace(".dop", ".bak");

            if( !File.Exists(backupPath) && File.Exists(ProfilePath))
                File.Copy(ProfilePath, backupPath, true);

            RijndaelManaged Password = new RijndaelManaged();
            Password.Key = PasswordKey;

            try
            {
                // Attach to crypto stream and write file
                string tempPath = TempPath + Path.DirectorySeparatorChar + "firstsave";
                if (Core != null)
                    tempPath = Core.GetTempPath();

                using (FileStream file = new FileStream(tempPath, FileMode.Create))
                {
                    // write encrypted part of file
                    Password.GenerateIV();
                    file.Write(Password.IV, 0, Password.IV.Length);
                    file.Write(PasswordSalt, 0, PasswordSalt.Length);

                    using (CryptoStream crypto = new CryptoStream(file, Password.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Write);

                        stream.WritePacket(Settings);

                        if (Core != null)
                        {
                            if (Core.Context.Lookup != null)
                            {
                                Core.Context.Lookup.Network.Cache.SaveIPs(stream);
                                Core.Context.Lookup.Network.Cache.SaveWeb(stream);
                            }

                            Core.Network.Cache.SaveIPs(stream);
                            Core.Network.Cache.SaveWeb(stream);

                            Core.SaveKeyIndex(stream);
                        }

                        if (OpIcon != null)
                            stream.WritePacket(new IconPacket(IdentityPacket.Icon, OpIcon));
                    }
                }

                // write unencrypted splash
                using (FileStream file = new FileStream(tempPath, FileMode.Open))
                {
                    file.Seek(0, SeekOrigin.End);

                    long startpos = file.Position;

                    PacketStream stream = new PacketStream(file, Protocol, FileAccess.Write);

                    // get right splash image (only used for startup logo, main setting is in link file)
                    if (OpSplash != null)
                    {
                        MemoryStream mem = new MemoryStream();
                        OpSplash.Save(mem, ImageFormat.Jpeg);
                        LargeDataPacket.Write(stream, IdentityPacket.Splash, mem.ToArray());
                    }
                    else
                        LargeDataPacket.Write(stream, IdentityPacket.Splash, null);

                    file.WriteByte(0); // end packet stream

                    byte[] last = BitConverter.GetBytes(startpos);
                    file.Write(last, 0, last.Length);
                }

                File.Copy(tempPath, ProfilePath, true);
                File.Delete(tempPath);
            }

            catch (Exception ex)
            {
                if (Core != null)
                    Core.ConsoleLog("Exception Identity::Save() " + ex.Message);
                else
                    Core.UserMessage("Profile Save Error:\n" + ex.Message + "\nBackup Restored");

                // restore backup
                if (File.Exists(backupPath))
                    File.Copy(backupPath, ProfilePath, true);
            }

            File.Delete(backupPath);
        }
Exemple #21
0
        private void Cache_FileAquired(OpVersionedFile cachefile)
        {
            try
            {
                // get link directly, even if in unloaded state we need the same reference
                OpTrust trust = null;
                TrustMap.SafeTryGetValue(cachefile.UserID, out trust);

                if (trust == null)
                {
                    trust = new OpTrust(cachefile);
                    TrustMap.SafeAdd(cachefile.UserID, trust);
                }
                else
                    trust.File = cachefile;

                // clean roots, if link has loopID, remove loop node entirely, it will be recreated if needed later
                ProjectRoots.LockReading(delegate()
                {
                    foreach (uint project in ProjectRoots.Keys)
                    {
                        OpLink link = trust.GetLink(project);

                        if (link == null)
                            continue;

                        ThreadedList<OpLink> roots = ProjectRoots[project];

                        roots.SafeRemove(link);

                        // remove loop node
                        if (link.LoopRoot != null)
                            roots.LockReading(delegate()
                            {
                                foreach (OpLink root in roots)
                                    if (root.UserID == link.LoopRoot.UserID)
                                    {
                                        roots.SafeRemove(root); // root is a loop node

                                        // remove associations with loop node
                                        foreach (OpLink downlink in root.Downlinks)
                                            downlink.LoopRoot = null;

                                        break;
                                    }
                            });
                    }
                });

                trust.Reset();

                // load data from link file
                string inheritName = null;
                string inheritOp = null;
                Bitmap inheritIcon = null;
                byte[] inheritSplash = null;

                using (TaggedStream file = new TaggedStream(Cache.GetFilePath(cachefile.Header), Network.Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(file, cachefile.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header packetRoot = null;

                    while (stream.ReadPacket(ref packetRoot))
                    {
                        if (packetRoot.Name == DataPacket.SignedData)
                        {
                            SignedData signed = SignedData.Decode(packetRoot);
                            G2Header embedded = new G2Header(signed.Data);

                            // figure out data contained
                            if (G2Protocol.ReadPacket(embedded))
                            {
                                if (embedded.Name == TrustPacket.ProjectData)
                                {
                                    ProjectData project = ProjectData.Decode(embedded);
                                    Process_ProjectData(trust, signed, project);

                                    if (project.ID == 0)
                                    {
                                        inheritName = project.UserName;
                                        inheritOp = project.Name;
                                    }
                                }

                                else if (embedded.Name == TrustPacket.LinkData)
                                    Process_LinkData(trust, signed, LinkData.Decode(embedded));
                            }
                        }

                        else if (packetRoot.Name == TrustPacket.WebCache)
                            Network.Cache.AddWebCache(WebCache.Decode(packetRoot));

                        else if (packetRoot.Name == TrustPacket.Icon)
                            inheritIcon = IconPacket.Decode(packetRoot).OpIcon;

                        else if (packetRoot.Name == TrustPacket.Splash)
                        {
                            LargeDataPacket splash = LargeDataPacket.Decode(packetRoot);

                            if (splash.Size > 0)
                                inheritSplash = LargeDataPacket.Read(splash, stream, TrustPacket.Splash);
                        }
                    }
                }

                // set new header
                trust.Loaded = true;

                // set as root if node has no uplinks
                foreach (OpLink link in trust.Links.Values)
                    if (link.Uplink == null)
                        AddRoot(link);
                    // if uplink is unknown - process link data will search for the unknown parent

                // if loop created, create new loop node with unique ID, assign all nodes in loop the ID and add as downlinks
                foreach (OpLink link in trust.Links.Values)
                    if (IsLooped(link))
                    {
                        uint project = link.Project;

                        OpLink loop = new OpTrust(project, (ulong)Core.RndGen.Next()).GetLink(project);
                        loop.IsLoopRoot = true;

                        List<ulong> uplinks = GetUnconfirmedUplinkIDs(trust.UserID, project);
                        uplinks.Add(trust.UserID);

                        foreach (ulong uplink in uplinks)
                        {
                            OpLink member = GetLink(uplink, project);

                            if (member == null)
                                continue;

                            member.LoopRoot = loop;

                            loop.Downlinks.Add(member);
                            loop.Confirmed.Add(member.UserID); //needed for getlowers
                        }

                        AddRoot(loop);
                    }

                trust.CheckRequestVersions();

                if (LinkUpdate != null)
                    LinkUpdate.Invoke(trust);

                if (Core.NewsWorthy(trust.UserID, 0, false))
                    Core.MakeNews(ServiceIDs.Trust, "Trust updated by " + Core.GetName(trust.UserID), trust.UserID, 0, true);

                // update subs
                if (Network.Established)
                {
                    List<LocationData> locations = new List<LocationData>();

                    ProjectRoots.LockReading(delegate()
                    {
                        foreach (uint project in ProjectRoots.Keys)
                            if (Core.UserID == trust.UserID || IsHigher(trust.UserID, project))
                                GetLocsBelow(Core.UserID, project, locations);
                    });

                    Store.PublishDirect(locations, trust.UserID, ServiceID, 0, cachefile.SignedHeader);
                }

                // inherit local settings
                if(Core.UserID == trust.UserID)
                {
                    if (inheritName != null)
                        Core.User.Settings.UserName = inheritName;
                }

                // inherit settings from highest node, first node in loop
                if (IsInheritNode(trust.UserID))
                {
                    if (inheritOp != null)
                        Core.User.Settings.Operation = inheritOp;

                    if (inheritIcon != null)
                    {
                        Core.User.OpIcon = inheritIcon;
                        Core.User.IconUpdate();
                    }

                    if (inheritSplash != null)
                        Core.User.OpSplash = (Bitmap)Bitmap.FromStream(new MemoryStream(inheritSplash));
                    else
                        Core.User.OpSplash = null;
                }

                // update interface node
                Core.RunInGuiThread(GuiUpdate, trust.UserID);

                foreach (OpLink link in trust.Links.Values)
                    foreach (OpLink downlink in link.Downlinks)
                        Core.RunInGuiThread(GuiUpdate, downlink.UserID);

            }
            catch (Exception ex)
            {
                Network.UpdateLog("Link", "Error loading file " + ex.Message);
            }
        }
Exemple #22
0
 void ProcessSplash(PacketStream stream)
 {
     G2Header root = null;
     if (stream.ReadPacket(ref root))
         if (root.Name == IdentityPacket.Splash)
         {
             LargeDataPacket start = LargeDataPacket.Decode(root);
             if (start.Size > 0)
             {
                 byte[] data = LargeDataPacket.Read(start, stream, IdentityPacket.Splash);
                 OpSplash = (Bitmap)Bitmap.FromStream(new MemoryStream(data));
             }
         }
 }
Exemple #23
0
        public void SaveLocal()
        {
            // create temp, write buddy list
            string tempPath = Core.GetTempPath();
            byte[] key = Utilities.GenerateKey(Core.StrongRndGen, 256);
            using (IVCryptoStream crypto = IVCryptoStream.Save(tempPath, key))
            {
                PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Write);

                BuddyList.LockReading(() =>
                {
                    foreach (OpBuddy buddy in BuddyList.Values)
                        stream.WritePacket(buddy);
                });

                IgnoreList.LockReading(() => // we need to ensure we have name/key for each ignore
                {
                    foreach (OpBuddy ignore in IgnoreList.Values)
                        stream.WritePacket(ignore);
                });
            }

            byte[] publicEncryptedKey = Core.User.Settings.KeyPair.Encrypt(key, false); //private key required to decrypt buddy list

            Cache.UpdateLocal(tempPath, publicEncryptedKey, null);
        }
Exemple #24
0
        private void LoadWorking()
        {
            OpStorage local = Storages.GetStorage(Core.UserID);

            if (local == null)
                return;

            // load working
            try
            {
                string path = Storages.GetWorkingPath(ProjectID);
                byte[] key = Storages.LocalFileKey;

                if (File.Exists(path)) // use locally committed storage file
                {
                    Modified = true; // working file present on startup, meaning there are changes lingering to be committed
                }
                else
                {
                    path = Storages.GetFilePath(local);

                    if (!File.Exists(path))
                        return;

                    key = local.File.Header.FileKey;
                }

                using (TaggedStream source = new TaggedStream(path, Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(source, key))
                {
                    PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                    G2Header header = null;
                    bool readingProject = false;

                    LocalFolder CurrentFolder = RootFolder;
                    string CurrentPath = RootPath;

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.Root)
                        {
                            StorageRoot root = StorageRoot.Decode(header);

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder folder = StorageFolder.Decode(header);

                                bool added = false;

                                while (!added)
                                {
                                    if (CurrentFolder.Info.UID == folder.ParentUID)
                                    {
                                        // tracked, so need to add multiple folders (archives) with same UIDs
                                        CurrentFolder = CurrentFolder.AddFolderInfo(folder);

                                        added = true;
                                    }
                                    else if (CurrentFolder.Parent == null) // error
                                        break;
                                    else if (CurrentFolder.Parent.GetType() == typeof(LocalFolder))
                                        CurrentFolder = CurrentFolder.Parent;
                                    else
                                        break;
                                }

                                if (!added)
                                {
                                    Debug.Assert(false);
                                    throw new Exception("Error loading CFS");
                                }
                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile file = StorageFile.Decode(header);

                                CurrentFolder.AddFileInfo(file);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("Storage", "Error loading headers " + ex.Message);
            }
        }
Exemple #25
0
        void Init(string path, G2Protocol protocol, ProcessTagsHandler processTags)
        {
            Seek(-8, SeekOrigin.End);

            byte[] sizeBytes = new byte[8];
            Read(sizeBytes, 0, sizeBytes.Length);
            long fileSize = BitConverter.ToInt64(sizeBytes, 0);

            if (processTags != null)
            {
                // read public packets
                Seek(fileSize, SeekOrigin.Begin);

                PacketStream stream = new PacketStream(this, protocol, FileAccess.Read);

                // dont need to close packetStream
                processTags.Invoke(stream);
            }

            // set public size down here so reading packet stream works without mixing up true file lenght
            InternalSize = fileSize;

            // set back to the beginning of the file
            Seek(0, SeekOrigin.Begin);
        }
Exemple #26
0
        public bool RefreshHigherChanges(ulong id)
        {
            // first remove changes from this id
            RemoveHigherChanges(RootFolder, id);

            bool save = false;

            OpStorage storage = Storages.GetStorage(id);

            if (storage == null)
                return save;

            // this is the first step in auto-integration
            // go through this id's storage file, and add any changes or updates to our own system
            string path = Storages.GetFilePath(storage);

            if (!File.Exists(path))
                return save;

            try
            {
                using (TaggedStream filex = new TaggedStream(path, Protocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(filex, storage.File.Header.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read);

                    ulong currentUID = 0;
                    LocalFolder currentFolder = RootFolder;
                    LocalFile currentFile = null;
                    bool ignoreCurrent = false;
                    bool readingProject = false;

                    G2Header header = null;

                    while (stream.ReadPacket(ref header))
                    {
                        if (header.Name == StoragePacket.Root)
                        {
                            StorageRoot root = StorageRoot.Decode(header);

                            readingProject = (root.ProjectID == ProjectID);
                        }

                        if (readingProject)
                        {
                            if (header.Name == StoragePacket.Folder)
                            {
                                StorageFolder readFolder = StorageFolder.Decode(header);

                                // if new uid
                                if (currentUID != readFolder.UID)
                                {
                                    // if only 1 entry in changes for previous file, remove it, its probably a dupe of local
                                    // and integration needs more than one file to happen
                                    if (currentFolder.HigherChanges.ContainsKey(id) && currentFolder.HigherChanges[id].Count == 1)
                                        currentFolder.HigherChanges.Remove(id);

                                    // set new id
                                    currentUID = readFolder.UID;

                                    // check scope
                                    ignoreCurrent = false;
                                    if (readFolder.Scope.Count > 0 && !Core.Trust.IsInScope(readFolder.Scope, Core.UserID, ProjectID))
                                        ignoreCurrent = true;

                                    bool added = false;

                                    while (!added)
                                    {
                                        if (currentFolder.Info.UID == readFolder.ParentUID)
                                        {
                                            LocalFolder subFolder = null;
                                            if (currentFolder.Folders.SafeTryGetValue(currentUID, out subFolder))
                                                currentFolder = subFolder;

                                            else
                                            {
                                                // if ignoring, add folder so we can traverse id's file, but dont save changes to local storage mapping
                                                if (ignoreCurrent)
                                                {
                                                    currentFolder = new LocalFolder(currentFolder, readFolder);
                                                    break;
                                                }

                                                // check for conflicting name
                                                currentFolder.Folders.LockReading(delegate()
                                                {
                                                    foreach (LocalFolder subfolder in currentFolder.Folders.Values)
                                                        if (!subfolder.Info.IsFlagged(StorageFlags.Archived) && subfolder.Info.Name == readFolder.Name)
                                                            subfolder.Info.Name = subfolder.Info.Name + ".fix";
                                                });

                                                // if not found, create folder
                                                currentFolder = currentFolder.AddFolderInfo(readFolder);
                                                save = true;
                                            }

                                            added = true;
                                        }

                                        else if (currentFolder.Parent == null)
                                            break; // error, couldn't find parent of folder that was read

                                        else if (currentFolder.Parent.GetType() == typeof(LocalFolder))
                                            currentFolder = currentFolder.Parent;

                                        else
                                            break;
                                    }
                                }

                                // if file does not equal null
                                if (currentFolder != null && !ignoreCurrent)
                                {
                                    // log change if file newer than ours
                                    // if if not in higher's history
                                    // or if file integrated by higher by a node we would have inherited from

                                    // we look for our own file in higher changes, if there then we can auto integrate

                                    if (readFolder.Date >= currentFolder.Info.Date)
                                        if (readFolder.IntegratedID == 0 ||
                                            readFolder.IntegratedID == Core.UserID ||
                                            Core.Trust.IsAdjacent(readFolder.IntegratedID, ProjectID))
                                            currentFolder.AddHigherChange(id, readFolder);
                                }

                            }

                            if (header.Name == StoragePacket.File)
                            {
                                StorageFile readFile = StorageFile.Decode(header);

                                // if new uid
                                if (currentUID != readFile.UID)
                                {
                                    // if only 1 entry in changes for previous file, remove it, its probably a dupe of local
                                    // and integration needs more than one file to happen
                                    if (currentFile != null && currentFile.HigherChanges.ContainsKey(id) && currentFile.HigherChanges[id].Count == 1)
                                        currentFile.HigherChanges.Remove(id);

                                    // set new id
                                    currentUID = readFile.UID;

                                    currentFile = null;

                                    // check scope
                                    ignoreCurrent = false;
                                    if (readFile.Scope.Count > 0 && !Core.Trust.IsInScope(readFile.Scope, Core.UserID, ProjectID))
                                    {
                                        ignoreCurrent = true;
                                        continue;
                                    }

                                    // if file exists with UID, else add file as temp, mark as changed
                                    if (!currentFolder.Files.SafeTryGetValue(currentUID, out currentFile))
                                    {
                                        // check for conflicting name
                                        currentFolder.Files.LockReading(delegate()
                                        {
                                            foreach (LocalFile checkFile in currentFolder.Files.Values)
                                                if (!checkFile.Info.IsFlagged(StorageFlags.Archived) && checkFile.Info.Name == readFile.Name)
                                                    checkFile.Info.Name = checkFile.Info.Name + ".fix";
                                        });

                                        currentFile = currentFolder.AddFileInfo(readFile);
                                        save = true;

                                        if (!Storages.FileExists(currentFile.Info))
                                            Storages.DownloadFile(id, currentFile.Info);
                                    }
                                }

                                // if file does not equal null
                                if (currentFile != null && !ignoreCurrent)
                                {
                                    if (readFile.Date >= currentFile.Info.Date)
                                        if (readFile.IntegratedID == 0 ||
                                            readFile.IntegratedID == Core.UserID ||
                                            Core.Trust.IsAdjacent(readFile.IntegratedID, ProjectID))
                                            currentFile.AddHigherChange(id, readFile);
                                }

                            }
                        }
                    }
                }
            }
            catch
            {

            }

            return save;
        }
Exemple #27
0
        public string GenerateInvite(string pubLink, out string name)
        {
            IdentityLink ident = IdentityLink.Decode(pubLink);

            // dont check opID, because invites come from different ops

            name = ident.Name;

            // deops://firesoft/invite/person@GlobalIM/originalopID~invitedata {op key web caches ips}

            string link = string.Format("deops://{0}/invite/{1}@{2}/",
                            HttpUtility.UrlEncode(User.Settings.Operation),
                            HttpUtility.UrlEncode(ident.Name),
                            HttpUtility.UrlEncode(ident.OpName));

            // encode invite info in user's public key
            byte[] data = new byte[4096];
            MemoryStream mem = new MemoryStream(data);
            PacketStream stream = new PacketStream(mem, GuiProtocol, FileAccess.Write);

            // write invite
            OneWayInvite invite = new OneWayInvite();
            invite.UserName = ident.Name;
            invite.OpName = User.Settings.Operation;
            invite.OpAccess = User.Settings.OpAccess;
            invite.OpID = User.Settings.OpKey;

            stream.WritePacket(invite);

            // write some contacts
            foreach (DhtContact contact in Network.Routing.GetCacheArea())
            {
                byte[] bytes = contact.Encode(GuiProtocol, InvitePacket.Contact);
                mem.Write(bytes, 0, bytes.Length);
            }

            // write web caches
            foreach (WebCache cache in Network.Cache.GetLastSeen(3))
                stream.WritePacket(new WebCache(cache, InvitePacket.WebCache));

            mem.WriteByte(0); // end packets

            byte[] packets = Utilities.ExtractBytes(data, 0, (int)mem.Position);
            byte[] encrypted = Utilities.KeytoRsa(ident.PublicKey).Encrypt(packets,false);

            // ensure that this link is opened from the original operation remote's public key came from
            byte[] final = Utilities.CombineArrays(ident.PublicOpID, encrypted);

            return link + Utilities.BytestoHex(final);
        }
Exemple #28
0
        public string GetPostTitle(OpPost post)
        {
            // loads info when first demanded, cached afterwards
            if (post.Info == null)
                try
                {
                    string path = GetPostPath(post.Header);
                    if (!File.Exists(path))
                        return "";

                    post.Attached = new List<PostFile>();

                    using (TaggedStream file = new TaggedStream(path, Network.Protocol))
                    using (IVCryptoStream crypto = IVCryptoStream.Load(file, post.Header.FileKey))
                    {
                        PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                        G2Header root = null;

                        while (stream.ReadPacket(ref root))
                        {
                            if (root.Name == BoardPacket.PostInfo)
                                post.Info = PostInfo.Decode(root);

                            else if (root.Name == BoardPacket.PostFile)
                                post.Attached.Add(PostFile.Decode(root));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Network.UpdateLog("Board", "Could not load post " + post.Header.SourceID.ToString() + ": " + ex.Message);
                }

            if (post.Info == null)
                return "";

            if (post.Header.ParentID == 0)
                return post.Info.Subject;
            else
                return post.Info.Quip;
        }
Exemple #29
0
        public void LoadHeaders()
        {
            List<string> goodPaths = new List<string>();

            try
            {
                goodPaths.Add(HeaderPath);

                if (!File.Exists(HeaderPath))
                    return;

                using (IVCryptoStream crypto = IVCryptoStream.Load(HeaderPath, LocalKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                        if (root.Name == DataPacket.SignedData)
                        {
                            SignedData signed = SignedData.Decode(root);
                            G2Header embedded = new G2Header(signed.Data);

                            // figure out data contained
                            if (G2Protocol.ReadPacket(embedded))
                                if (embedded.Name == DataPacket.VersionedFile)
                                {
                                    VersionedFileHeader header = VersionedFileHeader.Decode(embedded);

                                    if(header.FileHash != null)
                                        goodPaths.Add(GetFilePath(header));

                                    Process_VersionedFile(null, signed, header);
                                }
                        }
                }

                // remove loose files
                foreach (string testPath in Directory.GetFiles(CachePath))
                    if (!goodPaths.Contains(testPath))
                        try { File.Delete(testPath); }
                        catch { }
            }
            catch (Exception ex)
            {
                Core.Network.UpdateLog("VersionedFile", "Error loading data " + ex.Message);
            }
        }
Exemple #30
0
        private void LoadHeaders()
        {
            List<string> goodPaths = new List<string>();

            // load shared file lists

            try
            {
                goodPaths.Add(HeaderPath);

                if (!File.Exists(HeaderPath))
                    return;

                using (IVCryptoStream crypto = IVCryptoStream.Load(HeaderPath, Core.User.Settings.FileKey))
                {
                    PacketStream stream = new PacketStream(crypto, Network.Protocol, FileAccess.Read);

                    G2Header root = null;

                    while (stream.ReadPacket(ref root))
                        if (root.Name == SharePacket.Collection)
                        {
                            ShareCollection copy = ShareCollection.Decode(root, Core.UserID);
                            //crit - ensure public path exists before loading up
                            Local.Hash = copy.Hash;
                            Local.Size = copy.Size;
                            Local.Key = copy.Key;
                        }
                        else if (root.Name == SharePacket.File)
                        {
                            SharedFile file = SharedFile.Decode(root, Core.Network.Local.ClientID);

                            if (file.SystemPath != null && !File.Exists(GetFilePath(file)))
                                file.SystemPath = null;

                            file.FileID = OpTransfer.GetFileID(ServiceID, file.Hash, file.Size);

                            if (File.Exists(GetFilePath(file)))
                            {
                                file.Completed = true;
                                file.Sources.Add(Core.Network.Local);
                            }

                            // incomplete, ensure partial file is saved into next run if need be
                            else
                            {
                                foreach (OpTransfer partial in Core.Transfers.Partials.Where(p => p.FileID == file.FileID))
                                    partial.SavePartial = true;
                            }

                            file.FileStatus = file.Completed ? "Secured" : "Incomplete";

                            Local.Files.SafeAdd(file);

                            // unhashed files aren't saved anymore
                            /* if app previous closed without hashing share, hash now
                            if (share.Hash == null && share.SystemPath != null &&
                                File.Exists(share.SystemPath))
                                ProcessFileShare(share);*/
                        }
                }

                // clears most of files in direcotry, others shared public lists are not persisted between runs
                foreach (string testPath in Directory.GetFiles(SharePath))
                    if (!goodPaths.Contains(testPath))
                        try { File.Delete(testPath); }
                        catch { }
            }
            catch (Exception ex)
            {
                Network.UpdateLog("VersionedFile", "Error loading data " + ex.Message);
            }
        }