Пример #1
0
int not_main(int argc, char *argv[])
{
  Http http;

//  HttpRequest *request1 = new HttpRequest("http://www.google.com");
  //http.AddRequest(request1);

//  HueLightResponse *request2 = new HueLightResponse("http://10.0.2.227/api/huelibrary/lights");
 // http.AddRequest(request2);

//HueLightResponse *IPAddr= new HueLightResponse("https://www.meethue.com/api/nupnp");
//http.AddRequest(IPAddr);

//  HttpRequest *request3 = new HueLightResponse("http://10.0.2.227/api/huelibrary/lights/1/state","{ \"on\": false, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");
 // http.AddRequest(request3);

  //HttpRequest *request = new HttpRequest("http://10.0.2.227/api/huelibrary/lights/3/state","{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");

//  http.AddRequest("http://www.google.com");
//  http.AddRequest("http://10.0.2.227/api/huelibrary/lights/3/state","{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");
  //http.AddRequest("http://10.0.2.227/");
 // http.AddRequest("http://10.0.2.227/api/huelibrary/lights");

  while (1)
  {
fprintf(stderr,"inside loop\n");
  // In some update loop called each frame
  http.Update();
  http.Status();
   sleep(1);
  }

 return 0;
}
Пример #2
0
  void stage_3(string &url)
  {
    rsprintf("Lacze z '%s' (3)", url.c_str());
    
    rs_progress_start = Time::in_usec();
    rs_info.status = RS::Downloading;
    rs_info.bytes = 0;
    rs_info.tmpspeed = 0;
    off_t length = 0;

    try { // TODO
      int code = http.get(rs_download_get_path(rs_info.url.c_str()).string().c_str(), length, url.c_str(), 
          "mirror=", NULL, rs_progress_callback, NULL);
     
      filesystem::ofstream head(rs_sessions_get_path(url, "-head3.http"));
      head.write(http.get_recv_header(), strlen(http.get_recv_header()));

      if (code == HTTP_OK) // Oczekujemy kodu 200
        rsprintf("Polaczono, code = %d, length = %lld", code, length);
      else {
        rsprintf("Polaczono, brak strony? code = %d, length = %lld, try again", code, length);
        throw DBreak();
      }

      //string clen = http.get_recv_header("content-length");
      //rsprintf("");
    } 
    catch (Exception &e) {
      rsprintf("Nastapil wyjatek: %s", e.what());
      throw DBreak();
    }  
  }
Пример #3
0
void Http::write_cb(bufferevent *bev, void *ctx)
{
	Http* http = (Http*)ctx;
	evbuffer *output = bufferevent_get_output(bev);
	if(http->get_all_send() && 
			evbuffer_get_length(output) == 0)
	{
		DEBUG_LOG("empty");
		Http::release(&http);
	}
}
Пример #4
0
//送信
void Result::Send() {
	Song *song = songs->GetSong(songs->GetNowSong());
	//曲IDのリクエスト作成
	char songReq[126] = { 0 };
	sprintf_s(songReq, 126, "song=%d", song->GetSongId());
	//ユーザーIDのリクエスト作成
	char userReq[32] = { 0 };
	sprintf_s(userReq, 32, "user=%s", user->GetUserId());
	//現在時刻の取得
	int temp[5] = { 0 };
	GetNowTime(temp);
	//年月日のリクエスト作成
	char dateReq[32] = { 0 };
	sprintf_s(dateReq, 32, "date=%02d-%02d-%02d %02d-%02d", temp[0], temp[1], temp[2], temp[3], temp[4]);
	//総合得点のリクエスト作成
	char totalReq[16] = { 0 };
	sprintf_s(totalReq, 16, "total=%d", this->total);
	//区間別採点のリクエスト作成
	char partReq[64] = { 0 };
	sprintf_s(partReq, 64, "part=%d", score[0]);
	for (int i = 1, n = this->max; i < n; i++) {
		sprintf_s(partReq, 64, "%s/%d", partReq, score[i]);
	}
	//体の部位採点のリクエスト作成
	char bodyPoint[4] = { 0 };
	for (int i = 0; i < 4; i++) {
		switch (point[i]) {
		case 1:bodyPoint[i] = 'A';	break;
		case 2:bodyPoint[i] = 'B';	break;
		case 3:bodyPoint[i] = 'C';	break;
		}
	}
	char bodyReq[32] = { 0 };
	sprintf_s(bodyReq, 32, "body=%c/%c/%c/%c", bodyPoint[0], bodyPoint[1], bodyPoint[2], bodyPoint[3]);
	//タイミングのリクエスト作成
	char timingReq[16] = { 0 };
	sprintf_s(timingReq, 16, "timing=%d", timing);
	//表情のリクエスト作成
	char expressionReq[16] = { 0 };
	sprintf_s(expressionReq, 16, "expression=%d", expression);
	//コメントのリクエスト作成
	WCHAR w_comment[256] = { 0 };
	mbstowcs(w_comment, comment, 256);
	char commentReq[256] = { 0 };
	sprintf_s(commentReq, 256, "comment=%s", w_comment);

	//urlを作成
	char url[512] = { 0 };
	sprintf_s(url, 512, "http://globalstudios.jp/mai-archive/api_add.php?%s&%s&%s&%s&%s&%s&%s&%s&%s", 
		songReq, userReq, dateReq, totalReq, partReq, bodyReq, timingReq, expressionReq, commentReq);
	Http http;
	if(!http.Send(url))printfDx("httpエラー");
}
Пример #5
0
  void stage_1(string &url)
  {
    rsprintf("Lacze z '%s'... (1)", url.c_str());
    char *buffer = NULL;
    size_t buflen = 0;

    try {
      int code = http.get(buffer, buflen, url.c_str());

      filesystem::ofstream head(rs_sessions_get_path(url, "-head1.http"));
      head.write(http.get_recv_header(), strlen(http.get_recv_header()));

      if (code == HTTP_OK) // Oczekujemy kodu 200
        rsprintf("Polaczono, code = %d, page = %p,%zd", code, buffer, buflen);
      else { 
        rsprintf("Polaczono, brak strony? code = %d, page = %p,%zd, sprobuje za chwile...", code, buffer, buflen);
        if (buffer) delete[] buffer;
        throw DBreak();
      }

      filesystem::ofstream page(rs_sessions_get_path(url, "-page1.html"));
      page.write(buffer, buflen);
    }
    catch (Exception &e) {
      rsprintf("Nastapil wyjatek: %s", e.what());
      throw DBreak();
    }

    // Sprawdzamy czy plik jest dostepny...
    if (regex_search(buffer, rs_regex_illegal_file) ||
        regex_search(buffer, rs_regex_illegal_file2) ||
        regex_search(buffer, rs_regex_not_available) ||
        regex_search(buffer, rs_regex_not_found)) {
      rsprintf("Plik '%s' jest niedostepny", url.c_str());
      delete[] buffer;
      //rs_info.status = RS::NotFound;
      throw DAbort(RS::NotFound);
    }

    // Szukamy nastepnego url'a...
    cmatch what;
    if (!regex_search(buffer, what, rs_regex_url)) {
      rsprintf("Brak odnosnika do nastepnej strony, sprobuje jeszcze raz...");
      delete[] buffer;
      throw DBreak();
    }

    url = what[1]; // ustawiamy nowy url
    delete[] buffer;
  }
