Esempio n. 1
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (File.Exists(txtLuaPath.Text))
            {
                WebRequestUtility remoteUploadUtility = new WebRequestUtility("DKPHistory Client", 10000);

                try
                {
                    if (Uri.TryCreate(txtRemoteUploadUrl.Text, UriKind.Absolute, out Uri uri))
                    {
                        if (!uri.Host.Equals("example.com", StringComparison.OrdinalIgnoreCase))
                        {
                            byte[]        fileContent = File.ReadAllBytes(txtLuaPath.Text);
                            string        authString  = GenerateAuthString();
                            BpWebResponse response    = remoteUploadUtility.POST(uri.OriginalString, fileContent, "application/octet-stream", new string[] { "X-Dkp-Auth", authString });
                            if (response.StatusCode == 200 && response.str.StartsWith("1"))
                            {
                                // Upload complete
                                MessageBox.Show("Upload Complete");
                            }
                            else
                            {
                                MessageBox.Show("Unable to upload lua file to remote server. Response status: " + response.StatusCode + ", Response body: " + response.str);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Unable to parse remote upload URL. Check configuration.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("Lua file not found.");
            }
        }
        private void fileManagement()
        {
            try
            {
                string            localLuaPath            = Globals.WritableDirectoryBase + "CommunityDKP.lua";
                long              minutesWaited           = 0;
                DateTime          lastFileWrite           = DateTime.MinValue;
                long              lastLocalBackupMinutes  = -99999999;
                long              lastRemoteUploadMinutes = -99999999;
                bool              needsLocalBackup        = false;
                bool              needsRemoteUpload       = false;
                string            previousHash            = null;
                bool              firstRun            = true;
                WebRequestUtility remoteUploadUtility = new WebRequestUtility("DKPHistory Client", 10000);

                while (firstRun || !ewhThreadWaiter.WaitOne(60000))
                {
                    firstRun = false;
                    minutesWaited++;

                    string hash        = null;
                    bool   fileChanged = false;

                    if (string.IsNullOrWhiteSpace(settings.luaFilePath))
                    {
                        continue;
                    }

                    // Make local copy of file
                    try
                    {
                        lock (LuaFileLock)
                        {
                            FileInfo fiSrc = new FileInfo(settings.luaFilePath);
                            if (!fiSrc.Exists)
                            {
                                Logger.Info("Could not find CommunityDKP.lua. Check configuration.");
                                continue;
                            }
                            if (lastFileWrite != fiSrc.LastWriteTimeUtc)
                            {
                                lastFileWrite = fiSrc.LastWriteTimeUtc;
                                File.Copy(fiSrc.FullName, localLuaPath, true);

                                // Read file
                                history = History.FromLuaFile(localLuaPath);

                                // Calculate Hash Code
                                hash              = Hash.GetMD5HexOfFile(localLuaPath);
                                fileChanged       = previousHash != hash;
                                previousHash      = hash;
                                needsLocalBackup  = needsLocalBackup || fileChanged;
                                needsRemoteUpload = needsRemoteUpload || fileChanged;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex, "Error doing local file management.");
                        continue;
                    }

                    // Make local backup of lua file
                    if (needsLocalBackup &&
                        !string.IsNullOrWhiteSpace(settings.localBackupPath) &&
                        settings.localBackupIntervalMinutes > 0 &&
                        minutesWaited - lastLocalBackupMinutes >= settings.localBackupIntervalMinutes)
                    {
                        lastLocalBackupMinutes = minutesWaited;
                        needsLocalBackup       = false;
                        try
                        {
                            if (!Directory.Exists(settings.localBackupPath))
                            {
                                Directory.CreateDirectory(settings.localBackupPath);
                            }
                            if (Directory.Exists(settings.localBackupPath))
                            {
                                DateTime fileTime   = File.GetLastWriteTime(localLuaPath);
                                string   bkFileName = Path.Combine(settings.localBackupPath, "CommunityDKP-" + fileTime.ToString("yyyy-MM-dd hh-mm-ss") + ".lua");
                                if (!File.Exists(bkFileName))
                                {
                                    File.Copy(localLuaPath, bkFileName, true);
                                }
                                // Backup complete
                            }
                            else
                            {
                                Logger.Info("Could not find or create local backup path. Check configuration.");
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex, "Error doing local backup.");
                        }
                    }

                    // Perform remote upload of lua file
                    if (needsRemoteUpload &&
                        !string.IsNullOrWhiteSpace(settings.remoteUploadUrl) &&
                        settings.remoteUploadIntervalMinutes > 0 &&
                        minutesWaited - lastRemoteUploadMinutes >= settings.remoteUploadIntervalMinutes)
                    {
                        needsRemoteUpload       = false;
                        lastRemoteUploadMinutes = minutesWaited;
                        try
                        {
                            if (Uri.TryCreate(settings.remoteUploadUrl, UriKind.Absolute, out Uri uri))
                            {
                                if (!uri.Host.Equals("example.com", StringComparison.OrdinalIgnoreCase))
                                {
                                    byte[]        fileContent = File.ReadAllBytes(localLuaPath);
                                    string        authString  = GenerateAuthString();
                                    BpWebResponse response    = remoteUploadUtility.POST(settings.remoteUploadUrl, fileContent, "application/octet-stream", new string[] { "X-Dkp-Auth", authString });
                                    if (response.StatusCode == 200 && response.str.StartsWith("1"))
                                    {
                                        // Upload complete
                                    }
                                    else
                                    {
                                        Logger.Info("Unable to upload lua file to remote server. Response status: " + response.StatusCode + ", Response body: " + response.str);
                                    }
                                }
                            }
                            else
                            {
                                Logger.Info("Unable to parse remote upload URL. Check configuration.");
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex, "Error doing remote upload.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex, "File management thread suffered a critical failure!");
            }
        }
Esempio n. 3
0
        protected override void threadLoop()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        WebRequestUtility wru = new WebRequestUtility("BandwidthMonitor");
                        wru.BasicAuthCredentials = new NetworkCredential(User, Pass);
                        // Learn the http_id, used in later requests
                        BpWebResponse response          = wru.GET(Address + "ipt-realtime.asp");
                        string        ipt_realtime_page = response.str;
                        Match         m_http_id         = Regex.Match(ipt_realtime_page, "'http_id' ?: ?'([^']+)',");
                        string        http_id           = null;
                        if (m_http_id.Success)
                        {
                            http_id = m_http_id.Groups[1].Value;
                        }
                        else
                        {
                            Logger.Debug("Could not find http_id in response from ipt-realtime.asp");
                            Thread.Sleep(30000);
                            continue;
                        }

                        // Begin retrieving bandwidth usage data.
                        Stopwatch sw = new Stopwatch();
                        // Tomato's bandwidth reporting uses cumulative totals, so we need to keep track of the previous records to know how much has changed.
                        Dictionary <string, BandwidthRecord> previousRecords = new Dictionary <string, BandwidthRecord>();
                        Stopwatch swDevList = new Stopwatch();
                        response = wru.POST(Address + "update.cgi", new string[] { "exec", "devlist", "_http_id", http_id });
                        if (string.IsNullOrWhiteSpace(response.str))
                        {
                            Logger.Info("Received null or whitespace response instead of expected devlist");
                            Thread.Sleep(30000);
                            continue;
                        }
                        HandleDevListResponse(response.str);
                        swDevList.Start();
                        while (true)
                        {
                            sw.Restart();
                            long time = TimeUtil.GetTimeInMsSinceEpoch();
                            response = wru.POST(Address + "update.cgi", new string[] { "exec", "iptmon", "_http_id", http_id });
                            foreach (Match m in rxGetIpData.GetMatches(response.str))
                            {
                                string ip          = m.Groups[1].Value;
                                long   downloadRaw = Hex.PrefixedHexToLong(m.Groups[2].Value);
                                long   uploadRaw   = Hex.PrefixedHexToLong(m.Groups[3].Value);

                                DeviceInfo      device;
                                BandwidthRecord prev;

                                if (!devices.TryGetValue(ip, out device))
                                {
                                    devices[ip] = device = new DeviceInfo(ip);
                                }

                                if (!previousRecords.TryGetValue(ip, out prev))
                                {
                                    previousRecords[ip] = prev = new BandwidthRecord(time, downloadRaw, uploadRaw);
                                }

                                device.Name   = GetName(device.Address);
                                device.MAC    = GetMac(device.Address);
                                device.Vendor = GetMacVendor(device.MAC);

                                long downloadBytes;
                                long uploadBytes;
                                if (downloadRaw < prev.Download)
                                {
                                    downloadBytes = downloadRaw + (0xFFFFFFFF - prev.Download);
                                }
                                else
                                {
                                    downloadBytes = downloadRaw - prev.Download;
                                }
                                if (uploadRaw < prev.Upload)
                                {
                                    uploadBytes = uploadRaw + (0xFFFFFFFF - prev.Upload);
                                }
                                else
                                {
                                    uploadBytes = uploadRaw - prev.Upload;
                                }

                                device.AddNewBandwidthRecord(new BandwidthRecord(time, downloadBytes / 2, uploadBytes / 2));

                                previousRecords[ip] = new BandwidthRecord(time, downloadRaw, uploadRaw);
                            }
                            if (swDevList.Elapsed > timeBetweenDevListUpdates)
                            {
                                swDevList.Restart();
                                response = wru.POST(Address + "update.cgi", new string[] { "exec", "devlist", "_http_id", http_id });
                                HandleDevListResponse(response.str);
                            }
                            sw.Stop();
                            TimeSpan timeToWait = timeBetweenBandwidthUpdates - sw.Elapsed;
                            if (timeToWait > TimeSpan.Zero)
                            {
                                Thread.Sleep(timeToWait);
                            }
                        }
                    }
                    catch (ThreadAbortException) { throw; }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex);
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (ThreadAbortException) { throw; }
            catch (Exception ex)
            {
                Logger.Debug(ex);
            }
        }