示例#1
0
        /*
         * public http()
         * {
         *      statusCode = 0;
         *      errorString = String.Empty;
         *      contentType = String.Empty;
         * }
         */

        public string binaryStream2MD5File(page p, BinaryReader binStream, string contentType, string contentLength)
        {
            string appPath  = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
            md5    MD5      = new md5();
            string fullPath = appPath + MD5.compute(p._page);

            nsGlobalOutput.output.write("\n + Downloading " + p.GenerateURL() + " ... ");
            nsGlobalOutput.output.write("   - Content-Type: " + contentType);
            nsGlobalOutput.output.write("   - Content-Length: " + contentLength + " bytes \n");

            try
            {
                int    BUFFER_SIZE          = 4096;
                byte[] buf                  = new byte[BUFFER_SIZE];
                System.IO.FileStream stream = new System.IO.FileStream(fullPath, System.IO.FileMode.Create);
                int n = binStream.Read(buf, 0, BUFFER_SIZE);
                while (n > 0)
                {
                    stream.Write(buf, 0, n);
                    n = binStream.Read(buf, 0, BUFFER_SIZE);
                }
                stream.Close();
            }
            catch (Exception e)
            {
                nsGlobalOutput.output.write("Error: " + e.Message);
            }
            finally
            {
                binStream.Close();
            }

            return(fullPath);
        }