Пример #6
0
int main(int argc, char *argv[]) {
	Main app(APP_SOCKETS);
	Http http;
	app.open(argc,argv);
	http.setUserAgent("Http Class User-Agent, v.0.1");

	http.get("www.google.com","");

	const char *fn = "http.txt";
	FILE *fp = fopen(fn,"wb");
	if(fp) {
		fwrite(http.getFile(),http.getFileSize(),1,fp);
		fclose(fp);
	} else perror(fn);
	return 0;
}
Пример #7
0
int main(int argc, const char * argv[])
{

    Http *http = new Http ( "GET / HTTP/1.1"
                            "Host: host.com"
                            "User-Agent: Mozilla/5.0 (X11; U; Linux i686; pl; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7"
                            "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8"
                            "Accept-Language: pl,en-us;q=0.7,en;q=0.3"
                            "Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7"
                            "Keep-Alive: 300"
                            "Connection: keep-alive");
    
    std::cout<<http->getHost()<<"\n";
    
    
    return 0;
}
Пример #8
0
void Http::read_cb(bufferevent *bev, void *ctx)
{
	DEBUG_LOG("read");
	Http* http = (Http*)ctx;

	if(http->bev == bev)
	{
		while(http->loop());	
	}
	else if(http->bev_cgi == bev)
	{
		evbuffer_add_buffer(bufferevent_get_output(http->bev), bufferevent_get_input(bev));
	}
	else
	{
		DEBUG_LOG("error read_cb");	
	}
}
Пример #9
0
void Http::download ( const std::string &url, const std::string &file, unsigned int timeoutMilliSeconds, Unknown *caller )
{
  // Open file.
  std::ofstream stream ( file.c_str(), std::ofstream::binary | std::ofstream::out );
  if ( false == stream.is_open() )
  {
    throw std::runtime_error ( "Error 2742979881: Failed to open file '" + file + "' for writing" );
  }
 
  // This will remove the file is there's an exception.
  Usul::Scope::RemoveFile removeFile ( file );
  
  Http http ( url, &stream, caller );
  http.download( timeoutMilliSeconds );
  
  // Keep the file.
  removeFile.remove ( false );
}
Пример #10
0
void Http::event_cb(bufferevent *bev, short events, void *ctx)
{
	if (events & BEV_EVENT_ERROR)
	{
		int err = EVUTIL_SOCKET_ERROR();

		if (err)
		{
			DEBUG_LOG("Socket error: %s\n", evutil_socket_error_to_string(err));
		}
	}

	if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
	{
		Http* http = (Http*) ctx;

		if(http->bev_cgi == bev)
		{
			evbuffer *output = bufferevent_get_output(http->bev);
			if(evbuffer_get_length(output) == 0)
			{
				DEBUG_LOG("release http");
				Http::release(&http);	
			}
			else
			{
				DEBUG_LOG("release unix");
				http->set_all_send(true);
				bufferevent_free(http->bev_cgi);
				http->bev_cgi = NULL;
			}	
		}
		else if(http->bev == bev)
		{
			DEBUG_LOG("release http");
			Http::release(&http);
		}
		else
		{
			DEBUG_LOG("error event_cb");	
		}
	}
}
Пример #11
0
void PluginTester::run()
{
	stopFlag = false;
    failed = 0;

	emit workingStarted();

	for (int n = 0; n < tests->count(); n++)
	{
		PluginTest *test = tests->at(n);
		//
        if ((onlyFailed && test->isTestOk()) || (onlySelected != -1 && n != onlySelected)) continue;
		//
		emit pluginTestRunning(test);
		// get video information
        emit workingProgress(n * 2, tests->count() * 2, QString("Getting <b>%1</b> video information... [1/2]").arg(test->getPluginTitle()));
		VideoInformationPlugin *plugin = new VideoInformationPlugin(NULL, pluginsDir + test->getPluginFile());
		VideoDefinition  vd = plugin->getVideoInformation(test->getUrl());
		// try to download video
		emit workingProgress(n * 2 + 1, tests->count() * 2, QString("Testing <b>%1</b> video download... [2/2]").arg(test->getPluginTitle()));
		Http *http = new Http();
		if (!vd.cookies.isEmpty()) http->addCookies(vd.cookies);
		if (!vd.headers.isEmpty()) http->addHeaderParameters(vd.headers);
		int contentLength = copyBetween(http->head(QUrl(vd.URL)), "Content-Length: ", "\n").toInt();
		delete http;
		// update test info
		test->setCaption(vd.title);
		test->setFlvUrl(vd.URL);
		test->setSize(contentLength);
		// increase failed tests
		if (!test->isTestOk()) failed++;
		// destroy plugin
		delete plugin;
		// finished
		emit pluginTestFinished(test);
		// small pause, prevent 100% cpu
		if (stopFlag) n = tests->count(); else sleep(1);
	}

	emit workingFinished(tests->count() - failed, failed);
}
Пример #12
0
int main(int argc, char **argv)
{
  Http http;
  char *page = NULL;
  size_t size = 0;

  for (int i = 1; i < argc; ++i) {
    cerr << "== GET '" << argv[i] << "' ==" << endl;
    
    try {
      //http.set_verbose(true);
      int code = http.get(page, size, argv[i]);
      if (page) delete[] page;

      const Http::Headers &hdrs = http.get_headers();

      Http::Headers::const_iterator it;
      const char *loc = http.get_recv_header("location");
      const char *coo = http.get_recv_header("set-cookie");
      const char *len = http.get_recv_header("content-length");
    
      cerr << "== code = " << code << endl;
      cerr << "== headers size = " << hdrs.size() << endl;
      cerr << "== location = " << (loc?loc:"?") << endl;
      cerr << "== set-cookie = " << (coo?coo:"?") << endl;
      cerr << "== content-length = " << (len?len:"?") << " (strona: " << size << ")"<< endl;
    } 
    catch (Exception &e) {
      cerr << "== exception: " << e.what() << endl;
    }
  }

  return 0;
}
int main(int argc, char const *argv[]) {
	Http http;
	stringstream ss;
	// See Web Service source file in https://github.com/JAlikhani/BooksWebServiceNodeJS
	// Web service temporarily deployed in Heroku
	// Output JSON file looks like:
	/*
	 {
		   "book": [

		      {
		         "id":"01",
		         "title": "In Search of Lost Time",
		         "author": "Marcel Proust"
		      },

		      {
		         "id":"02",
		         "title": "Moby Dick",
		         "author": "Herman Melville"
		      },

		      {
		         "id":"03",
		         "title": "Hamlet",
		         "author": "William Shakespeare"
		      },

		      {
		         "id":"04",
		         "title": "The Odyssey",
		         "author": "Homer"
		      }
		   ]
		}
	 */
	ss << http.Request("floating-fjord-16663.herokuapp.com", 80, "/books", "application/json");
	JSONParser jsonParser(ss.str());
	cout << jsonParser.Books();
}
Пример #14
0
    Benchmark(int argc, char** argv) : res(argc,argv) {
      // response headers
      res.set_content_type("application/json");

      // create prepared statement
      stmt = mysql_stmt_init(db.connection());
      static const char* sql="SELECT randomNumber FROM World WHERE id = ?";
      mysql_stmt_prepare(stmt,sql,strlen(sql));

      ustmt = mysql_stmt_init(db.connection());
      static const char* usql="UPDATE World SET randomNumber = ? WHERE id = ?";
      mysql_stmt_prepare(ustmt,usql,strlen(usql));
    }
