Exemple #1
0
/**
 * xmlNanoHTTPFetch:
 * @URL:  The URL to load
 * @filename:  the filename where the content should be saved
 * @contentType:  if available the Content-Type information will be
 *                returned at that location
 *
 * This function try to fetch the indicated resource via HTTP GET
 * and save it's content in the file.
 *
 * Returns -1 in case of failure, 0 incase of success. The contentType,
 *     if provided must be freed by the caller
 */
int
xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
    void *ctxt = NULL;
    char *buf = NULL;
    int fd;
    int len;

    if (filename == NULL) return(-1);
    ctxt = xmlNanoHTTPOpen(URL, contentType);
    if (ctxt == NULL) return(-1);

    if (!strcmp(filename, "-"))
        fd = 0;
    else {
        fd = open(filename, O_CREAT | O_WRONLY, 00644);
	if (fd < 0) {
	    xmlNanoHTTPClose(ctxt);
	    if ((contentType != NULL) && (*contentType != NULL)) {
	        xmlFree(*contentType);
		*contentType = NULL;
	    }
	    return(-1);
	}
    }

    xmlNanoHTTPFetchContent( ctxt, &buf, &len );
    if ( len > 0 ) {
	    if (write(fd, buf, len)) {}
    }

    xmlNanoHTTPClose(ctxt);
    close(fd);
    return(0);
}
Exemple #2
0
bool Weather::Refresh() {
  std::string escaped_city = city_;
  std::replace(escaped_city.begin(), escaped_city.end(), ' ', '+');
  const std::string url =
      std::string("http://www.google.com/ig/api?weather=") + escaped_city;

  std::unique_ptr<void> context(xmlNanoHTTPOpen(url.c_str(), NULL));
  if (context.get() == NULL) {
    fprintf(stderr, "xmlNanoHTTPOpen failed\n");
    return false;
  }

  // TODO: better buffer size logic
  std::unique_ptr<char[]> buffer(new char[4096]);
  int bytes_read = xmlNanoHTTPRead(context.get(), buffer.get(), 4096);
  if (bytes_read == -1) {
    fprintf(stderr, "xmlNanoHTTPRead failed due to parameter error\n");
    return false;
  }

  if (doc_) {
    xmlFreeDoc(doc_);
    doc_ = NULL;
  }
  doc_ = xmlReadMemory(buffer.get(), strlen(buffer.get()),
                       url.c_str(), NULL, 0);
  if (doc_ == NULL) {
    fprintf(stderr, "xmlReadMemory failed\n");
    return false;
  }

  if (icon_ != VG_INVALID_HANDLE) {
    vgDestroyImage(icon_);
    icon_ = VG_INVALID_HANDLE;
  }
  std::string icon_url =
      std::string("http://www.google.com") +
      EvaluateXPath("/xml_api_reply/weather/current_conditions/icon");
  icon_ = ImageLoader::Load(icon_url);
  if (icon_ == VG_INVALID_HANDLE) {
    return false;
  }

  return true;
}
void GetXMLHttp() {
	void * Ctxt;
	char *contentType;
	
	xmlNanoHTTPInit();
	
	Ctxt = xmlNanoHTTPOpen(XML_URL, &contentType);

	if (Ctxt == 0)
		printf("ERROR: xmlNanoHTTPOpen() == 0\n");

	if (xmlNanoHTTPReturnCode(Ctxt) != 200)
		printf("ERROR: HTTP Code != OK\n");

	// open output file
	FILE *fp;
	fp=fopen("test_get.xml","w");
	

	// Write to file
	const int Size = 2048;
	char Buffer[Size];
	int Count;

	while ((Count = xmlNanoHTTPRead(Ctxt, Buffer, Size)) > 0)
		fprintf(fp,"%s",Buffer);	
		//File.write(Buffer, Count);
		
	fclose(fp);

	if (Count == 0)
		printf("STATUS: Connection closed\n");

	if (Count == -1)
		printf("ERROR: xmlNanoHTTPRead() == -1\n");
	
		
	// Free ressources
	xmlFree(contentType);
	xmlNanoHTTPClose(Ctxt);
	xmlNanoHTTPCleanup();
}
int
raptor_www_libxml_fetch(raptor_www *www) 
{
  if(www->proxy)
    xmlNanoHTTPScanProxy(www->proxy);

  www->ctxt=xmlNanoHTTPOpen((const char*)raptor_uri_as_string(www->uri), &www->type);
  if(!www->ctxt)
    return 1;
  
  if(www->type) {
    if(www->content_type) {
      www->content_type(www, www->content_type_userdata, www->type);
      if(www->failed) {
        xmlNanoHTTPClose(www->ctxt);
        return 1;
      }
    }
  }

  www->status_code=xmlNanoHTTPReturnCode(www->ctxt);
  
  while(1) {
    int len=xmlNanoHTTPRead(www->ctxt, www->buffer, RAPTOR_WWW_BUFFER_SIZE);
    if(len<0)
      break;
    
    www->total_bytes += len;

    if(www->write_bytes)
      www->write_bytes(www, www->write_bytes_userdata, www->buffer, len, 1);
    
    if(len < RAPTOR_WWW_BUFFER_SIZE || www->failed)
      break;
  }
  
  xmlNanoHTTPClose(www->ctxt);

  return www->failed;
}
Exemple #5
0
static void* cacheopen(char const* url) {
    const char* basename = strrchr(url,'/');
    assert(basename);

    static char dest[508];
    snprintf(dest,508,"%s/%s",cacheDir,basename);

    bool didtemp = false;

    int doopen(void) {
        int result = open(dest,O_RDONLY);
        if(result<0) {
            char temp[512];
            snprintf(temp,512,"%s.temp",dest);

            if(xmlIOHTTPMatch(url)) {
                void* ctx = NULL;
#if W3_ARE_NOT_MORONS
                ctx = xmlNanoHTTPOpen(url, NULL);
                if(xmlNanoHTTPReturnCode(ctx) != 200)
#else
                if(true)
#endif
                {
                    // XXX: it always is... w3.org dies on HTTP/1.0
#if W3_ARE_NOT_MORONS
                    xmlNanoHTTPClose(ctx);
#endif
                    fprintf(stderr,"Curl fallback for %s\n",url);
                    int pid = fork();
                    if(pid == 0) {
                        execlp("curl","curl","-o",temp,url,NULL);
                        abort();
                    }
                    int status = 0;
                    waitpid(pid,&status,0);
                    if(!(WIFEXITED(status) && (0 == WEXITSTATUS(status)))) {
                        fprintf(stderr,"CUrl failed! %x %d\n",status,WEXITSTATUS(status));
                        abort();
                    }
                } else {
                    assert(0==xmlNanoHTTPSave(ctx,temp));
                }
            } else if(xmlIOFTPMatch(url)) {
                void* ftp = xmlNanoFTPOpen(url);
                int out = open(temp,O_WRONLY|O_TRUNC|O_CREAT,0644);
                assert(out>0);
                char buf[0x1000];
                for(;;) {
                    int amt = xmlNanoFTPRead(ftp, buf, 0x1000);
                    if(amt==0) break;
                    assert(amt>0);
                    write(out,buf,amt);
                }
                close(out);            
            } else {
                FILE* fp = xmlFileOpen(url);
                struct stat fpstat;
                if(!fp) {
                    fprintf(stderr,"No idea what to do with url %s\n",url);
                    abort();
                }
                int inp = fileno(fp);
                assert(0==fstat(inp,&fpstat));
                off_t left = fpstat.st_size;
                int out = open(temp,O_WRONLY|O_TRUNC|O_CREAT,0644);
                assert(out>0);
                do {
                    ssize_t amt = sendfile(out,inp,NULL,left);
                    if(amt<0) {
                        perror(url);
                    }
                    assert(amt>=0);
                    left -= amt;
                } while(left > 0);
                fclose(fp);
                close(out);
            }
            rename(temp,dest); // doesn't matter if fails
            unlink(temp); // in case it failed
            return doopen();
        }
        return result;
    }
Exemple #6
0
void CheckVersionNumber()
{
	//==== Init Nano HTTP ====//
	xmlNanoHTTPInit();
	xmlNanoHTTPScanProxy(NULL);

	//==== Compute Version Number ====//
	int ver_no = 10000*VSP_VERSION_MAJOR + 100*VSP_VERSION_MINOR + VSP_VERSION_CHANGE;

	char cCurrentPath[FILENAME_MAX];
	GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));

	int user_id = 0;
	int path_len = strlen(cCurrentPath);

	for ( int i = 0 ; i < path_len ; i++ )
	{
		srand ( (unsigned int)cCurrentPath[i] );
		user_id += rand() % 100000 + 1;
	}

	//==== Post User Info To Server ====//
	char poststr[256];
	sprintf( poststr, "postvar1=%d&postvar2=%d\r\n", user_id, ver_no);
	int poststrlen = strlen(poststr);
	char*  headers = "Content-Type: application/x-www-form-urlencoded \n";

	void * ctx = 0;
	ctx = xmlNanoHTTPMethod("http://www.openvsp.org/vspuse_post.php", "POST", poststr, NULL, headers, poststrlen );

	if ( ctx )
		xmlNanoHTTPClose(ctx);

	ctx = 0;

	//==== Open Settings File ====//
	bool check_version_flag = true;
	FILE* vsptime_fp = fopen( ".vsptime", "r" );
	if ( vsptime_fp )
	{
		char str[256];
		fgets( str, 256, vsptime_fp );
		int vsp_time = atoi( str );
		int del_time =  (int)time(NULL) - vsp_time;
		if ( del_time < 60*60*24*7 )				// Check Every Week
			check_version_flag = false;

		fclose( vsptime_fp );
	}

	//==== Enough Time Has Passed - Check For New Version ====//
	if ( check_version_flag )
	{
		//==== Webpage with Version Info ====//
		char * pContentType = 0;
		ctx = xmlNanoHTTPOpen("http://www.openvsp.org/latest_version.html", &pContentType);

		int retCode = xmlNanoHTTPReturnCode(ctx);

		//==== Http Return Code 200 -> OK  ====//
		string contentStr;
		if ( retCode == 200 )
		{
			char buf[2048];
			int len = 1;
			while (len > 0 && contentStr.size() < 10000 )
			{
				len = xmlNanoHTTPRead(ctx, buf, sizeof(buf));
				contentStr.append( buf, len );
			}
		}

		//==== Pulled A String From Server =====//
		if ( contentStr.size() > 0 )
		{
			int major_ver, minor_ver, change_ver;
			bool valid = ExtractVersionNumber( contentStr, &major_ver, &minor_ver, &change_ver );

			if ( valid )
			{
				if ( major_ver != VSP_VERSION_MAJOR ||minor_ver != VSP_VERSION_MINOR || change_ver != VSP_VERSION_CHANGE )
				{
					if ( screenMgrPtr )
						screenMgrPtr->MessageBox("A new version of OpenVSP is available at http://www.openvsp.org/");
				}
			}
		}
		//===== Write Time =====//
		FILE* vsptime_fp = fopen( ".vsptime", "w" );
		if ( vsptime_fp )
		{
			fprintf( vsptime_fp, "%d", time(NULL) );
			fclose( vsptime_fp );
		}
	}

	if ( ctx )
		xmlNanoHTTPClose(ctx);

	xmlNanoHTTPCleanup();
}
Exemple #7
0
/**
 * Returns the contents of the requested URL
 *
 * @param pczURL The URL to retrieve.
 * @param piRetCode The return code supplied with the response.
 * @param piDataSize The resulting data length [out].
 *
 * @return A pointer to a null-terminated buffer containing the textual
 *         representation of the response. Must be freed by the caller.
 */
