Exemplo n.º 1
0
 private static void ReconnectElapsed(object sender, ElapsedEventArgs e)
 {
     try
     {
         string s = Wsa.Ping();
         if (s == "OK")
         {
             ReconnectTimer.Stop();
             MainForm.LogMessageToFile("Reconnecting...");
             if (MainForm.Conf.ServicesEnabled)
             {
                 try
                 {
                     s = Connect(MainForm.Conf.Loopback);
                     if (s == "OK")
                     {
                         MainForm.StopAndStartServer();
                         ForceSync(MainForm.IPAddress, MainForm.Conf.LANPort, MainForm.MWS.GetObjectList());
                     }
                     WebsiteLive = true;
                     MainForm.LogMessageToFile("Connected");
                 }
                 catch (Exception ex)
                 {
                     MainForm.LogExceptionToFile(ex);
                     ReconnectTimer.Start();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MainForm.LogExceptionToFile(ex);
     }
 }
Exemplo n.º 2
0
        private static bool SendHTTPReq(string source, string cookies, string login, string password)
        {
            bool           b  = false;
            HttpStatusCode sc = 0;

            HttpWebRequest req;
            var            res = ConnectionFactory.GetResponse(source, cookies, login, password, out req);

            if (res != null)
            {
                sc = res.StatusCode;
                if (sc == HttpStatusCode.OK)
                {
                    string ct = res.ContentType.ToLower();
                    if (ct.IndexOf("text", StringComparison.Ordinal) == -1)
                    {
                        b = true;
                    }
                }
                res.Close();
            }

            MainForm.LogMessageToFile("Status " + sc + " at " + source, "Uri Checker");

            return(b);
        }
Exemplo n.º 3
0
        public static string SendTweet(string message)
        {
            if (!MainForm.Conf.ServicesEnabled)
            {
                return(WebservicesDisabledMessage);
            }
            string r = "";

            if (WebsiteLive)
            {
                try
                {
                    r = Wsa.SendTweet(MainForm.Conf.WSUsername, MainForm.Conf.WSPassword, message);
                    if (r != "OK")
                    {
                        MainForm.LogMessageToFile(r);
                    }
                }
                catch (Exception ex)
                {
                    MainForm.LogExceptionToFile(ex);
                    WebsiteLive = false;
                }
                if (WebsiteLive)
                {
                    return(r);
                }
            }
            return(LocRm.GetString("iSpyDown"));
        }
Exemplo n.º 4
0
            //-------------------------------------------------------------
            // constructors
            //-------------------------------------------------------------

            public RemoteControlDevice()
            {
                // Register the input device to receive the commands from the
                // remote device. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwmt/html/remote_control.asp
                // for the vendor defined usage page.

                var rid = new RAWINPUTDEVICE[3];

                rid[0].usUsagePage = 0xFFBC;
                rid[0].usUsage     = 0x88;
                rid[0].dwFlags     = 0;
                rid[0].hwndTarget  = this.Handle;

                rid[1].usUsagePage = 0x0C;
                rid[1].usUsage     = 0x01;
                rid[1].dwFlags     = 0;
                rid[1].hwndTarget  = this.Handle;

                rid[2].usUsagePage = 0x0C;
                rid[2].usUsage     = 0x80;
                rid[2].dwFlags     = 0;
                rid[2].hwndTarget  = this.Handle;

                if (!RegisterRawInputDevices(rid,
                                             (uint)rid.Length,
                                             (uint)Marshal.SizeOf(rid[0]))
                    )
                {
                    MainForm.LogMessageToFile("Failed to register raw input devices.");
                }
            }
Exemplo n.º 5
0
        private static bool SendRTSPReq(string addr, string login, string password)
        {
            bool b = false;

            try
            {
                var uri = new Uri(addr);

                var request = "OPTIONS " + addr + " RTSP/1.0\r\n" +
                              "CSeq: 1\r\n" +
                              "User-Agent: iSpy\r\n" +
                              "Accept: */*\r\n";

                if (!String.IsNullOrEmpty(login))
                {
                    var authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(login + ":" + password));
                    request += "Authorization: Basic " + authInfo + "\r\n";
                }

                request += "\r\n";

                IPAddress host   = IPAddress.Parse(uri.DnsSafeHost);
                var       hostep = new IPEndPoint(host, uri.Port);

                var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    ReceiveTimeout = 2000
                };
                sock.Connect(hostep);

                var response = sock.Send(Encoding.UTF8.GetBytes(request));
                if (response > 0)
                {
                    var    bytesReceived = new byte[200];
                    var    bytes         = sock.Receive(bytesReceived, bytesReceived.Length, 0);
                    string resp          = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                    if (resp.IndexOf("200 OK", StringComparison.Ordinal) != -1)
                    {
                        b = true;
                    }
                    MainForm.LogMessageToFile("RTSP attempt: " + resp + " at " + addr);
                }
                sock.Close();
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
            }
            return(b);
        }
Exemplo n.º 6
0
 public static string LoadCertificate(string fileName)
 {
     try
     {
         _sslCertificate = X509Certificate.CreateFromCertFile(fileName);
         MainForm.LogMessageToFile("Loaded SSL Certificate: " + _sslCertificate.ToString(false));
         return("OK");
     }
     catch (Exception ex)
     {
         MainForm.LogExceptionToFile(ex);
         return(ex.Message);
     }
 }
Exemplo n.º 7
0
        private void DoCheckPassword()
        {
            var g = MainForm.Conf.Permissions.First(p => p.name == ddlAccount.SelectedItem.ToString());

            if (txtPassword.Text == EncDec.DecryptData(g.password, MainForm.Conf.EncryptCode))
            {
                if (MainForm.Group != g.name)
                {
                    MainForm.NeedsResourceUpdate = true;
                }
                MainForm.Group = g.name;
                DialogResult   = DialogResult.OK;
                MainForm.LogMessageToFile("Login: "******"PasswordIncorrect"), LocRm.GetString("Note"));

            Close();
        }
Exemplo n.º 8
0
        private static bool SendHTTPReq(string addr, string cookies, string login, string password)
        {
            bool           b  = false;
            HttpStatusCode sc = 0;

            try
            {
                var wc = (HttpWebRequest)WebRequest.Create(addr);  //args[0]);
                wc.AllowAutoRedirect = true;
                wc.UserAgent         = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19";
                wc.Timeout           = 3000;
                wc.ReadWriteTimeout  = 3000;
                wc.Method            = "GET";
                var authInfo = "";
                if (!String.IsNullOrEmpty(login))
                {
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(login + ":" + password));
                    wc.Headers["Authorization"] = "Basic " + authInfo;
                }

                if (!String.IsNullOrEmpty(cookies))
                {
                    cookies = cookies.Replace("[AUTH]", authInfo);
                    var      myContainer = new CookieContainer();
                    string[] coll        = cookies.Split(';');
                    foreach (var ckie in coll)
                    {
                        if (!String.IsNullOrEmpty(ckie))
                        {
                            string[] nv = ckie.Split('=');
                            if (nv.Length == 2)
                            {
                                var cookie = new Cookie(nv[0].Trim(), nv[1].Trim());
                                myContainer.Add(new Uri(wc.RequestUri.ToString()), cookie);
                            }
                        }
                    }
                    wc.CookieContainer = myContainer;
                }
                using (var res = (HttpWebResponse)wc.GetResponse())
                {
                    sc = res.StatusCode;
                    if (sc == HttpStatusCode.OK)
                    {
                        string ct = res.ContentType.ToLower();
                        if (ct.IndexOf("text", StringComparison.Ordinal) == -1)
                        {
                            b = true;
                        }
                    }
                }
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    //sc = ((HttpWebResponse) we.Response).StatusCode;
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
            }
            MainForm.LogMessageToFile("Status " + sc + " at " + addr);

            return(b);// sc == HttpStatusCode.OK;
        }