Пример #15
0
    int exec() {

      vf array;

      // query fortunes
      mysql_query(db.connection(), "SELECT id, message FROM Fortune;");
      MYSQL_RES *sqlres = mysql_store_result(db.connection());
      if (!sqlres) throw runtime_error(mysql_error(db.connection()));
      MYSQL_ROW row;
      while( (row=mysql_fetch_row(sqlres)) ){
        array.push_back(Fortune(atoi(row[0]),row[1]));
      }
      mysql_free_result(sqlres);

      // add on the fly
      array.push_back(Fortune(0,"Additional fortune added at request time."));

      // sort
      sort(array.begin(),array.end());

      // output html
      res << "<!DOCTYPE html>"
          "<html>"
          "<head><title>Fortunes</title></head>"
          "<body>"
          "<table>"
          "<tr><th>id</th><th>message</th></tr>";
      for(unsigned z=0;z<array.size();++z) {
        Fortune &az = array[z];
        res << "<tr>"
               "<td>" << az.id << "</td>"
               "<td>" << xml::escape(az.message) << "</td>"
               "</tr>";
      }
      res << "</table>"
             "</body>"
             "</html>";

      return res.end();
    }
Пример #16
0
    int exec() {

      id = rand()%10000;

      // reset statement for reuse
      if(mysql_stmt_reset(stmt)) throw runtime_error(mysql_stmt_error(stmt));

      // create and use input parameter
      memset(param, 0, sizeof(param));
      param[0].buffer_type = MYSQL_TYPE_LONG;
      param[0].buffer = (char *)&id;
      param[0].buffer_length = sizeof(id);
      param[0].is_null = 0;
      param[0].length = NULL;
      if(mysql_stmt_bind_param(stmt,param)) throw runtime_error(mysql_stmt_error(stmt));

      // create and fill result buffer
      memset(results, 0, sizeof(results));
      results[0].buffer_type= MYSQL_TYPE_LONG;
      results[0].buffer = &randomNumber;
      results[0].buffer_length = sizeof(randomNumber);
      results[0].is_null = 0;
      results[0].length = &len1;
      if(mysql_stmt_bind_result(stmt, results)) throw runtime_error(mysql_stmt_error(stmt));

      // execute statement
      if(mysql_stmt_execute(stmt)) throw runtime_error(mysql_stmt_error(stmt));
      if(mysql_stmt_fetch(stmt)) randomNumber = 0;

      // output json
      JsonObj obj;
      obj.add("id",id);
      obj.add("randomNumber",randomNumber);
      res << obj.to_s();

      return res.end();
    }
