Exemplo n.º 1
3
void OptionWidget::startServer()
{
    WebServer* svr = WebServer::getInstance();
    svr->setDocumentRoot(_edit_rootdir->text().toStdString().c_str());
    svr->setPort(_edit_port->text().toUShort());
    svr->setEnableDirectoryListing(_cbox_dirlist->isChecked());
    svr->start();

    _btn_start->setEnabled(false);
    _btn_stop->setEnabled(true);
    _btn_restart->setEnabled(true);
}
Exemplo n.º 2
0
int main(int argc, char* argv[])
{
    WebServer server;
    server.start();

    return 0;
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
  QCoreApplication app(argc, argv);

  app.setApplicationName("WebServer");
  app.setApplicationVersion("0.03");
  app.setOrganizationName("Open E-Government Project");
  app.setOrganizationDomain("open-egov.de");

  if (QCoreApplication::arguments().contains("--verbose")) {
    qDebug() << app.applicationName() << " Version " << app.applicationVersion();
    qDebug() << "Running with PID: " << getpid();
  }

  //qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

  WebServer server;
  //http://doc.trolltech.com/4.5/qhostaddress.html
  //Null, LocalHost, LocalHostIPv6, Broadcast, and Any.
  //QHostAddress::AnyIPv6
  //QHostAddress::LocalHostIPv6
  if (! server.listen(QHostAddress::Any, 80)) {
    qDebug() << "Unable to start the server: " << server.errorString();
    return 0;
  }

  qDebug() << QObject::tr("The server is running on port %1.").arg(server.serverPort());

  return app.exec();
}
Exemplo n.º 4
0
/* ================================================================== *
 * Function: web_index
 * Description: Static callback function to display the homepage of the web server
 * Parameters: See Webduino documentation
 *             obj is a pointer to the instance of Server that added the callback
 * ================================================================== */
void web_index(WebServer &server, WebServer::ConnectionType type, char * c, bool b, void * obj) {
    server.httpSuccess();

    if (type != WebServer::HEAD) {
      server.printP(control_panel);
    }
}
Exemplo n.º 5
0
int main( int argc, char ** argv )
{
    QCoreApplication a(argc, argv);
    //Check whether running as root
    if( getuid() != 0){
      qDebug() << "pc-restserver must be started as root!";
      return 1;
    }
      //Setup the log file
    if(DEBUG){
      qDebug() << "pc-restserver Log File:" << logfile.fileName();
      if(QFile::exists(logfile.fileName()+".old")){ QFile::remove(logfile.fileName()+".old"); }
      if(logfile.exists()){ QFile::rename(logfile.fileName(), logfile.fileName()+".old"); }
      //Make sure the parent directory exists
      if(!QFile::exists("/var/log")){
        QDir dir;
        dir.mkpath("/var/log");
      }
      logfile.open(QIODevice::WriteOnly | QIODevice::Append);
      qInstallMessageHandler(MessageOutput);
    }
      
    //Create and start the daemon
    qDebug() << "Starting the PC-BSD REST server interface....";
    WebServer *w = new WebServer(); 
    if( w->startServer() ){
      //Now start the event loop
      QTimer::singleShot(1000, w, SLOT(stopServer()) ); //for testing purposes
      int ret = a.exec();
      logfile.close();
      return ret;
    }else{
      return 1;
    }
}
Exemplo n.º 6
0
void OptionWidget::updateShowData()
{
    WebServer* svr = WebServer::getInstance();

    _edit_port->setText(QString().setNum(svr->getPort()));
    _edit_rootdir->setText(QString(svr->getDocumentRoot()));
    _cbox_dirlist->setChecked(svr->isEnableDirectoryListing());
}
Exemplo n.º 7
0
void OptionWidget::reStartServer()
{
    WebServer* svr = WebServer::getInstance();
    svr->reStart();
    _btn_start->setEnabled(false);
    _btn_stop->setEnabled(true);
    _btn_restart->setEnabled(true);
}
/** Static function: just call the current instance's uri handler function
 *
 *	\param networkConnection Mongoose network connection struct.
 *	\param eventCode Mongoose event code.
 *	\param dataPointer Mongoose event data, could be the http message.
 *
 */