Exemplo n.º 9
0
        private void PortScanner(IEnumerable <int> ports, string ipaddress, ManualResetEvent mre)
        {
            bool found;

            if (!DnsEntries.Contains(ipaddress))
            {
                const string data   = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[]       buffer = Encoding.ASCII.GetBytes(data);

                var       netMon  = new Ping();
                var       options = new PingOptions(128, true);
                PingReply pr      = netMon.Send(ipaddress, 3000, buffer, options);
                found = pr != null && pr.Status == IPStatus.Success;
            }
            else
            {
                found = true;
            }
            if (found)
            {
                MainForm.LogMessageToFile("Ping response from " + ipaddress);
                string hostname = "Unknown";
                try
                {
                    var ipToDomainName = Dns.GetHostEntry(ipaddress);
                    hostname = ipToDomainName.HostName;
                }
                catch
                {
                }

                foreach (int iport in ports)
                {
                    try
                    {
                        string req     = ipaddress + ":" + iport;
                        var    request = (HttpWebRequest)WebRequest.Create("http://" + req);
                        request.Referer           = "";
                        request.Timeout           = 3000;
                        request.UserAgent         = "Mozilla/5.0";
                        request.AllowAutoRedirect = false;

                        HttpWebResponse response = null;

                        try
                        {
                            response = (HttpWebResponse)request.GetResponse();
                        }
                        catch (WebException e)
                        {
                            response = (HttpWebResponse)e.Response;
                        }
                        catch (Exception ex)
                        {
                            MainForm.LogMessageToFile("Web error from " + ipaddress + ":" + iport + " " + ex.Message);
                        }
                        if (response != null)
                        {
                            MainForm.LogMessageToFile("Web response from " + ipaddress + ":" + iport + " " +
                                                      response.StatusCode);
                            if (response.Headers != null)
                            {
                                string webserver = "yes";
                                foreach (string k in response.Headers.AllKeys)
                                {
                                    if (k.ToLower().Trim() == "server")
                                    {
                                        webserver = response.Headers[k];
                                    }
                                }
                                lock (_dt)
                                {
                                    DataRow dr = _dt.NewRow();
                                    dr[0] = ipaddress;
                                    dr[1] = iport;
                                    dr[2] = hostname;
                                    dr[3] = webserver;
                                    _dt.Rows.Add(dr);
                                    _dt.AcceptChanges();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MainForm.LogMessageToFile("Web error from " + ipaddress + ":" + iport + " " + ex.Message);
                    }
                }
                UISync.Execute(() => dataGridView1.Refresh());
            }
            mre.Set();
        }
Exemplo n.º 10
0
        private void PortScannerManager(string host)
        {
            var ports = new List <int>();

            foreach (string s in txtPorts.Text.Split(','))
            {
                int p;
                if (int.TryParse(s, out p))
                {
                    if (p < 65535 && p > 0)
                    {
                        ports.Add(p);
                    }
                }
            }
            UISync.Execute(() => pbScanner.Value = 0);

            var manualEvents = new ManualResetEvent[MaxThreads];
            int j;

            for (int k = 0; k < MaxThreads; k++)
            {
                manualEvents[k] = new ManualResetEvent(true);
            }

            var ipranges = new List <string>();

            if (host == LocRm.GetString("AllAdaptors"))
            {
                ipranges.AddRange(from string s in ddlHost.Items where s != LocRm.GetString("AllAdaptors") select s);
            }
            else
            {
                ipranges.Add(host);
            }

            UISync.Execute(() => pbScanner.Maximum = ipranges.Count * 254);
            MainForm.LogMessageToFile("Scanning LAN");
            j = 0;
            foreach (string IP in DnsEntries)
            {
                string ip      = IP;
                int    k       = j;
                var    scanner = new Thread(p => PortScanner(ports, ip, manualEvents[k]));
                scanner.Start();

                j = WaitHandle.WaitAny(manualEvents);
                UISync.Execute(() => pbScanner.PerformStep());
                if (_exiting)
                {
                    break;
                }
            }

            if (!_exiting)
            {
                j = 0;
                foreach (string shost in ipranges)
                {
                    for (int i = 0; i < 255; i++)
                    {
                        string ip = shost.Replace("x", i.ToString(CultureInfo.InvariantCulture));
                        if (!DnsEntries.Contains(ip))
                        {
                            int k = j;
                            manualEvents[k].Reset();
                            var scanner = new Thread(p => PortScanner(ports, ip, manualEvents[k]));
                            scanner.Start();

                            j = WaitHandle.WaitAny(manualEvents);
                            UISync.Execute(() => pbScanner.PerformStep());
                        }
                        if (_exiting)
                        {
                            break;
                        }
                    }
                    if (_exiting)
                    {
                        break;
                    }
                }
            }

            if (j > 0)
            {
                WaitHandle.WaitAll(manualEvents);
            }


            //populate MAC addresses
            try
            {
                var arpStream = ExecuteCommandLine("arp", "-a");
                // Consume first three lines
                for (int i = 0; i < 3; i++)
                {
                    arpStream.ReadLine();
                }
                // Read entries
                while (!arpStream.EndOfStream)
                {
                    var line = arpStream.ReadLine();
                    if (line != null)
                    {
                        line = line.Trim();
                        while (line.Contains("  "))
                        {
                            line = line.Replace("  ", " ");
                        }
                        var parts = line.Trim().Split(' ');

                        if (parts.Length == 3)
                        {
                            for (int i = 0; i < _dt.Rows.Count; i++)
                            {
                                DataRow dr = _dt.Rows[i];
                                string  ip = parts[0];
                                if (ip == dr["IP Address"].ToString().Split(':')[0])
                                {
                                    dr["MAC Address"] = parts[1];
                                }
                            }
                        }
                    }
                }
                _dt.AcceptChanges();
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
            }

            UISync.Execute(ResetControls);
        }
Exemplo n.º 11
0
        private static void Upload()
        {           
            UserState us = UploadFiles.Dequeue();
            Console.WriteLine("youtube: upload " + us.AbsoluteFilePath);

            var settings = new YouTubeRequestSettings("iSpy", MainForm.Conf.YouTubeKey, MainForm.Conf.YouTubeUsername, MainForm.Conf.YouTubePassword);
            var request = new YouTubeRequest(settings);

            var v = new Google.YouTube.Video
                        {
                            Title = "iSpy: " + us.CameraData.name,
                            Description = MainForm.Website+": free open source surveillance software: " +
                                          us.CameraData.description
                        };
            if (us.CameraData == null)
            {
                if (UploadFiles.Count > 0)
                    Upload();
                return;
            }
            v.Keywords = us.CameraData.settings.youtube.tags;
            if (v.Keywords.Trim() == "")
                v.Keywords = "ispyconnect"; //must specify at least one keyword
            v.Tags.Add(new MediaCategory(us.CameraData.settings.youtube.category));
            v.YouTubeEntry.Private = !us.Ispublic;
            v.Media.Categories.Add(new MediaCategory(us.CameraData.settings.youtube.category));
            v.Private = !us.Ispublic;
            v.Author = "iSpyConnect.com - Camera Security Software (open source)";

            if (us.EmailOnComplete != "")
                v.Private = false;

            string contentType = MediaFileSource.GetContentTypeForFileName(us.AbsoluteFilePath);
            v.YouTubeEntry.MediaSource = new MediaFileSource(us.AbsoluteFilePath, contentType);

            // add the upload uri to it
            //var link =
            //    new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/" +
            //                 MainForm.Conf.YouTubeAccount + "/uploads") {Rel = ResumableUploader.CreateMediaRelation};
            //v.YouTubeEntry.Links.Add(link);

            bool success = false;
            ((GDataRequestFactory)request.Service.RequestFactory).Timeout = 60 * 60 * 1000;
            Google.YouTube.Video vCreated = null;
            try
            {
                vCreated = request.Upload(v);
                success = true;
            }
            catch (GDataRequestException ex1)
            {
                MainForm.LogErrorToFile("YouTube Uploader: " + ex1.ResponseString+" ("+ex1.Message+")");
                if (ex1.ResponseString=="NoLinkedYouTubeAccount")
                {
                    MainForm.LogMessageToFile(
                        "This is because the Google account you connected has not been linked to YouTube yet. The simplest way to fix it is to simply create a YouTube channel for that account: http://www.youtube.com/create_channel");
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
            }
            if (success)
            {
                Console.WriteLine("Uploaded: http://www.youtube.com/watch?v=" + vCreated.VideoId);

                string msg = "YouTube video uploaded: <a href=\"http://www.youtube.com/watch?v=" + vCreated.VideoId + "\">" +
                                vCreated.VideoId + "</a>";
                if (vCreated.Private)
                    msg += " (private)";
                else
                    msg += " (public)";
                MainForm.LogMessageToFile(msg);

                if (us.EmailOnComplete != "" && us.Ispublic)
                {
                    SendYouTubeMails(us.EmailOnComplete, us.Message, vCreated.VideoId);
                }
                //check against most recent uploaded videos
                MainForm.Conf.UploadedVideos += "," + us.AbsoluteFilePath + "|" + vCreated.VideoId;
                if (MainForm.Conf.UploadedVideos.Length > 10000)
                    MainForm.Conf.UploadedVideos = "";
            }
            if (UploadFiles.Count>0)
                Upload();
        }
Exemplo n.º 12
0
        internal void MergeMedia()
        {
            if (_ffmpegProcess != null)
            {
                return;
            }

            if (!Helper.HasFeature(Enums.Features.Recording))
            {
                return;
            }
            _pbMerge = new List <FilesFile>();

            _currentObject = ((Li)ddlObject.SelectedItem);
            if (_currentObject.Ot == 1)
            {
                var vl = MainClass.GetVolumeLevel(_currentObject.ID);
                _pbMerge = vl.FileList.Where(
                    p => p.CreatedDateTicks >= dateTimePicker1.Value.Ticks &&
                    p.CreatedDateTicks <= dateTimePicker2.Value.Ticks).OrderBy(p => p.CreatedDateTicks).ToList();
            }
            else
            {
                var cw = MainClass.GetCameraWindow(_currentObject.ID);
                _pbMerge = cw.FileList.Where(
                    p => p.CreatedDateTicks >= dateTimePicker1.Value.Ticks &&
                    p.CreatedDateTicks <= dateTimePicker2.Value.Ticks).OrderBy(p => p.CreatedDateTicks).ToList();
            }

            if (_pbMerge.Count > 0)
            {
                var    first = _pbMerge.First();
                string ext   = first.Filename.Substring(first.Filename.LastIndexOf(".", StringComparison.Ordinal) + 1);
                var    date  = DateTime.Now;

                _dir     = Helper.GetFullPath(_currentObject.Ot, _currentObject.ID);
                _outfile = _currentObject.ID + "_" + String.Format("Merge_{0}-{1}-{2}_{3}-{4}-{5}",
                                                                   date.Year, Helper.ZeroPad(date.Month), Helper.ZeroPad(date.Day),
                                                                   Helper.ZeroPad(date.Hour), Helper.ZeroPad(date.Minute),
                                                                   Helper.ZeroPad(date.Second)) + "." + ext;

                string filelist = _pbMerge.Aggregate("",
                                                     (current, file) => current + ("file '" + _dir + file.Filename + "'" + Environment.NewLine));

                File.WriteAllText(Program.AppDataPath + "concat.txt", filelist);
                if (filelist != "")
                {
                    var startInfo = new ProcessStartInfo
                    {
                        FileName  = "\"" + Program.AppPath + "ffmpeg.exe\"",
                        Arguments =
                            "-f concat -i \"" + Program.AppDataPath + "concat.txt" +
                            "\" -codec copy \"" + _dir + _outfile + "\"",
                        RedirectStandardOutput = false,
                        RedirectStandardError  = false,
                        UseShellExecute        = false,
                        CreateNoWindow         = false
                    };
                    MainForm.LogMessageToFile("Merge: " + startInfo.FileName + " " + startInfo.Arguments);
                    _ffmpegProcess = new Process {
                        StartInfo = startInfo, EnableRaisingEvents = true
                    };
                    _ffmpegProcess.Exited            += FfmpegMergeProcessExited;
                    _ffmpegProcess.ErrorDataReceived += FfmpegMergeProcessErrorDataReceived;
                    try
                    {
                        _ffmpegProcess.Start();
                    }
                    catch (Exception e)
                    {
                        _ffmpegProcess = null;
                        MainForm.LogExceptionToFile(e);
                    }
                }
                button1.Enabled = false;
            }
        }
Exemplo n.º 13
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string sUrlToReadFileFrom = Url;
            var    url      = new Uri(sUrlToReadFileFrom);
            var    request  = WebRequest.Create(url);
            var    response = request.GetResponse();
            // gets the size of the file in bytes

            Int64 iSize = response.ContentLength;

            // keeps track of the total bytes downloaded so we can update the progress bar
            int iRunningByteTotal = 0;

            // use the webclient object to download the file

            using (Stream streamRemote = response.GetResponseStream())
            {
                if (streamRemote != null)
                {
                    streamRemote.ReadTimeout = 8000;
                    // loop the stream and get the file into the byte buffer
                    var byteBuffer = new byte[iSize];
                    int iByteSize;
                    while ((iByteSize = streamRemote.Read(byteBuffer, iRunningByteTotal, byteBuffer.Length - iRunningByteTotal)) > 0 && !backgroundWorker1.CancellationPending)
                    {
                        iRunningByteTotal += iByteSize;

                        // calculate the progress out of a base "100"
                        var dIndex = (double)(iRunningByteTotal);
                        var dTotal = (double)byteBuffer.Length;
                        var dProgressPercentage = (dIndex / dTotal);
                        var iProgressPercentage = (int)(dProgressPercentage * 100);

                        // update the progress bar
                        backgroundWorker1.ReportProgress(iProgressPercentage);
                        int total = iRunningByteTotal;
                        UISync.Execute(() => lblProgress.Text = total + " / " + iSize);
                    }
                    if (!backgroundWorker1.CancellationPending)
                    {
                        if (SaveLocation.EndsWith(".xml"))
                        {
                            var ms  = new MemoryStream(byteBuffer);
                            var doc = new XmlDocument();
                            try
                            {
                                doc.Load(ms);
                                doc.Save(SaveLocation);
                                success = true;
                            }
                            catch (Exception ex)
                            {
                                MainForm.LogExceptionToFile(ex);
                                DialogResult = DialogResult.Cancel;
                                aborting     = true;
                                Close();
                                return;
                            }
                            ms.Dispose();
                        }
                    }
                    else
                    {
                        MainForm.LogMessageToFile("Update cancelled");
                    }
                }
                else
                {
                    MainForm.LogErrorToFile("Response stream from " + Url + " failed");
                }
            }
            response.Close();
        }
Exemplo n.º 14
0
        private bool Sftp(string server, int port, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
        {
            bool failed = false;

            error = "";
            try
            {
                int i = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                {
                    filename += ".tmp";
                }

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                var methods = new List <AuthenticationMethod> {
                    new PasswordAuthenticationMethod(username, password)
                };

                var con = new ConnectionInfo(server, port, username, methods.ToArray());
                using (var client = new SftpClient(con))
                {
                    client.Connect();

                    var filepath = filename.Trim('/').Split('/');
                    var path     = "";
                    for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                    {
                        path += filepath[iDir] + "/";
                        try
                        {
                            client.CreateDirectory(path);
                        }
                        catch
                        {
                            //directory exists
                        }
                    }
                    if (path != "")
                    {
                        client.ChangeDirectory(path);
                    }

                    filename = filepath[filepath.Length - 1];

                    using (Stream stream = new MemoryStream(contents))
                    {
                        client.UploadFile(stream, filename);
                        if (rename)
                        {
                            try
                            {
                                //delete target file?
                                client.DeleteFile(filename.Substring(0, filename.Length - 4));
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                            client.RenameFile(filename, filename.Substring(0, filename.Length - 4));
                        }
                    }

                    client.Disconnect();
                }


                MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP");
            }
            catch (Exception ex)
            {
                error  = ex.Message;
                failed = true;
            }
            return(!failed);
        }
Exemplo n.º 15
0
        public bool FTP(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename, bool useSftp)
        {
            bool failed = false;

            if (useSftp)
            {
                return(Sftp(server, port, username, password, filename, counter, contents, out error, rename));
            }
            try
            {
                var target = new Uri(server + ":" + port);
                int i      = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                {
                    filename += ".tmp";
                }

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                //try uploading
                //directory tree
                var           filepath = filename.Trim('/').Split('/');
                var           path     = "";
                FtpWebRequest request;
                for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                {
                    path               += filepath[iDir] + "/";
                    request             = (FtpWebRequest)WebRequest.Create(target + path);
                    request.Credentials = new NetworkCredential(username, password);
                    request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                    try { request.GetResponse(); }
                    catch
                    {
                        //directory exists
                    }
                }

                request             = (FtpWebRequest)WebRequest.Create(target + filename);
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = passive;
                //request.UseBinary = true;
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = contents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(contents, 0, contents.Length);
                requestStream.Close();

                var response = (FtpWebResponse)request.GetResponse();
                if (response.StatusCode != FtpStatusCode.ClosingData)
                {
                    MainForm.LogErrorToFile("FTP Failed: " + response.StatusDescription, "FTP");
                    failed = true;
                }

                response.Close();

                if (rename && !failed)
                {
                    //delete existing
                    request             = (FtpWebRequest)WebRequest.Create(target + filename.Substring(0, filename.Length - 4));
                    request.Credentials = new NetworkCredential(username, password);
                    request.UsePassive  = passive;
                    //request.UseBinary = true;
                    request.Method = WebRequestMethods.Ftp.DeleteFile;
                    filename       = "/" + filename;

                    try
                    {
                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.ActionNotTakenFileUnavailable &&
                            response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            MainForm.LogErrorToFile("FTP Delete Failed: " + response.StatusDescription, "FTP");
                            failed = true;
                        }

                        response.Close();
                    }
                    catch
                    {
                        //MainForm.LogExceptionToFile(ex, "FTP");
                        //ignore
                    }

                    //rename file
                    if (!failed)
                    {
                        request             = (FtpWebRequest)WebRequest.Create(target + filename);
                        request.Credentials = new NetworkCredential(username, password);
                        request.UsePassive  = passive;
                        //request.UseBinary = true;
                        request.Method = WebRequestMethods.Ftp.Rename;
                        filename       = "/" + filename;

                        request.RenameTo = filename.Substring(0, filename.Length - 4);

                        response = (FtpWebResponse)request.GetResponse();
                        if (response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            MainForm.LogErrorToFile("FTP Rename Failed: " + response.StatusDescription, "FTP");
                            failed = true;
                        }
                        response.Close();
                    }
                }
                if (!failed)
                {
                    MainForm.LogMessageToFile("FTP'd " + filename + " to " + server + ":" + port, "FTP");
                }
                error = failed ? "FTP Failed. Check Log" : "";
            }
            catch (Exception ex)
            {
                error  = ex.Message;
                failed = true;
            }
            return(!failed);
        }