Пример #17
0
int HttpPlugin::get_info(Task *task) {
    Http http;

    http.set_timeout(task->timeout);
    http.set_log(&debug_log);
#ifdef HAVE_SSL
    if (task->url.get_protocol() == HTTPS) {
        http.set_use_ssl(true);
    }
#endif

    if (task->url.get_user() != NULL) {
        http.auth(task->url.get_user(),
                task->url.get_password() ? task->url.get_password() : "");
    }

    if (task->get_referer() != NULL) {
        http.header("Referer", task->get_referer());
    } else {
        http.header("Referer", task->url.get_url());
    }

    if (task->fileSize > 0) {
        // test the Range
        http.set_range(1);
    }

    if (task->proxy.get_type() == HTTP_PROXY) {
        if (task->proxy.get_host() == NULL) {
            return -1;
        }
        if (http.connect(task->proxy.get_host(), task->proxy.get_port()) < 0) {
            return -2;
        }
        http.set_host(task->url.get_host(), task->url.get_port());
        if (task->proxy.get_user() != NULL) {
            http.proxy_auth(task->proxy.get_user(),
                    task->proxy.get_password() ? task->proxy.get_password() : "");
        }

        if (http.get(task->url.get_url()) < 0) {
            return -2;
        }
    } else {
        if (http.connect(task->url.get_host(), task->url.get_port()) < 0) {
            return -2;
        }
        if (http.get(task->url.get_encoded_path()) < 0) {
            return -2;
        }
    }

    if (http.parse_header() < 0) return -2;
    switch (http.get_status_code()) {
        case 200:  // HTTP_STATUS_OK
        case 206:  // HTTP_STATUS_PARTIAL_CONTENTS
        case 300:  // HTTP_STATUS_MULTIPLE_CHOICES
        case 304:  // HTTP_STATUS_NOT_MODIFIED
            break;
        case 301:  // HTTP_STATUS_MOVED_PERMANENTLY
        case 302:  // HTTP_STATUS_MOVED_TEMPORARILY
        case 303:  // HTTP_SEE_OTHER
        case 307:  // HTTP_STATUS_TEMPORARY_REDIRECT
            {  // redirect
                task->fileSize = -1;  // if not, the new location's filesize is wrong
                const char *location = http.get_header("Location");
                if (location == NULL) {
                    // I do not know when this will happen, but no harm
                    location = http.get_header("Content-Location");
                    if (location == NULL) return -1;
                }
                if (strcmp(location, task->url.get_url()) == 0) break;
                if (task->url.reset_url(location) < 0) return -2;
                return S_REDIRECT;
            }
        case 305:  // HTTP_USE_PROXY
            {   // get the content through the proxy
                task->fileSize = -1;  // if not, the new location's filesize is wrong
                return S_REDIRECT;
            }
        case 408:  // HTTP_CLIENT_TIMEOUT
        case 504:  // HTTP_GATEWAY_TIMEOUT
        case 503:  // HTTP_UNAVAILABLE
        case 502:  // HTTP_BAD_GATEWAY
            {   // these errors can retry later
                return -2;
            }
        default:
            return -1;
    }

    // if the page is an active page, we maybe can not get the filesize
    if (task->fileSize < 0) {
        task->fileSize = http.get_file_size();
        if (task->fileSize > 1) {
            // we need test whether the Range header is supported or not
            return -2;
        }
    } else {
        // IIS never return the Accept-Ranges header
        // We need check the Content-Range header for the resuming
        const char *ptr = http.get_header("Content-Range");
        if (ptr) {
            while (*ptr != '\0' && !ISDIGIT(*ptr)) ptr++;
            if (*ptr++ == '1' && *ptr == '-') {
                // get the filesize again for ensure the size
                task->fileSize = 1 + http.get_file_size();
                task->resumeSupported = true;
            }
        }
    }

    const char *filename;
    filename = http.get_header("Content-Disposition");
    if (filename) {
        filename = strstr(filename, "filename=");
        if (filename) {
            filename += strlen("filename=");
            if (task->get_local_file() == NULL) {
                task->set_local_file(filename);
            }
        }
    }


    if (task->get_local_file() == NULL &&  task->url.get_file() == NULL) {
        task->set_local_file("index.html");
    }

    return 0;
};
Пример #18
0
int HttpPlugin::download(Task& task, Block *block) {
    block->state = STOP;
    if (task.resumeSupported) {
        if (block->downloaded >= block->size) {
            block->state = EXIT;
            return 0;
        } else {
            block->bufferFile.seek(block->startPoint + block->downloaded);
        }
    } else {
        block->bufferFile.seek(0);
        block->downloaded = 0;
    }

    Http http;
    http.set_timeout(task.timeout);
    http.set_log(&debug_log);
#ifdef HAVE_SSL
    if (task.url.get_protocol() == HTTPS) {
        http.set_use_ssl(true);
    }
#endif

    if (task.resumeSupported) {
        // the end is not set for the schedule purpose
        http.set_range(block->startPoint + block->downloaded);
    }

    if (task.url.get_user() != NULL) {
        http.auth(task.url.get_user(),
                task.url.get_password() ? task.url.get_password() : "");
    }

    if (task.get_referer() != NULL) {
        http.header("Referer", task.get_referer());
    } else {
        http.header("Referer", task.url.get_url());
    }

    if (task.proxy.get_type() == HTTP_PROXY) {
        if (http.connect(task.proxy.get_host(), task.proxy.get_port()) < 0) {
            return -2;
        }
        http.set_host(task.url.get_host(), task.url.get_port());
        if (task.proxy.get_user() != NULL) {
            http.proxy_auth(task.proxy.get_user(),
                    task.proxy.get_password() ? task.proxy.get_password() : "");
        }
        if (http.get(task.url.get_url()) < 0) {
            return -2;
        }
    } else {
        if (http.connect(task.url.get_host(), task.url.get_port()) < 0) {
            return -2;
        }
        if (http.get(task.url.get_encoded_path()) < 0) {
            return -2;
        }
    }

    if (http.parse_header() < 0) return -2;
    // the service maybe unreachable temply
    // some servers alway return 302, so nasty
    if (http.get_status_code() >= 400) return -2;

_re_retr:
    block->state = RETR;
    if (block->bufferFile.retr_data_from(&http, &block->downloaded,
                block->size - block->downloaded) < 0) {
        block->state = STOP;
        return -2;
    }

    if (task.resumeSupported && block->downloaded < block->size) {
        block->state = STOP;
        return -2;
    }

    block->state = WAIT;
    usleep(500000);
    if (block->state == WAKEUP) goto _re_retr;
    block->state = EXIT;
    return 0;
};
Пример #19
0
/* Loop the readStream list, and return the already stream */
int StreamManager::HttpParseHeader(){

    WebStream *webStream = NULL;
    list<WebStream *>::iterator ite;
    
    ESLog::ISLog("HTTP HEADER SETS PARSE START\n", __FILE__, __LINE__);

    ESLog::ISLog("readStreamSize:%d\n", __FILE__, __LINE__, this->readStream.size());
    /* loop */
    for( ite = this->readStream.begin(); ite != this->readStream.end(); ++ite ) {

        int result = -1;
        webStream = *ite;

        
        ESLog::ISLog("read webStream->http ptr:%u\n", __FILE__, __LINE__, webStream->GetHttpPtr());
        ESLog::ISLog("read webStream->fd:%d\n", __FILE__, __LINE__, webStream->GetTcpConnFd());
        ESLog::ISLog("read webStream->Status:%s\n", __FILE__, __LINE__, webStream->GetStatusDesc());

        /* if the readStream has writed */
        if( webStream->GetStatus() == WSTREAM_WRITE ) {
            continue;
        }

        /* is http protocol parser exist */
        if( !webStream->IsHttpParserExist() ) {
            ESLog::ISLog("An new Http Object Create \n", __FILE__, __LINE__ );
            Http *httpParser = new Http();
            httpParser->SetWebStreamPtr(webStream);
            webStream->SetHttpParser(httpParser);
            ESLog::ISLog("New Http read webStream->http ptr:%u\n", __FILE__, __LINE__, webStream->GetHttpPtr());
        }

        ESLog::ISLog("read WebStream->HttpStatus:%s\n", __FILE__, __LINE__, webStream->GetHttpPtr()->GetStatusDesc());

        /* if the header has parserd*/
        if( webStream->GetHttpPtr()->GetStatus() == HTTP_REQHEAD_PARSED  ) {
            continue;
        }

        /* if the latest http parsed over, again init http object */
        if( webStream->GetHttpPtr()->GetStatus() == HTTP_RESSEND_OVER  ) {
            
            webStream->GetHttpPtr()->ReInit();
        }

        /* parse the http header, if the http header parsed, then we give the webStream to the
           session/application, it will send to a idle thread to tackle the session
           if return 0, the header parser over; if return > 0 , it still to parser;
           if return < 0 , there is an error happend */
        result = webStream->ParseHttpHeader();  // <--i) set the status of the webStream , http Status
        if( result < 0 ) {
            
            ESLog::ISLog("ParseHttpHeader Erorr START\n", __FILE__, __LINE__ );
            webStream->SetStatus(WSTREAM_ERROR);
            //webStream->GetHttpPtr()->SetStatus(HTTP_RESSEND_OVER);
            //Server::Instance()->GetIOLoop().ModToReadEventFd(webStream->GetTcpConnFd(), (void *)webStream);
            //webStream->ReInit();
            //this->DeleteReadWebStream(webStream);

            Server::Instance()->GetIOLoop().DelReadEventFd(webStream->GetTcpConnFd());

            //webStream->FreeTcpConn();
            //webStream->FreeHttp();
            //webStream->ReInit();
            //webStream->SetStatus(WSTREAM_UNINITILIZED);
            //this->AddIdleStream(webStream);

            ESLog::ISLog("ParseHttpHeader Erorr END\n", __FILE__, __LINE__ );
            continue;
            //break;
            //return  result;  // an error happend
        }

        /* the header has passed  */
        if( webStream->GetHttpPtr()->GetStatus() == HTTP_REQHEAD_PARSED ) {
            //webStream->GetHttpPtr()->SetStatus(2);
            ESLog::ISLog("there is http head parsed\n", __FILE__, __LINE__);
            webStream->SetStatus(WSTREAM_UNDISPATHED);
            this->AddTaskWebStream(webStream);
        }
        
    }

    ESLog::ISLog("HTTP HEADER SETS PARSE END\n", __FILE__, __LINE__);
}
Пример #20
0
void onAttributeSet_callback(const uint8_t requestId, const uint16_t attributeId, const uint16_t valueLen, const uint8_t *value)
{
  HttpRequest *request = NULL;
  char hue_request[1024];
  fprintf(stdout,"onAttributeSet_callback: %d len: %d %x %s\n",attributeId,valueLen,*value,value);
  switch (attributeId)
  {
fprintf(stderr,"BUTTON PRESSED!\n");
break;
        case AF_LIGHT1:
          fprintf(stdout,"AF_LIGHT1 == %d\n",*value);
          sprintf(hue_request,"%slights/1/state",hue_prefix);
          if (*value)
  request = new HttpRequest(hue_request,"{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");
          else
  request = new HttpRequest(hue_request,"{ \"on\": false, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");

 http.AddRequest(request);

        break;
        case AF_LIGHT2:
          fprintf(stdout,"AF_LIGHT2 == %d\n",*value);
          sprintf(hue_request,"%slights/2/state",hue_prefix);
          if (*value)
  request = new HttpRequest(hue_request,"{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");
          else
  request = new HttpRequest(hue_request,"{ \"on\": false, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");

 http.AddRequest(request);

        break;
        case AF_LIGHT3:
          fprintf(stdout,"AF_LIGHT3 == %d\n",*value);
          sprintf(hue_request,"%slights/3/state",hue_prefix);
fprintf(stderr,"LIGHT 3 CHANGE STATE: %s\n",hue_request);
          if (*value)
  request = new HttpRequest(hue_request,"{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");
          else
  request = new HttpRequest(hue_request,"{ \"on\": false, \"hue\": 25500, \"sat\": 100, \"bri\": 100 }");

 http.AddRequest(request);

        break;
#if 0
        case AF_LIGHT1BRI:
        {
          uint16_t *light3Value= (uint16_t *) value;
          uint8_t *light3Value2= (uint8_t *) value;
          sprintf(hue_request,"%slights/1/state",hue_prefix);
          fprintf(stdout,"AF_LIGHT3 == %d %d %d\n",*value,*light3Value,*light3Value2);
          char command[512];
          
            sprintf(command, "{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": %d }",*light3Value2);
fprintf(stderr,"!!!! [%s]\n",command);
  		request = new HttpRequest(hue_request,(const char *)command);
               http.AddRequest(request);

        }
        case AF_LIGHT2BRI:
        {
          uint16_t *light3Value= (uint16_t *) value;
          uint8_t *light3Value2= (uint8_t *) value;
          sprintf(hue_request,"%slights/2/state",hue_prefix);
          fprintf(stdout,"AF_LIGHT3 == %d %d %d\n",*value,*light3Value,*light3Value2);
          char command[512];
          
            sprintf(command, "{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": %d }",*light3Value2);
fprintf(stderr,"!!!! [%s]\n",command);
  		request = new HttpRequest(hue_request,(const char *)command);
               http.AddRequest(request);

        }
#endif
        case AF_LIGHT3BRI:
        {
          uint16_t *light3Value= (uint16_t *) value;
          uint8_t *light3Value2= (uint8_t *) value;
          sprintf(hue_request,"%slights/3/state",hue_prefix);
          fprintf(stdout,"AF_LIGHT3 == %d %d %d\n",*value,*light3Value,*light3Value2);
          char command[512];
          
            sprintf(command, "{ \"on\": true, \"hue\": 25500, \"sat\": 100, \"bri\": %d }",*light3Value2);
fprintf(stderr,"!!!! [%s]\n",command);
  		request = new HttpRequest(hue_request,(const char *)command);
               http.AddRequest(request);

        }
        break;
	case AF_LIGHT1LABEL:
          {
          char *light1Label= (char *) value;
          fprintf(stdout,"bAF_LIGHT1LABEL == %s %d\n",light1Label);
          }

	case AF_LIGHT2LABEL:
          {
          char *light2Label= (char *) value;
          fprintf(stdout,"bAF_LIGHT2LABEL == %s %d\n",light2Label);
          }

	case AF_LIGHT3LABEL:
          {
          char *light3Label= (char *) value;
          fprintf(stdout,"bAF_LIGHT3LABEL == %s %d\n",light3Label);
          }
        
  }
    if (theLib->setAttributeComplete(requestId, attributeId, valueLen, value) != afSUCCESS) {
        fprintf(stderr,"setAttributeComplete failed!");
    }

  
}
Пример #21
0
int main(int argc, char *argv[])
{

  HueLightResponse *hueLightResponder= NULL;
  HueIPResponse *IPAddr= new HueIPResponse("https://www.meethue.com/api/nupnp");
  http.AddRequest(IPAddr);

  int state = HUE_STATE_NEED_IP;

        struct pollfd fdset[2];
        int nfds = 2;
        int gpio_fd, timeout, rc;
        char *buf[MAX_BUF];
        unsigned int interrupt_line= 17;/*17;*/
        unsigned int reset_line= 4;
        int len;
        int counter=0;

	Stream *theLog = new linuxLog();
        afSPI *theSPI = new linuxSPI();

        gpio_export(interrupt_line);
        gpio_set_dir(interrupt_line, 0);
        gpio_set_edge(interrupt_line, "falling");
        gpio_fd = gpio_fd_open(interrupt_line);

        timeout = POLL_TIMEOUT;

        fprintf(stdout,"Test\n");

        theLib = iafLib::create(0,isr_callback,onAttributeSet_callback,onAttributeSetComplete_callback,theLog,theSPI);
        theLib->mcuISR();

/* we need to hook up and use the reset line */
        gpio_export(reset_line);
        gpio_set_dir(reset_line, 1);
	gpio_set_value(reset_line,0);
    
        timespec sleep_time;
        timespec remaining;
        sleep_time.tv_sec=0;
        sleep_time.tv_nsec=250000;
        nanosleep(&sleep_time,&remaining);
         /* check for E_INTR? and call again? */
	gpio_set_value(reset_line,1);

        while (1) {
                counter++;
                memset((void*)fdset, 0, sizeof(fdset));

                fdset[0].fd = STDIN_FILENO;
                fdset[0].events = POLLIN;

                fdset[1].fd = gpio_fd;
                fdset[1].events = POLLPRI;

                lseek(gpio_fd, 0, SEEK_SET);    /* consume any prior interrupt */
                read(gpio_fd, buf, sizeof (buf));


                rc = poll(fdset, nfds, timeout);

                if (rc < 0) {
                        printf("\npoll() failed!\n");
                        return -1;
                }

                if (rc == 0) {
                        printf(".");
                }

                if (fdset[1].revents & POLLPRI) {
                        len = read(fdset[1].fd, buf, MAX_BUF);
                        printf("\npoll() GPIO %d interrupt occurred\n", interrupt_line);
                lseek(gpio_fd, 0, SEEK_SET);    /* consume interrupt */
                read(gpio_fd, buf, sizeof (buf));

                        theLib->mcuISR();
                }

                if (fdset[0].revents & POLLIN) {
                        (void)read(fdset[0].fd, buf, 1);
                        //printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);
                }



		switch (state)
		{
		   case HUE_STATE_NEED_IP:
			// we need to check and see if we have an IP, then we can switch
  			if (IPAddr->completed())
{
                          state = HUE_STATE_HAS_IP;
                          IPAddr->get_ip(hue_ip);
                        fprintf(stderr,"IP: %s\n",hue_ip);
			sprintf(hue_prefix,"http://%s/api/huelibrary/",hue_ip);
                        state = HUE_STATE_HAS_IP;
}
			break;
		   case HUE_STATE_HAS_IP:

                // every so many loops check and start the lights query to update the lights..
		if (counter % 100 == 0)
                {
                   //check to see how many HTTP requests are outstanding
                   if (hueLightResponder == NULL)
                   { 
printf("****initializing new request to get the lights\n");
                      char hue_request[1024];
                      sprintf(hue_request,"%slights",hue_prefix);
                      hueLightResponder =  new HueLightResponse(hue_request,theLib);
                      http.AddRequest(hueLightResponder);
                   }
                   else if (hueLightResponder->completed())
                   {
                      delete hueLightResponder;
                      char hue_request[1024];
                      sprintf(hue_request,"%slights",hue_prefix);
                      hueLightResponder =  new HueLightResponse(hue_request,theLib);
                      http.AddRequest(hueLightResponder);
                   }
                  

                }

                }

  	http.Update();
  	http.Status();
        theLib->loop();
        fflush(stdout);
        }

    gpio_fd_close(gpio_fd);
   return 0;
}
Пример #22
0
int Http::_progressCB ( void *userData, double thisDownload, double totalDownloaded, double thisUpload, double totalUploaded )
{
  Http *me ( reinterpret_cast<Http *> ( userData ) );
  return ( ( 0x0 == me ) ? 0 : me->_progress ( thisDownload, totalDownloaded, thisUpload, totalUploaded ) );
}
Пример #23
0
size_t Http::_writeDataCB ( void *buffer, size_t sizeOfOne, size_t numElements, void *userData )
{
  Http *me ( reinterpret_cast<Http *> ( userData ) );
  return ( ( 0x0 == me ) ? 0 : me->_writeData ( buffer, sizeOfOne, numElements ) );
}
Пример #24
0
 Benchmark(int argc,char** argv) : res(argc,argv) {
   res.set_content_type("application/json");
 }