gpointer
getURL(const gchar * pczURL, gint * piRetCode, gint * piDataSize)
{
    /* nanohttp magic */
#define iBufReadSize 1024
    gint iReadSize = 0;
    gint iCurrSize = 0;

    gpointer pInBuffer = NULL;
    gpointer pInBufferRef = NULL;

    gchar cReadBuffer[iBufReadSize];
    bzero(cReadBuffer, iBufReadSize);

    xmlNanoHTTPInit();

    char * pContentType = NULL;
    void * pHTTPContext = NULL;

    pHTTPContext = xmlNanoHTTPOpen(pczURL, &pContentType);

    if (!pHTTPContext)
    {
        // failure
        cleanup(pHTTPContext, pContentType);

        *piRetCode = -1;

        return pInBuffer; // it's NULL
    }

    *piRetCode = xmlNanoHTTPReturnCode(pHTTPContext);

    if (*piRetCode != HTTP_STATUS_OK)
    {
        // failure
        cleanup(pHTTPContext, pContentType);

        return pInBuffer; // it's NULL
    }

    while ((iReadSize = xmlNanoHTTPRead(pHTTPContext, cReadBuffer, iBufReadSize)) > 0)
    {
        // set return code
        *piRetCode = xmlNanoHTTPReturnCode(pHTTPContext);

        /* Maintain pointer to old location, free on failure */
        pInBufferRef = pInBuffer;

        pInBuffer = g_try_realloc(pInBuffer, iCurrSize + iReadSize);

        if (!pInBuffer || *piRetCode != HTTP_STATUS_OK)
        {
            // failure
            cleanup(pHTTPContext, pContentType);

            g_free(pInBufferRef);

            return pInBuffer; // it's NULL
        }

        memcpy(pInBuffer + iCurrSize, cReadBuffer, iReadSize);

        iCurrSize += iReadSize;

        // clear read buffer
        bzero(cReadBuffer, iBufReadSize);

        *piDataSize = iCurrSize;
    }

    if (iReadSize < 0)
    {
        // error
        g_free(pInBuffer);

        pInBuffer = NULL;
    }
    else
    {
        /* Maintain pointer to old location, free on failure */
        pInBufferRef = pInBuffer;

        // need to add '\0' at the end
        pInBuffer = g_try_realloc(pInBuffer, iCurrSize + 1);

        if (!pInBuffer)
        {
            // failure
            g_free(pInBufferRef);

            pInBuffer = NULL;
        }
        else
        {
            memcpy(pInBuffer + iCurrSize, "\0", 1);
        }
    }

    // finish up
    cleanup(pHTTPContext, pContentType);

    return pInBuffer;
}