void WebServer::eventHandler(struct mg_connection *networkConnection,
		int eventCode, void *dataPointer){
	if (eventCode == MG_EV_HTTP_REQUEST){
		WebServer* self = (WebServer *) networkConnection->user_data;
		struct http_message *httpMessage = (struct http_message *) dataPointer;

		Request request(*networkConnection, *httpMessage);
		self->handleRequest(request);
	}
}
Exemplo n.º 9
0
int main(int argc, char* argv[]) {
    WebServer* server = new WebServer();

    server->port = 8181;
    server->addController("/", new IndexController());

    server->run();
    delete server;
    return 0;
}
Exemplo n.º 10
0
/* ================================================================== *
 * Function: web_input
 * Description: Static callback function to handle input to the server
 * Parameters: See Webduino documentation
 *             obj is a pointer to the instance of Server that added the callback
 * ================================================================== */
void web_input(WebServer &server, WebServer::ConnectionType type, char * c, bool b, void * obj) {
    if (type == WebServer::POST) {
        Server * s = (Server *) obj;
        bool repeat;
        char name[16], value[16];
        do {
            // Read all POST params, returns false when no more params
            repeat = server.readPOSTparam(name, 16, value, 16);

            if (strcmp(name, "visualizer") == 0) {
                int type = strtol(value, NULL, 10);
                // Ensure type is valid, default to VISUALIZER_BARS
                switch (type) {
                    case VISUALIZER_BARS:
                    case VISUALIZER_BARS_MIDDLE:
                    case VISUALIZER_PULSE:
                    case VISUALIZER_PLASMA:
                    case VISUALIZER_RAINBOW:
                    case VISUALIZER_WHEEL:
                        s->set_visualizer(type); break;
                    default:
                        s->set_visualizer(VISUALIZER_BARS); break;
                }
            } else if (strcmp(name, "other") == 0) {
                int type = strtol(value, NULL, 10);
                // Ensure type is valid, default to BOUNCING_LINES
                switch (type) {
                    case BOUNCING_LINES:
                    case BAR_TEST:
                    case PIXEL_TEST:
                    case AMBIENT_LIGHTING:
                        s->set_visualizer(type); break;
                    default:
                        s->set_visualizer(BOUNCING_LINES); break;
                }
            } else if (strcmp(name, "power") == 0) {
                s->set_power(strtol(value, NULL, 10));
            }
        } while (repeat);
            // after procesing the POST data, tell the web browser to reload
            // the page using a GET method.
            server.httpSeeOther("/web_input");
            return;
        }

        /* for a GET or HEAD, send the standard "it's all OK headers" */
        server.httpSuccess();

        /* we don't output the body for a HEAD request */
        if (type == WebServer::GET) {
            server.printP(control_panel);
        }
}
Exemplo n.º 11
0
int main(int argc, char * argv[])
{

	if(argc == 3){
		WebServer<HttpRequest> wb = WebServer<HttpRequest>("127.0.0.1", 8080, atoi( argv[1]), atoi(argv[2]) );
		wb.run();
	}
	else{
		WebServer<HttpRequest> wb = WebServer<HttpRequest>("127.0.0.1", 8080, 16, 10000);
		wb.run();
	}
}
Exemplo n.º 12
0
void InitializeGarageDoorWebserver()
{
  static uint8_t auLocalMAC[] = LOCAL_MAC_ADDRESS;
  static uint8_t auLocalIPAddress[] = LOCAL_IP_ADDRESS;

  AccessControlServer.setDefaultCommand(ShowWebRoot);
  AccessControlServer.addCommand("LetMeIn.html", CheckLogin);
  AccessControlServer.addCommand("index.html", ShowWebRoot);
  AccessControlServer.setFailureCommand(ShowPageNotFound);

  Ethernet.begin(auLocalMAC, auLocalIPAddress);
  AccessControlServer.begin();
}
Exemplo n.º 13
0
void RestDhtApi::dht(WebServer &server, WebServer::ConnectionType type,
		char *url_tail, bool tail_complete) {
	URLPARAM_RESULT rc;
	char name[32];
	char value[32];

	//server.httpSuccess("application/json");
	server.httpSuccess();

	if (type != WebServer::GET)
		return;

	if (strlen(url_tail)) {

		DHT dht;

		while (strlen(url_tail)) {

			rc = server.nextURLparam(&url_tail, name, 32, value, 32);

			String param = String(name);

			if (param == "pin") {

				String vl = value;
				int v = atoi(vl.c_str());

				dht.setup(v);

				dht.getMinimumSamplingPeriod();

				double hum = dht.getHumidity();
				double tempC = dht.getTemperature();
				double tempF = dht.toFahrenheit(tempC);

				Serial.println(v);

				Serial.print(dht.getStatusString());
				Serial.print(" - ");
				Serial.print(hum, 1);
				Serial.print("% - ");
				Serial.print(tempC, 1);
				Serial.print("C - ");
				Serial.print(tempF, 1);
				Serial.println("F");

			}

		}
	}
}
Exemplo n.º 14
0
void WebManager::pushButtonCmd(WebServer& server, WebServer::ConnectionType type, char* url_tail, bool tail_complete) {
#ifdef PRINT_DEBUG_MSGS
	Serial.println("ajax_action");
#endif
	if (getInstance()->m_webserver->checkCredentials(IOManager::getInstance()->m_credentialsFile->m_authCredentials)) {
		if (type == WebServer::POST) {
			IOManager::getInstance()->m_actionDoorCmd->toggleFor();
		}

		/* for a GET or HEAD, send the standard "it's all OK headers" */
		server.httpSuccess();
	} else {
		/* send a 401 error back causing the web browser to prompt the user for credentials */
		server.httpUnauthorized();
	}
}
Exemplo n.º 15
0
void WebServer::defaultFailCmd(WebServer &server,
                               WebServer::ConnectionType type,
                               char *url_tail,
                               bool tail_complete)
{
  server.httpFail();
}
Exemplo n.º 16
0
void CheckLogin(WebServer &rServer, WebServer::ConnectionType Type, char *pchUrlTail, bool bTailComplete)
{

  rServer.httpSuccess();

  switch (Type)
  {
  case WebServer::GET:
    SendErrorPage(rServer);
    break;

  case WebServer::POST:
    if (IsValidLogin(rServer))
    {
      ActivateGarageDoor();
      SendAccessGrantedPage(rServer);
    }
    else
      SendAccessDeniedPage(rServer);
    break;

    // None of these are expected, so we don't respond. 
  case WebServer::INVALID:
  case WebServer::HEAD:
  case WebServer::PUT:
  case WebServer::DELETE:
  case WebServer::PATCH:
  default:
    break;
  }
}
Exemplo n.º 17
0
/* ================================================================== *
 * Function: tick
 * Description: Periodically call to serve HTTP connections
 * Parameters: none
 * ================================================================== */