Пример #25
0
    int exec() {

      int n = res.get_i("queries=");
      if(n<1) n = 1;
      if(n>500) n = 500;

      vw array;

      while(n--) {

        id = rand()%10000;
        newNumber = rand()%10000+1;

        // reset statement for reuse
        if(mysql_stmt_reset(stmt)) throw runtime_error(mysql_stmt_error(stmt));
        if(mysql_stmt_reset(ustmt)) throw runtime_error(mysql_stmt_error(ustmt));

        // create and use input parameter
        memset(param, 0, sizeof(param));
        param[0].buffer_type = MYSQL_TYPE_LONG;
        param[0].buffer = (char *)&id;
        param[0].buffer_length = sizeof(id);
        param[0].is_null = 0;
        param[0].length = NULL;
        if(mysql_stmt_bind_param(stmt,param)) throw runtime_error(mysql_stmt_error(stmt));

        // create and fill result buffer
        memset(results, 0, sizeof(results));
        results[0].buffer_type= MYSQL_TYPE_LONG;
        results[0].buffer = &randomNumber;
        results[0].buffer_length = sizeof(randomNumber);
        results[0].is_null = 0;
        results[0].length = &len1;
        if(mysql_stmt_bind_result(stmt, results)) throw runtime_error(mysql_stmt_error(stmt));

        // create and use update parameter
        memset(param_update, 0, sizeof(param_update));
        param_update[0].buffer_type = MYSQL_TYPE_LONG;
        param_update[0].buffer = (char *)&newNumber;
        param_update[0].buffer_length = sizeof(newNumber);
        param_update[0].is_null = 0;
        param_update[0].length = 0;
        param_update[1].buffer_type = MYSQL_TYPE_LONG;
        param_update[1].buffer = (char *)&id;
        param_update[1].buffer_length = sizeof(id);
        param_update[1].is_null = 0;
        param_update[1].length = 0;

        // execute statement
        if(mysql_stmt_execute(stmt)) throw runtime_error(mysql_stmt_error(stmt));
        if(mysql_stmt_bind_param(ustmt,param_update)) throw runtime_error(mysql_stmt_error(ustmt));
        if(mysql_stmt_fetch(stmt)) randomNumber = 0;

        // add to array (required by specification)
        array.push_back(World(id,newNumber));
      }

      // output json
      res << '[';
      for(unsigned z=0;z<array.size();++z) {
        if(z>0) res << ',';
        World &az = array[z];
        JsonObj obj;
        obj.add("id",az.id);
        obj.add("randomNumber",az.randomNumber);
        res << obj.to_s();
      }
      res << ']';

      return res.end();
    }