示例#2
0
        // legge i parametri passati dalla riga di comando
        public bool readCommandLine(string[] _args)
        {
            // legge gli argomenti dalla linea di comando
            if (GlobalVars.args.readArgs(_args) == false)
            {
                return(false);
            }


            {
                // controlla che l'URL da indicizzare sia valido
                // se manca l'http iniziale ce lo aggiunge
                if (!GlobalVars.args.startURL.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
                {
                    GlobalVars.args.startURL = "http://" + GlobalVars.args.startURL;
                }

                page startPage = new page(GlobalVars.args.startURL, GlobalVars.args.startURL, null);
                if (startPage.isValidPage == false)
                {
                    nsGlobalOutput.output.write("Invalid URL [" + GlobalVars.args.startURL + "]");
                    return(false);
                }

                // imposta il dominio corrente da indicizzare
                GlobalVars.threadsVars.currentDomain = startPage;

                return(true);
            }
        }
示例#3
0
        /* indexMP3
         * indicizza le informazioni estratte dal file MP3
         */
        public bool indexMP3(page p, mp3 MP3Info)
        {
            string outStr;
            string sql;
            bool   ret;

            outStr  = "\n";
            outStr += " + Indexing MP3 [ " + p.GenerateURL() + " ]\n";
            outStr += "   - Title   : " + MP3Info.mp3Title + "\n";
            outStr += "   - Artist  : " + MP3Info.mp3Artist + "\n";
            outStr += "   - Album   : " + MP3Info.mp3Album + "\n";
            outStr += "   - Genre   : " + MP3Info.mp3Genre + "\n";
            outStr += "   - Duration: " + MP3Info.mp3Length + " seconds\n";
            outStr += "\n";

            nsGlobalOutput.output.write(outStr);

            sql = "INSERT INTO mp3 (host_id, filename, mp3_size, mp3_artist, mp3_title, mp3_album, mp3_genre, mp3_duration) " +
                  "VALUES(" + p._hostID + ", " +
                  "'" + myMySQLEscapeString(p._page) + "', " +
                  "'" + MP3Info.mp3Size + "', " +
                  "'" + myMySQLEscapeString(MP3Info.mp3Artist) + "', " +
                  "'" + myMySQLEscapeString(MP3Info.mp3Title) + "', " +
                  "'" + myMySQLEscapeString(MP3Info.mp3Album) + "', " +
                  "'" + myMySQLEscapeString(MP3Info.mp3Genre) + "', " +
                  MP3Info.mp3Length + ")";


            GlobalVars.threadsVars.mutexMySQLPageList.WaitOne();
            try
            {
                ret = GlobalVars.mysqlConn.connPageList.executeSQLQuery(sql);
            }
            catch (Exception e)
            {
                nsGlobalOutput.output.write("SQL Error: " + e.Message + "\n\nSQL: -===[\n" + sql.Substring(0, 1000) + "\n]===-\n\n");
                ret = false;
            }
            finally
            {
                GlobalVars.threadsVars.mutexMySQLPageList.ReleaseMutex();
            }

            return(ret);
        }
示例#4
0
        public int GetHostId(page p)
        {
            int hostID;

            try
            {
                // prende l'ID del primo url libero
                hostID = int.Parse(GlobalVars.mysqlConn.connHostList.getValueFromTable("hostlist", "id", " hostname = '" + p._hostname + "' AND port = " + p._port + " "));
                if (hostID > 0)
                {
                    return(hostID);
                }
            }
            catch
            {
            }

            return(0);
        }
示例#5
0
        /* stopIndexThisSite
         * imposta il dominio corrente come: "indicizzato" (status=1)
         */
        public bool stopIndexThisSite(page p)
        {
            if (p._hostID > 0)
            {
                GlobalVars.mysqlConn.connHostList.executeSQLQuery(" UPDATE hostlist SET " +
                                                                  "  status = 1 " +
                                                                  ", indexed_pages = " + GlobalVars.limits.curPages +
                                                                  ", time_sec = " + ((DateTime.Now.Ticks - GlobalVars.limits.startTime) / 10000000) +
                                                                  ", bytes_downloaded = " + GlobalVars.limits.curBytes +
                                                                  ", error_pages = " + GlobalVars.limits.curErrorCodes +
                                                                  ", crawler_id = '' " +
                                                                  " WHERE id = " + p._hostID + " limit 1");
            }
            else
            {
                return(false);
            }

            return(true);
        }
示例#6
0
        /* indexPDF
         * indicizza le informazioni estratte dal file PDF
         */
        public bool indexPDF(page p, int pdfSize, string pdf2text)
        {
            string outStr;
            string sql;
            bool   ret;

            outStr  = "\n";
            outStr += " + Indexing PDF [ " + p.GenerateURL() + " ]\n";

            nsGlobalOutput.output.write(outStr);

            html htmp = new html();

            pdf2text = htmp.removeUnWantedChars(pdf2text);

            addContent2Index(p._hostID, p._hostname, p._page, p._title, p._anchorText, p._depthLevel, pdf2text, pdf2text);

            sql = "INSERT INTO pdf (host_id, filename, pdf_size, pdf_text) " +
                  "VALUES(" + p._hostID + ", " +
                  "'" + myMySQLEscapeString(p._page) + "', " +
                  "'" + pdfSize + "', " +
                  "'" + myMySQLEscapeString(pdf2text) + "') ";


            GlobalVars.threadsVars.mutexMySQLPageList.WaitOne();
            try
            {
                ret = GlobalVars.mysqlConn.connPageList.executeSQLQuery(sql);
            }
            catch (Exception e)
            {
                nsGlobalOutput.output.write("SQL Error: " + e.Message + "\n\nSQL: -===[\n" + sql.Substring(0, 1000) + "\n]===-\n\n");
                ret = false;
            }
            finally
            {
                GlobalVars.threadsVars.mutexMySQLPageList.ReleaseMutex();
            }

            return(ret);
        }
示例#7
0
        public page getFirstAvailableURL()
        {
            int    hostID;
            string url;

            try
            {
                if (GlobalVars.readConfFile.sqlWhereHostlist == "")
                {
                    GlobalVars.readConfFile.sqlWhereHostlist = "1=1";
                }

                // prende l'ID del primo url libero
                hostID = int.Parse(GlobalVars.mysqlConn.connHostList.getValueFromTable("hostlist", "id", "status=0 AND ( " + GlobalVars.readConfFile.sqlWhereHostlist + " ) ORDER by priority DESC"));
                if (hostID > 0)
                {
                    // setta l'url come "in scansionamento"
                    GlobalVars.mysqlConn.connHostList.executeSQLQuery("UPDATE hostlist SET status = 2, crawler_id = '" + myMySQLEscapeString(GlobalVars.OpenWebSpider.ID) + "' WHERE id = " + hostID);

                    // prende l'url
                    url = GlobalVars.mysqlConn.connHostList.getValueFromTable("hostlist", "CONCAT('http://', hostname, ':', port)", "id = " + hostID);

                    nsGlobalOutput.output.write("\n\n\n");

                    nsGlobalOutput.output.write(" + Indexing new domain:  " + url);

                    nsGlobalOutput.output.write("\n");

                    page ret = new page(url, url, null);
                    ret._hostID = hostID;

                    return(ret);
                }
            }
            catch
            {
                return(null);
            }

            return(null);
        }
示例#8
0
        /* GetURLs
         * estrae tutti gli URL e gli ANCHOR TEXT(dal TAG: A) dai seguenti TAG:
         *  - BASE ... HREF
         *  - A ... HREF
         *  - FRAME ... SRC
         *  - IFRAME ... SRC
         *
         *  (?<base><base\s?[^>]*\shref\s*=\s*(?:(?:[\"\'](?<url>[^\"\']*)[\"\'])|(?<url>[^\s>]*))[^>]*[>])|(?<links><a\s?[^>]*\shref\s*=\s*(?:(?:[\"\'](?<url>[^\"\']*)[\"\'])|(?<url>[^\s>]*))[^>]*[>](?<anchor>(.|\s)*?)</a>)|(?<frames><i?frame\s?[^>]*\ssrc\s*=\s*(?:(?:[\"\'](?<url>[^\"\']*)[\"\'])|(?<url>[^\s>]*))[^>]*[>])
         *
         *
         *  Testo di prova:
         *
         *  <base href="baseURL1"> <a href="url1"> an1 </a><a href=u2> a2 </a> <a href = u3 > a3 </a> <frame src="frame1">  <iframe src="iframe1">
         *
         */
        public int GetURLs(string HTML, page parentPage)
        {
            int nRetURLs = 0;

            // gestisce il tag: BASE
            page baseURL = null;

            MatchCollection mcURLs = regexExtractURLs.Matches(HTML);

            try
            {
                foreach (Match mMatch in mcURLs)
                {
                    string strURL = mMatch.Groups["url"].ToString().Trim();

                    // toglie TAG HTML dall'anchor text (es.: <a href = test> <img src=abc> </a> )
                    string strAnchorText = UnHTML(mMatch.Groups["anchor"].ToString().Trim());

                    if (mMatch.Groups["base"].ToString().Length > 0 && strURL.Length > 0)
                    {
                        /* abbiamo un URL di un TAG <BASE> */
                        baseURL = new page(strURL, "base", null);
                        // se non è un URL valido lo ignora
                        if (!baseURL.isValidPage)
                        {
                            nsGlobalOutput.output.write("INVALID BASE URL FOUND: " + strURL);
                            baseURL = null;
                        }

                        //nsGlobalOutput.output.write("Base: " + strURL, true );
                    }

                    page pageNewPage;
                    if (baseURL == null)
                    {
                        pageNewPage = new page(strURL, strAnchorText, parentPage);
                    }
                    else
                    {
                        // se abbiamo trovato un tag BASE: consideralo la parentPage
                        pageNewPage = new page(strURL, strAnchorText, baseURL);
                    }

                    if (pageNewPage.isValidPage)
                    {
                        // incrementa il numero di URLs validi
                        nRetURLs++;

                        // salva la relazione corrente
                        GlobalVars.threadsVars.mutexRelsList.WaitOne();
                        try
                        {
                            GlobalVars.relsList.addRel(parentPage, pageNewPage);
                        }
                        catch (Exception e)
                        {
                            nsGlobalOutput.output.write("Error Adding Rel: " + e.Message);
                        }
                        finally
                        {
                            GlobalVars.threadsVars.mutexRelsList.ReleaseMutex();
                        }

                        // la pagina è del dominio corrente?
                        if (pageNewPage._hostname == GlobalVars.threadsVars.currentDomain._hostname &&
                            pageNewPage._port == GlobalVars.threadsVars.currentDomain._port)
                        {
                            // blocca il mutex associato alla lista, aggiunge l'URL e rilascia il mutex
                            GlobalVars.threadsVars.mutexAccessURLList.WaitOne();
                            try
                            {
                                GlobalVars.urlsLists.addURL(pageNewPage);
                            }
                            catch (Exception e)
                            {
                                nsGlobalOutput.output.write("Error Adding URL: " + e.Message);
                            }
                            finally
                            {
                                GlobalVars.threadsVars.mutexAccessURLList.ReleaseMutex();
                            }
                        }
                        else
                        {
                            // aggiunge host esterni SOLO SE specificato da riga di comando
                            if (GlobalVars.args.addExternalHosts == true)
                            {
                                // aggiunge l'URL alla cache degli host esterni
                                GlobalVars.threadsVars.mutexAccessExternURLList.WaitOne();
                                try
                                {
                                    GlobalVars.externUrlsLists.addURL(pageNewPage);
                                }
                                catch (Exception e)
                                {
                                    nsGlobalOutput.output.write("Error Adding External URL: " + e.Message);
                                }
                                finally
                                {
                                    GlobalVars.threadsVars.mutexAccessExternURLList.ReleaseMutex();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                nsGlobalOutput.output.write("Error Adding External URL: " + e.Message);
            }

            // dobbiamo indicizzare le immagini?
            if (GlobalVars.args.indexImages == true)
            {
                MatchCollection mcImages = regexExtractImages.Matches(HTML);
                foreach (Match mMatch in mcImages)
                {
                    string strURL = mMatch.Groups["url"].ToString().Trim();

                    page pageNewPage;
                    if (baseURL == null)
                    {
                        pageNewPage = new page(strURL, "", parentPage);
                    }
                    else
                    {
                        // se abbiamo trovato un tag BASE: consideralo la parentPage
                        pageNewPage = new page(strURL, "", baseURL);
                    }

                    if (pageNewPage.isValidPage)
                    {
                        //estrai ALT e TITLE
                        string imgAlt   = regexExtractImagesALT.Match(mMatch.Value).Groups["text"].ToString();
                        string imgTitle = regexExtractImagesTITLE.Match(mMatch.Value).Groups["text"].ToString();

                        // blocca il mutex associato alla lista, aggiunge l'URL e rilascia il mutex
                        GlobalVars.threadsVars.mutexAccessURLList.WaitOne();
                        try
                        {
                            GlobalVars.imagesLists.addURL(parentPage, pageNewPage, imgAlt, imgTitle);
                        }
                        catch (Exception e)
                        {
                            nsGlobalOutput.output.write("Error Adding URL: " + e.Message);
                        }
                        finally
                        {
                            GlobalVars.threadsVars.mutexAccessURLList.ReleaseMutex();
                        }
                    }
                }
            }

            // ritorna il numero di URLs validi
            return(nRetURLs);
        }
示例#9
0
        /* tests
         *      page pg1 = new page("http://www.google.com/prova/asd/deheh/uh12345/#segnalibro", "", null);
         *      page pg2 = new page("/test/prova.php", "", pg1);
         *      page pg3 = new page("prova.php3?deheheh#ciao", "", pg2);
         *      nsGlobalOutput.output.write("url: " + pg1._url + " host: " + pg1._hostname + " port: " + pg1._port + " page: " + pg1._page  );
         *      nsGlobalOutput.output.write("url: " + pg2._url + " host: " + pg2._hostname + " port: " + pg2._port + " page: " + pg2._page  );
         *      nsGlobalOutput.output.write("url: " + pg3._url + " host: " + pg3._hostname + " port: " + pg3._port + " page: " + pg3._page  );
         *
         */
        public page(string u, string a, page parentPage)
        {
            isValidPage = false;
            isIndexed   = 0;
            _hostID     = 0;

            // protocolli non supportati
            if (u.Length == 0 ||
                u.StartsWith("https:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("mailto:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("javascript:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("ftp:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("about:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("irc:", StringComparison.CurrentCultureIgnoreCase) ||
                u.StartsWith("news:", StringComparison.CurrentCultureIgnoreCase))
            {
                isValidPage = false;
                return;
            }

            _url        = u.Replace("&amp;", "&");
            _anchorText = a;

            /* inizialmente il titolo viene impostato come anchor_text;
             * se poi è una pagina HTML verrà estratto dal TAG TITLE
             */
            _title = a;

            /* _depthLevel
             * se abbiamo una parent Page: _depthLevel = parentPage._depthLevel + 1
             * altrimenti default = 0
             */
            if (parentPage == null)
            {
                _depthLevel = 0;
            }
            else
            {
                _depthLevel = parentPage._depthLevel + 1;
            }

            // cerca un #segnalibro
            {
                int tSharp = _url.IndexOf("#");

                if (tSharp >= 0)
                {
                    _url = _url.Remove(tSharp, _url.Length - tSharp);
                }
            }

            if (_url == "")
            {
                isValidPage = false;
                return;
            }

            // isFullURL è true se l'URL inizia con "http://" o "//"
            bool isFullURL = false;

            if (_url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
            {
                _url      = _url.Remove(0, 7);
                isFullURL = true;
            }

            if (_url.StartsWith("//"))
            {
                _url      = _url.Remove(0, 2);
                isFullURL = true;
            }

            // se è un URL completo:
            if (isFullURL)
            {
                // - estraiamo dominio e pagina
                {
                    int tToken1 = _url.IndexOf("/");
                    if (tToken1 > 0)
                    {
                        _hostname = _url.Substring(0, tToken1).ToLower();
                        _page     = _url.Substring(tToken1, _url.Length - tToken1);
                    }
                    else
                    {
                        _hostname = _url.ToLower();
                        _page     = "/";
                    }

                    _port = getPortNum(ref _hostname);

                    isValidPage = true;

                    // se la pagina genitore è la stessa dell'URL che stiamo parsando e ha un HostID?
                    // assegna l'hostID evitando di cercarlo nel DB
                    if (parentPage != null && parentPage._hostID > 0 && parentPage._hostname == _hostname)
                    {
                        _hostID = parentPage._hostID;
                    }
                    else
                    {
                        // l'hostID per gli URL esterni vengono trovati a fine indicizzazione del dominio corrente
                    }
                }
            }
            else
            {
                // non è un URL completo ( senza http:// )

                // se non abbiamo una pagina genitore non possiamo continuare!!!
                if (parentPage != null)
                {
                    _hostname = parentPage._hostname.ToLower();
                    _port     = parentPage._port;
                    _hostID   = parentPage._hostID;

                    string baseDir = string.Empty;

                    // se l'url non inizia con '/' dobbiamo cercare la directory dall'URL genitore (es.: url = "test.html")
                    // altrimenti abbiamo la directory esatta nell'URL (es.: url = "/dir1/dir2/test.html")
                    if (_url[0] != '/')
                    {
                        baseDir = GetDir(parentPage._page);
                    }

                    _page = baseDir + _url;

                    isValidPage = true;
                }
            }

            // se arriviamo qui e la pagina non è valida: non serve continuare!
            if (isValidPage == false)
            {
                return;
            }

            // normalizza la pagina
            normalizePage();

            // controllare la validità dell'hostname e della pagina
            Regex testHostname = new Regex("^[a-zA-Z0-9\\-\\.]+$", RegexOptions.IgnoreCase);

            if (!testHostname.IsMatch(_hostname))
            {
                isValidPage = false;
                return;
            }

            // controlla la validità della pagina in base alla lunghezza dei campi
            if (_hostname.Length > GlobalVars.dbLimits.maxHostnameLength ||
                _hostname.Length < 2 ||
                _page.Length > GlobalVars.dbLimits.maxPageLength ||
                _title.Length > GlobalVars.dbLimits.maxTitleLength ||
                _anchorText.Length > GlobalVars.dbLimits.maxAnchorText)
            {
                isValidPage = false;
            }

            return;
        }
示例#10
0
        /* startIndexThisSite
         * inserisce il dominio corrente nel DB se non esiste altrimenti aggiorna lo stato(=2)
         * ritorna l'hostID
         */
        public int startIndexThisSite(page p)
        {
            // prova a recuperare l'host_id dal DB
            if (p._hostID == 0)
            {
                p._hostID = GetHostId(p);
            }

            // definisce lo stato "Indicizzazione in corso"
            int status = 2;

            // se siamo in sola aggiunta dell'host: mettilo come "Da indicizzare"
            if (GlobalVars.args.add2Hostlist == true)
            {
                status = 0;
            }

            // se l'host non è presente nel DB: inseriscilo
            if (p._hostID == 0)
            {
                GlobalVars.mysqlConn.connHostList.executeSQLQuery("INSERT IGNORE INTO hostlist (hostname, port, status, lastvisit, crawler_id) VALUES('" + myMySQLEscapeString(p._hostname) + "', " + p._port + ", " + status + ", curdate(), '" + myMySQLEscapeString(GlobalVars.OpenWebSpider.ID) + "')");
                p._hostID = GetHostId(p);
            }
            else
            {
                GlobalVars.mysqlConn.connHostList.executeSQLQuery("UPDATE hostlist SET status = " + status + ", lastvisit=curdate(), crawler_id = '" + myMySQLEscapeString(GlobalVars.OpenWebSpider.ID) + "' WHERE id = " + p._hostID + " limit 1");
            }

            // se siamo in sola aggiunta dell'host: non eliminare l'indice
            if (GlobalVars.args.add2Hostlist == true)
            {
                return(p._hostID);
            }


            // == eliminazione record dell'indice ==

            // a questo punto hostID è sicuramente settato
            // lo usiamo per eliminare le vecchie pagine indicizzate e le relazioni
            if (p._hostID != 0)
            {
                // elimina le pagine
                GlobalVars.mysqlConn.connPageList.executeSQLQuery("DELETE FROM pages where host_id = " + p._hostID);

                // elimina le relazioni
                GlobalVars.mysqlConn.connHostList.executeSQLQuery("DELETE FROM rels where host_id = " + p._hostID);

                // se stiamo indicizzando le immagini: le rimuove
                if (GlobalVars.args.indexImages == true)
                {
                    GlobalVars.mysqlConn.connPageList.executeSQLQuery("DELETE FROM images where src_host_id = " + p._hostID);
                }

                // se stiamo indicizzando gli MP3: rimuovili
                if (GlobalVars.args.indexMP3 == true)
                {
                    GlobalVars.mysqlConn.connPageList.executeSQLQuery("DELETE FROM mp3 where host_id = " + p._hostID);
                }

                // se stiamo indicizzando i PDF: rimuovili
                if (GlobalVars.args.indexPDF == true)
                {
                    GlobalVars.mysqlConn.connPageList.executeSQLQuery("DELETE FROM pdf where host_id = " + p._hostID);
                }
            }

            return(p._hostID);
        }
示例#11
0
        public bool indexThisPage(page p, html h)
        {
            // se negli argomenti è specificato di non indicizzare: esci
            if (GlobalVars.args.noIndex)
            {
                return(false);
            }

            string text2Index = string.Empty;

            try
            {
                // controlla che le regex permettano l'indicizzazione di questa pagina
                // 1. stiamo usano hostlist_extras?
                if (GlobalVars.limits.useHostlist_Extras_limits == true)
                {
                    // 2. c'è una regex valida per le inclusioni?
                    if (GlobalVars.limits.he_regex_include_pages != "")
                    {
                        Regex testIncludePageRegex = new Regex(GlobalVars.limits.he_regex_include_pages, RegexOptions.IgnoreCase);
                        // se la pagina corrente NON VERIFICA l'espressione regolare: non indicizzare
                        if (!testIncludePageRegex.IsMatch(p._page))
                        {
                            return(false);
                        }
                    }

                    // 3. c'è una regex valida per le esclusioni?
                    if (GlobalVars.limits.he_regex_exclude_pages != "")
                    {
                        Regex testExcludePageRegex = new Regex(GlobalVars.limits.he_regex_exclude_pages, RegexOptions.IgnoreCase);
                        // se la pagina corrente VERIFICA l'espressione regolare: non indicizzare
                        if (testExcludePageRegex.IsMatch(p._page))
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                nsGlobalOutput.output.write("\n\n + Error while parsing hostlist_extras regex: " + e.Message + "\n\n");
            }

            if (p.isValidPage && h.HTML != "")
            {
                if (h.contentType.StartsWith("text/html", StringComparison.CurrentCultureIgnoreCase))
                {
                    text2Index = h.UnHTML(h.HTML);
                }
                else if (h.contentType.StartsWith("text/", StringComparison.CurrentCultureIgnoreCase))
                {
                    // indicizza il testo (es.: *.txt; *.c; *.h)
                    text2Index = h.removeUnWantedChars(h.HTML).Trim();
                }
                else
                {
                    return(false);
                }

                return(addContent2Index(p._hostID, p._hostname, p._page, p._title, p._anchorText, p._depthLevel, text2Index, h.HTML));
            }
            return(false);
        }
示例#12
0
        public string getURL(string URL, page p, bool followRedirects)
        {
            errorString = String.Empty;
            contentType = String.Empty;
            statusCode  = 0;
            HTML        = String.Empty;

            try
            {
                HttpWebRequest request = HttpWebRequest.Create(URL) as HttpWebRequest;

                // imposta l'user-agent
                request.UserAgent = GlobalVars.OpenWebSpider.USERAGENT;

                // imposta il timeout (default: un minuto 60.000 ms)
                request.Timeout = GlobalVars.args.reqTimeout * 1000;

                // segue i redirect
                if (followRedirects)
                {
                    request.AllowAutoRedirect            = true;
                    request.MaximumAutomaticRedirections = 5;
                }
                else
                {
                    request.AllowAutoRedirect = false;
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.CharacterSet == null)
                {
                    return(HTML);
                }

                // Support to Encodings
                Encoding responseEncoding;
                responseEncoding = Encoding.UTF8;   //default UTF-8
                if (response.CharacterSet.Trim() != "")
                {
                    responseEncoding = Encoding.GetEncoding(response.CharacterSet);
                }

                StreamReader sr           = new StreamReader(response.GetResponseStream(), responseEncoding);
                BinaryReader binaryStream = new BinaryReader(response.GetResponseStream());

                statusCode = (int)response.StatusCode;

                contentType = response.Headers["Content-Type"];

                // il content-type di questa pagina è testo?
                if (contentType.StartsWith("text", StringComparison.CurrentCultureIgnoreCase))
                {
                    HTML = sr.ReadToEnd();
                }
                else if (GlobalVars.args.indexMP3 && contentType.ToLower() == "audio/mpeg")
                {
                    // se sappiamo chi è il padre e ha un hostID valido allora indicizza l'MP3
                    if (p != null)
                    {
                        if (p.isValidPage && p._hostID > 0)
                        {
                            string fullPath = binaryStream2MD5File(p, binaryStream, response.Headers["Content-Type"], response.Headers["Content-Length"]);

                            mp3 MP3 = new mp3(fullPath);
                            deleteFile(fullPath);

                            MP3.mp3Size = int.Parse(response.Headers["Content-Length"]);

                            db __db = new db();
                            __db.indexMP3(p, MP3);
                        }
                    }
                }
                else if (GlobalVars.args.indexPDF && contentType.ToLower() == "application/pdf")
                {
                    // se sappiamo chi è il padre e ha un hostID valido allora indicizza il PDF
                    if (p != null)
                    {
                        if (p.isValidPage && p._hostID > 0)
                        {
                            string fullPath = binaryStream2MD5File(p, binaryStream, response.Headers["Content-Type"], response.Headers["Content-Length"]);

                            pdf PDF = new pdf(fullPath);
                            deleteFile(fullPath);

                            db __db = new db();
                            __db.indexPDF(p, int.Parse(response.Headers["Content-Length"]), PDF.pdfText);
                        }
                    }
                }
                else
                {
                    HTML = string.Empty;
                }

                // forza l'encoding corrente a UTF-8
                Encoding utf8 = Encoding.Unicode;

                byte[] responseEncodingBytes = responseEncoding.GetBytes(HTML);

                byte[] utf8Bytes = Encoding.Convert(responseEncoding,
                                                    utf8,
                                                    responseEncodingBytes);

                HTML = utf8.GetString(utf8Bytes);

                sr.Close();
            }
            catch (WebException e)
            {
                // TODO: in caso di 404 leggere ugualmente lo stream e ritornare l'HTML

                HttpWebResponse response = (HttpWebResponse)e.Response;
                if (response != null)
                {
                    // in caso di eccezione: prova a recuperare da qui lo status code
                    statusCode = (int)response.StatusCode;

                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        string challenge = null;
                        challenge = response.GetResponseHeader("WWW-Authenticate");
                        if (challenge != null)
                        {
                            errorString = "The following challenge was raised by the server:" + challenge;
                        }
                    }
                    else
                    {
                        errorString = "The following WebException was raised : " + e.Message;
                    }
                }
                else
                {
                    errorString = "Response Received from server was null";
                }
            }
            catch (Exception e)
            {
                errorString = "The following Exception was raised :" + e.Message;
            }

            return(HTML);
        }
示例#13
0
 public string getURL(page p, bool followRedirects)
 {
     return(getURL(p.GenerateURL(), p, followRedirects));
 }
示例#14
0
        // inizia l'indicizzazione
        public bool startCrawling()
        {
            // inizializza le liste degli URL da indicizzare e esterni(cache) + la lista delle relazioni
            GlobalVars.urlsLists.init();
            GlobalVars.externUrlsLists.init();
            GlobalVars.relsList.init();
            GlobalVars.imagesLists.init();

            // inizializza i thread
            threads = new threading();

            bool haveToIndexSomething = true;

            // funzioni per l'accesso al DBs
            db __db = new db();

            // attiva l'handler per la pressione di CTRL+C
            nsGlobalOutput.output.handleCTRLC();

            while (haveToIndexSomething)
            {
                // svuota le liste
                nsGlobalOutput.output.write(" + Clearing structures...");
                GlobalVars.urlsLists.clear();
                GlobalVars.externUrlsLists.l.Clear();
                GlobalVars.relsList.rels.Clear();
                GlobalVars.imagesLists.clear();

                nsGlobalOutput.output.write("");

                // init mutexes
                threads.initMutexes();

                if (isMysqlNeeded())
                {
                    // *******************************************************************
                    nsGlobalOutput.output.write(" + Checking connection to MySQL servers...");
                    if (GlobalVars.mysqlConn.connHostList.ping() == false || GlobalVars.mysqlConn.connPageList.ping() == false)
                    {
                        nsGlobalOutput.output.write("   - One or both MySQL server disconnected, trying to reconnect!");
                        if (mysqlConnect() == false)
                        {
                            nsGlobalOutput.output.write("   - Unable to connect to one or both MySQL server!");
                            break;
                        }
                    }
                    // *******************************************************************

                    // inserisce/aggiorna nel DB il sito corrente e ritorna l'hostID
                    GlobalVars.threadsVars.currentDomain._hostID = __db.startIndexThisSite(GlobalVars.threadsVars.currentDomain);
                }

                // a questo punto ha aggiunto l'HOST al DB: possiamo uscire
                if (GlobalVars.args.add2Hostlist == true)
                {
                    nsGlobalOutput.output.write("\n\n");
                    nsGlobalOutput.output.write(" + Host added to the table of the hosts!");
                    nsGlobalOutput.output.write("   - Hostname : " + GlobalVars.threadsVars.currentDomain._hostname);
                    nsGlobalOutput.output.write("   - Host ID  : " + GlobalVars.threadsVars.currentDomain._hostID);
                    nsGlobalOutput.output.write("\n\n");
                    break;
                }

                if (isMysqlNeeded())
                {
                    // carica i limiti dal DB [ hostlist_extras ] se presenti
                    GlobalVars.limits.loadHostlistExtraLimits(GlobalVars.threadsVars.currentDomain._hostID);
                }

                GlobalVars.limits.showLimits();

                // setta il tempo esatto di inizio dell'indicizzazione del dominio corrente
                GlobalVars.limits.startTime = DateTime.Now.Ticks;

                // azzera le pagine, i bytes indicizzati e gli errori HTTP
                GlobalVars.limits.curPages      = 0;
                GlobalVars.limits.curBytes      = 0;
                GlobalVars.limits.curErrorCodes = 0;

                // se siamo in stress test non controllare il file robots.txt
                if (GlobalVars.args.stressTest == false)
                {
                    // recupera e analizza il file: robots.txt
                    {
                        robots prb = new robots();
                        http   tmpHttpRobotsTxt = new http();
                        string tmpsRobotsTxt;
                        tmpsRobotsTxt = tmpHttpRobotsTxt.getURL("http://" + GlobalVars.threadsVars.currentDomain._hostname + ":" + GlobalVars.threadsVars.currentDomain._port + "/robots.txt", null, false);
                        if (tmpHttpRobotsTxt.statusCode == 200)
                        {
                            prb.parseRobotsTxt(tmpsRobotsTxt);
                        }
                        else
                        {
                            nsGlobalOutput.output.write("   - robots.txt not found");
                        }
                    }
                }

                nsGlobalOutput.output.write("");

                // aggiunge al primo posto della lista la prima pagina da indicizzare
                GlobalVars.urlsLists.addURL(GlobalVars.threadsVars.currentDomain);

                // crea i threads che indicizzeranno le pagine
                try
                {
                    threads.createThreads();
                }
                catch (Exception e)
                {
                    nsGlobalOutput.output.write("   - Error while creating threads: " + e.Message);
                    threads.killThreads();
                    return(false);
                }

                try
                {
                    bool waitThreads = true;

                    while (waitThreads)
                    {
                        System.Threading.Thread.Sleep(250);

                        __db.checkCrawlerAct();

                        // se abbiamo premuto CTRL+C : esci dal ciclo di indicizzazione
                        if (GlobalVars.OpenWebSpider.stopItGracefully == true)
                        {
                            waitThreads = false;
                        }

                        // controlla ogni tot millisecondi se ci sono altre pagine da indicizzare
                        // se no: passa al prossimo dominio

                        GlobalVars.threadsVars.mutexAccessURLList.WaitOne();
                        try
                        {
                            if (GlobalVars.urlsLists.getPageByStatus(0) == null && GlobalVars.urlsLists.getPageByStatus(2) == null)
                            {
                                waitThreads = false;
                            }
                        }
                        catch (Exception e)
                        {
                            nsGlobalOutput.output.write("   - Error 1 [Wait Threads]: " + e.Message);
                        }
                        finally
                        {
                            GlobalVars.threadsVars.mutexAccessURLList.ReleaseMutex();
                        }

                        // controlla i limiti
                        if (GlobalVars.limits.checkLimits() == false)
                        {
                            waitThreads = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    nsGlobalOutput.output.write("   - Error 2 [Wait Threads]: " + e.Message);
                }

                // killa i threads
                threads.killThreads();


                // *******************************************************************
                // ri-controlla la connessione al mysql e se down prova a ristabilirla
                if (isMysqlNeeded())
                {
                    nsGlobalOutput.output.write(" + Checking connection to MySQL servers...");
                    if (GlobalVars.mysqlConn.connHostList.ping() == false || GlobalVars.mysqlConn.connPageList.ping() == false)
                    {
                        nsGlobalOutput.output.write("   - One or both MySQL server disconnected, trying to reconnect!");
                        if (mysqlConnect() == false)
                        {
                            nsGlobalOutput.output.write("   - Unable to connect to one or both MySQL server!");
                            break;
                        }
                    }
                }

                // *******************************************************************

                // aggiorna nel DB il sito corrente ("indicizzato"; status = 1)
                __db.stopIndexThisSite(GlobalVars.threadsVars.currentDomain);

                // stampa le statistiche di indicizzazione
                printCurDomainStats();

                if (isMysqlNeeded())
                {
                    // lascia intatti i duplicati?
                    if (!GlobalVars.args.keepDup)
                    {
                        // elimina le pagine con MD5 duplicato lasciando solo quella con id minore
                        __db.deleteDuplicatedPages(GlobalVars.threadsVars.currentDomain._hostID);
                    }

                    // riversa gli URL esterni trovati nel DB
                    __db.swapExternURLs2DB();

                    // salva le relazioni nel DB
                    __db.saveRels();

                    //salva le immagini
                    __db.saveImages();

                    // calcolo del rank delle pagine
                    new rank(GlobalVars.threadsVars.currentDomain._hostID);
                }

                // c'è stata una pressione di CTRL+C : esci
                if (GlobalVars.OpenWebSpider.stopItGracefully == true)
                {
                    break;
                }

                // abbiamo indicizzato il primo sito! dobbiamo continuare?
                if (GlobalVars.args.singleHostMode == true)
                {
                    haveToIndexSomething = false;                      // siamo in single host mode; non indicizzare nient'altro
                }
                else
                {
                    // recupera il primo host libero dal DB
                    page p = __db.getFirstAvailableURL();

                    if (p == null)
                    {
                        // impossibile trovare un URL: esci!!!
                        haveToIndexSomething = false;

                        nsGlobalOutput.output.write(" + Nothing to do: no available website to index!!! (Try to add: --add-external to the command line arguments) ");
                    }
                    else
                    {
                        // imposta il dominio corrente da indicizzare
                        GlobalVars.threadsVars.currentDomain = p;
                        haveToIndexSomething = true;
                    }
                }
            }

            return(true);
        }