void Server::tick() {
    char buff[256];
    int len = 256;

    /* process incoming connections one at a time forever */
    webserver.processConnection(buff, &len);
}
Exemplo n.º 18
0
// --------------- Page request handlers
void ShowWebRoot(WebServer &rServer, WebServer::ConnectionType Type, char *pchUrlTail, bool bTailComplete)
{
  // Expire grace login period when the home page is shown. 
  PasswordManager.ClearGracePassword();

  // We show the password entry page as the web root. Presents a form that asks for a password.
  rServer.httpSuccess();

  switch (Type)
  {
  case WebServer::GET:
    SendLoginPage(rServer);
    break;

  case WebServer::POST:
    SendErrorPage(rServer);
    break;

    // None of these are expected, so we don't respond. 
  case WebServer::INVALID:
  case WebServer::HEAD:
  case WebServer::PUT:
  case WebServer::DELETE:
  case WebServer::PATCH:
  default:
    break;
  }
}
Exemplo n.º 19
0
void ProcessGarageDoorWebserver()
{
  char achBuffer[64];
  int nBufferLength = sizeof(achBuffer);

  AccessControlServer.processConnection(achBuffer, &nBufferLength);
}
Exemplo n.º 20
0
void loop()
{
    char buff[64];
    int len = 64;
    
    /* process incoming connections one at a time forever */
    webserver.processConnection(buff, &len);
}
Exemplo n.º 21
0
void setup() {
#if DEBUG
    Serial.begin(9600);
    Serial.println("Hello world.");
#endif
    
    /* setup our default command that will be run when the user accesses
     * the root page on the server */
    webserver.setDefaultCommand(&helloCmd);
    
    /* run the same command if you try to load /index.html, a common
     * default page name */
    webserver.addCommand("index.html", &helloCmd);
    
    /* start the webserver */
    webserver.begin();
}
Exemplo n.º 22
0
/* ================================================================== *
 * Function: init
 * Description: Initialize the server
 * Parameters: none
 * ================================================================== */