Пример #26
0
 int exec() {
   JsonObj obj;
   obj.add("message","Hello, World!");
   res << obj.to_s();
   return res.end();
 }
Пример #27
0
  void stage_2(string &url)
  {
    rsprintf("Lacze z '%s' (2)", url.c_str());
    char *buffer = NULL;
    size_t buflen = 0;

    try {
      int code = http.get(buffer, buflen, url.c_str(), "dl.start=Free");

      filesystem::ofstream head(rs_sessions_get_path(url, "-head2.http"));
      head.write(http.get_recv_header(), strlen(http.get_recv_header()));

      if (code == HTTP_OK) // Oczekujemy kodu 200
        rsprintf("Polaczono, code = %d, page = %p,%zd", code, buffer, buflen);
      else {
        rsprintf("Polaczono, brak strony? code = %d, page = %p,%zd, try again", code, buffer, buflen);
        if (buffer) delete[] buffer;
        throw DBreak();
      }

      filesystem::ofstream page(rs_sessions_get_path(url, "-page2.html"));
      page.write(buffer, buflen);
    }
    catch (Exception &e) {
      rsprintf("Nastapil wyjatek: %s", e.what());
      throw DBreak();
    }

    if (regex_search(buffer, rs_regex_try_later)) {
      rsprintf("Nie mozna teraz pobierac pliku, sprobuje za chwile, czekam...");
      rs_wait(RS::Waiting, RS::Preparing, rs_waiting_try_later);
      delete[] buffer;
      throw DAgain();
    }

    if (regex_search(buffer, rs_regex_reached_limit)) {
      rsprintf("Wyczerpal sie limit pobran, czekam...");
      rs_wait(RS::Limit, RS::Preparing, rs_waiting_limit);
      delete[] buffer;
      throw DAgain();
    }

    if (regex_search(buffer, rs_regex_server_busy)) {
      rsprintf("Serwery sa przeciazone, czekam...");
      rs_wait(RS::Busy, RS::Preparing, rs_waiting_busy);
      delete[] buffer;
      throw DAgain();
    }

    if (regex_search(buffer, rs_regex_server_busy)) {
      rsprintf("Brak wolnych slotow, czekam...");
      rs_wait(RS::Busy, RS::Preparing, rs_waiting_busy);
      delete[] buffer;
      throw DAgain();
    }

    if (regex_search(buffer, rs_regex_already_downloading)) {
      rsprintf("Ktos o tym samym IP pobiera juz jakis plik, czekam...");
      rs_wait(RS::Rivalry, RS::Preparing, rs_waiting_rivalry);
      delete[] buffer;
      throw DAgain();
    }

    size_t wait_for = 0;
    string ssize;
    cmatch what;

    if (regex_search(buffer, what, rs_regex_time)) {
      wait_for = strtol(what[1].str().c_str(), 0, 10) + 5;
      rsprintf("Czekam %zd sek...", wait_for);
    } else {
      wait_for = 5;
      rsprintf("Nieznany czas oczekiwania, sprobuje %zd sek...", wait_for);
    }

    if (!regex_search(buffer, what, rs_regex_size)) {
      rsprintf("Nieznany rozmiar pliku, jeszcze raz...");
      delete[] buffer;
      throw DBreak();
    }
    ssize = what[1];
    rs_info.all_bytes = 1000*strtol(ssize.c_str(), 0, 10);

    try {
      vector<pair<string, string> > srvs;
      for (cregex_iterator it(buffer, buffer+buflen, rs_regex_server), end; it != end; ++it)
        srvs.push_back(make_pair<string, string>((*it)[2], (*it)[1]));

      if (!srvs.size()) {
        rsprintf("Brak serwerow, przerywam...");
        throw DBreak();
      }

      size_t i = 0;
      while (rs_favorites_servers[i]) {
        size_t found = 0, end = srvs.size();

        while (found < end) {
          if (srvs[found].first == rs_favorites_servers[i]) break;
          ++found;
        }

        if (found == end) {
          rsprintf("Brak serwera '%s', szukam dalej...", rs_favorites_servers[i]);
          ++i;
          continue;
        }

        rsprintf("Wybieram serwer '%s'...", rs_favorites_servers[i]);
        url = srvs[found].second;
        break;
      }

      if (!rs_favorites_servers[i]) {
        url = srvs[0].second;
        rsprintf("Brak jakiegokolwiek ulubionego serwera, wybieram pierwszy z brzegu '%s'",
            srvs[0].first.c_str());
      }
    }
    catch (DBreak) { delete[] buffer; throw; }
    catch (DExc &e) { delete[] buffer; throw e; }

    rs_wait(RS::Waiting, RS::Preparing, wait_for);
    delete[] buffer;
  }