Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4051 lines
130 KiB

  1. // TODO: Allow trident to download frames (and process new html)
  2. // nuke urlmon code (use trident always)
  3. #include "private.h"
  4. #include "shui.h"
  5. #include "downld.h"
  6. #include "subsmgrp.h"
  7. #include <ocidl.h>
  8. #include <initguid.h>
  9. #include <mluisupp.h>
  10. extern HICON g_webCrawlerIcon;
  11. extern HICON g_channelIcon;
  12. extern HICON g_desktopIcon;
  13. void LoadDefaultIcons();
  14. #undef TF_THISMODULE
  15. #define TF_THISMODULE TF_WEBCRAWL
  16. #define _ERROR_REPROCESSING -1
  17. // DWORD field of the m_pPages string list
  18. const DWORD DATA_RECURSEMASK = 0x000000FF; // Levels of recursion from this page
  19. const DWORD DATA_DLSTARTED = 0x80000000; // Have we started downloading
  20. const DWORD DATA_DLFINISHED = 0x40000000; // Have we finished this page
  21. const DWORD DATA_DLERROR = 0x20000000; // An error during download
  22. const DWORD DATA_CODEBASE = 0x10000000; // Is codebase
  23. const DWORD DATA_LINK = 0x08000000; // Is link from page (not dependency)
  24. // DWORD field of m_pPendingLinks string list
  25. const DWORD DATA_ROBOTSTXTMASK=0x00000FFF; // index into m_pRobotsTxt list
  26. // used internally; not actually stored in string list field
  27. const DWORD DATA_ROBOTSTXT = 0x01000000; // Is robots.txt
  28. // m_pDependencyLinks uses m_pPages values
  29. // DWORD field of m_pRobotsTxt is NULL or (CWCDwordStringList *)
  30. // DWORD field of m_pRobotsTxt referenced string list
  31. const DWORD DATA_ALLOW = 0x80000000;
  32. const DWORD DATA_DISALLOW = 0x40000000;
  33. const WCHAR c_wszRobotsMetaName[] = L"Robots\n";
  34. const int c_iRobotsMetaNameLen = 7; // string len without nullterm
  35. const WCHAR c_wszRobotsNoFollow[] = L"NoFollow";
  36. const int c_iRobotsNoFollow = 8;
  37. const WCHAR c_wszRobotsTxtURL[] = L"/robots.txt";
  38. const DWORD MAX_ROBOTS_SIZE = 8192; // Max size of robots.txt file
  39. // tokens for parsing of robots.txt
  40. const CHAR c_szRobots_UserAgent[] = "User-Agent:";
  41. const CHAR c_szRobots_OurUserAgent[] = "MSIECrawler";
  42. const CHAR c_szRobots_Allow[] = "Allow:";
  43. const CHAR c_szRobots_Disallow[] = "Disallow:";
  44. // This GUID comes from Trident and is a hack for getting PARAM values for APPLET tags.
  45. DEFINE_GUID(CGID_JavaParambagCompatHack, 0x3050F405, 0x98B5, 0x11CF, 0xBB, 0x82, 0x00, 0xAA, 0x00, 0xBD, 0xCE, 0x0B);
  46. // This GUID is helpfully not defined elsewhere.
  47. DEFINE_GUID(CLSID_JavaVM, 0x08B0E5C0, 0x4FCB, 0x11CF, 0xAA, 0xA5, 0x00, 0x40, 0x1C, 0x60, 0x85, 0x01);
  48. // Get host channel agent's subscription item, if any.
  49. inline HRESULT CWebCrawler::GetChannelItem(ISubscriptionItem **ppChannelItem)
  50. {
  51. IServiceProvider *pSP;
  52. HRESULT hr = E_NOINTERFACE;
  53. if (ppChannelItem)
  54. *ppChannelItem = NULL;
  55. if (SUCCEEDED(m_pAgentEvents->QueryInterface(IID_IServiceProvider, (void **)&pSP)) && pSP)
  56. {
  57. ISubscriptionItem *pTempChannelItem = NULL;
  58. pSP->QueryService(CLSID_ChannelAgent, IID_ISubscriptionItem, (void **)&pTempChannelItem);
  59. pSP->Release();
  60. if(pTempChannelItem)
  61. hr = S_OK;
  62. if(ppChannelItem)
  63. *ppChannelItem = pTempChannelItem;
  64. else
  65. {
  66. if(pTempChannelItem)
  67. pTempChannelItem->Release();
  68. }
  69. }
  70. return hr;
  71. }
  72. //////////////////////////////////////////////////////////////////////////
  73. //
  74. // Helper functions - copied over from urlmon\download\helpers.cxx - Is there
  75. // an equivalent routine or better place for this, webcrawl.cpp?
  76. //
  77. //////////////////////////////////////////////////////////////////////////
  78. // ---------------------------------------------------------------------------
  79. // %%Function: GetVersionFromString
  80. //
  81. // converts version in text format (a,b,c,d) into two dwords (a,b), (c,d)
  82. // The printed version number is of format a.b.d (but, we don't care)
  83. // ---------------------------------------------------------------------------
  84. HRESULT
  85. GetVersionFromString(const char *szBuf, LPDWORD pdwFileVersionMS, LPDWORD pdwFileVersionLS)
  86. {
  87. const char *pch = szBuf;
  88. char ch;
  89. *pdwFileVersionMS = 0;
  90. *pdwFileVersionLS = 0;
  91. if (!pch) // default to zero if none provided
  92. return S_OK;
  93. if (StrCmpA(pch, "-1,-1,-1,-1") == 0) {
  94. *pdwFileVersionMS = 0xffffffff;
  95. *pdwFileVersionLS = 0xffffffff;
  96. }
  97. USHORT n = 0;
  98. USHORT a = 0;
  99. USHORT b = 0;
  100. USHORT c = 0;
  101. USHORT d = 0;
  102. enum HAVE { HAVE_NONE, HAVE_A, HAVE_B, HAVE_C, HAVE_D } have = HAVE_NONE;
  103. for (ch = *pch++;;ch = *pch++) {
  104. if ((ch == ',') || (ch == '\0')) {
  105. switch (have) {
  106. case HAVE_NONE:
  107. a = n;
  108. have = HAVE_A;
  109. break;
  110. case HAVE_A:
  111. b = n;
  112. have = HAVE_B;
  113. break;
  114. case HAVE_B:
  115. c = n;
  116. have = HAVE_C;
  117. break;
  118. case HAVE_C:
  119. d = n;
  120. have = HAVE_D;
  121. break;
  122. case HAVE_D:
  123. return E_INVALIDARG; // invalid arg
  124. }
  125. if (ch == '\0') {
  126. // all done convert a,b,c,d into two dwords of version
  127. *pdwFileVersionMS = ((a << 16)|b);
  128. *pdwFileVersionLS = ((c << 16)|d);
  129. return S_OK;
  130. }
  131. n = 0; // reset
  132. } else if ( (ch < '0') || (ch > '9'))
  133. return E_INVALIDARG; // invalid arg
  134. else
  135. n = n*10 + (ch - '0');
  136. } /* end forever */
  137. // NEVERREACHED
  138. }
  139. /////////////////////////////////////////////////////////////////////////////////////////
  140. // CombineBaseAndRelativeURLs -
  141. // Three URLs are combined by following rules (this is used for finding the URL
  142. // to load Applet CABs from.) Three inputs, the Base URL, the Code Base URL
  143. // and the file name URL.
  144. //
  145. // If file name URL is absolute return it.
  146. // Otherwise if CodeBase URL is absolute combine it with filename and return.
  147. // Otherwise if Base URL is absolute, combine CodeBase and fileName URL, then
  148. // combine with Base URL and return it.
  149. ////////////////////////////////////////////////////////////////////////////////////////
  150. HRESULT CombineBaseAndRelativeURLs(LPCWSTR szBaseURL, LPCWSTR szRelative1, LPWSTR *szRelative2)
  151. {
  152. WCHAR wszTemp[INTERNET_MAX_URL_LENGTH];
  153. DWORD dwLen = ARRAYSIZE(wszTemp);
  154. ASSERT(szRelative2); // should never happen.
  155. if (szRelative2 == NULL)
  156. return E_FAIL;
  157. if (IsValidURL(NULL, *szRelative2, 0) == S_OK)
  158. return S_OK;
  159. if (szRelative1 && (IsValidURL(NULL, szRelative1, 0) == S_OK))
  160. {
  161. if (SUCCEEDED(UrlCombineW((LPCWSTR)szRelative1, (LPCWSTR)*szRelative2, (LPWSTR)wszTemp, &dwLen, 0)))
  162. {
  163. BSTR bstrNew = SysAllocString(wszTemp);
  164. if (bstrNew)
  165. {
  166. SAFEFREEBSTR(*szRelative2);
  167. *szRelative2 = bstrNew;
  168. return S_OK;
  169. }
  170. }
  171. }
  172. if (szBaseURL && (IsValidURL(NULL, szBaseURL, 0) == S_OK))
  173. {
  174. LPWSTR szNewRel = NULL;
  175. WCHAR wszCombined[INTERNET_MAX_URL_LENGTH];
  176. if (szRelative1)
  177. {
  178. // NOTE: lstr[cpy|cat]W are macroed to work on Win95.
  179. DWORD dwLen2 = lstrlenW(*szRelative2);
  180. StrCpyNW(wszTemp, szRelative1, ARRAYSIZE(wszTemp) - 1); //paranoia
  181. DWORD dwTempLen = lstrlenW(wszTemp);
  182. if ((dwLen2 > 0) && ((*szRelative2)[dwLen2-1] == (unsigned short)L'\\') ||
  183. ((*szRelative2)[dwLen2-1] == (unsigned short) L'/'))
  184. {
  185. StrNCatW(wszTemp, *szRelative2, ARRAYSIZE(wszTemp) - dwTempLen);
  186. }
  187. else
  188. {
  189. StrNCatW(wszTemp, L"/", ARRAYSIZE(wszTemp) - dwTempLen);
  190. StrNCatW(wszTemp, *szRelative2, ARRAYSIZE(wszTemp) - dwTempLen - 1);
  191. }
  192. szNewRel = wszTemp;
  193. }
  194. else
  195. {
  196. szNewRel = *szRelative2;
  197. }
  198. dwLen = INTERNET_MAX_URL_LENGTH;
  199. if (SUCCEEDED(UrlCombineW((LPCWSTR)szBaseURL, (LPCWSTR)szNewRel, (LPWSTR)wszCombined, &dwLen, 0)))
  200. {
  201. BSTR bstrNew = SysAllocString(wszCombined);
  202. if (bstrNew)
  203. {
  204. SAFEFREEBSTR(*szRelative2);
  205. *szRelative2 = bstrNew;
  206. return S_OK;
  207. }
  208. }
  209. }
  210. // In all likelyhood one of the URL's in bad and nothing good can be done.
  211. return E_FAIL;
  212. }
  213. //////////////////////////////////////////////////////////////////////////
  214. //
  215. // CWebCrawler implementation
  216. //
  217. //////////////////////////////////////////////////////////////////////////
  218. //
  219. // CWebCrawler Helpers
  220. //
  221. CWebCrawler::CWebCrawler()
  222. {
  223. DBG("Creating CWebCrawler object");
  224. InitializeCriticalSection(&m_critDependencies);
  225. }
  226. CWebCrawler::~CWebCrawler()
  227. {
  228. _CleanUp();
  229. DeleteCriticalSection(&m_critDependencies);
  230. DBG("Destroyed CWebCrawler object");
  231. }
  232. void CWebCrawler::CleanUp()
  233. {
  234. _CleanUp();
  235. CDeliveryAgent::CleanUp();
  236. }
  237. void CWebCrawler::_CleanUp()
  238. {
  239. if (m_pCurDownload)
  240. {
  241. m_pCurDownload->DoneDownloading();
  242. m_pCurDownload->Release();
  243. m_pCurDownload = NULL;
  244. }
  245. CRunDeliveryAgent::SafeRelease(m_pRunAgent);
  246. SAFEFREEBSTR(m_bstrHostName);
  247. SAFEFREEBSTR(m_bstrBaseURL);
  248. SAFELOCALFREE(m_pszLocalDest);
  249. SAFELOCALFREE(m_pBuf);
  250. EnterCriticalSection(&m_critDependencies);
  251. SAFEDELETE(m_pDependencies);
  252. LeaveCriticalSection(&m_critDependencies);
  253. if (m_pDownloadNotify)
  254. {
  255. m_pDownloadNotify->LeaveMeAlone();
  256. m_pDownloadNotify->Release();
  257. m_pDownloadNotify=NULL;
  258. }
  259. SAFEDELETE(m_pPages);
  260. SAFEDELETE(m_pPendingLinks);
  261. SAFEDELETE(m_pDependencyLinks);
  262. SAFERELEASE(m_pUrlIconHelper);
  263. FreeRobotsTxt();
  264. FreeCodeBaseList();
  265. }
  266. // Format of m_pRobotsTxt:
  267. // Array of hostnames for which we have attempted to get Robots.txt
  268. // DWORD for each hostname contains pointer to CDwordStringList of Robots.txt data,
  269. // or 0 if we couldn't find robots.txt for that host name
  270. // Robots.txt data stored in form: url, flag = allow or disallow
  271. void CWebCrawler::FreeRobotsTxt()
  272. {
  273. if (m_pRobotsTxt)
  274. {
  275. DWORD_PTR dwPtr;
  276. int iLen = m_pRobotsTxt->NumStrings();
  277. for (int i=0; i<iLen; i++)
  278. {
  279. dwPtr = m_pRobotsTxt->GetStringData(i);
  280. if (dwPtr)
  281. {
  282. delete ((CWCStringList *)dwPtr);
  283. m_pRobotsTxt->SetStringData(i, 0);
  284. }
  285. }
  286. delete m_pRobotsTxt;
  287. m_pRobotsTxt = NULL;
  288. }
  289. }
  290. void CWebCrawler::FreeCodeBaseList()
  291. {
  292. if (m_pCodeBaseList) {
  293. CCodeBaseHold *pcbh;
  294. int iLen = m_pCodeBaseList->NumStrings();
  295. for (int i=0; i<iLen; i++)
  296. {
  297. pcbh = (CCodeBaseHold *)m_pCodeBaseList->GetStringData(i);
  298. if (pcbh != NULL)
  299. {
  300. SAFEFREEBSTR(pcbh->szDistUnit);
  301. SAFEDELETE(pcbh);
  302. m_pCodeBaseList->SetStringData(i, 0);
  303. }
  304. }
  305. SAFEDELETE(m_pCodeBaseList);
  306. }
  307. }
  308. HRESULT CWebCrawler::StartOperation()
  309. {
  310. ISubscriptionItem *pItem = m_pSubscriptionItem;
  311. DWORD dwTemp;
  312. ASSERT(pItem);
  313. DBG("CWebCrawler in StartOperation");
  314. if (m_pCurDownload || GetBusy())
  315. {
  316. DBG_WARN("Webcrawl busy, returning failure");
  317. return E_FAIL;
  318. }
  319. SAFEFREEBSTR(m_bstrBaseURL);
  320. if (FAILED(
  321. ReadBSTR(pItem, c_szPropURL, &m_bstrBaseURL)) ||
  322. !m_bstrBaseURL ||
  323. !CUrlDownload::IsValidURL(m_bstrBaseURL))
  324. {
  325. DBG_WARN("Couldn't get valid URL, aborting");
  326. SetEndStatus(E_INVALIDARG);
  327. SendUpdateNone();
  328. return E_INVALIDARG;
  329. }
  330. if (SHRestricted2W(REST_NoSubscriptionContent, NULL, 0))
  331. SetAgentFlag(FLAG_CHANGESONLY);
  332. if (IsAgentFlagSet(FLAG_CHANGESONLY))
  333. {
  334. m_dwRecurseLevels = 0;
  335. m_dwRecurseFlags = WEBCRAWL_DONT_MAKE_STICKY;
  336. DBG("Webcrawler is in 'changes only' mode.");
  337. }
  338. else
  339. {
  340. /*
  341. BSTR bstrLocalDest=NULL;
  342. SAFELOCALFREE(m_pszLocalDest);
  343. ReadBSTR(c_szPropCrawlLocalDest, &bstrLocalDest);
  344. if (bstrLocalDest && bstrLocalDest[0])
  345. {
  346. int iLen = SysStringByteLen(bstrLocalDest)+1;
  347. m_pszLocalDest = (LPTSTR) MemAlloc(LMEM_FIXED, iLen);
  348. if (m_pszLocalDest)
  349. {
  350. MyOleStrToStrN(m_pszLocalDest, iLen, bstrLocalDest);
  351. }
  352. }
  353. SAFEFREEBSTR(bstrLocalDest);
  354. */
  355. m_dwRecurseLevels=0;
  356. ReadDWORD(pItem, c_szPropCrawlLevels, &m_dwRecurseLevels);
  357. if (!IsAgentFlagSet(DELIVERY_AGENT_FLAG_NO_RESTRICTIONS))
  358. {
  359. // Note: MaxWebcrawlLevels is stored as N+1 because 0
  360. // disables the restriction
  361. dwTemp = SHRestricted2W(REST_MaxWebcrawlLevels, NULL, 0);
  362. if (dwTemp && m_dwRecurseLevels >= dwTemp)
  363. m_dwRecurseLevels = dwTemp - 1;
  364. }
  365. m_dwRecurseFlags=0;
  366. ReadDWORD(pItem, c_szPropCrawlFlags, &m_dwRecurseFlags);
  367. // Read max size in cache in KB
  368. m_dwMaxSize=0;
  369. ReadDWORD(pItem, c_szPropCrawlMaxSize, &m_dwMaxSize);
  370. if (!IsAgentFlagSet(DELIVERY_AGENT_FLAG_NO_RESTRICTIONS))
  371. {
  372. dwTemp = SHRestricted2W(REST_MaxSubscriptionSize, NULL, 0);
  373. if (dwTemp && (!m_dwMaxSize || m_dwMaxSize > dwTemp))
  374. m_dwMaxSize = dwTemp;
  375. }
  376. if (IsRecurseFlagSet(WEBCRAWL_DONT_MAKE_STICKY))
  377. dwTemp = 0;
  378. // Read old group ID
  379. ReadLONGLONG(pItem, c_szPropCrawlGroupID, &m_llOldCacheGroupID);
  380. // Read new ID if present
  381. m_llCacheGroupID = 0;
  382. ReadLONGLONG(pItem, c_szPropCrawlNewGroupID, &m_llCacheGroupID);
  383. if (m_llCacheGroupID)
  384. {
  385. DBG("Adding to existing cache group");
  386. }
  387. } // !ChangesOnly
  388. // finish initializing new operation
  389. m_iDownloadErrors = 0;
  390. m_dwCurSize = 0;
  391. m_lMaxNumUrls = (m_dwRecurseLevels) ? -1 : 1;
  392. SAFEFREEBSTR(m_bstrHostName);
  393. m_dwCurSize = NULL;
  394. m_pPages = NULL;
  395. m_pDependencies = NULL;
  396. // After calling this, we'll reenter either in "StartDownload" (connection successful)
  397. // or in "AbortUpdate" with GetEndStatus() == INET_E_AGENT_CONNECTION_FAILED
  398. return CDeliveryAgent::StartOperation();
  399. }
  400. HRESULT CWebCrawler::AgentPause(DWORD dwFlags)
  401. {
  402. DBG("CWebCrawler::AgentPause");
  403. // Abort our current url
  404. if (m_pRunAgent)
  405. {
  406. m_pRunAgent->AgentPause(dwFlags);
  407. }
  408. if (m_pCurDownload)
  409. {
  410. m_pCurDownload->AbortDownload();
  411. m_pCurDownload->DestroyBrowser();
  412. }
  413. return CDeliveryAgent::AgentPause(dwFlags);
  414. }
  415. HRESULT CWebCrawler::AgentResume(DWORD dwFlags)
  416. {
  417. DBG("CWebCrawler::AgentResume");
  418. if (m_pRunAgent)
  419. {
  420. m_pRunAgent->AgentResume(dwFlags);
  421. }
  422. else
  423. {
  424. // If we just increased our cache size, reprocess same url
  425. if (SUBSCRIPTION_AGENT_RESUME_INCREASED_CACHE & dwFlags)
  426. {
  427. DBG("CWebCrawler reprocessing same url after cache size increase");
  428. OnDownloadComplete(0, _ERROR_REPROCESSING);
  429. }
  430. else
  431. {
  432. // If we're not still downloading, restart our same url
  433. if (0 == m_iNumPagesDownloading)
  434. {
  435. if (FAILED(ActuallyStartDownload(m_pCurDownloadStringList, m_iCurDownloadStringIndex, TRUE)))
  436. {
  437. ASSERT_MSG(0, "CWebCrawler::AgentResume"); // this should never happen
  438. SetEndStatus(E_FAIL);
  439. CleanUp();
  440. }
  441. }
  442. }
  443. }
  444. return CDeliveryAgent::AgentResume(dwFlags);
  445. }
  446. // Forcibly abort current operation
  447. HRESULT CWebCrawler::AgentAbort(DWORD dwFlags)
  448. {
  449. DBG("CWebCrawler::AgentAbort");
  450. if (m_pCurDownload)
  451. {
  452. m_pCurDownload->DoneDownloading();
  453. }
  454. if (m_pRunAgent)
  455. {
  456. m_pRunAgent->AgentAbort(dwFlags);
  457. }
  458. return CDeliveryAgent::AgentAbort(dwFlags);
  459. }
  460. //---------------------------------------------------------------
  461. //
  462. HRESULT CWebCrawler::StartDownload()
  463. {
  464. ASSERT(!m_pCurDownload);
  465. m_iPagesStarted = 0;
  466. m_iRobotsStarted = 0;
  467. m_iDependencyStarted = 0;
  468. m_iDependenciesProcessed = 0;
  469. m_iTotalStarted = 0;
  470. m_iCodeBaseStarted = 0;
  471. m_iNumPagesDownloading = 0;
  472. // Create new cache group
  473. if (IsAgentFlagSet(FLAG_CHANGESONLY))
  474. {
  475. m_llCacheGroupID = 0;
  476. }
  477. else
  478. {
  479. if (!m_llCacheGroupID)
  480. {
  481. m_llCacheGroupID = CreateUrlCacheGroup(
  482. (IsRecurseFlagSet(WEBCRAWL_DONT_MAKE_STICKY) ? 0 : CACHEGROUP_FLAG_NONPURGEABLE), 0);
  483. ASSERT_MSG(m_llCacheGroupID != 0, "Create cache group failed");
  484. }
  485. }
  486. // Create string lists
  487. m_pPages = new CWCDwordStringList;
  488. if (m_pPages)
  489. m_pPages->Init(m_dwRecurseLevels ? -1 : 512);
  490. else
  491. SetEndStatus(E_FAIL);
  492. if (m_dwRecurseLevels && !IsRecurseFlagSet(WEBCRAWL_IGNORE_ROBOTSTXT))
  493. {
  494. m_pRobotsTxt = new CWCDwordStringList;
  495. if (m_pRobotsTxt)
  496. m_pRobotsTxt->Init(512);
  497. else
  498. SetEndStatus(E_FAIL);
  499. }
  500. // FEATURE : Shouldn't allocate this memory in changes only mode
  501. m_pCodeBaseList = new CWCDwordStringList;
  502. if (m_pCodeBaseList)
  503. m_pCodeBaseList->Init(512);
  504. else
  505. SetEndStatus(E_FAIL);
  506. // Avoid duplicate processing of dependencies
  507. if (!IsAgentFlagSet(FLAG_CHANGESONLY))
  508. {
  509. m_pDependencies = new CWCDwordStringList;
  510. if (m_pDependencies)
  511. m_pDependencies->Init();
  512. else
  513. SetEndStatus(E_FAIL);
  514. }
  515. if (GetEndStatus() == E_FAIL)
  516. return E_FAIL;
  517. m_pCurDownload = new CUrlDownload(this, 0);
  518. if (!m_pCurDownload)
  519. return E_OUTOFMEMORY;
  520. // Add first URL to string list, then start it
  521. if ((CWCStringList::STRLST_ADDED == m_pPages->AddString(m_bstrBaseURL, m_dwRecurseLevels)) &&
  522. m_pPages->NumStrings() == 1)
  523. {
  524. return StartNextDownload();
  525. }
  526. SetEndStatus(E_FAIL);
  527. return E_FAIL;
  528. }
  529. // Attempts to begin the next download
  530. HRESULT CWebCrawler::StartNextDownload()
  531. {
  532. if (!m_pPages || m_iNumPagesDownloading)
  533. return E_FAIL;
  534. CWCStringList *pslUrls = NULL;
  535. int iIndex = 0;
  536. // See if we have any more URLs to download.
  537. // Check dependency links first
  538. if (m_pDependencyLinks)
  539. {
  540. ProcessDependencyLinks(&pslUrls, &iIndex);
  541. #ifdef DEBUG
  542. if (pslUrls) DBG("Downloading dependency link (frame):");
  543. #endif
  544. }
  545. if (!pslUrls)
  546. {
  547. // Check robots.txt
  548. if (m_pRobotsTxt && (m_iRobotsStarted < m_pRobotsTxt->NumStrings()))
  549. {
  550. pslUrls = m_pRobotsTxt;
  551. iIndex = m_iRobotsStarted ++;
  552. }
  553. else if (m_pPendingLinks) // add pending links to pages list
  554. {
  555. // Pending links to process and we've retrieved all robots.txt
  556. // Process pending links (validate & add to download list)
  557. ProcessPendingLinks();
  558. }
  559. if (!pslUrls && (m_iPagesStarted < m_pPages->NumStrings()))
  560. {
  561. DWORD_PTR dwTmp;
  562. ASSERT(!m_pDependencyLinks);// should be downloaded already
  563. ASSERT(!m_pPendingLinks); // should be validated already
  564. // Skip any pages we've started
  565. while (m_iPagesStarted < m_pPages->NumStrings())
  566. {
  567. dwTmp = m_pPages->GetStringData(m_iPagesStarted);
  568. if (IsFlagSet(dwTmp, DATA_DLSTARTED))
  569. m_iPagesStarted++;
  570. else
  571. break;
  572. }
  573. if (m_iPagesStarted < m_pPages->NumStrings())
  574. {
  575. pslUrls = m_pPages;
  576. iIndex = m_iPagesStarted ++;
  577. }
  578. }
  579. if (!pslUrls && (m_iCodeBaseStarted < m_pCodeBaseList->NumStrings()))
  580. {
  581. // Nothing else pull, do code bases last.
  582. while (m_iCodeBaseStarted < m_pCodeBaseList->NumStrings())
  583. {
  584. CCodeBaseHold *pcbh = (CCodeBaseHold *)
  585. m_pCodeBaseList->GetStringData(m_iCodeBaseStarted);
  586. if (IsFlagSet(pcbh->dwFlags, DATA_DLSTARTED))
  587. m_iCodeBaseStarted++;
  588. else
  589. break;
  590. }
  591. while (m_iCodeBaseStarted < m_pCodeBaseList->NumStrings())
  592. {
  593. // We have some codebases to download.
  594. // We return if the download is async and simply
  595. // start the next one if it finishes synchronously
  596. iIndex = m_iCodeBaseStarted;
  597. m_iCodeBaseStarted++; // increment so that next download is not repeated
  598. // Init the cur download infor for resume if paused
  599. m_iCurDownloadStringIndex = iIndex;
  600. m_pCurDownloadStringList = m_pCodeBaseList;
  601. if(ActuallyDownloadCodeBase(m_pCodeBaseList, iIndex, FALSE) == E_PENDING)
  602. return S_OK; // We break out of the while and try next download in OnAgentEnd()
  603. }
  604. }
  605. }
  606. if (pslUrls)
  607. {
  608. m_iCurDownloadStringIndex = iIndex;
  609. m_pCurDownloadStringList = pslUrls;
  610. return ActuallyStartDownload(pslUrls, iIndex);
  611. }
  612. DBG("WebCrawler: StartNextDownload failing, nothing more to download.");
  613. return E_FAIL;
  614. }
  615. HRESULT CWebCrawler::ActuallyStartDownload(CWCStringList *pslUrls, int iIndex, BOOL fReStart /* = FALSE */)
  616. {
  617. // We have urls to download. Do it.
  618. DWORD_PTR dwData;
  619. LPCWSTR pwszURL;
  620. DWORD dwBrowseFlags;
  621. BDUMethod method;
  622. BDUOptions options;
  623. if(pslUrls == m_pCodeBaseList)
  624. {
  625. ASSERT(fReStart); // Should happen only with resume
  626. HRESULT hr = ActuallyDownloadCodeBase(m_pCodeBaseList, iIndex, fReStart);
  627. if(E_PENDING == hr)
  628. return S_OK;
  629. return E_FAIL; // hackhack - since we don't handle synchronous downloads well - we hang if
  630. // resumed download is synchronous
  631. }
  632. if (pslUrls != m_pRobotsTxt)
  633. {
  634. dwData = pslUrls->GetStringData(iIndex);
  635. #ifdef DEBUG
  636. if (fReStart)
  637. if (~(dwData & DATA_DLSTARTED)) DBG_WARN("WebCrawler: Trying to restart one we haven't started yet!");
  638. else
  639. if ((dwData & DATA_DLSTARTED)) DBG_WARN("WebCrawler: Trying to download one we've already started?");
  640. #endif
  641. pslUrls->SetStringData(iIndex, DATA_DLSTARTED | dwData);
  642. }
  643. else
  644. dwData = DATA_ROBOTSTXT;
  645. pwszURL = pslUrls->GetString(iIndex);
  646. ASSERT(iIndex < pslUrls->NumStrings());
  647. #ifdef DEBUG
  648. int iMax = m_lMaxNumUrls;
  649. if (iMax<0)
  650. iMax = m_pPages->NumStrings() + ((m_pRobotsTxt) ? m_pRobotsTxt->NumStrings() : 0);
  651. TraceMsgA(TF_THISMODULE, "WebCrawler GET_URL (%d of %c%d) Recurse %d : %ws",
  652. m_iTotalStarted+1, ((m_lMaxNumUrls>0) ? ' ' : '?'), iMax,
  653. pslUrls->GetStringData(iIndex) & DATA_RECURSEMASK, pwszURL);
  654. #endif
  655. dwBrowseFlags = DLCTL_DOWNLOADONLY |
  656. DLCTL_NO_FRAMEDOWNLOAD | DLCTL_NO_SCRIPTS | DLCTL_NO_JAVA |
  657. DLCTL_NO_RUNACTIVEXCTLS;
  658. if (IsRecurseFlagSet(WEBCRAWL_GET_IMAGES)) dwBrowseFlags |= DLCTL_DLIMAGES;
  659. if (IsRecurseFlagSet(WEBCRAWL_GET_VIDEOS)) dwBrowseFlags |= DLCTL_VIDEOS;
  660. if (IsRecurseFlagSet(WEBCRAWL_GET_BGSOUNDS)) dwBrowseFlags |= DLCTL_BGSOUNDS;
  661. if (!IsRecurseFlagSet(WEBCRAWL_GET_CONTROLS)) dwBrowseFlags |= DLCTL_NO_DLACTIVEXCTLS;
  662. if (IsRecurseFlagSet(WEBCRAWL_PRIV_OFFLINE_MODE))
  663. {
  664. dwBrowseFlags |= DLCTL_FORCEOFFLINE;
  665. dwBrowseFlags &= ~(DLCTL_DLIMAGES | DLCTL_VIDEOS | DLCTL_BGSOUNDS);
  666. DBG("GET is OFFLINE");
  667. }
  668. m_pCurDownload->SetDLCTL(dwBrowseFlags);
  669. #ifdef DEBUG
  670. if (fReStart)
  671. {
  672. ASSERT(m_iCurDownloadStringIndex == iIndex);
  673. ASSERT(m_pCurDownloadStringList == pslUrls);
  674. }
  675. #endif
  676. if (!fReStart)
  677. {
  678. // Get the info for change detection, unless we already know it's changed
  679. if (!IsAgentFlagSet(FLAG_CRAWLCHANGED) && !(dwData & DATA_ROBOTSTXT))
  680. {
  681. TCHAR szUrl[INTERNET_MAX_URL_LENGTH];
  682. m_varChange.vt = VT_EMPTY;
  683. if (IsAgentFlagSet(FLAG_CHANGESONLY))
  684. {
  685. // "Changes Only" mode, we have persisted a change detection code
  686. ASSERT(m_iTotalStarted == 0);
  687. LPCWSTR pPropChange = c_szPropChangeCode;
  688. m_pSubscriptionItem->ReadProperties(1, &pPropChange, &m_varChange);
  689. }
  690. BOOL fMustGET = TRUE;
  691. MyOleStrToStrN(szUrl, INTERNET_MAX_URL_LENGTH, pwszURL);
  692. PreCheckUrlForChange(szUrl, &m_varChange, &fMustGET);
  693. if (IsAgentFlagSet(FLAG_CHANGESONLY) && !fMustGET)
  694. SetAgentFlag(FLAG_HEADONLY);
  695. }
  696. m_iTotalStarted ++;
  697. }
  698. if (IsPaused())
  699. {
  700. DBG("WebCrawler paused, not starting another download");
  701. if (m_pCurDownload)
  702. m_pCurDownload->DestroyBrowser(); // free browser until resumed
  703. return E_PENDING;
  704. }
  705. m_iNumPagesDownloading ++;
  706. // Send our update progress with the url we're about to download
  707. SendUpdateProgress(pwszURL, m_iTotalStarted, m_lMaxNumUrls, (m_dwCurSize >> 10));
  708. if (IsAgentFlagSet(FLAG_HEADONLY))
  709. {
  710. ASSERT(m_iTotalStarted == 1);
  711. method = BDU2_HEADONLY; // Only get HEAD info with Urlmon
  712. }
  713. else if (IsAgentFlagSet(FLAG_CHANGESONLY) // Only want HTML, or
  714. || m_pszLocalDest // We're going to move this one file, or
  715. || (dwData & DATA_ROBOTSTXT)) // This is a robots.txt, so
  716. {
  717. method = BDU2_URLMON; // Get with Urlmon
  718. }
  719. else if (m_iTotalStarted == 1) // First file, we need status code, so
  720. {
  721. ISubscriptionItem *pCDFItem;
  722. method = BDU2_SNIFF; // Get with Urlmon then MSHTML (if HTML)
  723. // Find out if we're hosted by channel agent
  724. if (SUCCEEDED(GetChannelItem(&pCDFItem)))
  725. {
  726. // If we're hosted by channel agent, use its original hostname
  727. BSTR bstrBaseUrl;
  728. if (SUCCEEDED(ReadBSTR(pCDFItem, c_szPropURL, &bstrBaseUrl)))
  729. {
  730. GetHostName(bstrBaseUrl, &m_bstrHostName);
  731. SysFreeString(bstrBaseUrl);
  732. }
  733. #ifdef DEBUG
  734. if (m_bstrHostName)
  735. TraceMsg(TF_THISMODULE, "Got host name from channel agent: %ws", m_bstrHostName);
  736. #endif
  737. pCDFItem->Release();
  738. DBG("Using 'smart' mode for first url in webcrawl; spawned from channel crawl");
  739. method = BDU2_SMART; // Use 'smart' mode for first url if channel crawl
  740. SetAgentFlag(FLAG_HOSTED);
  741. }
  742. }
  743. else
  744. method = BDU2_SMART; // Get with Urlmon or MSHTML as appropriate
  745. if (dwData & DATA_ROBOTSTXT)
  746. options = BDU2_NEEDSTREAM; // Need IStream to parse robots.txt
  747. else
  748. options = BDU2_NONE;
  749. options |= BDU2_DOWNLOADNOTIFY_REQUIRED; // Always get download notify callbacks
  750. if (IsRecurseFlagSet(WEBCRAWL_ONLY_LINKS_TO_HTML) && (dwData & DATA_LINK))
  751. {
  752. // Don't follow any links unless they are to html pages.
  753. options |= BDU2_FAIL_IF_NOT_HTML;
  754. }
  755. if (FAILED(m_pCurDownload->BeginDownloadURL2(pwszURL,
  756. method, options, m_pszLocalDest,
  757. m_dwMaxSize ? (m_dwMaxSize<<10)-m_dwCurSize : 0)))
  758. {
  759. DBG("BeginDownloadURL2 failed (ignoring & waiting for OnDownloadComplete call)");
  760. }
  761. return S_OK;
  762. }
  763. HRESULT CWebCrawler::ActuallyDownloadCodeBase(CWCStringList *pslUrls, int iIndex, BOOL fReStart)
  764. {
  765. CCodeBaseHold *pcbh;
  766. LPCWSTR pwszURL;
  767. HRESULT hr = S_OK;
  768. if (pslUrls != m_pCodeBaseList)
  769. {
  770. ASSERT(0);
  771. DBG_WARN("WebCrawler: Wrong URLs being processed as CodeBase.");
  772. hr = E_FAIL;
  773. goto Exit;
  774. }
  775. pcbh = (CCodeBaseHold *)pslUrls->GetStringData(iIndex);
  776. #ifdef DEBUG
  777. if (fReStart)
  778. if (~(pcbh->dwFlags & DATA_DLSTARTED)) DBG_WARN("WebCrawler: Trying to restart CodeBase D/L we haven't started yet!");
  779. else
  780. if ((pcbh->dwFlags & DATA_DLSTARTED)) DBG_WARN("WebCrawler: Trying to download CodeBase D/L we've already started?");
  781. #endif
  782. pcbh->dwFlags |= DATA_DLSTARTED;
  783. pwszURL = pslUrls->GetString(iIndex);
  784. ASSERT(iIndex < pslUrls->NumStrings());
  785. if (!fReStart)
  786. m_iTotalStarted ++;
  787. if (IsPaused())
  788. {
  789. DBG("WebCrawler paused, not starting another download");
  790. if (m_pCurDownload)
  791. m_pCurDownload->DestroyBrowser(); // free browser until resumed
  792. return S_FALSE;
  793. }
  794. m_iNumPagesDownloading ++;
  795. // Send our update progress with the CODEBASE we're about to download
  796. SendUpdateProgress(pwszURL, m_iTotalStarted, m_lMaxNumUrls);
  797. if (m_pRunAgent)
  798. {
  799. ASSERT(0);
  800. DBG_WARN("WebCrawler: Attempting to download next CODEBASE when not done last one.");
  801. hr = E_FAIL;
  802. goto Exit;
  803. }
  804. else
  805. {
  806. // create subscription item for CDL agent.
  807. ISubscriptionItem *pItem = NULL;
  808. if (m_dwMaxSize && ((m_dwCurSize>>10) >= m_dwMaxSize))
  809. {
  810. // We've exceeded our maximum download KB limit and can't continue.
  811. DBG_WARN("WebCrawler: Exceeded Maximum KB download limit with CodeBase download.");
  812. SetEndStatus(hr = INET_E_AGENT_MAX_SIZE_EXCEEDED);
  813. goto Exit;
  814. }
  815. if (!m_pSubscriptionItem ||
  816. FAILED(hr = DoCloneSubscriptionItem(m_pSubscriptionItem, NULL, &pItem)))
  817. {
  818. goto Exit;
  819. }
  820. ASSERT(pItem != NULL);
  821. WriteOLESTR(pItem, c_szPropURL, pwszURL);
  822. WriteOLESTR(pItem, L"DistUnit", pcbh->szDistUnit);
  823. WriteDWORD(pItem, L"VersionMS", pcbh->dwVersionMS);
  824. WriteDWORD(pItem, L"VersionLS", pcbh->dwVersionLS);
  825. if (m_dwMaxSize)
  826. WriteDWORD(pItem, c_szPropCrawlMaxSize, m_dwMaxSize - (m_dwCurSize>>10)); // KB limit for us to pull.
  827. m_pRunAgent = new CRunDeliveryAgent();
  828. if (m_pRunAgent)
  829. hr = m_pRunAgent->Init((CRunDeliveryAgentSink *)this, pItem, CLSID_CDLAgent);
  830. pItem->Release();
  831. if (m_pRunAgent && SUCCEEDED(hr))
  832. {
  833. hr = m_pRunAgent->StartAgent();
  834. //if (hr == E_PENDING)
  835. //{
  836. //hr = S_OK;
  837. //}
  838. }
  839. else
  840. {
  841. hr = E_OUTOFMEMORY;
  842. }
  843. }
  844. Exit:
  845. return hr;
  846. }
  847. HRESULT CWebCrawler::ProcessDependencyLinks(CWCStringList **ppslUrls, int *piStarted)
  848. {
  849. ASSERT(ppslUrls && !*ppslUrls && piStarted);
  850. int iIndex;
  851. DWORD_PTR dwData;
  852. if (!m_pDependencyLinks)
  853. return S_FALSE;
  854. // See if we have any more dependency links to download
  855. while (m_iDependencyStarted < m_pDependencyLinks->NumStrings())
  856. {
  857. if (!m_pPages->FindString(m_pDependencyLinks->GetString(m_iDependencyStarted),
  858. m_pDependencyLinks->GetStringLen(m_iDependencyStarted), &iIndex))
  859. {
  860. ASSERT(0); // find string failed?!? We added it above!
  861. return E_FAIL;
  862. }
  863. ASSERT(iIndex>=0 && iIndex<m_pPages->NumStrings());
  864. m_iDependencyStarted ++;
  865. // See if we've downloaded this yet.
  866. dwData = m_pPages->GetStringData(iIndex);
  867. if (!(dwData & DATA_DLSTARTED))
  868. {
  869. // Nope. Start download.
  870. *ppslUrls = m_pPages;
  871. *piStarted = iIndex;
  872. return S_OK;
  873. }
  874. // We have already downloaded this page. Go to next dependency link.
  875. }
  876. // Done processing. Clear for next page.
  877. SAFEDELETE(m_pDependencyLinks);
  878. return S_FALSE;
  879. }
  880. HRESULT CWebCrawler::ProcessPendingLinks()
  881. {
  882. int iNumLinks, iAddCode, i, iAddIndex, iRobotsIndex;
  883. LPCWSTR pwszUrl;
  884. BOOL fAllow;
  885. if (!m_pPendingLinks)
  886. return S_FALSE;
  887. ASSERT(m_lMaxNumUrls<0);
  888. ASSERT(0 == (m_dwPendingRecurseLevel & ~DATA_RECURSEMASK));
  889. iNumLinks = m_pPendingLinks->NumStrings();
  890. TraceMsg(TF_THISMODULE, "Processing %d pending links from %ws",
  891. iNumLinks, m_pPages->GetString(m_iPagesStarted-1));
  892. // Add the links to our global page list
  893. for (i=0; i<iNumLinks; i++)
  894. {
  895. // Validate with robots.txt if appropriate
  896. pwszUrl = m_pPendingLinks->GetString(i);
  897. iRobotsIndex = (int)(m_pPendingLinks->GetStringData(i) & DATA_ROBOTSTXTMASK);
  898. ValidateWithRobotsTxt(pwszUrl, iRobotsIndex, &fAllow);
  899. if (fAllow)
  900. {
  901. /*
  902. As long as we retrieve pages in decreasing-recursion order (top to bottom), we don't
  903. have to worry about bumping pages to a higher recurse level (except for frames).
  904. */
  905. iAddCode = m_pPages->AddString(pwszUrl,
  906. DATA_LINK | m_dwPendingRecurseLevel,
  907. &iAddIndex);
  908. if (iAddCode == CWCStringList::STRLST_FAIL)
  909. break;
  910. }
  911. }
  912. SAFEDELETE(m_pPendingLinks);
  913. return S_OK;
  914. }
  915. // Combine with our base url to get full url
  916. // We use this for frames, but also for <Link> tags, since the processing is identical
  917. HRESULT CWebCrawler::CheckFrame(IUnknown *punkItem, BSTR *pbstrItem, DWORD_PTR dwBaseUrl, DWORD *pdwStringData)
  918. {
  919. WCHAR wszCombined[INTERNET_MAX_URL_LENGTH];
  920. DWORD dwLen = ARRAYSIZE(wszCombined);
  921. ASSERT(pbstrItem && *pbstrItem && punkItem && dwBaseUrl);
  922. if (!pbstrItem || !*pbstrItem || !punkItem || !dwBaseUrl)
  923. return E_FAIL; // bogus
  924. if (SUCCEEDED(UrlCombineW((LPCWSTR)dwBaseUrl, *pbstrItem, wszCombined, &dwLen, 0)))
  925. {
  926. BSTR bstrNew = SysAllocString(wszCombined);
  927. if (bstrNew)
  928. {
  929. SysFreeString(*pbstrItem);
  930. *pbstrItem = bstrNew;
  931. return S_OK;
  932. }
  933. }
  934. TraceMsg(TF_WARNING, "CWebCrawler::CheckFrame failing. Not getting frame or <link> url=%ws.", *pbstrItem);
  935. return E_FAIL; // Couldn't combine url; don't add
  936. }
  937. // See if we should follow this link. Clears pbstrItem if not.
  938. // Accepts either pLink or pArea
  939. HRESULT CWebCrawler::CheckLink(IUnknown *punkItem, BSTR *pbstrItem, DWORD_PTR dwThis, DWORD *pdwStringData)
  940. {
  941. HRESULT hrRet = S_OK;
  942. CWebCrawler *pThis = (CWebCrawler *)dwThis;
  943. ASSERT(pbstrItem && *pbstrItem && punkItem && dwThis);
  944. if (!pbstrItem || !*pbstrItem || !punkItem || !dwThis)
  945. return E_FAIL; // bogus
  946. // First see if it's 'valid'
  947. // We only add the link if it's HTTP (or https)
  948. // (we don't want to get mailto: links, for example)
  949. if (CUrlDownload::IsValidURL(*pbstrItem))
  950. {
  951. // Strip off any anchor
  952. CUrlDownload::StripAnchor(*pbstrItem);
  953. }
  954. else
  955. {
  956. // Skip this link
  957. SysFreeString(*pbstrItem);
  958. *pbstrItem = NULL;
  959. return S_FALSE;
  960. }
  961. if (pThis->IsRecurseFlagSet(WEBCRAWL_ONLY_LINKS_TO_HTML))
  962. {
  963. // See if we can tell that this is not an HTML link
  964. if (CUrlDownload::IsNonHtmlUrl(*pbstrItem))
  965. {
  966. // Skip this link
  967. SysFreeString(*pbstrItem);
  968. *pbstrItem = NULL;
  969. return S_FALSE;
  970. }
  971. }
  972. if (!(pThis->IsRecurseFlagSet(WEBCRAWL_LINKS_ELSEWHERE)))
  973. {
  974. BSTR bstrHost=NULL;
  975. IHTMLAnchorElement *pLink=NULL;
  976. IHTMLAreaElement *pArea=NULL;
  977. // Check to see if the host names match
  978. punkItem->QueryInterface(IID_IHTMLAnchorElement, (void **)&pLink);
  979. if (pLink)
  980. {
  981. pLink->get_hostname(&bstrHost);
  982. pLink->Release();
  983. }
  984. else
  985. {
  986. punkItem->QueryInterface(IID_IHTMLAreaElement, (void **)&pArea);
  987. if (pArea)
  988. {
  989. pArea->get_hostname(&bstrHost);
  990. pArea->Release();
  991. }
  992. else
  993. {
  994. DBG_WARN("CWebCrawler::CheckLink Unable to get Area or Anchor interface!");
  995. return E_FAIL; // Bad element
  996. }
  997. }
  998. if (!bstrHost || !*bstrHost)
  999. {
  1000. DBG_WARN("CWebCrawler::CheckLink : (pLink|pArea)->get_hostname() failed");
  1001. hrRet = S_OK; // always accept if get_hostname fails
  1002. }
  1003. else
  1004. {
  1005. if (pThis->m_bstrHostName && MyAsciiCmpW(bstrHost, pThis->m_bstrHostName))
  1006. {
  1007. // Skip url; different host name.
  1008. SAFEFREEBSTR(*pbstrItem);
  1009. hrRet = S_FALSE;
  1010. }
  1011. }
  1012. SAFEFREEBSTR(bstrHost);
  1013. }
  1014. if (*pbstrItem && pdwStringData)
  1015. {
  1016. pThis->GetRobotsTxtIndex(*pbstrItem, TRUE, pdwStringData);
  1017. *pdwStringData &= DATA_ROBOTSTXTMASK;
  1018. }
  1019. else if (pdwStringData)
  1020. *pdwStringData = 0;
  1021. return hrRet;
  1022. }
  1023. // S_OK : Already retrieved this robots.txt info
  1024. // S_FALSE : Haven't yet retrieved this robots.txt info
  1025. // E_* : Bad
  1026. HRESULT CWebCrawler::GetRobotsTxtIndex(LPCWSTR pwszUrl, BOOL fAddToList, DWORD *pdwRobotsTxtIndex)
  1027. {
  1028. HRESULT hr=S_OK;
  1029. int iIndex=-1;
  1030. if (m_pRobotsTxt)
  1031. {
  1032. // See which robots.txt file we should use to validate this link
  1033. // If not yet available, add it to the list to be downloaded
  1034. DWORD dwBufLen = lstrlenW(pwszUrl) + ARRAYSIZE(c_wszRobotsTxtURL); //This get's us a terminating NULL
  1035. LPWSTR pwszRobots = (LPWSTR)MemAlloc(LMEM_FIXED, dwBufLen * sizeof(WCHAR));
  1036. int iAddCode;
  1037. if (pwszRobots)
  1038. {
  1039. // PERF: do the internetcombine in startnextdownload
  1040. if (SUCCEEDED(UrlCombineW(pwszUrl, c_wszRobotsTxtURL, pwszRobots, &dwBufLen, 0))
  1041. && !memcmp(pwszRobots, L"http", 4 * sizeof(WCHAR)))
  1042. {
  1043. if (fAddToList)
  1044. {
  1045. iAddCode = m_pRobotsTxt->AddString(pwszRobots, 0, &iIndex);
  1046. }
  1047. else
  1048. {
  1049. if (m_pRobotsTxt->FindString(pwszRobots, -1, &iIndex))
  1050. {
  1051. iAddCode = CWCStringList::STRLST_DUPLICATE;
  1052. }
  1053. else
  1054. {
  1055. iIndex=-1;
  1056. iAddCode = CWCStringList::STRLST_FAIL;
  1057. }
  1058. }
  1059. if (CWCStringList::STRLST_FAIL == iAddCode)
  1060. hr = E_FAIL; // bad news
  1061. else if (CWCStringList::STRLST_ADDED == iAddCode)
  1062. hr = S_FALSE; // haven't gotten it yet
  1063. else
  1064. hr = S_OK; // already got it
  1065. }
  1066. MemFree(pwszRobots);
  1067. }
  1068. else
  1069. hr = E_OUTOFMEMORY;
  1070. }
  1071. else
  1072. {
  1073. hr = E_FAIL; // too many robots.txt files???
  1074. }
  1075. *pdwRobotsTxtIndex = iIndex;
  1076. return hr;
  1077. }
  1078. // iRobotsIndex : Index into robots.txt, -1 if unavailable
  1079. HRESULT CWebCrawler::ValidateWithRobotsTxt(LPCWSTR pwszUrl, int iRobotsIndex, BOOL *pfAllow)
  1080. {
  1081. int iNumDirectives, i;
  1082. CWCStringList *pslThisRobotsTxt=NULL;
  1083. *pfAllow = TRUE;
  1084. if (!m_pRobotsTxt)
  1085. return S_OK;
  1086. if (iRobotsIndex == -1)
  1087. {
  1088. DWORD dwIndex;
  1089. if (S_OK != GetRobotsTxtIndex(pwszUrl, FALSE, &dwIndex))
  1090. return E_FAIL;
  1091. iRobotsIndex = (int)dwIndex;
  1092. }
  1093. if ((iRobotsIndex >= 0) && iRobotsIndex<m_pRobotsTxt->NumStrings())
  1094. {
  1095. pslThisRobotsTxt = (CWCStringList *)(m_pRobotsTxt->GetStringData(iRobotsIndex));
  1096. if (pslThisRobotsTxt)
  1097. {
  1098. iNumDirectives = pslThisRobotsTxt->NumStrings();
  1099. for (i=0; i<iNumDirectives; i++)
  1100. {
  1101. // See if this url starts with the same thing as the directive
  1102. if (!MyAsciiCmpNIW(pwszUrl, pslThisRobotsTxt->GetString(i), pslThisRobotsTxt->GetStringLen(i)))
  1103. {
  1104. // hit! see if this is "allow" or "disallow"
  1105. if (!(pslThisRobotsTxt->GetStringData(i) & DATA_ALLOW))
  1106. {
  1107. TraceMsg(TF_THISMODULE, "ValidateWithRobotsTxt disallowing: (%ws) (%ws)",
  1108. pslThisRobotsTxt->GetString(i), pwszUrl);
  1109. *pfAllow = FALSE;
  1110. m_iSkippedByRobotsTxt ++;
  1111. }
  1112. break;
  1113. }
  1114. }
  1115. }
  1116. return S_OK;
  1117. }
  1118. return E_FAIL;
  1119. }
  1120. typedef struct
  1121. {
  1122. LPCWSTR pwszThisUrl;
  1123. CWCStringList *pslGlobal;
  1124. BOOL fDiskFull;
  1125. DWORD dwSize;
  1126. GROUPID llGroupID;
  1127. }
  1128. ENUMDEPENDENCIES;
  1129. // Doesn't process it if we already have it in the global dependency list
  1130. HRESULT CWebCrawler::CheckImageOrLink(IUnknown *punkItem, BSTR *pbstrItem, DWORD_PTR dwEnumDep, DWORD *pdwStringData)
  1131. {
  1132. if (!dwEnumDep)
  1133. return E_FAIL;
  1134. ENUMDEPENDENCIES *pEnumDep = (ENUMDEPENDENCIES *) dwEnumDep;
  1135. WCHAR wszCombinedUrl[INTERNET_MAX_URL_LENGTH];
  1136. DWORD dwLen = ARRAYSIZE(wszCombinedUrl);
  1137. HRESULT hr;
  1138. if (pEnumDep->fDiskFull)
  1139. return E_ABORT; // Abort enumeration
  1140. if (SUCCEEDED(UrlCombineW(pEnumDep->pwszThisUrl, *pbstrItem, wszCombinedUrl, &dwLen, 0)))
  1141. {
  1142. TCHAR szCombinedUrl[INTERNET_MAX_URL_LENGTH];
  1143. BYTE chBuf[MY_MAX_CACHE_ENTRY_INFO];
  1144. if (pEnumDep->pslGlobal != NULL)
  1145. {
  1146. int iCode = pEnumDep->pslGlobal->AddString(*pbstrItem, 0);
  1147. if (CWCStringList::STRLST_ADDED != iCode)
  1148. {
  1149. // The string already existed (or Add failed). Don't process this.
  1150. return S_OK;
  1151. }
  1152. }
  1153. // Process this url.
  1154. MyOleStrToStrN(szCombinedUrl, INTERNET_MAX_URL_LENGTH, wszCombinedUrl);
  1155. hr = GetUrlInfoAndMakeSticky(NULL, szCombinedUrl,
  1156. (LPINTERNET_CACHE_ENTRY_INFO)chBuf, sizeof(chBuf),
  1157. pEnumDep->llGroupID);
  1158. if (E_OUTOFMEMORY == hr)
  1159. {
  1160. pEnumDep->fDiskFull = TRUE;
  1161. return E_ABORT; // Skip rest of enumeration
  1162. }
  1163. if (SUCCEEDED(hr))
  1164. pEnumDep->dwSize += ((LPINTERNET_CACHE_ENTRY_INFO)chBuf)->dwSizeLow;
  1165. }
  1166. return S_OK;
  1167. }
  1168. HRESULT CWebCrawler::MatchNames(BSTR bstrName, BOOL fPassword)
  1169. {
  1170. static const WCHAR c_szPassword1[] = L"password";
  1171. static const WCHAR c_szUsername1[] = L"user";
  1172. static const WCHAR c_szUsername2[] = L"username";
  1173. HRESULT hr = E_FAIL;
  1174. LPCTSTR pszKey = c_szRegKeyPasswords;
  1175. // See if the name matches our preset options.
  1176. // Should these be localized? I don't think so or subscribing to
  1177. // US sites will fail in international versions of the browser.
  1178. if (fPassword)
  1179. {
  1180. if (StrCmpIW(bstrName, c_szPassword1) == 0)
  1181. {
  1182. hr = S_OK;
  1183. }
  1184. }
  1185. else
  1186. {
  1187. if ((StrCmpIW(bstrName, c_szUsername1) == 0) ||
  1188. (StrCmpIW(bstrName, c_szUsername2) == 0))
  1189. {
  1190. hr = S_OK;
  1191. }
  1192. else
  1193. {
  1194. pszKey = c_szRegKeyUsernames;
  1195. }
  1196. }
  1197. // Try the registry for custom form names if the presets didn't match.
  1198. if (FAILED(hr))
  1199. {
  1200. LONG lRes;
  1201. HKEY hKey;
  1202. DWORD cValues;
  1203. DWORD i;
  1204. lRes = RegOpenKeyEx(HKEY_CURRENT_USER, pszKey, 0, KEY_READ, &hKey);
  1205. if (ERROR_SUCCESS == lRes)
  1206. {
  1207. lRes = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &cValues, NULL, NULL, NULL, NULL);
  1208. if (ERROR_SUCCESS == lRes)
  1209. {
  1210. for (i = 0; i < cValues; i++)
  1211. {
  1212. TCHAR szValueName[MAX_PATH];
  1213. DWORD cchValueName = ARRAYSIZE(szValueName);
  1214. lRes = SHEnumValue(hKey, i, szValueName, &cchValueName, NULL, NULL, NULL);
  1215. if (ERROR_SUCCESS == lRes)
  1216. {
  1217. WCHAR wszValueName[MAX_PATH];
  1218. MyStrToOleStrN(wszValueName, ARRAYSIZE(wszValueName), szValueName);
  1219. if (StrCmpIW(bstrName, wszValueName) == 0)
  1220. {
  1221. hr = S_OK;
  1222. break;
  1223. }
  1224. }
  1225. }
  1226. }
  1227. lRes = RegCloseKey(hKey);
  1228. ASSERT(ERROR_SUCCESS == lRes);
  1229. }
  1230. }
  1231. return hr;
  1232. }
  1233. HRESULT CWebCrawler::FindAndSubmitForm(void)
  1234. {
  1235. // FindAndSubmitForm - If there is a user name and password in
  1236. // the start item, this will attempt to fill in and submit
  1237. // a form. It should only be called on the top level page of a
  1238. // webcrawl. We still need to check the host name in case we were
  1239. // spawned from a channel crawl.
  1240. //
  1241. // return values: S_OK successfully found and submitted a form -> restart webcrawl
  1242. // S_FALSE no username, no form, or unrecognized form ->continue webcrawl
  1243. // E_FAIL submit failed -> abort webcrawl
  1244. //
  1245. HRESULT hrReturn = S_FALSE;
  1246. HRESULT hr = S_OK;
  1247. BSTR bstrUsername = NULL;
  1248. BSTR bstrPassword = NULL;
  1249. BSTR bstrInputType= NULL;
  1250. static const WCHAR c_szInputTextType[]=L"text";
  1251. // If our host name doesn't match the root host name, don't return auth
  1252. // information.
  1253. if (m_bstrHostName)
  1254. {
  1255. LPWSTR pwszUrl, bstrHostName=NULL;
  1256. m_pCurDownload->GetRealURL(&pwszUrl); // may re-enter Trident
  1257. if (pwszUrl)
  1258. {
  1259. GetHostName(pwszUrl, &bstrHostName);
  1260. LocalFree(pwszUrl);
  1261. }
  1262. if (bstrHostName)
  1263. {
  1264. if (MyAsciiCmpW(bstrHostName, m_bstrHostName))
  1265. {
  1266. hr = E_FAIL;
  1267. }
  1268. SysFreeString(bstrHostName);
  1269. }
  1270. }
  1271. if (SUCCEEDED(hr))
  1272. hr = ReadBSTR(m_pSubscriptionItem, c_szPropCrawlUsername, &bstrUsername);
  1273. if (SUCCEEDED(hr) && bstrUsername && bstrUsername[0])
  1274. {
  1275. // NOTE: We don't allow NULL passwords.
  1276. hr = ReadPassword(m_pSubscriptionItem, &bstrPassword);
  1277. if (SUCCEEDED(hr) && bstrPassword && bstrPassword[0])
  1278. {
  1279. IHTMLDocument2 *pDoc = NULL;
  1280. hr = m_pCurDownload->GetDocument(&pDoc);
  1281. if (SUCCEEDED(hr) && pDoc)
  1282. {
  1283. IHTMLElementCollection *pFormsCollection = NULL;
  1284. hr = pDoc->get_forms(&pFormsCollection);
  1285. if (SUCCEEDED(hr) && pFormsCollection)
  1286. {
  1287. long length;
  1288. hr = pFormsCollection->get_length(&length);
  1289. TraceMsg(TF_THISMODULE, "**** FOUND USER NAME, PASSWORD, & %d FORMS ****", (int)length);
  1290. if (SUCCEEDED(hr) && length > 0)
  1291. {
  1292. // We only check the first form for a user name and password.
  1293. // Why do we pass an index to IHTMLElementCollection when
  1294. // the interface prototype says it takes a name?
  1295. IDispatch *pDispForm = NULL;
  1296. VARIANT vIndex, vEmpty;
  1297. VariantInit(&vIndex);
  1298. VariantInit(&vEmpty);
  1299. vIndex.vt = VT_I4;
  1300. vIndex.lVal = 0;
  1301. hr = pFormsCollection->item(vIndex, vEmpty, &pDispForm);
  1302. if (SUCCEEDED(hr) && pDispForm)
  1303. {
  1304. IHTMLFormElement *pForm = NULL;
  1305. hr = pDispForm->QueryInterface(IID_IHTMLFormElement, (void **)&pForm);
  1306. if (SUCCEEDED(hr) && pForm)
  1307. {
  1308. // Enum form elements looking for the input types we care about.
  1309. // Would it be faster to use tags()?
  1310. hr = pForm->get_length(&length);
  1311. if (SUCCEEDED(hr) && length >= 2)
  1312. {
  1313. // TraceMsg(TF_THISMODULE, "**** FORM ELEMENTS (%d) ****", (int)length);
  1314. BOOL fUsernameSet = FALSE;
  1315. BOOL fPasswordSet = FALSE;
  1316. IDispatch *pDispItem = NULL;
  1317. long i;
  1318. for (i = 0; i < length; i++)
  1319. {
  1320. vIndex.lVal = i; // re-use vIndex above
  1321. hr = pForm->item(vIndex, vEmpty, &pDispItem);
  1322. if (SUCCEEDED(hr) && pDispItem)
  1323. {
  1324. IHTMLInputTextElement *pInput = NULL;
  1325. // QI was the easiest way to tell them apart...
  1326. // InputText is derived from InputPassword
  1327. hr = pDispItem->QueryInterface(IID_IHTMLInputTextElement, (void **)&pInput);
  1328. SAFERELEASE(pDispItem);
  1329. if (SUCCEEDED(hr) && pInput)
  1330. {
  1331. hr = pInput->get_type(&bstrInputType);
  1332. ASSERT(SUCCEEDED(hr) && bstrInputType);
  1333. BSTR bstrName = NULL;
  1334. if (StrCmpIW(bstrInputType, c_szInputTextType) == 0)
  1335. {
  1336. // We found an INPUT element with attribute TYPE="text".
  1337. // Set it if the NAME attribute matches.
  1338. // Only setting the first matching input.
  1339. // Do we care about max length or does put_value handle it?
  1340. // TraceMsg(TF_THISMODULE, "**** FORM ELEMENT INPUT (%d) ****", (int)i);
  1341. if (!fUsernameSet)
  1342. {
  1343. hr = pInput->get_name(&bstrName);
  1344. ASSERT(SUCCEEDED(hr) && bstrName);
  1345. if (SUCCEEDED(hr) && bstrName && SUCCEEDED(MatchNames(bstrName, FALSE)))
  1346. {
  1347. hr = pInput->put_value(bstrUsername);
  1348. if (SUCCEEDED(hr))
  1349. fUsernameSet = TRUE;
  1350. }
  1351. }
  1352. }
  1353. else
  1354. {
  1355. // We found an INPUT element with attribute TYPE="password"
  1356. // Set it if the name attribute matches.
  1357. // Only setting the first matching input.
  1358. // Do we care about max length or does put_value handle it?
  1359. // TraceMsg(TF_THISMODULE, "**** FORM ELEMENT PASSWORD (%d) ****", (int)i);
  1360. if (!fPasswordSet)
  1361. {
  1362. hr = pInput->get_name(&bstrName);
  1363. ASSERT(SUCCEEDED(hr) && bstrName);
  1364. if (SUCCEEDED(hr) && bstrName && SUCCEEDED(MatchNames(bstrName, TRUE)))
  1365. {
  1366. hr = pInput->put_value(bstrPassword);
  1367. if (SUCCEEDED(hr))
  1368. fPasswordSet = TRUE;
  1369. }
  1370. }
  1371. }
  1372. SAFEFREEBSTR(bstrName);
  1373. SAFERELEASE(pInput);
  1374. }
  1375. }
  1376. }
  1377. // Submit the form is everything was set.
  1378. if (fUsernameSet && fPasswordSet)
  1379. {
  1380. ASSERT(!m_pCurDownload->GetFormSubmitted());
  1381. m_pCurDownload->SetFormSubmitted(TRUE);
  1382. hr = pForm->submit();
  1383. if (SUCCEEDED(hr))
  1384. {
  1385. m_iNumPagesDownloading ++;
  1386. TraceMsg(TF_THISMODULE, "**** FORM SUBMIT WORKED ****");
  1387. hrReturn = S_OK;
  1388. }
  1389. else
  1390. {
  1391. TraceMsg(TF_THISMODULE, "**** FORM SUBMIT FAILED ****");
  1392. hrReturn = E_FAIL;
  1393. }
  1394. }
  1395. }
  1396. SAFERELEASE(pForm);
  1397. }
  1398. SAFERELEASE(pDispForm);
  1399. }
  1400. // only length
  1401. }
  1402. SAFERELEASE(pFormsCollection);
  1403. }
  1404. SAFERELEASE(pDoc);
  1405. }
  1406. // free bstr below because we check for empty bstrs
  1407. }
  1408. SAFEFREEBSTR(bstrPassword);
  1409. }
  1410. SAFEFREEBSTR(bstrUsername);
  1411. return hrReturn;
  1412. }
  1413. // Make page and dependencies sticky and get total size
  1414. HRESULT CWebCrawler::MakePageStickyAndGetSize(LPCWSTR pwszURL, DWORD *pdwSize, BOOL *pfDiskFull)
  1415. {
  1416. ASSERT(m_pDependencies || IsRecurseFlagSet(WEBCRAWL_DONT_MAKE_STICKY));
  1417. HRESULT hr;
  1418. TCHAR szThisUrl[INTERNET_MAX_URL_LENGTH]; // use ansi internally
  1419. BYTE chBuf[MY_MAX_CACHE_ENTRY_INFO];
  1420. LPINTERNET_CACHE_ENTRY_INFO lpInfo = (LPINTERNET_CACHE_ENTRY_INFO) chBuf;
  1421. DWORD dwBufSize = sizeof(chBuf);
  1422. *pdwSize = 0;
  1423. // First we make our base url sticky and check it for changes
  1424. MyOleStrToStrN(szThisUrl, INTERNET_MAX_URL_LENGTH, pwszURL);
  1425. hr = GetUrlInfoAndMakeSticky(NULL, szThisUrl, lpInfo, dwBufSize, m_llCacheGroupID);
  1426. if (E_OUTOFMEMORY != hr)
  1427. {
  1428. if (SUCCEEDED(hr))
  1429. *pdwSize += lpInfo->dwSizeLow;
  1430. if (!IsAgentFlagSet(FLAG_CRAWLCHANGED) && SUCCEEDED(hr))
  1431. {
  1432. hr = PostCheckUrlForChange(&m_varChange, lpInfo, lpInfo->LastModifiedTime);
  1433. // If we FAILED, we mark it as changed.
  1434. if (hr == S_OK || FAILED(hr))
  1435. {
  1436. SetAgentFlag(FLAG_CRAWLCHANGED);
  1437. DBG("URL has changed; will flag webcrawl as changed");
  1438. }
  1439. // "Changes Only" mode, persist change detection code
  1440. if (IsAgentFlagSet(FLAG_CHANGESONLY))
  1441. {
  1442. ASSERT(m_iTotalStarted == 1);
  1443. WriteVariant(m_pSubscriptionItem, c_szPropChangeCode, &m_varChange);
  1444. return S_OK; // We know there are no dependencies
  1445. }
  1446. hr = S_OK;
  1447. }
  1448. }
  1449. else
  1450. {
  1451. *pfDiskFull = TRUE;
  1452. }
  1453. // Now we make all the new dependencies we downloaded for this page sticky
  1454. if (!*pfDiskFull && m_pDependencies)
  1455. {
  1456. EnterCriticalSection(&m_critDependencies);
  1457. for (; m_iDependenciesProcessed < m_pDependencies->NumStrings(); m_iDependenciesProcessed ++)
  1458. {
  1459. MyOleStrToStrN(szThisUrl, INTERNET_MAX_URL_LENGTH, m_pDependencies->GetString(m_iDependenciesProcessed));
  1460. hr = GetUrlInfoAndMakeSticky(NULL, szThisUrl, lpInfo, dwBufSize, m_llCacheGroupID);
  1461. if (E_OUTOFMEMORY == hr)
  1462. {
  1463. *pfDiskFull = TRUE;
  1464. break;
  1465. }
  1466. if (SUCCEEDED(hr))
  1467. *pdwSize += lpInfo->dwSizeLow;
  1468. }
  1469. LeaveCriticalSection(&m_critDependencies);
  1470. }
  1471. if (*pfDiskFull)
  1472. {
  1473. DBG_WARN("Webcrawler: UrlCache full trying to make sticky");
  1474. return E_OUTOFMEMORY;
  1475. }
  1476. return S_OK;
  1477. }
  1478. // true if found token & made null-term
  1479. LPSTR GetToken(LPSTR pszBuf, /*inout*/int *piBufPtr, /*out*/int *piLen)
  1480. {
  1481. static const CHAR szWhitespace[] = " \t\n\r";
  1482. int iPtr = *piBufPtr;
  1483. int iLen;
  1484. while (1)
  1485. {
  1486. // skip leading whitespace
  1487. iPtr += StrSpnA(pszBuf+iPtr, szWhitespace);
  1488. if (!pszBuf[iPtr])
  1489. return NULL;
  1490. if (pszBuf[iPtr] == '#')
  1491. {
  1492. // comment; skip line
  1493. while (pszBuf[iPtr] && pszBuf[iPtr]!='\r' && pszBuf[iPtr]!='\n') iPtr++;
  1494. if (!pszBuf[iPtr])
  1495. return NULL;
  1496. continue;
  1497. }
  1498. // skip to next whitespace
  1499. iLen = StrCSpnA(pszBuf+iPtr, szWhitespace);
  1500. if (iLen == 0)
  1501. return NULL; // shoudln't happen
  1502. *piBufPtr = iLen + iPtr;
  1503. if (piLen)
  1504. *piLen = iLen;
  1505. if (pszBuf[iLen+iPtr])
  1506. {
  1507. pszBuf[iLen+iPtr] = NULL;
  1508. ++ *piBufPtr;
  1509. }
  1510. break;
  1511. }
  1512. // TraceMsgA(TF_THISMODULE, "GetToken returning \"%s\"", (LPSTR)(pszBuf+iPtr));
  1513. return pszBuf + iPtr;
  1514. }
  1515. // === Support functions for OnDownloadComplete
  1516. // ParseRobotsTxt gets the stream from CUrlDownload, parses it, and fills in parsed
  1517. // info to *ppslRet
  1518. HRESULT CWebCrawler::ParseRobotsTxt(LPCWSTR pwszRobotsTxtURL, CWCStringList **ppslRet)
  1519. {
  1520. // Given a robots.txt file (from CUrlDownload), it
  1521. // parses the file and fills in a string list with appropriate
  1522. // info.
  1523. *ppslRet = FALSE;
  1524. CHAR szRobotsTxt[MAX_ROBOTS_SIZE];
  1525. HRESULT hr=S_OK;
  1526. LPSTR pszToken;
  1527. IStream *pstm=NULL;
  1528. DWORD_PTR dwData;
  1529. hr = m_pCurDownload->GetStream(&pstm);
  1530. if (SUCCEEDED(hr))
  1531. {
  1532. STATSTG st;
  1533. DWORD dwSize;
  1534. DBG("CWebCrawler parsing robots.txt file");
  1535. pstm->Stat(&st, STATFLAG_NONAME);
  1536. dwSize = st.cbSize.LowPart;
  1537. if (st.cbSize.HighPart || dwSize >= MAX_ROBOTS_SIZE)
  1538. {
  1539. szRobotsTxt[0] = 0;
  1540. DBG("CWebCrawler: Robots.Txt too big; ignoring");
  1541. hr = E_FAIL;
  1542. }
  1543. else
  1544. {
  1545. hr = pstm->Read(szRobotsTxt, dwSize, NULL);
  1546. szRobotsTxt[dwSize] = 0;
  1547. }
  1548. pstm->Release();
  1549. pstm=NULL;
  1550. if ((szRobotsTxt[0] == 0xff) && (szRobotsTxt[1] == 0xfe))
  1551. {
  1552. DBG_WARN("Unicode robots.txt! Ignoring ...");
  1553. hr = E_FAIL;
  1554. }
  1555. }
  1556. if (FAILED(hr))
  1557. return hr;
  1558. int iPtr = 0;
  1559. WCHAR wchBuf2[256];
  1560. WCHAR wchBuf[INTERNET_MAX_URL_LENGTH];
  1561. DWORD dwBufSize;
  1562. // Find the first "user-agent" which matches
  1563. while ((pszToken = GetToken(szRobotsTxt, &iPtr, NULL)) != NULL)
  1564. {
  1565. if (lstrcmpiA(pszToken, c_szRobots_UserAgent))
  1566. continue;
  1567. pszToken = GetToken(szRobotsTxt, &iPtr, NULL);
  1568. if (!pszToken)
  1569. break;
  1570. if ((*pszToken == '*') ||
  1571. (!lstrcmpiA(pszToken, c_szRobots_OurUserAgent)))
  1572. {
  1573. TraceMsgA(TF_THISMODULE, "Using user agent segment: \"%s\"", pszToken);
  1574. break;
  1575. }
  1576. }
  1577. if (!pszToken)
  1578. return E_FAIL;
  1579. CWCStringList *psl = new CWCDwordStringList;
  1580. if (psl)
  1581. {
  1582. psl->Init(2048);
  1583. // Look for Allow: or Disallow: sections
  1584. while ((pszToken = GetToken(szRobotsTxt, &iPtr, NULL)) != NULL)
  1585. {
  1586. if (!lstrcmpiA(pszToken, c_szRobots_UserAgent))
  1587. break; // end of our 'user-agent' section
  1588. dwData = 0;
  1589. if (!lstrcmpiA(pszToken, c_szRobots_Allow)) dwData = DATA_ALLOW;
  1590. if (!lstrcmpiA(pszToken, c_szRobots_Disallow)) dwData = DATA_DISALLOW;
  1591. if (!dwData)
  1592. continue; // look for next token
  1593. pszToken = GetToken(szRobotsTxt, &iPtr, NULL);
  1594. if (!pszToken)
  1595. break;
  1596. // Ensure that they don't have blank entries; we'll abort if so
  1597. if (!lstrcmpiA(pszToken, c_szRobots_UserAgent) ||
  1598. !lstrcmpiA(pszToken, c_szRobots_Allow) ||
  1599. !lstrcmpiA(pszToken, c_szRobots_Disallow))
  1600. {
  1601. break;
  1602. }
  1603. // Combine this url with the base for this site.
  1604. dwBufSize = ARRAYSIZE(wchBuf);
  1605. if (SHAnsiToUnicode(pszToken, wchBuf2, ARRAYSIZE(wchBuf2)) &&
  1606. SUCCEEDED(UrlCombineW(pwszRobotsTxtURL, wchBuf2, wchBuf, &dwBufSize, 0)))
  1607. {
  1608. TraceMsgA(TF_THISMODULE, "Robots.txt will %s urls with %s (%ws)",
  1609. ((dwData==DATA_ALLOW) ? c_szRobots_Allow : c_szRobots_Disallow),
  1610. pszToken, wchBuf);
  1611. // if this is a duplicate url we effectively ignore this directive
  1612. // thanks to CWCStringList removing duplicates for us
  1613. psl->AddString(wchBuf, dwData);
  1614. }
  1615. }
  1616. }
  1617. if (psl && (psl->NumStrings() > 0))
  1618. {
  1619. *ppslRet = psl;
  1620. return S_OK;
  1621. }
  1622. if (psl)
  1623. delete psl;
  1624. return E_FAIL;
  1625. }
  1626. HRESULT CWebCrawler::GetRealUrl(int iPageIndex, LPWSTR *ppwszThisUrl)
  1627. {
  1628. m_pCurDownload->GetRealURL(ppwszThisUrl);
  1629. if (*ppwszThisUrl)
  1630. {
  1631. return S_OK;
  1632. }
  1633. DBG_WARN("m_pCurDownload->GetRealURL failed!!!");
  1634. // Get url from string list
  1635. LPCWSTR pwszUrl=NULL;
  1636. pwszUrl = m_pPages->GetString(iPageIndex);
  1637. if (pwszUrl)
  1638. {
  1639. *ppwszThisUrl = StrDupW(pwszUrl);
  1640. }
  1641. return (*ppwszThisUrl) ? S_OK : E_OUTOFMEMORY;
  1642. }
  1643. // Allocates BSTR for host name.
  1644. HRESULT CWebCrawler::GetHostName(LPCWSTR pwszThisUrl, BSTR *pbstrHostName)
  1645. {
  1646. if (pwszThisUrl)
  1647. {
  1648. URL_COMPONENTSA comp;
  1649. LPSTR pszUrl;
  1650. int iLen;
  1651. // InternetCrackUrlW(pszUrl, 0, 0, &comp) // this is even slower than converting it ourselves...
  1652. // convert to ansi
  1653. iLen = lstrlenW(pwszThisUrl) + 1;
  1654. pszUrl = (LPSTR)MemAlloc(LMEM_FIXED, iLen);
  1655. if (pszUrl)
  1656. {
  1657. SHUnicodeToAnsi(pwszThisUrl, pszUrl, iLen);
  1658. // crack out the host name
  1659. ZeroMemory(&comp, sizeof(comp));
  1660. comp.dwStructSize = sizeof(comp);
  1661. comp.dwHostNameLength = 1; // indicate that we want the host name
  1662. if (InternetCrackUrlA(pszUrl, 0, 0, &comp))
  1663. {
  1664. *pbstrHostName = SysAllocStringLen(NULL, comp.dwHostNameLength);
  1665. if (*pbstrHostName)
  1666. {
  1667. comp.lpszHostName[comp.dwHostNameLength] = 0; // avoid debug rip
  1668. SHAnsiToUnicode(comp.lpszHostName, *pbstrHostName, comp.dwHostNameLength + 1);
  1669. ASSERT((*pbstrHostName)[comp.dwHostNameLength] == 0);
  1670. }
  1671. }
  1672. MemFree((HLOCAL)pszUrl);
  1673. }
  1674. }
  1675. return S_OK;
  1676. }
  1677. // Gets partly validated (CUrlDownload::IsValidUrl and hostname validation)
  1678. // string lists and leaves in m_pPendingLinks
  1679. // Remaining validation is robots.txt if any
  1680. HRESULT CWebCrawler::GetLinksFromPage()
  1681. {
  1682. // Get links from this page that we want to follow.
  1683. CWCStringList *pslLinks=NULL, slMeta;
  1684. IHTMLDocument2 *pDoc;
  1685. BOOL fFollowLinks = TRUE;
  1686. int i;
  1687. slMeta.Init(2048);
  1688. m_pCurDownload->GetDocument(&pDoc);
  1689. if (pDoc)
  1690. {
  1691. // See if there is a META tag telling us not to follow
  1692. CHelperOM::GetCollection(pDoc, &slMeta, CHelperOM::CTYPE_META, NULL, 0);
  1693. for (i=0; i<slMeta.NumStrings(); i++)
  1694. {
  1695. if (!StrCmpNIW(slMeta.GetString(i), c_wszRobotsMetaName, c_iRobotsMetaNameLen))
  1696. {
  1697. LPCWSTR pwszContent = slMeta.GetString(i) + c_iRobotsMetaNameLen;
  1698. TraceMsg(TF_THISMODULE, "Found 'robots' meta tag; content=%ws", pwszContent);
  1699. while (pwszContent && *pwszContent)
  1700. {
  1701. if (!StrCmpNIW(pwszContent, c_wszRobotsNoFollow, c_iRobotsNoFollow))
  1702. {
  1703. DBG("Not following links from this page.");
  1704. fFollowLinks = FALSE;
  1705. break;
  1706. }
  1707. pwszContent = StrChrW(pwszContent+1, L',');
  1708. if (pwszContent && *pwszContent)
  1709. pwszContent ++;
  1710. }
  1711. break;
  1712. }
  1713. }
  1714. if (fFollowLinks)
  1715. {
  1716. if (m_pPendingLinks)
  1717. pslLinks = m_pPendingLinks;
  1718. else
  1719. {
  1720. pslLinks = new CWCDwordStringList;
  1721. if (pslLinks)
  1722. pslLinks->Init();
  1723. else
  1724. return E_OUTOFMEMORY;
  1725. }
  1726. CHelperOM::GetCollection(pDoc, pslLinks, CHelperOM::CTYPE_LINKS, &CheckLink, (DWORD_PTR)this);
  1727. CHelperOM::GetCollection(pDoc, pslLinks, CHelperOM::CTYPE_MAPS, &CheckLink, (DWORD_PTR)this);
  1728. }
  1729. pDoc->Release();
  1730. pDoc=NULL;
  1731. }
  1732. m_pPendingLinks = pslLinks;
  1733. return S_OK;
  1734. }
  1735. // Gets 'dependency links' such as frames from a page
  1736. HRESULT CWebCrawler::GetDependencyLinksFromPage(LPCWSTR pwszThisUrl, DWORD dwRecurse)
  1737. {
  1738. CWCStringList *psl=NULL;
  1739. IHTMLDocument2 *pDoc;
  1740. int i, iAdd, iIndex, iOldMax;
  1741. DWORD_PTR dwData;
  1742. if (m_pDependencyLinks)
  1743. psl = m_pDependencyLinks;
  1744. else
  1745. {
  1746. m_iDependencyStarted = 0;
  1747. psl = new CWCStringList;
  1748. if (psl)
  1749. psl->Init(2048);
  1750. else
  1751. return E_OUTOFMEMORY;
  1752. }
  1753. iOldMax = psl->NumStrings();
  1754. m_pCurDownload->GetDocument(&pDoc);
  1755. if (pDoc)
  1756. {
  1757. // Add Frames ("Frame" and "IFrame" tags) if present
  1758. CHelperOM::GetCollection(pDoc, psl, CHelperOM::CTYPE_FRAMES, CheckFrame, (DWORD_PTR)pwszThisUrl);
  1759. }
  1760. SAFERELEASE(pDoc);
  1761. m_pDependencyLinks = psl;
  1762. // Add the new urls to the main page list
  1763. for (i = iOldMax; i<psl->NumStrings(); i++)
  1764. {
  1765. iAdd = m_pPages->AddString(m_pDependencyLinks->GetString(i),
  1766. dwRecurse,
  1767. &iIndex);
  1768. if (m_lMaxNumUrls > 0 && iAdd==CWCStringList::STRLST_ADDED)
  1769. m_lMaxNumUrls ++;
  1770. if (iAdd == CWCStringList::STRLST_FAIL)
  1771. return E_OUTOFMEMORY;
  1772. if (iAdd == CWCStringList::STRLST_DUPLICATE)
  1773. {
  1774. // bump up recursion level of old page if necessary
  1775. // See if we've downloaded this yet.
  1776. dwData = m_pPages->GetStringData(iIndex);
  1777. if (!(dwData & DATA_DLSTARTED))
  1778. {
  1779. // Haven't downloaded it yet.
  1780. // Update the recurse levels if necessary.
  1781. if ((dwData & DATA_RECURSEMASK) < dwRecurse)
  1782. {
  1783. dwData = (dwData & ~DATA_RECURSEMASK) | dwRecurse;
  1784. }
  1785. // Turn off the "link" bit
  1786. dwData &= ~DATA_LINK;
  1787. m_pPages->SetStringData(iIndex, dwData);
  1788. }
  1789. #ifdef DEBUG
  1790. // Shouldn't happen; this frame already dl'd with lower recurse level
  1791. else
  1792. ASSERT((dwData & DATA_RECURSEMASK) >= dwRecurse);
  1793. #endif
  1794. }
  1795. }
  1796. return S_OK;
  1797. }
  1798. //-------------------------------------
  1799. // OnDownloadComplete
  1800. //
  1801. // Called when a url is finished downloading, it processes the url
  1802. // and kicks off the next download
  1803. //
  1804. HRESULT CWebCrawler::OnDownloadComplete(UINT iID, int iError)
  1805. {
  1806. int iPageIndex = m_iCurDownloadStringIndex;
  1807. BOOL fOperationComplete = FALSE;
  1808. BOOL fDiskFull = FALSE;
  1809. BSTR bstrCDFURL = NULL; // CDF URL if there is one
  1810. LPWSTR pwszThisUrl=NULL;
  1811. HRESULT hr;
  1812. TraceMsg(TF_THISMODULE, "WebCrawler: OnDownloadComplete(%d)", iError);
  1813. ASSERT(m_pPages);
  1814. ASSERT(iPageIndex < m_pCurDownloadStringList->NumStrings());
  1815. if (_ERROR_REPROCESSING != iError)
  1816. {
  1817. m_iNumPagesDownloading --;
  1818. ASSERT(m_iNumPagesDownloading == 0);
  1819. }
  1820. if (m_pCurDownloadStringList == m_pRobotsTxt)
  1821. {
  1822. CWCStringList *pslNew=NULL;
  1823. // Process robots.txt file
  1824. if (SUCCEEDED(ParseRobotsTxt(m_pRobotsTxt->GetString(iPageIndex), &pslNew)))
  1825. {
  1826. m_pRobotsTxt->SetStringData(iPageIndex, (DWORD_PTR)(pslNew));
  1827. }
  1828. }
  1829. else
  1830. {
  1831. // Process normal file
  1832. ASSERT(m_pCurDownloadStringList == m_pPages);
  1833. DWORD dwData, dwRecurseLevelsFromThisPage;
  1834. dwData = (DWORD)m_pPages->GetStringData(iPageIndex);
  1835. dwRecurseLevelsFromThisPage = dwData & DATA_RECURSEMASK;
  1836. dwData |= DATA_DLFINISHED;
  1837. if (iError > 0)
  1838. dwData |= DATA_DLERROR;
  1839. // mark as downloaded
  1840. m_pCurDownloadStringList->SetStringData(iPageIndex, dwData);
  1841. // Is this the first page?
  1842. if (m_iTotalStarted == 1)
  1843. {
  1844. // Check the HTTP response code
  1845. DWORD dwResponseCode;
  1846. hr = m_pCurDownload->GetResponseCode(&dwResponseCode);
  1847. if (SUCCEEDED(hr))
  1848. {
  1849. hr = CheckResponseCode(dwResponseCode);
  1850. if (FAILED(hr))
  1851. fOperationComplete = TRUE;
  1852. }
  1853. else
  1854. DBG("CWebCrawler failed to GetResponseCode");
  1855. // Get the Charset
  1856. BSTR bstrCharSet=NULL;
  1857. IHTMLDocument2 *pDoc=NULL;
  1858. // -> Bharats --------
  1859. // Find a link tag and store it away the cdf by copying it (if it points to a cdf.)
  1860. // do url combine of this cdf
  1861. if (SUCCEEDED(m_pCurDownload->GetDocument(&pDoc)) && pDoc &&
  1862. SUCCEEDED(pDoc->get_charset(&bstrCharSet)) && bstrCharSet)
  1863. {
  1864. WriteOLESTR(m_pSubscriptionItem, c_szPropCharSet, bstrCharSet);
  1865. TraceMsg(TF_THISMODULE, "Charset = \"%ws\"", bstrCharSet);
  1866. SysFreeString(bstrCharSet);
  1867. }
  1868. else
  1869. WriteEMPTY(m_pSubscriptionItem, c_szPropCharSet);
  1870. if(pDoc)
  1871. {
  1872. if(FAILED(GetChannelItem(NULL))) // A Doc exists and this download is not from a channel itself
  1873. {
  1874. IHTMLLinkElement *pLink = NULL;
  1875. hr = SearchForElementInHead(pDoc, OLESTR("REL"), OLESTR("OFFLINE"),
  1876. IID_IHTMLLinkElement, (IUnknown **)&pLink);
  1877. if(S_OK == hr)
  1878. {
  1879. hr = pLink->get_href(&bstrCDFURL);
  1880. pLink->Release();
  1881. }
  1882. }
  1883. pDoc->Release();
  1884. pDoc = NULL;
  1885. }
  1886. }
  1887. if ((iError != _ERROR_REPROCESSING) && (iError != BDU2_ERROR_NONE))
  1888. {
  1889. if (iError != BDU2_ERROR_NOT_HTML)
  1890. m_iDownloadErrors ++;
  1891. if (iError == BDU2_ERROR_MAXSIZE)
  1892. {
  1893. SetEndStatus(INET_E_AGENT_MAX_SIZE_EXCEEDED);
  1894. fOperationComplete = TRUE;
  1895. }
  1896. }
  1897. else
  1898. {
  1899. // Don't process this url if we already have set fOperationComplete
  1900. if (!fOperationComplete)
  1901. {
  1902. // Did we get *just* the HEAD info?
  1903. if (IsAgentFlagSet(FLAG_HEADONLY))
  1904. {
  1905. SYSTEMTIME stLastModified;
  1906. FILETIME ftLastModified;
  1907. if (SUCCEEDED(m_pCurDownload->GetLastModified(&stLastModified)) &&
  1908. SystemTimeToFileTime(&stLastModified, &ftLastModified))
  1909. {
  1910. DBG("Retrieved 'HEAD' info; change detection based on Last Modified");
  1911. hr = PostCheckUrlForChange(&m_varChange, NULL, ftLastModified);
  1912. // If we FAILED, we mark it as changed.
  1913. if (hr == S_OK || FAILED(hr))
  1914. {
  1915. SetAgentFlag(FLAG_CRAWLCHANGED);
  1916. DBG("URL has changed; will flag webcrawl as changed");
  1917. }
  1918. // "Changes Only" mode, persist change detection code
  1919. ASSERT(IsAgentFlagSet(FLAG_CHANGESONLY));
  1920. ASSERT(m_iTotalStarted == 1);
  1921. WriteVariant(m_pSubscriptionItem, c_szPropChangeCode, &m_varChange);
  1922. }
  1923. }
  1924. else
  1925. {
  1926. // Get real URL in case we were redirected
  1927. if (FAILED(GetRealUrl(iPageIndex, &pwszThisUrl)))
  1928. {
  1929. fOperationComplete = TRUE; // bad
  1930. }
  1931. else
  1932. {
  1933. ASSERT(pwszThisUrl);
  1934. // Get host name from first page if necessary
  1935. if ((iPageIndex==0) &&
  1936. (m_dwRecurseLevels>0) &&
  1937. !IsRecurseFlagSet(WEBCRAWL_LINKS_ELSEWHERE) &&
  1938. !m_bstrHostName)
  1939. {
  1940. GetHostName(pwszThisUrl, &m_bstrHostName);
  1941. #ifdef DEBUG
  1942. if (m_bstrHostName)
  1943. TraceMsg(TF_THISMODULE, "Just got first host name: %ws", m_bstrHostName);
  1944. else
  1945. DBG_WARN("Get first host name failed!!!");
  1946. #endif
  1947. }
  1948. DWORD dwCurSize = 0, dwRepeat = 0;
  1949. HRESULT hr1;
  1950. do
  1951. {
  1952. hr1 = S_OK;
  1953. // Make page and dependencies sticky and get their total size
  1954. fDiskFull = FALSE;
  1955. MakePageStickyAndGetSize(pwszThisUrl, &dwCurSize, &fDiskFull);
  1956. if (fDiskFull && (dwRepeat < 2))
  1957. {
  1958. // If we couldn't make stuff sticky, ask host to make cache bigger
  1959. hr1 = m_pAgentEvents->ReportError(&m_SubscriptionCookie,
  1960. INET_E_AGENT_EXCEEDING_CACHE_SIZE, NULL);
  1961. if (hr1 == E_PENDING)
  1962. {
  1963. // Host is going to ask the user to increase the cache size.
  1964. // Host should either abort or resume us later.
  1965. SetAgentFlag(FLAG_WAITING_FOR_INCREASED_CACHE);
  1966. goto done;
  1967. }
  1968. else if (hr1 == INET_S_AGENT_INCREASED_CACHE_SIZE)
  1969. {
  1970. // Host just increased the cache size. Try it again.
  1971. }
  1972. else
  1973. {
  1974. // Not gonna do it. Abort.
  1975. }
  1976. }
  1977. }
  1978. while ((hr1 == INET_S_AGENT_INCREASED_CACHE_SIZE) && (++dwRepeat <= 2));
  1979. m_dwCurSize += dwCurSize;
  1980. // Is there form based authentication that we need to handle
  1981. // on the top page of this subscription?
  1982. if (!fDiskFull && (0 == iPageIndex) && !m_pCurDownload->GetFormSubmitted())
  1983. {
  1984. hr = FindAndSubmitForm();
  1985. if (S_OK == hr)
  1986. {
  1987. // Successfully submitted form. Bail and wait for the next OnDownloadComplete() call.
  1988. // FEATURE: Should we make the form URL and dependencies sticky?
  1989. return S_OK;
  1990. }
  1991. else if (FAILED(hr))
  1992. {
  1993. // We failed trying to submit the form. Bail.
  1994. // FEATURE: Should we set a better error string?
  1995. SetEndStatus(E_FAIL);
  1996. CleanUp();
  1997. return S_OK;
  1998. }
  1999. // else no form - fall through
  2000. }
  2001. TraceMsg(TF_THISMODULE, "WebCrawler up to %d kb", (int)(m_dwCurSize>>10));
  2002. if ((m_lMaxNumUrls < 0) &&
  2003. !dwRecurseLevelsFromThisPage &&
  2004. !(dwData & DATA_CODEBASE))
  2005. {
  2006. m_lMaxNumUrls = m_pPages->NumStrings() + ((m_pRobotsTxt) ? m_pRobotsTxt->NumStrings() : 0);
  2007. }
  2008. } // SUCCEEDED(GetRealUrl)
  2009. } // !FLAG_HEADONLY
  2010. } // !fOperationComplete
  2011. // If we're in "Changes Only" mode, we're done.
  2012. if (IsAgentFlagSet(FLAG_CHANGESONLY))
  2013. fOperationComplete = TRUE;
  2014. // Check to see if we're past our max size
  2015. if (!fOperationComplete && fDiskFull || (m_dwMaxSize && (m_dwCurSize >= (m_dwMaxSize<<10))))
  2016. {
  2017. #ifdef DEBUG
  2018. if (fDiskFull)
  2019. DBG_WARN("Disk/cache full; aborting.");
  2020. else
  2021. TraceMsg(TF_WARNING, "Past maximum size; aborting. (%d kb of %d kb)", (int)(m_dwCurSize>>10), (int)m_dwMaxSize);
  2022. #endif
  2023. // abort operation
  2024. fOperationComplete = TRUE;
  2025. if (fDiskFull)
  2026. {
  2027. SetEndStatus(INET_E_AGENT_CACHE_SIZE_EXCEEDED);
  2028. }
  2029. else
  2030. {
  2031. SetEndStatus(INET_E_AGENT_MAX_SIZE_EXCEEDED);
  2032. }
  2033. }
  2034. if (!fOperationComplete)
  2035. {
  2036. // Get any links from page
  2037. // Get "dependency links" from page - frames, etc.
  2038. // we do this even if a CDF file is specified
  2039. // Essentially, since the user has no clue about the CDF
  2040. // file - we do not want to confuse the user
  2041. GetDependencyLinksFromPage(pwszThisUrl, dwRecurseLevelsFromThisPage);
  2042. if (dwRecurseLevelsFromThisPage)
  2043. {
  2044. // Get links from this page that we want to follow.
  2045. GetLinksFromPage();
  2046. if (m_pPendingLinks)
  2047. TraceMsg(TF_THISMODULE,
  2048. "Total of %d unique valid links found", m_pPendingLinks->NumStrings());
  2049. m_dwPendingRecurseLevel = dwRecurseLevelsFromThisPage - 1;
  2050. }
  2051. }
  2052. } // !iError
  2053. } // !robots.txt
  2054. if(!fOperationComplete)
  2055. StartCDFDownload(bstrCDFURL, pwszThisUrl);
  2056. if(!m_fCDFDownloadInProgress)
  2057. {
  2058. // Don't try code downloads or any of the rest until you're done with
  2059. // the cdf download
  2060. // See if we have any more URLs to download.
  2061. if (!fOperationComplete && FAILED(StartNextDownload()))
  2062. fOperationComplete = TRUE; // No, we're done!
  2063. }
  2064. CheckOperationComplete(fOperationComplete);
  2065. done:
  2066. if (pwszThisUrl)
  2067. MemFree(pwszThisUrl);
  2068. SAFEFREEBSTR(bstrCDFURL);
  2069. return S_OK;
  2070. }
  2071. HRESULT CWebCrawler::StartCDFDownload(WCHAR *pwszCDFURL, WCHAR *pwszBaseUrl)
  2072. {
  2073. HRESULT hr = E_FAIL;
  2074. m_fCDFDownloadInProgress = FALSE;
  2075. if(pwszCDFURL)
  2076. {
  2077. // We have a CDF File - begin download of it
  2078. if (m_pRunAgent)
  2079. {
  2080. ASSERT(0);
  2081. DBG_WARN("WebCrawler: Attempting to download next CDF when nother CDF exists.");
  2082. hr = E_FAIL;
  2083. goto Exit;
  2084. }
  2085. else
  2086. {
  2087. // create subscription item for CDL agent.
  2088. ISubscriptionItem *pItem = NULL;
  2089. if (m_dwMaxSize && ((m_dwCurSize>>10) >= m_dwMaxSize))
  2090. {
  2091. // We've exceeded our maximum download KB limit and can't continue.
  2092. DBG_WARN("WebCrawler: Exceeded Maximum KB download limit with CodeBase download.");
  2093. SetEndStatus(hr = INET_E_AGENT_MAX_SIZE_EXCEEDED);
  2094. goto Exit;
  2095. }
  2096. if (!m_pSubscriptionItem ||
  2097. FAILED(hr = DoCloneSubscriptionItem(m_pSubscriptionItem, NULL, &pItem)))
  2098. {
  2099. goto Exit;
  2100. }
  2101. ASSERT(pItem != NULL);
  2102. ASSERT(pwszCDFURL != NULL);
  2103. WCHAR wszCombined[INTERNET_MAX_URL_LENGTH];
  2104. DWORD dwBufSize = ARRAYSIZE(wszCombined);
  2105. if (SUCCEEDED(UrlCombineW(pwszBaseUrl, pwszCDFURL, wszCombined, &dwBufSize, 0)))
  2106. {
  2107. WriteOLESTR(pItem, c_szPropURL, wszCombined);
  2108. WriteEMPTY(pItem, c_szPropCrawlGroupID); // clear the old cache group id - don't want
  2109. // children to know of it
  2110. // The crawler already has a cache group id that we simply use as the new ID
  2111. WriteLONGLONG(pItem, c_szPropCrawlNewGroupID, m_llCacheGroupID);
  2112. WriteDWORD(pItem, c_szPropChannelFlags, CHANNEL_AGENT_PRECACHE_ALL);
  2113. // Finally - since we know that this is for offline use, we just set the flags to precache all
  2114. m_pRunAgent = new CRunDeliveryAgent();
  2115. if (m_pRunAgent)
  2116. hr = m_pRunAgent->Init((CRunDeliveryAgentSink *)this, pItem, CLSID_ChannelAgent);
  2117. pItem->Release();
  2118. if (m_pRunAgent && SUCCEEDED(hr))
  2119. {
  2120. hr = m_pRunAgent->StartAgent();
  2121. if (hr == E_PENDING)
  2122. {
  2123. hr = S_OK;
  2124. m_fCDFDownloadInProgress = TRUE;
  2125. }
  2126. }
  2127. else
  2128. {
  2129. hr = E_OUTOFMEMORY;
  2130. }
  2131. }
  2132. }
  2133. }
  2134. Exit:
  2135. if((S_OK != hr) && m_pRunAgent)
  2136. {
  2137. CRunDeliveryAgent::SafeRelease(m_pRunAgent);
  2138. }
  2139. return hr;
  2140. }
  2141. // CRunDeliveryAgentSink call back method to signal the end of a codebase download.
  2142. HRESULT CWebCrawler::OnAgentEnd(const SUBSCRIPTIONCOOKIE *pSubscriptionCookie,
  2143. long lSizeDownloaded, HRESULT hrResult, LPCWSTR wszResult,
  2144. BOOL fSynchronous)
  2145. {
  2146. ASSERT(m_pRunAgent != NULL);
  2147. BOOL fOperationComplete = FALSE;
  2148. CRunDeliveryAgent::SafeRelease(m_pRunAgent);
  2149. if(m_fCDFDownloadInProgress)
  2150. {
  2151. m_fCDFDownloadInProgress = FALSE;
  2152. }
  2153. else
  2154. {
  2155. int iPageIndex = m_iCurDownloadStringIndex;
  2156. BOOL fDiskFull = FALSE;
  2157. CCodeBaseHold *pcbh = NULL;
  2158. BOOL fError;
  2159. LPCWSTR pwszThisURL=NULL;
  2160. TraceMsg(TF_THISMODULE, "WebCrawler: OnAgentEnd of CRunDeliveryAgentSink");
  2161. ASSERT(m_pCodeBaseList);
  2162. ASSERT(iPageIndex < m_pCurDownloadStringList->NumStrings());
  2163. ASSERT(m_pCurDownloadStringList == m_pCodeBaseList);
  2164. m_iNumPagesDownloading --;
  2165. ASSERT(m_iNumPagesDownloading == 0);
  2166. pcbh = (CCodeBaseHold *)m_pCodeBaseList->GetStringData(iPageIndex);
  2167. pwszThisURL = m_pCodeBaseList->GetString(iPageIndex);
  2168. ASSERT(pwszThisURL);
  2169. pcbh->dwFlags |= DATA_DLFINISHED;
  2170. fError = FAILED(hrResult);
  2171. if (fSynchronous)
  2172. {
  2173. fError = TRUE;
  2174. ASSERT(FAILED(hrResult)); // we can't succeed synchronously...
  2175. }
  2176. //NOTE: The CDL agent will abort if it finds the file exceeds the MaxSizeKB. In this case the file is not
  2177. // counted and there may be other smaller CAB's that can be downloaded, so we continue to proceed.
  2178. if (fError)
  2179. {
  2180. pcbh->dwFlags |= DATA_DLERROR;
  2181. m_iDownloadErrors ++;
  2182. SetEndStatus(hrResult);
  2183. }
  2184. else
  2185. {
  2186. BYTE chBuf[MY_MAX_CACHE_ENTRY_INFO];
  2187. LPINTERNET_CACHE_ENTRY_INFO lpInfo = (LPINTERNET_CACHE_ENTRY_INFO) chBuf;
  2188. TCHAR szUrl[INTERNET_MAX_URL_LENGTH];
  2189. MyOleStrToStrN(szUrl, INTERNET_MAX_URL_LENGTH, pwszThisURL);
  2190. if (FAILED(GetUrlInfoAndMakeSticky(NULL, szUrl,
  2191. lpInfo, sizeof(chBuf), m_llCacheGroupID)))
  2192. {
  2193. //REVIEW: Do something here? Unlikely to occur in practice.
  2194. fOperationComplete = TRUE;
  2195. ASSERT(0);
  2196. }
  2197. else
  2198. {
  2199. m_dwCurSize += lpInfo->dwSizeLow;
  2200. }
  2201. TraceMsg(TF_THISMODULE, "WebCrawler up to %d kb", (int)(m_dwCurSize>>10));
  2202. if (m_dwMaxSize && ((m_dwCurSize>>10)>m_dwMaxSize))
  2203. {
  2204. // abort operation
  2205. fOperationComplete = TRUE;
  2206. if (fDiskFull)
  2207. SetEndStatus(INET_E_AGENT_CACHE_SIZE_EXCEEDED);
  2208. else
  2209. SetEndStatus(INET_E_AGENT_MAX_SIZE_EXCEEDED);
  2210. }
  2211. } // !fError
  2212. }
  2213. // See if we have any more URLs to download.
  2214. if (!fOperationComplete && FAILED(StartNextDownload()))
  2215. fOperationComplete = TRUE; // No, we're done!
  2216. if(!fSynchronous)
  2217. CheckOperationComplete(fOperationComplete);
  2218. return S_OK;
  2219. }
  2220. //////////////////////////////////////////////////////////////////////////
  2221. //
  2222. // CheckCompleteOperation :: If parameter is TRUE, then all downloads are
  2223. // complete, the appropriate STATUS_CODE is set
  2224. // and clean up initiated.
  2225. //
  2226. //////////////////////////////////////////////////////////////////////////
  2227. void CWebCrawler::CheckOperationComplete(BOOL fOperationComplete)
  2228. {
  2229. if (fOperationComplete)
  2230. {
  2231. DBG("WebCrawler complete. Shutting down.");
  2232. if (INET_S_AGENT_BASIC_SUCCESS == GetEndStatus())
  2233. {
  2234. // Set end status appropriately
  2235. if (m_iDownloadErrors)
  2236. {
  2237. if (m_iPagesStarted<=1)
  2238. {
  2239. DBG("Webcrawl failed - first URL failed.");
  2240. SetEndStatus(E_INVALIDARG);
  2241. }
  2242. else
  2243. {
  2244. DBG("Webcrawl succeeded - some URLs failed.");
  2245. SetEndStatus(INET_S_AGENT_PART_FAIL);
  2246. }
  2247. }
  2248. else
  2249. {
  2250. DBG("Webcrawl succeeded");
  2251. if (!IsAgentFlagSet(FLAG_CRAWLCHANGED))
  2252. {
  2253. SetEndStatus(S_FALSE);
  2254. DBG("No changes were detected");
  2255. }
  2256. else
  2257. {
  2258. DBG("Webcrawl succeeded");
  2259. SetEndStatus(S_OK);
  2260. }
  2261. }
  2262. }
  2263. if (m_llOldCacheGroupID)
  2264. {
  2265. DBG("Nuking old cache group.");
  2266. if (!DeleteUrlCacheGroup(m_llOldCacheGroupID, 0, 0))
  2267. {
  2268. DBG_WARN("Failed to delete old cache group!");
  2269. }
  2270. }
  2271. WriteLONGLONG(m_pSubscriptionItem, c_szPropCrawlGroupID, m_llCacheGroupID);
  2272. m_lSizeDownloadedKB = ((m_dwCurSize+511)>>10);
  2273. WriteDWORD(m_pSubscriptionItem, c_szPropCrawlActualSize, m_lSizeDownloadedKB);
  2274. if (m_lMaxNumUrls >= 0)
  2275. {
  2276. WriteDWORD(m_pSubscriptionItem, c_szPropActualProgressMax, m_lMaxNumUrls);
  2277. }
  2278. // Send a robots.txt warning to the user if we ended up not downloading stuff
  2279. // because of the server's robots.txt file
  2280. if (m_iSkippedByRobotsTxt != 0)
  2281. {
  2282. HRESULT hr = S_OK; // Make it an "information" message
  2283. WCHAR wszMessage[200];
  2284. if (m_iPagesStarted==1)
  2285. {
  2286. hr = INET_E_AGENT_WARNING; // Unless we're missing almost everything
  2287. }
  2288. if (MLLoadStringW(IDS_CRAWL_ROBOTS_TXT_WARNING, wszMessage, ARRAYSIZE(wszMessage)))
  2289. {
  2290. m_pAgentEvents->ReportError(&m_SubscriptionCookie, hr, wszMessage);
  2291. }
  2292. }
  2293. // Will call "UpdateEnd"
  2294. CleanUp();
  2295. }
  2296. }
  2297. HRESULT CWebCrawler::ModifyUpdateEnd(ISubscriptionItem *pEndItem, UINT *puiRes)
  2298. {
  2299. // Customize our end status string
  2300. switch (GetEndStatus())
  2301. {
  2302. case INET_E_AGENT_MAX_SIZE_EXCEEDED :
  2303. *puiRes = IDS_AGNT_STATUS_SIZELIMIT; break;
  2304. case INET_E_AGENT_CACHE_SIZE_EXCEEDED :
  2305. *puiRes = IDS_AGNT_STATUS_CACHELIMIT; break;
  2306. case E_FAIL : *puiRes = IDS_CRAWL_STATUS_NOT_OK; break;
  2307. case S_OK :
  2308. if (!IsAgentFlagSet(FLAG_CHANGESONLY))
  2309. *puiRes = IDS_CRAWL_STATUS_OK;
  2310. else
  2311. *puiRes = IDS_URL_STATUS_OK;
  2312. break;
  2313. case S_FALSE :
  2314. if (!IsAgentFlagSet(FLAG_CHANGESONLY))
  2315. *puiRes = IDS_CRAWL_STATUS_UNCHANGED;
  2316. else
  2317. *puiRes = IDS_URL_STATUS_UNCHANGED;
  2318. break;
  2319. case INET_S_AGENT_PART_FAIL : *puiRes = IDS_CRAWL_STATUS_MOSTLYOK; break;
  2320. }
  2321. return CDeliveryAgent::ModifyUpdateEnd(pEndItem, puiRes);
  2322. }
  2323. HRESULT CWebCrawler::DownloadStart(LPCWSTR pchUrl, DWORD dwDownloadId, DWORD dwType, DWORD dwReserved)
  2324. {
  2325. HRESULT hr = S_OK, hr2;
  2326. // free threaded
  2327. EnterCriticalSection(&m_critDependencies);
  2328. if (NULL == pchUrl)
  2329. {
  2330. DBG_WARN("CWebCrawler::DownloadStart pchUrl=NULL");
  2331. }
  2332. else
  2333. {
  2334. // Check to see if this is already in our dependencies list and abort if so
  2335. if (CWCStringList::STRLST_ADDED != m_pDependencies->AddString(pchUrl, 0))
  2336. {
  2337. hr = E_ABORT; // Don't download this thing.
  2338. TraceMsg(TF_THISMODULE, "Aborting mshtml url (already added): %ws", pchUrl);
  2339. }
  2340. if (SUCCEEDED(hr))
  2341. {
  2342. // Check to see if this fails the robots.txt and abort if so
  2343. // Note, this will only work if we happen to have already gotten this robots.txt
  2344. // Need to abort here if we haven't gotten it, then get it, then get just this dep. Yuck.
  2345. // Also shouldn't do the check if this is the first page downloaded
  2346. DWORD dwIndex;
  2347. hr2 = GetRobotsTxtIndex(pchUrl, FALSE, &dwIndex);
  2348. if (SUCCEEDED(hr2))
  2349. {
  2350. BOOL fAllow;
  2351. if (SUCCEEDED(ValidateWithRobotsTxt(pchUrl, dwIndex, &fAllow)))
  2352. {
  2353. if (!fAllow)
  2354. hr = E_ABORT; // ooh, failed the test.
  2355. }
  2356. }
  2357. }
  2358. }
  2359. LeaveCriticalSection(&m_critDependencies);
  2360. return hr;
  2361. }
  2362. HRESULT CWebCrawler::DownloadComplete(DWORD dwDownloadId, HRESULT hrNotify, DWORD dwReserved)
  2363. {
  2364. // free threaded
  2365. // Do nothing. We may wish to post message to make sticky here. We may wish to
  2366. // mark as downloaded in string list here.
  2367. // EnterCriticalSection(&m_critDependencies);
  2368. // LeaveCriticalSection(&m_critDependencies);
  2369. return S_OK;
  2370. }
  2371. /* 41927 (IE5 4491)
  2372. HRESULT CWebCrawler::OnGetReferer(LPCWSTR *ppwszReferer)
  2373. {
  2374. if (m_iPagesStarted <= 1)
  2375. {
  2376. *ppwszReferer = NULL;
  2377. return S_FALSE;
  2378. }
  2379. if (m_pCurDownloadStringList == m_pRobotsTxt)
  2380. {
  2381. // Referer is last page from main list to be downloaded
  2382. *ppwszReferer = m_pPages->GetString(m_iPagesStarted-1);
  2383. return S_OK;
  2384. }
  2385. if (m_pCurDownloadStringList == m_pPages)
  2386. {
  2387. // Referer is stored in string list data
  2388. *ppwszReferer = m_pPages->GetString(
  2389. ((m_pPages->GetStringData(m_iCurDownloadStringIndex) & DATA_REFERERMASK) >> DATA_REFERERSHIFT));
  2390. return S_OK;
  2391. }
  2392. // We don't return a referer for code bases
  2393. ASSERT(m_pCurDownloadStringList == m_pCodeBaseList);
  2394. return S_FALSE;
  2395. }
  2396. */
  2397. HRESULT CWebCrawler::OnAuthenticate(HWND *phwnd, LPWSTR *ppszUsername, LPWSTR *ppszPassword)
  2398. {
  2399. HRESULT hr, hrRet=E_FAIL;
  2400. ASSERT(phwnd && ppszUsername && ppszPassword);
  2401. ASSERT((HWND)-1 == *phwnd && NULL == *ppszUsername && NULL == *ppszPassword);
  2402. // If our host name doesn't match the root host name, don't return auth
  2403. // information.
  2404. LPWSTR pwszUrl, bstrHostName=NULL;
  2405. m_pCurDownload->GetRealURL(&pwszUrl); // may re-enter Trident
  2406. if (pwszUrl)
  2407. {
  2408. GetHostName(pwszUrl, &bstrHostName);
  2409. LocalFree(pwszUrl);
  2410. }
  2411. if (bstrHostName)
  2412. {
  2413. if (!m_bstrHostName || !MyAsciiCmpW(bstrHostName, m_bstrHostName))
  2414. {
  2415. // Host names match. Return auth information.
  2416. // If we're hosted by channel agent, use its auth information
  2417. ISubscriptionItem *pChannel=NULL;
  2418. ISubscriptionItem *pItem=m_pSubscriptionItem;
  2419. if (SUCCEEDED(GetChannelItem(&pChannel)))
  2420. {
  2421. pItem = pChannel;
  2422. }
  2423. hr = ReadOLESTR(pItem, c_szPropCrawlUsername, ppszUsername);
  2424. if (SUCCEEDED(hr))
  2425. {
  2426. BSTR bstrPassword = NULL;
  2427. hr = ReadPassword(pItem, &bstrPassword);
  2428. if (SUCCEEDED(hr))
  2429. {
  2430. int len = (lstrlenW(bstrPassword) + 1) * sizeof(WCHAR);
  2431. *ppszPassword = (LPWSTR) CoTaskMemAlloc(len);
  2432. if (*ppszPassword)
  2433. {
  2434. CopyMemory(*ppszPassword, bstrPassword, len);
  2435. }
  2436. SAFEFREEBSTR(bstrPassword);
  2437. if (*ppszPassword)
  2438. {
  2439. hrRet = S_OK;
  2440. }
  2441. }
  2442. }
  2443. if (FAILED(hrRet))
  2444. {
  2445. SAFEFREEOLESTR(*ppszUsername);
  2446. SAFEFREEOLESTR(*ppszPassword);
  2447. }
  2448. SAFERELEASE(pChannel);
  2449. }
  2450. SysFreeString(bstrHostName);
  2451. }
  2452. return hrRet;
  2453. }
  2454. HRESULT CWebCrawler::OnClientPull(UINT iID, LPCWSTR pwszOldURL, LPCWSTR pwszNewURL)
  2455. {
  2456. // CUrlDownload is informing us it's about to do a client pull.
  2457. // Let's send out a progress report for the new url
  2458. SendUpdateProgress(pwszNewURL, m_iTotalStarted, m_lMaxNumUrls);
  2459. // Now we need to process the current url: make it and dependencies sticky
  2460. DWORD dwCurSize=0;
  2461. BOOL fDiskFull=FALSE;
  2462. MakePageStickyAndGetSize(pwszOldURL, &dwCurSize, &fDiskFull);
  2463. m_dwCurSize += dwCurSize;
  2464. TraceMsg(TF_THISMODULE, "WebCrawler processed page prior to client pull - now up to %d kb", (int)(m_dwCurSize>>10));
  2465. // Tell CUrlDownload to go ahead and download the new url
  2466. return S_OK;
  2467. }
  2468. HRESULT CWebCrawler::OnOleCommandTargetExec(const GUID *pguidCmdGroup, DWORD nCmdID,
  2469. DWORD nCmdexecopt, VARIANTARG *pvarargIn,
  2470. VARIANTARG *pvarargOut)
  2471. {
  2472. HRESULT hr = OLECMDERR_E_NOTSUPPORTED;
  2473. IPropertyBag2 *pPropBag = NULL;
  2474. int i;
  2475. //REVIEW: CLSID for this not yet defined.
  2476. if ( pguidCmdGroup
  2477. && (*pguidCmdGroup == CGID_JavaParambagCompatHack)
  2478. && (nCmdID == 0)
  2479. && (nCmdexecopt == MSOCMDEXECOPT_DONTPROMPTUSER))
  2480. {
  2481. if (!IsRecurseFlagSet(WEBCRAWL_GET_CONTROLS))
  2482. {
  2483. goto Exit;
  2484. }
  2485. uCLSSPEC ucs;
  2486. QUERYCONTEXT qc = { 0 };
  2487. ucs.tyspec = TYSPEC_CLSID;
  2488. ucs.tagged_union.clsid = CLSID_JavaVM;
  2489. // Check to see if Java VM is installed. Don't try to get applets if not.
  2490. if (!SUCCEEDED(FaultInIEFeature(NULL, &ucs, &qc, FIEF_FLAG_PEEK)))
  2491. {
  2492. goto Exit;
  2493. }
  2494. ULONG enIndex;
  2495. const DWORD enMax = 7, enMin = 0;
  2496. PROPBAG2 pb[enMax];
  2497. VARIANT vaProps[enMax];
  2498. HRESULT hrResult[enMax];
  2499. enum { enCodeBase = 0, enCabBase, enCabinets, enArchive, enUsesLib, enLibrary, enUsesVer };
  2500. LPWSTR pwszThisURL = NULL;
  2501. int chLen;
  2502. //REVIEW: This will need to be reviewed later when matching trident code is available
  2503. // and details worked out.
  2504. if ((pvarargIn->vt != VT_UNKNOWN) ||
  2505. (FAILED(pvarargIn->punkVal->QueryInterface(IID_IPropertyBag2, (void **)&pPropBag))))
  2506. {
  2507. goto Exit;
  2508. }
  2509. if (FAILED(GetRealUrl(m_iCurDownloadStringIndex, &pwszThisURL)))
  2510. {
  2511. pwszThisURL = StrDupW(L"");
  2512. }
  2513. // PROPBAG2 structure for data retrieval
  2514. for (i=enMin; i<enMax; i++)
  2515. {
  2516. pb[i].dwType = PROPBAG2_TYPE_DATA;
  2517. pb[i].vt = VT_BSTR;
  2518. pb[i].cfType = NULL; // CLIPFORMAT
  2519. pb[i].dwHint = 0; // ????
  2520. pb[i].pstrName = NULL;
  2521. pb[i].clsid = CLSID_NULL; // ????
  2522. vaProps[i].vt = VT_EMPTY;
  2523. vaProps[i].bstrVal = NULL;
  2524. hrResult[i] = E_FAIL;
  2525. }
  2526. if (((pb[enCodeBase].pstrName = SysAllocString(L"CODEBASE")) != NULL) &&
  2527. ((pb[enCabBase].pstrName = SysAllocString(L"CABBASE")) != NULL) &&
  2528. ((pb[enCabinets].pstrName = SysAllocString(L"CABINETS")) != NULL) &&
  2529. ((pb[enArchive].pstrName = SysAllocString(L"ARCHIVE")) != NULL) &&
  2530. ((pb[enUsesLib].pstrName = SysAllocString(L"USESLIBRARY")) != NULL) &&
  2531. ((pb[enLibrary].pstrName = SysAllocString(L"USESLIBRARYCODEBASE")) != NULL) &&
  2532. ((pb[enUsesVer].pstrName = SysAllocString(L"USESLIBRARYVERSION")) != NULL))
  2533. {
  2534. //Read returns E_FAIL even if it read some of the properties.
  2535. //Since we check hrResult's below this isn't a big deal.
  2536. hr = pPropBag->Read(enMax, &pb[0], NULL, &vaProps[0], &hrResult[0]);
  2537. {
  2538. BSTR szCodeBase = NULL;
  2539. // check for CODEBASE
  2540. if (SUCCEEDED(hrResult[enCodeBase]) && (vaProps[enCodeBase].vt == VT_BSTR))
  2541. {
  2542. szCodeBase = vaProps[enCodeBase].bstrVal;
  2543. }
  2544. // add a trailing slash if not already present
  2545. chLen = lstrlenW(szCodeBase);
  2546. if (chLen && szCodeBase[chLen-1] != '/')
  2547. {
  2548. LPWSTR szNewCodeBase = 0;
  2549. szNewCodeBase = (LPWSTR) LocalAlloc(0,sizeof(WCHAR)*(chLen+2));
  2550. if (szNewCodeBase)
  2551. {
  2552. StrCpyW(szNewCodeBase, szCodeBase);
  2553. StrCatW(szNewCodeBase, L"/");
  2554. SAFEFREEBSTR(szCodeBase);
  2555. szCodeBase = vaProps[enCodeBase].bstrVal = SysAllocString(szNewCodeBase);
  2556. LocalFree(szNewCodeBase);
  2557. }
  2558. }
  2559. // check for CABBASE
  2560. if (SUCCEEDED(hrResult[enCabBase]) && (vaProps[enCabBase].vt == VT_BSTR))
  2561. {
  2562. BSTR szCabBase = vaProps[enCabBase].bstrVal;
  2563. // Add CABBASE URL to list of CABs to pull.
  2564. if (SUCCEEDED(CombineBaseAndRelativeURLs(pwszThisURL, szCodeBase, &szCabBase)))
  2565. {
  2566. m_pPages->AddString(szCabBase, 0);
  2567. }
  2568. }
  2569. // check for CABINETS
  2570. for (enIndex = enCabinets; enIndex<(enArchive+1); enIndex++)
  2571. {
  2572. if (SUCCEEDED(hrResult[enIndex]) && (vaProps[enIndex].vt == VT_BSTR))
  2573. {
  2574. BSTR szCur = vaProps[enIndex].bstrVal, szPrev = NULL;
  2575. while (szCur)
  2576. {
  2577. WCHAR wcCur = *szCur;
  2578. if ((wcCur == L'+') || (wcCur == L',') || (wcCur == L'\0'))
  2579. {
  2580. BSTR szLast = szPrev, szCabBase = NULL;
  2581. BOOL bLastFile = FALSE;
  2582. if (!szPrev)
  2583. {
  2584. szLast = vaProps[enIndex].bstrVal;
  2585. }
  2586. szPrev = szCur; szPrev++;
  2587. if (*szCur == L'\0')
  2588. {
  2589. bLastFile = TRUE;
  2590. }
  2591. *szCur = (unsigned short)L'\0';
  2592. // szLast points to current CabBase.
  2593. szCabBase = SysAllocString(szLast);
  2594. if (SUCCEEDED(CombineBaseAndRelativeURLs(pwszThisURL, szCodeBase, &szCabBase)))
  2595. {
  2596. int iAdd=m_pPages->AddString(szCabBase, DATA_CODEBASE);
  2597. if (m_lMaxNumUrls > 0 && iAdd==CWCStringList::STRLST_ADDED)
  2598. m_lMaxNumUrls ++;
  2599. }
  2600. SAFEFREEBSTR(szCabBase);
  2601. if (bLastFile)
  2602. {
  2603. szCur = NULL;
  2604. break;
  2605. }
  2606. }
  2607. szCur++;
  2608. } // while (szCur)
  2609. } // cabinets
  2610. }
  2611. // check for USESLIBRARY* parameters.
  2612. CCodeBaseHold *pcbh = NULL;
  2613. if (SUCCEEDED(hrResult[enUsesLib]) && (vaProps[enUsesLib].vt == VT_BSTR) &&
  2614. SUCCEEDED(hrResult[enLibrary]) && (vaProps[enLibrary].vt == VT_BSTR))
  2615. {
  2616. BSTR szThisLibCAB = NULL;
  2617. pcbh = new CCodeBaseHold();
  2618. if (pcbh)
  2619. {
  2620. pcbh->szDistUnit = SysAllocString(vaProps[enUsesLib].bstrVal);
  2621. pcbh->dwVersionMS = pcbh->dwVersionLS = -1;
  2622. pcbh->dwFlags = 0;
  2623. szThisLibCAB = SysAllocString(vaProps[enLibrary].bstrVal);
  2624. if (FAILED(CombineBaseAndRelativeURLs(pwszThisURL, szCodeBase, &szThisLibCAB)) ||
  2625. m_pCodeBaseList->AddString(szThisLibCAB, (DWORD_PTR)pcbh) != CWCStringList::STRLST_ADDED)
  2626. {
  2627. SAFEFREEBSTR(pcbh->szDistUnit);
  2628. SAFEDELETE(pcbh);
  2629. }
  2630. SAFEFREEBSTR(szThisLibCAB);
  2631. }
  2632. }
  2633. // Check for USESLIBRARYVERSION (optional)
  2634. if (pcbh && SUCCEEDED(hrResult[enUsesVer]) && (vaProps[enUsesVer].vt == VT_BSTR))
  2635. {
  2636. int iLen = SysStringByteLen(vaProps[enUsesVer].bstrVal)+1;
  2637. CHAR *szVerStr = (LPSTR)MemAlloc(LMEM_FIXED, iLen);
  2638. if (szVerStr)
  2639. {
  2640. SHUnicodeToAnsi(vaProps[enUsesVer].bstrVal, szVerStr, iLen);
  2641. if (FAILED(GetVersionFromString(szVerStr,
  2642. &pcbh->dwVersionMS, &pcbh->dwVersionLS)))
  2643. {
  2644. hr = HRESULT_FROM_WIN32(GetLastError());
  2645. MemFree(szVerStr);
  2646. SAFEFREEBSTR(pcbh->szDistUnit);
  2647. SAFEDELETE(pcbh);
  2648. }
  2649. MemFree(szVerStr);
  2650. }
  2651. }
  2652. }
  2653. } // Read properties
  2654. for (i=enMin; i<enMax; i++)
  2655. {
  2656. SAFEFREEBSTR(pb[i].pstrName);
  2657. }
  2658. if (pwszThisURL)
  2659. LocalFree(pwszThisURL);
  2660. hr = S_OK;
  2661. }
  2662. Exit:
  2663. SAFERELEASE(pPropBag);
  2664. return hr;
  2665. }
  2666. HRESULT CWebCrawler::GetDownloadNotify(IDownloadNotify **ppOut)
  2667. {
  2668. HRESULT hr=S_OK;
  2669. if (m_pDownloadNotify)
  2670. {
  2671. m_pDownloadNotify->LeaveMeAlone();
  2672. m_pDownloadNotify->Release();
  2673. m_pDownloadNotify=NULL;
  2674. }
  2675. m_pDownloadNotify = new CDownloadNotify(this);
  2676. if (m_pDownloadNotify)
  2677. {
  2678. *ppOut = m_pDownloadNotify;
  2679. m_pDownloadNotify->AddRef();
  2680. }
  2681. else
  2682. {
  2683. hr = E_OUTOFMEMORY;
  2684. *ppOut = NULL;
  2685. }
  2686. return hr;
  2687. }
  2688. //---------------------------------------------------------------
  2689. // CWebCrawler::CDownloadNotify class
  2690. //---------------------------------------------------------------
  2691. CWebCrawler::CDownloadNotify::CDownloadNotify(CWebCrawler *pParent)
  2692. {
  2693. ASSERT(pParent);
  2694. m_cRef = 1;
  2695. m_pParent = pParent;
  2696. pParent->AddRef();
  2697. InitializeCriticalSection(&m_critParent);
  2698. }
  2699. CWebCrawler::CDownloadNotify::~CDownloadNotify()
  2700. {
  2701. DBG("Destroying CWebCrawler::CDownloadNotify");
  2702. ASSERT(!m_pParent);
  2703. SAFERELEASE(m_pParent);
  2704. DeleteCriticalSection(&m_critParent);
  2705. }
  2706. void CWebCrawler::CDownloadNotify::LeaveMeAlone()
  2707. {
  2708. if (m_pParent)
  2709. {
  2710. EnterCriticalSection(&m_critParent);
  2711. SAFERELEASE(m_pParent);
  2712. LeaveCriticalSection(&m_critParent);
  2713. }
  2714. }
  2715. // IUnknown members
  2716. HRESULT CWebCrawler::CDownloadNotify::QueryInterface(REFIID riid, void **ppv)
  2717. {
  2718. if ((IID_IUnknown == riid) ||
  2719. (IID_IDownloadNotify == riid))
  2720. {
  2721. *ppv = (IDownloadNotify *)this;
  2722. }
  2723. else
  2724. {
  2725. *ppv = NULL;
  2726. return E_NOINTERFACE;
  2727. }
  2728. ((LPUNKNOWN)*ppv)->AddRef();
  2729. return S_OK;
  2730. }
  2731. ULONG CWebCrawler::CDownloadNotify::AddRef(void)
  2732. {
  2733. return InterlockedIncrement(&m_cRef);
  2734. }
  2735. ULONG CWebCrawler::CDownloadNotify::Release(void)
  2736. {
  2737. if (0L != InterlockedDecrement(&m_cRef))
  2738. return 1L;
  2739. delete this;
  2740. return 0L;
  2741. }
  2742. // IDownloadNotify
  2743. HRESULT CWebCrawler::CDownloadNotify::DownloadStart(LPCWSTR pchUrl, DWORD dwDownloadId, DWORD dwType, DWORD dwReserved)
  2744. {
  2745. HRESULT hr = E_ABORT; // abort it if we have nobody listening
  2746. TraceMsg(TF_THISMODULE, "DownloadStart id=%d url=%ws", dwDownloadId, pchUrl ? pchUrl : L"(null)");
  2747. EnterCriticalSection(&m_critParent);
  2748. if (m_pParent)
  2749. hr = m_pParent->DownloadStart(pchUrl, dwDownloadId, dwType, dwReserved);
  2750. LeaveCriticalSection(&m_critParent);
  2751. return hr;
  2752. }
  2753. HRESULT CWebCrawler::CDownloadNotify::DownloadComplete(DWORD dwDownloadId, HRESULT hrNotify, DWORD dwReserved)
  2754. {
  2755. HRESULT hr = S_OK;
  2756. // TraceMsg(TF_THISMODULE, "DownloadComplete id=%d hr=%x", dwDownloadId, hrNotify);
  2757. EnterCriticalSection(&m_critParent);
  2758. if (m_pParent)
  2759. hr = m_pParent->DownloadComplete(dwDownloadId, hrNotify, dwReserved);
  2760. LeaveCriticalSection(&m_critParent);
  2761. return hr;
  2762. }
  2763. //////////////////////////////////////////////////////////////////////////
  2764. //
  2765. // Other functions
  2766. //
  2767. //////////////////////////////////////////////////////////////////////////
  2768. // Make a single absolute or relative url sticky and get size
  2769. HRESULT GetUrlInfoAndMakeSticky(
  2770. LPCTSTR pszBaseUrl,
  2771. LPCTSTR pszThisUrl,
  2772. LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo,
  2773. DWORD dwBufSize,
  2774. GROUPID llCacheGroupID)
  2775. {
  2776. DWORD dwSize;
  2777. TCHAR szCombined[INTERNET_MAX_URL_LENGTH];
  2778. #if 0 // Make lpCacheEntryInfo optional
  2779. BYTE chBuf[MY_MAX_CACHE_ENTRY_INFO];
  2780. if (!lpCacheEntryInfo)
  2781. {
  2782. lpCacheEntryInfo = (LPINTERNET_CACHE_ENTRY_INFO)chBuf;
  2783. dwBufSize = sizeof(chBuf);
  2784. }
  2785. #else
  2786. ASSERT(lpCacheEntryInfo);
  2787. #endif
  2788. // Combine urls if necessary
  2789. if (pszBaseUrl)
  2790. {
  2791. dwSize = ARRAYSIZE(szCombined);
  2792. if (SUCCEEDED(UrlCombine(pszBaseUrl, pszThisUrl,
  2793. szCombined, &dwSize, 0)))
  2794. {
  2795. pszThisUrl = szCombined;
  2796. }
  2797. else
  2798. DBG_WARN("UrlCombine failed!");
  2799. }
  2800. // Add the size of this URL
  2801. lpCacheEntryInfo->dwStructSize = dwBufSize;
  2802. if (!GetUrlCacheEntryInfo(pszThisUrl, lpCacheEntryInfo, &dwBufSize))
  2803. {
  2804. #ifdef DEBUG
  2805. if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  2806. DBG_WARN("Failed GetUrlCacheEntryInfo, insufficient buffer");
  2807. else
  2808. TraceMsgA(llCacheGroupID ? TF_WARNING : TF_THISMODULE,
  2809. "Failed GetUrlCacheEntryInfo (not in cache) URL=%ws", pszThisUrl);
  2810. #endif
  2811. return E_FAIL;
  2812. }
  2813. // Add to new group
  2814. if (llCacheGroupID != 0)
  2815. {
  2816. if (!SetUrlCacheEntryGroup(pszThisUrl, INTERNET_CACHE_GROUP_ADD,
  2817. llCacheGroupID, NULL, 0, NULL))
  2818. {
  2819. switch (GetLastError())
  2820. {
  2821. case ERROR_FILE_NOT_FOUND: // Huh? Must not have been able to add the index entry?
  2822. case ERROR_DISK_FULL:
  2823. return E_OUTOFMEMORY;
  2824. case ERROR_NOT_ENOUGH_QUOTA:
  2825. return S_OK; // We do our own quota handling.
  2826. default:
  2827. TraceMsgA(TF_WARNING | TF_THISMODULE, "GetUrlInfoAndMakeSticky: Got unexpected error from SetUrlCacheEntryGroup() - GLE = 0x%08x", GetLastError());
  2828. return E_FAIL;
  2829. }
  2830. }
  2831. }
  2832. return S_OK;
  2833. }
  2834. // GenerateCode will generate a DWORD code from a file.
  2835. #define ELEMENT_PER_READ 256
  2836. #define ELEMENT_SIZE sizeof(DWORD)
  2837. HRESULT GenerateCode(LPCTSTR lpszLocalFileName, DWORD *pdwRet)
  2838. {
  2839. DWORD dwCode=0;
  2840. DWORD dwData[ELEMENT_PER_READ], i, dwRead;
  2841. HRESULT hr = S_OK;
  2842. HANDLE hFile;
  2843. hFile = CreateFile(lpszLocalFileName, GENERIC_READ,
  2844. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
  2845. 0, NULL);
  2846. if (INVALID_HANDLE_VALUE != hFile)
  2847. {
  2848. do
  2849. {
  2850. dwRead = 0;
  2851. if (ReadFile(hFile, dwData, ELEMENT_PER_READ * ELEMENT_SIZE, &dwRead, NULL))
  2852. {
  2853. for (i=0; i<dwRead / ELEMENT_SIZE; i++)
  2854. {
  2855. dwCode = (dwCode << 31) | (dwCode >> 1) + dwData[i];
  2856. // dwCode += dwData[i];
  2857. }
  2858. }
  2859. }
  2860. while (ELEMENT_PER_READ * ELEMENT_SIZE == dwRead);
  2861. CloseHandle(hFile);
  2862. }
  2863. else
  2864. {
  2865. hr = E_FAIL;
  2866. TraceMsg(TF_THISMODULE|TF_WARNING,"GenerateCode: Unable to open cache file, Error=%x", GetLastError());
  2867. }
  2868. *pdwRet = dwCode;
  2869. return hr;
  2870. }
  2871. // S_OK : We retrieved a good last modified or content code to use
  2872. // S_FALSE : We fell back to using the one passed into pvarChange
  2873. // E_FAIL : We failed miserably.
  2874. // E_INVALIDARG : Get a clue
  2875. // *pfGetContent : TRUE if we need a GET for PostCheckUrlForChange to work right
  2876. HRESULT PreCheckUrlForChange(LPCTSTR lpURL, VARIANT *pvarChange, BOOL *pfGetContent)
  2877. {
  2878. BYTE chBuf[MY_MAX_CACHE_ENTRY_INFO];
  2879. LPINTERNET_CACHE_ENTRY_INFO lpInfo = (LPINTERNET_CACHE_ENTRY_INFO) chBuf;
  2880. if (pvarChange->vt != VT_EMPTY && pvarChange->vt != VT_I4 && pvarChange->vt != VT_CY)
  2881. return E_INVALIDARG;
  2882. if (SUCCEEDED(GetUrlInfoAndMakeSticky(NULL, lpURL, lpInfo, sizeof(chBuf), 0)))
  2883. {
  2884. FILETIME ftOldLastModified = *((FILETIME *) &pvarChange->cyVal);
  2885. if (lpInfo->LastModifiedTime.dwHighDateTime || lpInfo->LastModifiedTime.dwLowDateTime)
  2886. {
  2887. // We have a last modified time. Use it or the persisted one.
  2888. if (pfGetContent)
  2889. *pfGetContent = FALSE;
  2890. if ((pvarChange->vt != VT_CY)
  2891. || (lpInfo->LastModifiedTime.dwHighDateTime > ftOldLastModified.dwHighDateTime)
  2892. || ((lpInfo->LastModifiedTime.dwHighDateTime == ftOldLastModified.dwHighDateTime)
  2893. && (lpInfo->LastModifiedTime.dwLowDateTime > ftOldLastModified.dwLowDateTime)))
  2894. {
  2895. // Cache Last Modified is newer than saved Last Modified. Use cache's.
  2896. pvarChange->vt = VT_CY;
  2897. pvarChange->cyVal = *((CY *)&(lpInfo->LastModifiedTime));
  2898. return S_OK;
  2899. }
  2900. ASSERT(pvarChange->vt == VT_CY);
  2901. // Persisted Last Modified time is most recent. Use it.
  2902. return S_OK;
  2903. }
  2904. DWORD dwCode;
  2905. if (SUCCEEDED(GenerateCode(lpInfo->lpszLocalFileName, &dwCode)))
  2906. {
  2907. pvarChange->vt = VT_I4;
  2908. pvarChange->lVal = (LONG) dwCode;
  2909. if (pfGetContent)
  2910. *pfGetContent = TRUE;
  2911. return S_OK;
  2912. }
  2913. // Failed GenerateCode. Weird. Fall through.
  2914. }
  2915. if (pvarChange->vt != VT_EMPTY)
  2916. {
  2917. if (pfGetContent)
  2918. *pfGetContent = (pvarChange->vt == VT_I4);
  2919. return S_FALSE;
  2920. }
  2921. // We don't have old change detection, we don't have cache content, better GET
  2922. if (pfGetContent)
  2923. *pfGetContent = TRUE;
  2924. return E_FAIL; // Couldn't get anything. pvarChange->vt==VT_EMPTY
  2925. }
  2926. // S_FALSE : no change
  2927. // S_OK : changed
  2928. // E_ : failure of some sort
  2929. // pvarChange from PreCheckUrlForChange. We return a new one.
  2930. // lpInfo : must be valid if *pfGetContent was TRUE
  2931. // ftNewLastModified : must be filled in if *pfGetContent was FALSE
  2932. HRESULT PostCheckUrlForChange(VARIANT *pvarChange,
  2933. LPINTERNET_CACHE_ENTRY_INFO lpInfo,
  2934. FILETIME ftNewLastModified)
  2935. {
  2936. HRESULT hr = S_FALSE;
  2937. VARIANT varChangeNew;
  2938. DWORD dwNewCode = 0;
  2939. if (!pvarChange || (pvarChange->vt != VT_I4 && pvarChange->vt != VT_CY && pvarChange->vt != VT_EMPTY))
  2940. return E_INVALIDARG;
  2941. varChangeNew.vt = VT_EMPTY;
  2942. if (ftNewLastModified.dwHighDateTime || ftNewLastModified.dwLowDateTime)
  2943. {
  2944. varChangeNew.vt = VT_CY;
  2945. varChangeNew.cyVal = *((CY *) &ftNewLastModified);
  2946. }
  2947. else
  2948. {
  2949. if (lpInfo &&
  2950. SUCCEEDED(GenerateCode(lpInfo->lpszLocalFileName, &dwNewCode)))
  2951. {
  2952. varChangeNew.vt = VT_I4;
  2953. varChangeNew.lVal = dwNewCode;
  2954. }
  2955. }
  2956. if (pvarChange->vt == VT_CY)
  2957. {
  2958. // We have an old last modified time. Use that to determine change.
  2959. FILETIME ftOldLastModified = *((FILETIME *) &(pvarChange->cyVal));
  2960. if ((!ftNewLastModified.dwHighDateTime && !ftNewLastModified.dwLowDateTime)
  2961. || (ftNewLastModified.dwHighDateTime > ftOldLastModified.dwHighDateTime)
  2962. || ((ftNewLastModified.dwHighDateTime == ftOldLastModified.dwHighDateTime)
  2963. && (ftNewLastModified.dwLowDateTime > ftOldLastModified.dwLowDateTime)))
  2964. {
  2965. // NewLastModified > OldLastModified (or we don't have a NewLastModified)
  2966. DBG("PostCheckUrlForChange change detected via Last Modified");
  2967. hr = S_OK; // We have changed
  2968. }
  2969. }
  2970. else if (pvarChange->vt == VT_I4)
  2971. {
  2972. // We have an old code. Use that to determine change.
  2973. DWORD dwOldCode = (DWORD) (pvarChange->lVal);
  2974. if ((dwOldCode != dwNewCode) ||
  2975. !dwNewCode)
  2976. {
  2977. DBG("PostCheckUrlForChange change detected via content code");
  2978. hr = S_OK; // We have changed
  2979. }
  2980. }
  2981. else
  2982. hr = E_FAIL; // No old code.
  2983. *pvarChange = varChangeNew;
  2984. return hr;
  2985. }
  2986. //////////////////////////////////////////////////////////////////////////
  2987. //
  2988. // CHelperOM implementation
  2989. //
  2990. //////////////////////////////////////////////////////////////////////////
  2991. CHelperOM::CHelperOM(IHTMLDocument2 *pDoc)
  2992. {
  2993. ASSERT(pDoc);
  2994. m_pDoc = pDoc;
  2995. if (pDoc)
  2996. pDoc->AddRef();
  2997. }
  2998. CHelperOM::~CHelperOM()
  2999. {
  3000. SAFERELEASE(m_pDoc);
  3001. }
  3002. HRESULT CHelperOM::GetTagCollection(
  3003. IHTMLDocument2 *pDoc,
  3004. LPCWSTR wszTagName,
  3005. IHTMLElementCollection **ppCollection)
  3006. {
  3007. IHTMLElementCollection *pAll=NULL;
  3008. IDispatch *pDisp=NULL;
  3009. VARIANT TagName;
  3010. HRESULT hr;
  3011. // We have to get "all", then sub-collection
  3012. hr = pDoc->get_all(&pAll);
  3013. if (pAll)
  3014. {
  3015. TagName.vt = VT_BSTR;
  3016. TagName.bstrVal = SysAllocString(wszTagName);
  3017. if (NULL == TagName.bstrVal)
  3018. hr = E_OUTOFMEMORY;
  3019. else
  3020. {
  3021. hr = pAll->tags(TagName, &pDisp);
  3022. SysFreeString(TagName.bstrVal);
  3023. }
  3024. pAll->Release();
  3025. }
  3026. if (pDisp)
  3027. {
  3028. hr = pDisp->QueryInterface(IID_IHTMLElementCollection,
  3029. (void **)ppCollection);
  3030. pDisp->Release();
  3031. }
  3032. if (FAILED(hr)) DBG("GetSubCollection failed");
  3033. return hr;
  3034. }
  3035. // Collections we get:
  3036. //
  3037. // IHTMLWindow2->get_document
  3038. // IHTMLDocument2 ->get_links
  3039. // IHTMLElementCollection->item
  3040. // ->get_hostname
  3041. // ->get_href
  3042. // ->get_all
  3043. // ->tags("map")
  3044. // IHTMLElementCollection ->item
  3045. // ->get_areas
  3046. // IHTMLElementCollection ->item
  3047. // IHTMLAreaElement ->get_href
  3048. // ->get_all
  3049. // ->tags("meta")
  3050. // IHTMLElementCollection ->item
  3051. // ->get_all
  3052. // ->tags("frame")
  3053. // IHTMLElementCollection ->item
  3054. // ->get_all
  3055. // ->tags("iframe")
  3056. // IHTMLElementCollection ->item
  3057. // We recurse EnumCollection to get the maps (since
  3058. // it's a collection of collections)
  3059. // hideous hack: IHTMLElementCollection can actually be IHTMLAreasCollection
  3060. // the interface used to be derived from the other. It still has identical
  3061. // methods. We typecast just in case that changes. Hopefully they will fix
  3062. // so that Areas is derived from Element again.
  3063. HRESULT CHelperOM::EnumCollection(
  3064. IHTMLElementCollection *pCollection,
  3065. CWCStringList *pStringList,
  3066. CollectionType Type,
  3067. PFN_CB pfnCB,
  3068. DWORD_PTR dwCBData)
  3069. {
  3070. IHTMLAnchorElement *pLink;
  3071. IHTMLMapElement *pMap;
  3072. IHTMLAreaElement *pArea;
  3073. IHTMLMetaElement *pMeta;
  3074. IHTMLElement *pEle;
  3075. IDispatch *pDispItem = NULL;
  3076. HRESULT hr;
  3077. BSTR bstrItem=NULL;
  3078. long l, lCount;
  3079. VARIANT vIndex, vEmpty, vData;
  3080. BSTR bstrTmp1, bstrTmp2;
  3081. DWORD dwStringData;
  3082. VariantInit(&vEmpty);
  3083. VariantInit(&vIndex);
  3084. VariantInit(&vData);
  3085. if (Type==CTYPE_MAP)
  3086. hr = ((IHTMLAreasCollection *)pCollection)->get_length(&lCount);
  3087. else
  3088. hr = pCollection->get_length(&lCount);
  3089. if (FAILED(hr))
  3090. lCount = 0;
  3091. #ifdef DEBUG
  3092. LPSTR lpDSTR[]={"Links","Maps","Areas (links) In Map", "Meta", "Frames"};
  3093. TraceMsgA(TF_THISMODULE, "CWebCrawler::GetCollection, %d %s found", lCount, lpDSTR[(int)Type]);
  3094. #endif
  3095. for (l=0; l<lCount; l++)
  3096. {
  3097. vIndex.vt = VT_I4;
  3098. vIndex.lVal = l;
  3099. dwStringData = 0;
  3100. if (Type==CTYPE_MAP)
  3101. hr = ((IHTMLAreasCollection *)pCollection)->item(vIndex, vEmpty, &pDispItem);
  3102. else
  3103. hr = pCollection->item(vIndex, vEmpty, &pDispItem);
  3104. if (SUCCEEDED(hr))
  3105. {
  3106. ASSERT(vData.vt == VT_EMPTY);
  3107. ASSERT(!bstrItem);
  3108. if (pDispItem)
  3109. {
  3110. // Get the URL from the IDispatch
  3111. switch(Type)
  3112. {
  3113. case CTYPE_LINKS: // get href from <a>
  3114. hr = pDispItem->QueryInterface(IID_IHTMLAnchorElement, (void **)&pLink);
  3115. if (SUCCEEDED(hr) && pLink)
  3116. {
  3117. hr = pLink->get_href(&bstrItem);
  3118. pLink->Release();
  3119. }
  3120. break;
  3121. case CTYPE_MAPS: // enumeration areas for this map
  3122. hr = pDispItem->QueryInterface(IID_IHTMLMapElement, (void **)&pMap);
  3123. if (SUCCEEDED(hr) && pMap)
  3124. {
  3125. IHTMLAreasCollection *pNewCollection=NULL;
  3126. // This gives us another collection. Enumerate it
  3127. // for the strings.
  3128. hr = pMap->get_areas(&pNewCollection);
  3129. if (pNewCollection)
  3130. {
  3131. hr = EnumCollection((IHTMLElementCollection *)pNewCollection, pStringList, CTYPE_MAP, pfnCB, dwCBData);
  3132. pNewCollection->Release();
  3133. }
  3134. pMap->Release();
  3135. }
  3136. break;
  3137. case CTYPE_MAP: // get href for this area
  3138. hr = pDispItem->QueryInterface(IID_IHTMLAreaElement, (void **)&pArea);
  3139. if (SUCCEEDED(hr) && pArea)
  3140. {
  3141. hr = pArea->get_href(&bstrItem);
  3142. pArea->Release();
  3143. }
  3144. break;
  3145. case CTYPE_META: // get meta name and content as single string
  3146. hr = pDispItem->QueryInterface(IID_IHTMLMetaElement, (void **)&pMeta);
  3147. if (SUCCEEDED(hr) && pMeta)
  3148. {
  3149. pMeta->get_name(&bstrTmp1);
  3150. pMeta->get_content(&bstrTmp2);
  3151. if (bstrTmp1 && bstrTmp2 && *bstrTmp1 && *bstrTmp2)
  3152. {
  3153. bstrItem = SysAllocStringLen(NULL, lstrlenW(bstrTmp1) +
  3154. lstrlenW(bstrTmp2) + 1);
  3155. StrCpyW(bstrItem, bstrTmp1);
  3156. StrCatW(bstrItem, L"\n");
  3157. StrCatW(bstrItem, bstrTmp2);
  3158. }
  3159. SysFreeString(bstrTmp1);
  3160. SysFreeString(bstrTmp2);
  3161. pMeta->Release();
  3162. }
  3163. break;
  3164. case CTYPE_FRAMES: // get "src" attribute
  3165. hr = pDispItem->QueryInterface(IID_IHTMLElement, (void **)&pEle);
  3166. if (SUCCEEDED(hr) && pEle)
  3167. {
  3168. bstrTmp1 = SysAllocString(L"SRC");
  3169. if (bstrTmp1)
  3170. {
  3171. hr = pEle->getAttribute(bstrTmp1, VARIANT_FALSE, &vData);
  3172. if (SUCCEEDED(hr) && vData.vt == VT_BSTR)
  3173. {
  3174. bstrItem = vData.bstrVal;
  3175. vData.vt = VT_EMPTY;
  3176. }
  3177. else
  3178. VariantClear(&vData);
  3179. SysFreeString(bstrTmp1);
  3180. }
  3181. else
  3182. {
  3183. hr = E_FAIL;
  3184. }
  3185. pEle->Release();
  3186. }
  3187. break;
  3188. default:
  3189. ASSERT(0);
  3190. // bug in calling code
  3191. }
  3192. if (SUCCEEDED(hr) && bstrItem)
  3193. {
  3194. // Verify we want to add this item to string list & get data
  3195. if (pfnCB)
  3196. hr = pfnCB(pDispItem, &bstrItem, dwCBData, &dwStringData);
  3197. if (SUCCEEDED(hr) && bstrItem && pStringList)
  3198. pStringList->AddString(bstrItem, dwStringData);
  3199. }
  3200. SAFERELEASE(pDispItem);
  3201. SAFEFREEBSTR(bstrItem);
  3202. }
  3203. }
  3204. if (E_ABORT == hr)
  3205. {
  3206. DBG_WARN("Aborting enumeration in CHelperOM::EnumCollection at callback's request.");
  3207. break;
  3208. }
  3209. }
  3210. return hr;
  3211. }
  3212. // Gets all urls from a collection, recursing through frames
  3213. HRESULT CHelperOM::GetCollection(
  3214. IHTMLDocument2 *pDoc,
  3215. CWCStringList *pStringList,
  3216. CollectionType Type,
  3217. PFN_CB pfnCB,
  3218. DWORD_PTR dwCBData)
  3219. {
  3220. HRESULT hr;
  3221. // Get the collection from the document
  3222. ASSERT(pDoc);
  3223. ASSERT(pStringList || pfnCB);
  3224. hr = _GetCollection(pDoc, pStringList, Type, pfnCB, dwCBData);
  3225. #if 0
  3226. // we enumerate for the top-level interface, then for subframes if any
  3227. long lLen=0, lIndex;
  3228. VARIANT vIndex, vResult;
  3229. vResult.vt = VT_EMPTY;
  3230. IHTMLWindow2 *pWin2=NULL;
  3231. if (SUCCEEDED(pWin->get_length(&lLen)) && lLen>0)
  3232. {
  3233. TraceMsg(TF_THISMODULE, "Also enumerating for %d subframes", (int)lLen);
  3234. for (lIndex=0; lIndex<lLen; lIndex++)
  3235. {
  3236. vIndex.vt = VT_I4;
  3237. vIndex.lVal = lIndex;
  3238. pWin->item(&vIndex, &vResult);
  3239. if (vResult.vt == VT_DISPATCH && vResult.pdispVal)
  3240. {
  3241. if (SUCCEEDED(vResult.pdispVal->QueryInterface(IID_IHTMLWindow2, (void **)&pWin2)) && pWin2)
  3242. {
  3243. GetCollection(pWin2, pStringList, Type);
  3244. pWin2->Release();
  3245. pWin2=NULL;
  3246. }
  3247. }
  3248. VariantClear(&vResult);
  3249. }
  3250. }
  3251. #endif
  3252. return hr;
  3253. }
  3254. // get all urls from a collection
  3255. HRESULT CHelperOM::_GetCollection(
  3256. IHTMLDocument2 *pDoc,
  3257. CWCStringList *pStringList,
  3258. CollectionType Type,
  3259. PFN_CB pfnCB,
  3260. DWORD_PTR dwCBData)
  3261. {
  3262. HRESULT hr;
  3263. IHTMLElementCollection *pCollection=NULL;
  3264. // From IHTMLDocument2 we get IHTMLElementCollection, then enumerate for the urls
  3265. // Get appropriate collection from document
  3266. switch (Type)
  3267. {
  3268. case CTYPE_LINKS:
  3269. hr = pDoc->get_links(&pCollection);
  3270. break;
  3271. case CTYPE_MAPS:
  3272. hr = GetTagCollection(pDoc, L"map", &pCollection);
  3273. break;
  3274. case CTYPE_META:
  3275. hr = GetTagCollection(pDoc, L"meta", &pCollection);
  3276. break;
  3277. case CTYPE_FRAMES:
  3278. hr = GetTagCollection(pDoc, L"frame", &pCollection);
  3279. break;
  3280. default:
  3281. hr = E_FAIL;
  3282. }
  3283. if (!pCollection) hr=E_NOINTERFACE;
  3284. #ifdef DEBUG
  3285. if (FAILED(hr)) DBG_WARN("CWebCrawler::_GetCollection: get_collection failed");
  3286. #endif
  3287. if (SUCCEEDED(hr))
  3288. {
  3289. hr = EnumCollection(pCollection, pStringList, Type, pfnCB, dwCBData);
  3290. // If we're getting frames, we need to enum "iframe" tags separately
  3291. if (SUCCEEDED(hr) && (Type == CTYPE_FRAMES))
  3292. {
  3293. SAFERELEASE(pCollection);
  3294. hr = GetTagCollection(pDoc, L"iframe", &pCollection);
  3295. if (SUCCEEDED(hr) && pCollection)
  3296. {
  3297. hr = EnumCollection(pCollection, pStringList, Type, pfnCB, dwCBData);
  3298. }
  3299. }
  3300. }
  3301. if (pCollection)
  3302. pCollection->Release();
  3303. return hr;
  3304. }
  3305. extern HRESULT LoadWithCookie(LPCTSTR, POOEBuf, DWORD *, SUBSCRIPTIONCOOKIE *);
  3306. // IExtractIcon members
  3307. STDMETHODIMP CWebCrawler::GetIconLocation(UINT uFlags, LPTSTR szIconFile, UINT cchMax, int * piIndex, UINT * pwFlags)
  3308. {
  3309. IUniformResourceLocator* pUrl = NULL;
  3310. IExtractIcon* pUrlIcon = NULL;
  3311. HRESULT hr = S_OK;
  3312. BOOL bCalledCoInit = FALSE;
  3313. if (!szIconFile || !piIndex || !pwFlags)
  3314. return E_INVALIDARG;
  3315. //zero out return values in case one of the COM calls fails...
  3316. *szIconFile = 0;
  3317. *piIndex = -1;
  3318. if (!m_pBuf) {
  3319. m_pBuf = (POOEBuf)MemAlloc(LPTR, sizeof(OOEBuf));
  3320. if (!m_pBuf)
  3321. return E_OUTOFMEMORY;
  3322. DWORD dwSize;
  3323. hr = LoadWithCookie(NULL, m_pBuf, &dwSize, &m_SubscriptionCookie);
  3324. RETURN_ON_FAILURE(hr);
  3325. }
  3326. if (m_pBuf->bDesktop)
  3327. {
  3328. StrCpyN(szIconFile, TEXT(":desktop:"), cchMax);
  3329. }
  3330. else
  3331. {
  3332. if (m_pUrlIconHelper)
  3333. {
  3334. hr = m_pUrlIconHelper->GetIconLocation (uFlags, szIconFile, cchMax, piIndex, pwFlags);
  3335. }
  3336. else
  3337. {
  3338. hr = CoCreateInstance (CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER, IID_IUniformResourceLocator, (void**)&pUrl);
  3339. if ((CO_E_NOTINITIALIZED == hr || REGDB_E_IIDNOTREG == hr) &&
  3340. SUCCEEDED (CoInitialize(NULL)))
  3341. {
  3342. bCalledCoInit = TRUE;
  3343. hr = CoCreateInstance (CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER, IID_IUniformResourceLocator, (void**)&pUrl);
  3344. }
  3345. if (SUCCEEDED (hr))
  3346. {
  3347. hr = pUrl->SetURL (m_pBuf->m_URL, 1);
  3348. if (SUCCEEDED (hr))
  3349. {
  3350. hr = pUrl->QueryInterface (IID_IExtractIcon, (void**)&pUrlIcon);
  3351. if (SUCCEEDED (hr))
  3352. {
  3353. hr = pUrlIcon->GetIconLocation (uFlags, szIconFile, cchMax, piIndex, pwFlags);
  3354. //pUrlIcon->Release(); //released in destructor
  3355. ASSERT (m_pUrlIconHelper == NULL);
  3356. m_pUrlIconHelper = pUrlIcon;
  3357. }
  3358. }
  3359. pUrl->Release();
  3360. }
  3361. //balance CoInit with CoUnit
  3362. //(we still have a pointer to the CLSID_InternetShortcut object, m_pUrlIconHelper,
  3363. //but since that code is in shdocvw there's no danger of it getting unloaded and
  3364. //invalidating our pointer, sez cdturner.)
  3365. if (bCalledCoInit)
  3366. CoUninitialize();
  3367. }
  3368. }
  3369. return hr;
  3370. }
  3371. STDMETHODIMP CWebCrawler::Extract(LPCTSTR szIconFile, UINT nIconIndex, HICON * phiconLarge, HICON * phiconSmall, UINT nIconSize)
  3372. {
  3373. HRESULT hr = S_OK;
  3374. if (!phiconLarge || !phiconSmall)
  3375. return E_INVALIDARG;
  3376. //zero out return values in case one of the COM calls fails...
  3377. *phiconLarge = NULL;
  3378. *phiconSmall = NULL;
  3379. if ((NULL != m_pBuf) && (m_pBuf->bDesktop))
  3380. {
  3381. LoadDefaultIcons();
  3382. *phiconLarge = *phiconSmall = g_desktopIcon;
  3383. }
  3384. else
  3385. {
  3386. if (!m_pUrlIconHelper)
  3387. return E_FAIL;
  3388. hr = m_pUrlIconHelper->Extract (szIconFile, nIconIndex, phiconLarge, phiconSmall, nIconSize);
  3389. }
  3390. return hr;
  3391. }