void Server::init() {
    /* Default command accessed through http://ip_address */
    webserver.setDefaultCommand(&web_index);

    /* Command to handle web inputs, accessed through http://ip_address/web_input */
    webserver.addCommand("web_input", &web_input, this);

    /* start the webserver */
    webserver.begin();

    // Print the IP so we know where to connect
    Particle.variable("ipAddress", myIpAddress, STRING);
    IPAddress myIp = WiFi.localIP();
    sprintf(myIpAddress, "%d.%d.%d.%d", myIp[0], myIp[1], myIp[2], myIp[3]);

    power_status = SERVER_POWER_ON;
}
Exemplo n.º 23
0
//----------------------------------------------------------------------------------------------------
// This function is called by webserver (by pointer on function). It manage http request
void WebManager::webPageCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
#ifdef PRINT_DEBUG_MSGS
	Serial.println("Index");
#endif
	if (getInstance()->m_webserver->checkCredentials(IOManager::getInstance()->m_credentialsFile->m_authCredentials)) {
		/* for a GET or HEAD, send the standard "it's all OK headers" */
		server.httpSuccess();

		/* we don't output the body for a HEAD request */
		if (type != WebServer::HEAD) {
			getInstance()->m_mainPage->print();
		}
	} else {
		/* send a 401 error back causing the web browser to prompt the user for credentials */
		server.httpUnauthorized();
	}
}
Exemplo n.º 24
0
/**
 * Main MHD callback for handling requests.
 *
 * @param cls argument given together with the function
 *        pointer when the handler was registered with MHD
 * @param connection handle identifying the incoming connection
 * @param url the requested url
 * @param method the HTTP method used ("GET", "PUT", etc.)
 * @param version the HTTP version string (i.e. "HTTP/1.1")
 * @param upload_data the data being uploaded (excluding HEADERS,
 *        for a POST that fits into memory and that is encoded
 *        with a supported encoding, the POST data will NOT be
 *        given in upload_data and is instead available as
 *        part of MHD_get_connection_values; very large POST
 *        data *will* be made available incrementally in
 *        upload_data)
 * @param upload_data_size set initially to the size of the
 *        upload_data provided; the method must update this
 *        value to the number of bytes NOT processed;
 * @param ptr pointer that the callback can set to some
 *        address and that will be preserved by MHD for future
 *        calls for this request; since the access handler may
 *        be called many times (i.e., for a PUT/POST operation
 *        with plenty of upload data) this allows the application
 *        to easily associate some request-specific state.
 *        If necessary, this state can be cleaned up in the
 *        global "MHD_RequestCompleted" callback (which
 *        can be set with the MHD_OPTION_NOTIFY_COMPLETED).
 *        Initially, <tt>*con_cls</tt> will be NULL.
 * @return MHS_YES if the connection was handled successfully,
 *         MHS_NO if the socket must be closed due to a serios
 *         error while handling the request
 */
static int
create_response (void *cls,
                 struct MHD_Connection *connection,
                 const char *url,
                 const char *method,
                 const char *version,
                 const char *upload_data,
                 size_t *upload_data_size,
                 void **ptr)
{
    if (cls != NULL)
    {
    WebServer *server = (WebServer *)cls;
    return server->createResponse(connection, url, method, version, upload_data, upload_data_size, ptr);
    }
    
    return MHD_NO;
}
Exemplo n.º 25
0
int main( int argc, char* argv[] )
{
	Arc_InitCore();
	Arc_InitNet();

	Log::AddInfoOutput("stdout", false);
	Log::AddErrorOutput("stderr", false);
	Log::AddInfoOutput("logs/info.log");
	Log::AddErrorOutput("logs/error.log");

	WebServer server;
	server.run();

	Log::CloseOutputs();

	Arc_TermNet();

	return 0;
}
Exemplo n.º 26
0
void RestApi::put(WebServer &server, WebServer::ConnectionType type,
		char *url_tail, bool tail_complete) {

	URLPARAM_RESULT rc;
	char name[32];
	char value[32];

	//server.httpSuccess("application/json");
	server.httpSuccess();

	if (type != WebServer::PUT)
		return;

	if (strlen(url_tail)) {
		while (strlen(url_tail)) {
			rc = server.nextURLparam(&url_tail, name, 32, value, 32);

			String param = String(name);
			String vl = value;

			int v = atoi(vl.c_str());

			if (v >= 0) {

				String t = name;
				char tp = t.charAt(0);
				String p = t.substring(1, 32);
				int pin = atoi(p.c_str());

				if (tp == 'd') {
                    digitalWrite(pin, v);
				} else {
                    analogWrite(pin, v);
                }

                Serial.print(pin + ":");
                Serial.println(v);

			}

		}
	}
}
Exemplo n.º 27
0
/* commands are functions that get called by the webserver framework
 * they can read any posted data from client, and they output to the
 * server to send data back to the web browser. */
