Example #1
0
string TeamStreamNet::HttpGet(string url)
{
	string resp("") ; char outBuff[HTTP_RESP_BUFF_SIZE] ; outBuff[0] = '\0' ; int st , len , totalLen = 0 ;
	if (!url.size() || !url.compare(0 , 8 , "https://")) return resp ;

	char userAgent[64] ; sprintf(userAgent , "User-Agent:TeamStream v%s (Mozilla)" , VERSION) ;
	JNL_HTTPGet get ; JNL::open_socketlib() ;
  get.addheader(userAgent) ; get.addheader("Accept:*/*") ; get.connect(url.c_str()) ;
	while (true)
	{
		if ((st = get.run()) < 0) break ; // connection error or invalid response header

		if (get.get_status() > 0 && get.get_status() == 2)
		{
      while ((len = get.bytes_available()) > 0)
      {
        char buf[HTTP_READ_BUFF_SIZE] ; if (len > HTTP_READ_BUFF_SIZE) len = HTTP_READ_BUFF_SIZE ;
				len = get.get_bytes(buf , len) ;
				if ((totalLen += len) < HTTP_RESP_BUFF_SIZE) strncat(outBuff , buf , len) ;
				else { strncat(outBuff , buf , len - (totalLen - HTTP_RESP_BUFF_SIZE) - 1) ; break ; }
      }
		}
		if (st == 1) break ; // connection closed
	}
	JNL::close_socketlib() ; return resp += outBuff ;
}
Example #2
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size,
              TCHAR   *variables,
              stack_t **stacktop)
{
  char buf[1024];
  char url[1024];
  char filename[1024];
  static char proxy[1024];
  BOOL bSuccess=FALSE;
  int timeout_ms=30000;
  int getieproxy=1;
  int manualproxy=0;
  int translation_version;

  const char *error=NULL;

  // translation version 2 & 1
  static char szDownloading[1024]; // "Downloading %s"
  static char szConnecting[1024];  // "Connecting ..."
  static char szSecond[1024];      // " (1 second remaining)" for v2
                                   // "second" for v1
  static char szMinute[1024];      // " (1 minute remaining)" for v2
                                   // "minute" for v1
  static char szHour[1024];        // " (1 hour remaining)" for v2
                                   // "hour" for v1
  static char szProgress[1024];    // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2
                                   // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1

  // translation version 2 only
  static char szSeconds[1024];     // " (%u seconds remaining)"
  static char szMinutes[1024];     // " (%u minutes remaining)"
  static char szHours[1024];       // " (%u hours remaining)"

  // translation version 1 only
  static char szPlural[1024];      // "s";
  static char szRemaining[1024];   // " (%d %s%s remaining)";

  EXDLL_INIT();

  PopStringA(url);
  if (!lstrcmpiA(url, "/TRANSLATE2")) {
    PopStringA(szDownloading);
    PopStringA(szConnecting);
    PopStringA(szSecond);
    PopStringA(szMinute);
    PopStringA(szHour);
    PopStringA(szSeconds);
    PopStringA(szMinutes);
    PopStringA(szHours);
    PopStringA(szProgress);
    PopStringA(url);
    translation_version=2;
  } else if (!lstrcmpiA(url, "/TRANSLATE")) {
    PopStringA(szDownloading);
    PopStringA(szConnecting);
    PopStringA(szSecond);
    PopStringA(szMinute);
    PopStringA(szHour);
    PopStringA(szPlural);
    PopStringA(szProgress);
    PopStringA(szRemaining);
    PopStringA(url);
    translation_version=1;
  } else {
    lstrcpyA(szDownloading, "Downloading %s");
    lstrcpyA(szConnecting, "Connecting ...");
    lstrcpyA(szSecond, " (1 second remaining)");
    lstrcpyA(szMinute, " (1 minute remaining)");
    lstrcpyA(szHour, " (1 hour remaining)");
    lstrcpyA(szSeconds, " (%u seconds remaining)");
    lstrcpyA(szMinutes, " (%u minutes remaining)");
    lstrcpyA(szHours, " (%u hours remaining)");
    lstrcpyA(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s");
    translation_version=2;
  }
  lstrcpynA(buf, url, 10);
  if (!lstrcmpiA(buf, "/TIMEOUT=")) {
    timeout_ms=my_atoi(url+9);
    PopStringA(url);
  }
  if (!lstrcmpiA(url, "/PROXY")) {
    getieproxy=0;
    manualproxy=1;
    PopStringA(proxy);
    PopStringA(url);
  }
  if (!lstrcmpiA(url, "/NOIEPROXY")) {
    getieproxy=0;
    PopStringA(url);
  }
  PopStringA(filename);

  HANDLE hFile = CreateFileA(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintfA(buf, "Unable to open %s", filename);
    error = buf;
  }
  else
  {
    if (parent)
    {
      uMsgCreate = RegisterWindowMessage(_T("nsisdl create"));

      lpWndProcOld = (WNDPROC)SetWindowLongPtr(parent,GWLP_WNDPROC,(LONG_PTR)ParentWndProc);

      SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

      // set initial text
      char *p = filename;
      while (*p) p++;
      while (*p !='\\' && p != filename) p = CharPrevA(filename, p);
      wsprintfA(buf, szDownloading, p != filename ? p + 1 : p);
      SetDlgItemTextA(childwnd, 1006, buf);
      SetWindowTextA(g_hwndStatic, szConnecting);
    }
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      JNL_HTTPGet *get = 0;

      static char main_buf[8192];
      char *buf=main_buf;
      char *p=NULL;

      HKEY hKey;
      if (getieproxy && RegOpenKeyExA(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueExA(hKey,"ProxyEnable",NULL,&t,(unsigned char*)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueExA(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }
      if (manualproxy == 1) {
        p = proxy;
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      __int64     cl = 0;
      int         len;
      __int64     sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_cancelled)
            error = "cancel";

        if (error)
        {
          if (parent)
          {
            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
            SetWindowLongPtr(parent, GWLP_WNDPROC, (LONG_PTR)lpWndProcOld);
          }
          break;
        }

        st = get->run ();

        if (st == -1) {
          lstrcpynA(url, get->geterrorstr(), sizeof(url));
          error = url;
        } else if (st == 1) {
          if (sofar < cl || get->get_status () != 2)
            error="download incomplete";
          else
          {
            bSuccess=TRUE;
            error = "success";
          }
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on connecting.";
            else
              Sleep(10); // don't busy-loop while connecting

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on getting headers.";
            else
              Sleep(10); // don't busy-loop while reading headers

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0)
                error = "Server did not specify content length.";
              else if (g_hwndProgressBar) {
                SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                g_file_size = cl;
              }
            }

            int data_downloaded = 0;
            while ((len = get->bytes_available ()) > 0) {
              data_downloaded++;
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps = (int)(sofar/(time_sofar?time_sofar:1));
                int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar;

                if (translation_version == 2) {
                  char *rtext=remain==1?szSecond:szSeconds;;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=remain==1?szMinute:szMinutes;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=remain==1?szHour:szHours;
                    }
                  }

                  char sofar_str[128];
                  char cl_str[128];
                  myitoa64(sofar/1024, sofar_str);
                  myitoa64(cl/1024, cl_str);

                  wsprintfA (buf,
                        szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s
                        sofar_str,
                        MulDiv64(100, sofar, cl),
                        cl_str,
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintfA(buf+lstrlenA(buf),rtext,
                        remain
                        );
                } else if (translation_version == 1) {
                  char *rtext=szSecond;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szMinute;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=szHour;
                    }
                  }

                  wsprintfA (buf,
                        szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s
                        int(sofar/1024),
                        MulDiv64(100, sofar, cl),
                        int(cl/1024),
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintfA(buf+lstrlenA(buf),szRemaining,
                        remain,
                        rtext,
                        remain==1?"":szPlural
                        );
                }
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";
              }
            }
            if (GetTickCount() > last_recv_time+timeout_ms)
            {
              if (sofar != cl)
              {
                error = "Downloading timed out.";
              }
              else
              {
                // workaround for bug #1713562
                //   buggy servers that wait for the client to close the connection.
                //   another solution would be manually stopping when cl == sofar,
                //   but then buggy servers that return wrong content-length will fail.
                bSuccess = TRUE;
                error = "success";
              }
            }
            else if (!data_downloaded)
              Sleep(10);

          } else {
            error = "Bad response status.";
          }
        }

      }

      // Clean up the connection then release winsock
      if (get) delete get;
      WSACleanup();
    }

    CloseHandle(hFile);
  }

  if (g_cancelled || !bSuccess) {
    DeleteFileA(filename);
  }

  PushStringA(error);
}
Example #3
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size, 
              char   *variables, 
              stack_t **stacktop)
{
  static char buf[1024];
  static char url[1024];
  static char filename[1024];
  int wasen=0;
  HWND hwndL=0;
  HWND hwndB=0;

  static char szDownloading[32];//= "Downloading %s";
  static char szConnecting[32];//= "Connecting ...";
  static char szSecond[32];//= "second";
  static char szMinute[32];//= "minute";
  static char szHour[32];//= "hour";
  static char szPlural[32];//= "s";
  static char szProgress[128];//= "%dkB (%d%%) of %dkB @ %d.%01dkB/s";
  static char szRemaining[128];//= " (%d %s%s remaining)";

  g_parent     = parent;
  EXDLL_INIT();

  popstring(url);
  if (!lstrcmpi(url, "/TRANSLATE")) {
    popstring(szDownloading);
    popstring(szConnecting);
    popstring(szSecond);
    popstring(szMinute);
    popstring(szHour);
    popstring(szPlural);
    popstring(szProgress);
    popstring(szRemaining);
    popstring(url);
  }
  else {
    lstrcpy(szDownloading, "Downloading %s");
    lstrcpy(szConnecting, "Connecting ...");
    lstrcpy(szSecond, "second");
    lstrcpy(szMinute, "minute");
    lstrcpy(szHour, "hour");
    lstrcpy(szPlural, "s");
    lstrcpy(szProgress, "%dkB (%d%%) of %dkB @ %d.%01dkB/s");
    lstrcpy(szRemaining, " (%d %s%s remaining)");
  }
  lstrcpyn(buf, url, 10);
  if (!lstrcmpi(buf, "/TIMEOUT=")) {
    g_timeout_ms=my_atoi(url+9);
    popstring(url);
  }
  popstring(filename);

  HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE) {
    wsprintf (buf, "Unable to open %s", filename);
    setuservariable(INST_0, buf);
  } else {  
    if (g_parent)
    {
      g_childwnd=FindWindowEx(g_parent,NULL,"#32770",NULL);
      hwndL=GetDlgItem(g_childwnd,1016);
      hwndB=GetDlgItem(g_childwnd,1027);
      if (hwndL && IsWindowVisible(hwndL)) ShowWindow(hwndL,SW_HIDE);
      else hwndL=NULL;
      if (hwndB && IsWindowVisible(hwndB)) ShowWindow(hwndB,SW_HIDE);
      else hwndB=NULL;

      wasen=EnableWindow(GetDlgItem(g_parent,IDCANCEL),1);
      lpWndProcOld = (void *) GetWindowLong(g_parent,GWL_WNDPROC);
      SetWindowLong(g_parent,GWL_WNDPROC,(long)ParentWndProc);

      g_dialog = CreateDialog((HINSTANCE)hModule, 
                    MAKEINTRESOURCE(IDD_DIALOG1),
                    g_childwnd,
                    DownloadDialogProc);
      if (g_dialog)
      {
        GetWindowRect(g_dialog,&cr);
        ScreenToClient(g_dialog,(LPPOINT)&cr);
        ScreenToClient(g_dialog,((LPPOINT)&cr)+1);
        GetWindowRect(GetDlgItem(g_childwnd,1016),&r);
        ScreenToClient(g_childwnd,(LPPOINT)&r);
        ScreenToClient(g_childwnd,((LPPOINT)&r)+1);
        SetWindowPos(g_dialog,0,r.left,r.top,r.right-r.left,cr.bottom-cr.top,SWP_NOACTIVATE|SWP_NOZORDER);
        AdjustSize(IDC_STATIC2);
        AdjustSize(IDC_PROGRESS1);
        ShowWindow(g_dialog,SW_SHOWNA);
        char *p=filename;
        while (*p) p++;
        while (*p != '\\' && p != filename) p=CharPrev(filename,p);
        wsprintf(buf,szDownloading, p+1);
        SetDlgItemText(g_childwnd,1006,buf);

        SetDlgItemText (g_dialog, IDC_STATIC2, szConnecting);
      }
    }

    g_hwndProgressBar = GetDlgItem (g_dialog, IDC_PROGRESS1);

    JNL_HTTPGet *get;
    char *error=NULL;
    
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      static char buf[8192]="";
      char *p=NULL;
      
      HKEY hKey;
      if (RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      int         cl;
      int         len;
      int         sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_dialog)
        {
          MSG msg;
          while (PeekMessage(&msg,g_dialog,0,0,PM_REMOVE))
          {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
          } 
        }
      
        Sleep(25);

        if (g_cancelled) break;

        st = get->run ();

        if (st == -1) {
          error=get->geterrorstr();
          break;
        } else if (st == 1) {
          if (sofar < cl)
            error="download incomplete";
          break;
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+g_timeout_ms < GetTickCount())
            {
              error = "Timed out on connecting.";
              break;
            }

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+g_timeout_ms < GetTickCount())
            {
              error = "Timed out on getting headers.";
              break;
            }

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0) {
                error = "Server did not specify content length.";
                break;
              } else if (g_dialog) {
                  SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0,30000));
                  g_file_size=cl;
              }
            }

            while ((len = get->bytes_available ()) > 0) {
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps=sofar/(time_sofar?time_sofar:1);
                int remain=MulDiv(time_sofar,cl,sofar) - time_sofar;
                char *rtext=szSecond;
                if (remain >= 60) 
                {
                  remain/=60;
                  rtext=szMinute;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szHour;
                  }
                }
                wsprintf (buf, 
                      szProgress,
                      sofar/1024,
                      MulDiv(100,sofar,cl),
                      cl/1024,
                      bps/1024,((bps*10)/1024)%10
                      );
                if (remain) wsprintf(buf+lstrlen(buf),szRemaining,
                      remain,
                      rtext,
                      remain==1?"":szPlural
                      );
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";

                break;
              }
            }
            if (GetTickCount() > last_recv_time+g_timeout_ms)
            {
              error = "Downloading timed out.";
              break;
            }

          } else {
            error = "Bad response status.";
            break;
          }
        }
        
      }

      WSACleanup();
    }

    CloseHandle(hFile);
    if (g_parent)
    {
      if (g_dialog) DestroyWindow(g_dialog);
      if (lpWndProcOld)
        SetWindowLong(g_parent,GWL_WNDPROC,(long)lpWndProcOld);
      if (g_childwnd)
      {
        if (hwndB) ShowWindow(hwndB,SW_SHOWNA);
        if (hwndL) ShowWindow(hwndL,SW_SHOWNA);
      }
      if (wasen) EnableWindow(GetDlgItem(g_parent,IDCANCEL),0);
    }

    if (g_cancelled) {
      setuservariable(INST_0, "cancel");
      DeleteFile(filename);
    } else if (error == NULL) {
      setuservariable(INST_0, "success");
    } else {
      DeleteFile(filename);
      setuservariable(INST_0, error);
    }
    
    delete get;
  }
}
Example #4
0
unsigned WINAPI BR_SearchObject::StartSearch (void* searchObject)
{
	BR_SearchObject* _this = (BR_SearchObject*)searchObject;
	JNL::open_socketlib();

	BR_Version versionL;
	LineParser lp(false);
	lp.parse(SWS_VERSION_STR);
	versionL.maj   = lp.gettoken_int(0);
	versionL.min   = lp.gettoken_int(1);
	versionL.rev   = lp.gettoken_int(2);
	versionL.build = lp.gettoken_int(3);

	// When searching by user request, lookup both official and beta
	bool searchO = true, searchB = true;
	if (_this->IsStartup())
		GetStartupSearchOptions(&searchO, &searchB, NULL);

	// Get official version and compare
	BR_Version versionO;
	int statusO = NO_CONNECTION;
	if (searchO && !_this->GetKillFlag())
	{
		JNL_HTTPGet web;
		web.addheader("User-Agent:SWS (Mozilla)");
		web.addheader("Accept:*/*");
		web.connect(SWS_URL_VERSION_H);
		time_t startTime = time(NULL);
		while (time(NULL) - startTime <= SEARCH_TIMEOUT && !_this->GetKillFlag())
		{
			_this->SetProgress((double)(time(NULL) - startTime) / (SEARCH_TIMEOUT*2));

			// Try to get version.h
			int run = web.run();
			if (run < 0 || web.get_status() < 0 || web.getreplycode() >= 400)
				break;
			if (run == 1 && web.getreplycode() == 200) //  get data only after the connection has closed
			{
				int size = web.bytes_available();
				if (char* buf = new (nothrow) char[size])
				{
					web.get_bytes(buf, size);
					char* token = strtok(buf, "\n");
					while (token != NULL)
					{
						if (sscanf(token, "#define SWS_VERSION %10d,%10d,%10d,%10d", &versionO.maj, &versionO.min, &versionO.rev, &versionO.build) > 0)
							break;
						token = strtok(NULL, "\n");
					}

					if (_this->CompareVersion(versionO, versionL) == 1)
						statusO = OFFICIAL_AVAILABLE;
					else
						statusO = UP_TO_DATE;

					delete[] buf;
					break;
				}
			}
		}
	}

	// Get beta version and compare
	BR_Version versionB;
	int statusB = NO_CONNECTION;
	if (searchB && !_this->GetKillFlag())
	{
		JNL_HTTPGet web;
		web.addheader("User-Agent:SWS (Mozilla)");
		web.addheader("Accept:*/*");
		web.connect(SWS_URL_BETA_VERSION_H);
		time_t startTime = time(NULL);
		while (time(NULL) - startTime <= SEARCH_TIMEOUT && !_this->GetKillFlag())
		{
			_this->SetProgress((double)(time(NULL) - startTime) / (SEARCH_TIMEOUT*2) + 0.5);

			// Try to get version.h
			int run = web.run();
			if (run < 0 || web.get_status() < 0 || web.getreplycode() >= 400)
				break;
			else if (run == 1 && web.getreplycode() == 200) //  get data only after the connection has closed
			{
				int size = web.bytes_available();
				if (char* buf = new (nothrow) char[size])
				{
					web.get_bytes(buf, size);
					char* token = strtok(buf, "\n");
					while (token != NULL)
					{
						if (sscanf(token, "#define SWS_VERSION %10d,%10d,%10d,%10d", &versionB.maj, &versionB.min, &versionB.rev, &versionB.build) > 0)
							break;
						token = strtok(NULL, "\n");
					}

					if (_this->CompareVersion(versionB, versionL) == 1)
						statusB = BETA_AVAILABLE;
					else
						statusB = UP_TO_DATE;

					delete[] buf;
					break;
				}
			}
		}
	}

	_this->SetProgress(1);

	// Give some breathing space to hwndDlg (i.e. SNM startup action may load screenset that repositions Reaper...)
	if (_this->IsStartup() && !_this->GetKillFlag())
		Sleep(1500);

	// When both versions are available and are identical, ignore beta
	if (statusO == OFFICIAL_AVAILABLE && statusB == BETA_AVAILABLE)
		if (!_this->CompareVersion(versionO, versionB))
			statusB = UP_TO_DATE;

	int status;
	if      (statusO == NO_CONNECTION && statusB == NO_CONNECTION)       status = NO_CONNECTION;
	else if (statusO == OFFICIAL_AVAILABLE && statusB == BETA_AVAILABLE) status = BOTH_AVAILABLE;
	else if (statusO == OFFICIAL_AVAILABLE)                              status = OFFICIAL_AVAILABLE;
	else if (statusB == BETA_AVAILABLE)                                  status = BETA_AVAILABLE;
	else                                                                 status = UP_TO_DATE;

	_this->SetStatus(versionO, versionB, status);
	JNL::close_socketlib();
	return 0;
}
int main(int argc, char **argv)
{

  if (argc != 3)
  {
    printf("usage: httpget <url> <outfile>\n");
    exit(0);
  }

  JNL_HTTPGet get;
  JNL::open_socketlib();

  get.addheader("User-Agent:PooHead (Mozilla)");
  get.addheader("Accept:*/*");
  get.connect(argv[1]);

  FILE *fp=fopen(argv[2],"wb");
  int headerstate=0;
  int has_printed_headers=0;
  int has_printed_reply=0;
  while (1)
  {
    int st=get.run();
    if (st<0)
    {
      printf("HTTPGet error: %s\n",get.geterrorstr());
      break;
    }
    if (get.get_status()>0)
    {
      if (!has_printed_reply)
      {
        has_printed_reply=1;
        printf("reply: %s (code:%d)\n",get.getreply(),get.getreplycode());
      }
      if (get.get_status()==2)
      {
        int len;
        if (!has_printed_headers)
        {
          has_printed_headers=1;
          printf("headers:\n");
          char *p=get.getallheaders();
          while (p&&*p)
          {
            printf("%s\n",p);
            p+=strlen(p)+1;
          }
        }
        while ((len=get.bytes_available()) > 0)
        {
          char buf[4096];
          if (len > 4096) len=4096;
          len=get.get_bytes(buf,len);
          if (len>0)fwrite(buf,len,1,fp);
        }
      }
    }
    if (st==1) // 1 means connection closed
    {
      printf("HTTPGet done!\n");
      break;
    }
  }
  if (fp) fclose(fp);
  JNL::close_socketlib();
  return 0;
}
Example #6
0
DWORD CALLBACK UpdateThread(LPVOID v) {
  #define RSZ 30
  int len;
  char response[RSZ], *r;
  char url[300];
  BOOL error = FALSE;
  static char pbuf[8192];
  char *p=NULL;
  *response = 0;

  if (getProxyInfo(pbuf))
  {
    p=strstr(pbuf,"http=");
    if (!p) p=pbuf;
    else {
      p+=5;
    }
    char *tp=strstr(p,";");
    if (tp) *tp=0;
    char *p2=strstr(p,"=");
    if (p2) p=0; // we found the wrong proxy
  }

  InitializeUpdate();

  JNL_HTTPGet *get = new JNL_HTTPGet(g_dns,8192,(p&&p[0])?p:NULL);
  lstrcpyA(url,NSIS_UPDATE);
  lstrcatA(url,g_sdata.brandingv);

  lstrcpyA(response,"");
  get->addheader("User-Agent: MakeNSISw (jnetlib)");
  get->addheader("Accept:*/*");
  get->connect(url);
  while (1) {
    int st=get->run();
    if (st<0) { error = TRUE; break; }//error
    if (get->get_status()==2) {
      while( (len=get->bytes_available()) ) {
        char b[RSZ];
        if (len>RSZ) len=RSZ;
        if (lstrlenA(response)+len>RSZ) break;
        len=get->get_bytes(b,len);
        b[len]=0;
        lstrcatA(response,b);
      }
    }
    if (st==1) break; //closed
  }
  r = response;
  while (r&&*r) {
    if (*r=='\n') { *r = 0; break; }
    r++;
  }
  if (error) {
    char buf[1000];
    wsprintfA(buf, "There was a problem checking for an update.  Please try again later.\n\nError: %s",get->geterrorstr());
    MessageBoxA(g_sdata.hwnd,buf,"NSIS Update",MB_OK|MB_ICONINFORMATION);
  }
  else if (*response=='1'&&lstrlenA(response)>2) {
    char buf[200];
    wsprintfA(buf, "NSIS %s is now available.  Would you like to download it now?",response+2);
    if (MessageBoxA(g_sdata.hwnd,buf,"NSIS Update",MB_YESNO|MB_ICONINFORMATION)==IDYES) {
      ShellExecuteA(g_sdata.hwnd,"open",NSIS_DL_URL,NULL,NULL,SW_SHOWNORMAL);
    }
  }
  else if (*response=='2'&&lstrlenA(response)>2) {
    char buf[200];
    wsprintfA(buf,"NSIS %s is now available.  Would you like to download this preview release now?",response+2);
    if (MessageBoxA(g_sdata.hwnd,buf,"NSIS Update",MB_YESNO|MB_ICONINFORMATION)==IDYES) {
      ShellExecuteA(g_sdata.hwnd,"open",NSIS_DL_URL,NULL,NULL,SW_SHOWNORMAL);
    }
  }
  else MessageBoxA(g_sdata.hwnd,"There is no update available for NSIS at this time.","NSIS Update",MB_OK|MB_ICONINFORMATION);
  delete get;
  EnableMenuItem(g_sdata.menu,IDM_NSISUPDATE,MF_ENABLED);
  return 0;
}
Example #7
0
    __declspec(dllexport) void download (HWND   parent,
                                         int    string_size,
                                         char   *variables,
                                         stack_t **stacktop)
    {
        char buf[1024];
        char url[1024];
        char filename[1024];
        static char proxy[1024];
        BOOL bSuccess=FALSE;
        int timeout_ms=30000;
        int getieproxy=1;
        int manualproxy=0;

        char *error=NULL;

        static char szDownloading[1024];//= "Downloading %s";
        static char szConnecting[1024];//= "Connecting ...";
        static char szSecond[1024];//= "second";
        static char szMinute[1024];//= "minute";
        static char szHour[1024];//= "hour";
        static char szPlural[1024];//= "s";
        static char szProgress[1024];//= "%dkB (%d%%) of %dkB @ %d.%01dkB/s";
        static char szRemaining[1024];//= " (%d %s%s remaining)";

        EXDLL_INIT();

        popstring(url);
        if (!lstrcmpi(url, "/TRANSLATE")) {
            popstring(szDownloading);
            popstring(szConnecting);
            popstring(szSecond);
            popstring(szMinute);
            popstring(szHour);
            popstring(szPlural);
            popstring(szProgress);
            popstring(szRemaining);
            popstring(url);
        }
        else {
            lstrcpy(szDownloading, "Downloading %s");
            lstrcpy(szConnecting, "Connecting ...");
            lstrcpy(szSecond, "second");
            lstrcpy(szMinute, "minute");
            lstrcpy(szHour, "hour");
            lstrcpy(szPlural, "s");
            lstrcpy(szProgress, "%dkB (%d%%) of %dkB @ %d.%01dkB/s");
            lstrcpy(szRemaining, " (%d %s%s remaining)");
        }
        lstrcpyn(buf, url, 10);
        if (!lstrcmpi(buf, "/TIMEOUT=")) {
            timeout_ms=my_atoi(url+9);
            popstring(url);
        }
        if (!lstrcmpi(url, "/PROXY")) {
            getieproxy=0;
            manualproxy=1;
            popstring(proxy);
            popstring(url);
        }
        if (!lstrcmpi(url, "/NOIEPROXY")) {
            getieproxy=0;
            popstring(url);
        }
        popstring(filename);

        HANDLE hFile = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

        if (hFile == INVALID_HANDLE_VALUE)
        {
            wsprintf(buf, "Unable to open %s", filename);
            error = buf;
        }
        else
        {
            if (parent)
            {
                uMsgCreate = RegisterWindowMessage("nsisdl create");

                lpWndProcOld = (void *)SetWindowLong(parent,GWL_WNDPROC,(long)ParentWndProc);

                SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

                // set initial text
                char *p = filename;
                while (*p) p++;
                while (*p != '\\' && p != filename) p = CharPrev(filename, p);
                wsprintf(buf, szDownloading, p != filename ? p + 1 : p);
                SetDlgItemText(childwnd, 1006, buf);
                SetWindowText(g_hwndStatic, szConnecting);
            }
            {
                WSADATA wsaData;
                WSAStartup(MAKEWORD(1, 1), &wsaData);

                JNL_HTTPGet *get = 0;

                static char main_buf[8192];
                char *buf=main_buf;
                char *p=NULL;

                HKEY hKey;
                if (getieproxy && RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
                {
                    DWORD l = 4;
                    DWORD t;
                    DWORD v;
                    if (RegQueryValueEx(hKey,"ProxyEnable",NULL,&t,(unsigned char *)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
                    {
                        l=8192;
                        if (RegQueryValueEx(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
                        {
                            p=strstr(buf,"http=");
                            if (!p) p=buf;
                            else {
                                p+=5;
                            }
                            char *tp=strstr(p,";");
                            if (tp) *tp=0;
                            char *p2=strstr(p,"=");
                            if (p2) p=0; // we found the wrong proxy
                        }
                    }
                    buf[8192-1]=0;
                    RegCloseKey(hKey);
                }
                if (manualproxy == 1) {
                    p = proxy;
                }

                DWORD start_time=GetTickCount();
                get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
                int         st;
                int         has_printed_headers = 0;
                int         cl;
                int         len;
                int         sofar = 0;
                DWORD last_recv_time=start_time;

                get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
                get->addheader ("Accept: */*");

                get->connect (url);

                while (1) {
                    if (g_cancelled)
                        error = "cancel";

                    if (error)
                    {
                        if (parent)
                        {
                            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
                            SetWindowLong(parent, GWL_WNDPROC, (long)lpWndProcOld);
                        }
                        break;
                    }

                    Sleep(25);

                    st = get->run ();

                    if (st == -1) {
                        lstrcpyn(url, get->geterrorstr(), sizeof(url));
                        error = url;
                    } else if (st == 1) {
                        if (sofar < cl)
                            error="download incomplete";
                        else
                        {
                            bSuccess=TRUE;
                            error = "success";
                        }
                    } else {

                        if (get->get_status () == 0) {
                            // progressFunc ("Connecting ...", 0);
                            if (last_recv_time+timeout_ms < GetTickCount())
                                error = "Timed out on connecting.";

                        } else if (get->get_status () == 1) {

                            progress_callback("Reading headers", 0);
                            if (last_recv_time+timeout_ms < GetTickCount())
                                error = "Timed out on getting headers.";

                        } else if (get->get_status () == 2) {

                            if (! has_printed_headers) {
                                has_printed_headers = 1;
                                last_recv_time=GetTickCount();

                                cl = get->content_length ();
                                if (cl == 0)
                                    error = "Server did not specify content length.";
                                else if (g_hwndProgressBar) {
                                    SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                                    g_file_size = cl;
                                }
                            }

                            while ((len = get->bytes_available ()) > 0) {
                                if (len > 8192)
                                    len = 8192;
                                len = get->get_bytes (buf, len);
                                if (len > 0) {
                                    last_recv_time=GetTickCount();
                                    DWORD dw;
                                    WriteFile(hFile,buf,len,&dw,NULL);
                                    sofar += len;
                                    int time_sofar=(GetTickCount()-start_time)/1000;
                                    int bps=sofar/(time_sofar?time_sofar:1);
                                    int remain=MulDiv(time_sofar,cl,sofar) - time_sofar;
                                    char *rtext=szSecond;
                                    if (remain >= 60)
                                    {
                                        remain/=60;
                                        rtext=szMinute;
                                        if (remain >= 60)
                                        {
                                            remain/=60;
                                            rtext=szHour;
                                        }
                                    }
                                    wsprintf (buf,
                                              szProgress,
                                              sofar/1024,
                                              MulDiv(100,sofar,cl),
                                              cl/1024,
                                              bps/1024,((bps*10)/1024)%10
                                             );
                                    if (remain) wsprintf(buf+lstrlen(buf),szRemaining,
                                                             remain,
                                                             rtext,
                                                             remain==1?"":szPlural
                                                            );
                                    progress_callback(buf, sofar);
                                } else {
                                    if (sofar < cl)
                                        error = "Server aborted.";
                                }
                            }
                            if (GetTickCount() > last_recv_time+timeout_ms)
                                error = "Downloading timed out.";

                        } else {
                            error = "Bad response status.";
                        }
                    }

                }

                // Clean up the connection then release winsock
                if (get) delete get;
                WSACleanup();
            }

            CloseHandle(hFile);
        }

        if (g_cancelled || !bSuccess) {
            DeleteFile(filename);
        }

        pushstring(error);
    }