void helloCmd(WebServer &server, WebServer::ConnectionType type, char *, bool)
{

    /* this line sends the standard "we're all OK" headers back to the
     browser */
    server.httpSuccess();
    
    /* if we're handling a GET or POST, we can output our data here.
     For a HEAD request, we just stop after outputting headers. */
    if (type != WebServer::HEAD)
    {
        /* this defines some HTML text in read-only memory aka PROGMEM.
         * This is needed to avoid having the string copied to our limited
         * amount of RAM. */
        const char *helloMsg = "<html><body><h1>Hello, Costanza!</h1></body></html>";

        /* this is a special form of print that outputs from PROGMEM */
        server.print(helloMsg);
    }
}
Exemplo n.º 28
0
void WebManager::getStateCmd(WebServer& server, WebServer::ConnectionType type, char* url_tail, bool tail_complete) {
#ifdef PRINT_DEBUG_MSGS
	Serial.println("ajax_refresh");
#endif
	if (getInstance()->m_webserver->checkCredentials(IOManager::getInstance()->m_credentialsFile->m_authCredentials)) {
		/* for a GET or HEAD, send the standard "it's all OK headers" */
		server.httpSuccess();
		server.print("{'state': ");
		server.print(DoorStateManager::getInstance()->m_currentState->getId());
		server.print(", 'obstacle': ");
		server.print(DoorStateManager::getInstance()->isObstacleDetected() ? "true" : "false");
		server.print(", 'forgottenOpened': ");
		server.print(DoorStateManager::getInstance()->isForgottenOpenedDoor() ? "true" : "false");
		server.print('}');
	} else {
		/* send a 401 error back causing the web browser to prompt the user for credentials */
		server.httpUnauthorized();
	}
}
Exemplo n.º 29
0
void RestApi::get(WebServer &server, WebServer::ConnectionType type,
		char *url_tail, bool tail_complete) {

	URLPARAM_RESULT rc;
	char name[32];
	char value[32];

	//server.httpSuccess("application/json");
	server.httpSuccess();

	if (type != WebServer::GET)
		return;

	if (strlen(url_tail)) {
		while (strlen(url_tail)) {
			rc = server.nextURLparam(&url_tail, name, 32, value, 32);

			String param = String(name);

			if (param == "pin") {

				String t = value;
				char tp = t.charAt(0);
				String p = t.substring(1, 32);
				int pin = atoi(p.c_str());

				if (tp == 'd') {
					Serial.println(digitalRead(pin));
				} else {
					Serial.println(analogRead(pin));
				}

			}

		}

	}
}
Exemplo n.º 30
0
int main(int argc, char* argv[]){
  JNIEnv* env;
  JavaVM* jvm;
  env = create_vm(&jvm);
  if (env == NULL){
    return 1;
  }else{
	cout << "JVM started" << endl;
	WebServer* web = new WebServer(env);
	web->main();
	Database* db = new Database(env);
	db->getDatabase();
	CommandExecutor* cmd = new CommandExecutor(env);
	cmd->addCommand("dir");
	cmd->run();
	string result = cmd->getResult();
	cout << "CPP: Output of command:" << endl;
	cout << "-----------------------------------------------------------" << endl;
	cout << result;
	cout << "-----------------------------------------------------------" << endl;
	return 0;
  }
}