Esempio n. 1
0
static int handler(struct mg_connection *conn) {
  char var1[500], var2[500], reply[2000];

  if (strcmp(conn->uri, "/handle_post_request") == 0) {
    // User has submitted a form, show submitted data and a variable value
    // Parse form data. var1 and var2 are guaranteed to be NUL-terminated
    mg_get_var(conn, "input_1", var1, sizeof(var1));
    mg_get_var(conn, "input_2", var2, sizeof(var2));

    // Send reply to the client, showing submitted form values.
    // POST data is in conn->content, data length is in conn->content_len
    snprintf(reply, sizeof(reply), "HTTP/1.0 200 OK\r\n"
             "Content-Type: text/plain\r\n\r\n"
             "Submitted data: [%.*s]\n"
             "Submitted data length: %d bytes\n"
             "input_1: [%s]\n"
             "input_2: [%s]\n",
             conn->content_len, conn->content, conn->content_len, var1, var2);
    mg_write(conn, reply, strlen(reply));
  } else {
    // Show HTML form.
    snprintf(reply, sizeof(reply), "HTTP/1.0 200 OK\r\n"
             "Content-Length: %d\r\n"
             "Content-Type: text/html\r\n\r\n%s",
             (int) strlen(html_form), html_form);
    mg_write(conn, reply, strlen(reply));
  }

  return 1;
}
Esempio n. 2
0
int RestfulApi::check_login_form_submission(struct mg_connection *conn)
  {

    char name[100], password[100], ssid[100], expire[100], expire_epoch[100];

     mg_get_var(conn, "name", name, sizeof(name));
     mg_get_var(conn, "password", password, sizeof(password));

     //To do: routine that validate users (maybe passprhase?)
     if (AuthenticateUser(name,password)){
       // Generate expiry date
       time_t t = time(NULL) + 3600;  // Valid for 1 hour
       snprintf(expire_epoch, sizeof(expire_epoch), "%lu", (unsigned long) t);
       strftime(expire, sizeof(expire), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&t));

       generate_ssid(name, expire_epoch, ssid, sizeof(ssid));
       // Set "session id" cookie, there could be some data encoded in it.
       mg_printf(conn,
                 "HTTP/1.1 302 Moved\r\n"
                 "Set-Cookie: ssid=%s; expire=\"%s\"; http-only; HttpOnly;\r\n"
                 "Location: /\r\n\r\n",
                 ssid, expire);
      fprintf(stderr,"\nAutenticated successfully\n");

      return MG_FALSE;
     }
      mg_printf(conn, "HTTP/1.1 302 Moved\r\nLocation: %s\r\n\r\n", s_error_uri);
     return MG_FALSE;
   }
Esempio n. 3
0
static int begin_request_handler(struct mg_connection *conn) {
  const struct mg_request_info *ri = mg_get_request_info(conn);
  char post_data[1024], input1[sizeof(post_data)], input2[sizeof(post_data)];
  int post_data_len;

  if (!strcmp(ri->uri, "/handle_post_request")) {
    // User has submitted a form, show submitted data and a variable value
    post_data_len = mg_read(conn, post_data, sizeof(post_data));

    // Parse form data. input1 and input2 are guaranteed to be NUL-terminated
    mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1));
    mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2));

    // Send reply to the client, showing submitted form values.
    mg_printf(conn, "HTTP/1.0 200 OK\r\n"
              "Content-Type: text/plain\r\n\r\n"
              "Submitted data: [%.*s]\n"
              "Submitted data length: %d bytes\n"
              "input_1: [%s]\n"
              "input_2: [%s]\n",
              post_data_len, post_data, post_data_len, input1, input2);
  } else {
    // Show HTML form.
    mg_printf(conn, "HTTP/1.0 200 OK\r\n"
              "Content-Length: %d\r\n"
              "Content-Type: text/html\r\n\r\n%s",
              (int) strlen(html_form), html_form);
  }
  return 1;  // Mark request as processed
}
Esempio n. 4
0
bool CManageModule::_HandleConn_Notice(struct mg_connection *conn)
{
	char starttime[MSG_VAR_LEN] = { 0 };
	char interval[MSG_VAR_LEN] = { 0 };
	char broadcasttimes[MSG_VAR_LEN] = { 0 };
	char content[MSG_VAR_LEN] = { 0 };
	mg_get_var(conn, MSG_VAR_STARTTIME, starttime, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_INTERVAL, interval, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_CASTTIMES, broadcasttimes, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_CONTENT, content, MSG_VAR_LEN);

	int64 tStartTime = atoll(starttime);
	int nInterVal = atoi(interval);
	int nCastTimes = atoi(broadcasttimes);

	if (tStartTime < 1 || nInterVal < 1 || nCastTimes < 1 || !content[0]) {
		Log.Error("Wrong notice. starttime: %lld, interval: %d, casttimes: %d, content: %s", tStartTime, nInterVal, nCastTimes, content);
		return false;
	}

	Message::GMManager msg;
	msg.set_starttime(tStartTime);
	msg.set_interval(nInterVal);
	msg.set_casttimes(nCastTimes);
	msg.set_content(content);

	PACKET_COMMAND pack;
	PROTOBUF_CMD_PACKAGE(pack, msg, B2G_MANAGE_NOTICE);
	SendGameMsg(&pack);

	Log.Notice("broadcast notice. starttime: %s, interval: %s, casttimes: %s, content: %s", starttime, interval, broadcasttimes, content);

	return true;
}
Esempio n. 5
0
static void test_mg_get_var(void) {
  static const char *post[] = {
    "a=1&&b=2&d&=&c=3%20&e=",
    "q=&st=2012%2F11%2F13+17%3A05&et=&team_id=",
    NULL
  };
  char buf[20];

  ASSERT(mg_get_var(post[0], strlen(post[0]), "a", buf, sizeof(buf)) == 1);
  ASSERT(buf[0] == '1' && buf[1] == '\0');
  ASSERT(mg_get_var(post[0], strlen(post[0]), "b", buf, sizeof(buf)) == 1);
  ASSERT(buf[0] == '2' && buf[1] == '\0');
  ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, sizeof(buf)) == 2);
  ASSERT(buf[0] == '3' && buf[1] == ' ' && buf[2] == '\0');
  ASSERT(mg_get_var(post[0], strlen(post[0]), "e", buf, sizeof(buf)) == 0);
  ASSERT(buf[0] == '\0');

  ASSERT(mg_get_var(post[0], strlen(post[0]), "d", buf, sizeof(buf)) == -1);
  ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, 2) == -2);

  ASSERT(mg_get_var(post[0], strlen(post[0]), "x", NULL, 10) == -2);
  ASSERT(mg_get_var(post[0], strlen(post[0]), "x", buf, 0) == -2);
  ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 16) == -2);
  ASSERT(mg_get_var(post[1], strlen(post[1]), "st", buf, 17) == 16);
}
Esempio n. 6
0
bool CManageModule::_HandleConn_Forbid(struct mg_connection *conn)
{
	char userid[MSG_VAR_LEN] = { 0 };
	char forcetime[MSG_VAR_LEN] = { 0 };
	char reason[MSG_VAR_LEN] = { 0 };
	mg_get_var(conn, MSG_VAR_USER, userid, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_FTIME, forcetime, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_REASON, reason, MSG_VAR_LEN);
	
	int64 uid = atoll(userid);
	int64 tforce = atoll(forcetime) * GTIME_HOUR_SEC + GetTimeSec();
	int treason = atol(reason);
	if (uid < 1 || tforce < 1) {
		Log.Error("[ManageModule] forbid user param wrong. user: %s, forcetime: %s", userid, forcetime);
		return false;
	}

	Message::GMManager msg;
	msg.set_userid(uid);
	msg.set_forcetime(tforce);
	msg.set_reason(treason);

	PACKET_COMMAND pack;
	PROTOBUF_CMD_PACKAGE(pack, msg, B2G_MANAGE_FORBID);
	SendGameMsg(&pack);

	Log.Notice("forbid user: %s forcetime: %s success.", userid, forcetime);

	return true;
}
Esempio n. 7
0
static void fileTransfer(struct mg_connection *conn) {
	char action[10];
	char protocol[10];
	char filename[50];
  mg_get_var(conn, "act", action, sizeof(action));
  mg_get_var(conn, "via", protocol, sizeof(protocol));
  mg_get_var(conn, "file", filename, sizeof(filename));

      if (!strcmp(action, "Download")) {
      	if (!strcmp(protocol, "udp")) {
sendMsg(filename, 0);
		initUDPClient(filename+2, IP);
      	}
      	else {
			initCDTCP(filename);
                
      	}

      }
      else {
      	if (!strcmp(protocol, "udp")) {
sendMsg(filename, 0);
				initUDPServer(filename+2, IP);
      	}
      	else {
      		sendMsg(filename, 0);
      	}

      }


}
Esempio n. 8
0
// A handler for the /authorize endpoint.
// Login page form sends user name and password to this endpoint.
static void authorize(struct mg_connection *conn,
                      const struct mg_request_info *request_info) {
  char user[32], password[32], referer[256];

  if(!strcmp(request_info->request_method, "POST")) {
    char post_data[1024];
    int post_data_len = mg_read(conn, post_data, sizeof(post_data));

    mg_get_var(post_data, post_data_len, "user", user, sizeof(user));
    mg_get_var(post_data, post_data_len, "password", password, sizeof(password));
    mg_get_var(post_data, post_data_len, "referer", referer, sizeof(referer));
  } else {
    // Fetch user name and password.
    get_qsvar(request_info, "user", user, sizeof(user));
    get_qsvar(request_info, "password", password, sizeof(password));
    get_qsvar(request_info, "ref", referer, sizeof(referer));
  }

  /* Referer url must begin with '/' */
  if((referer[0] != '/') || (strcmp(referer, AUTHORIZE_URL) == 0))
    strcpy(referer, "/");

  if(ntop->checkUserPassword(user, password)) {
    set_cookie(conn, user, referer);
  } else {
    // Authentication failure, redirect to login.
    redirect_to_login(conn, request_info);
  }
}
Esempio n. 9
0
// A handler for the /authorize endpoint.
// Login page form sends user name and password to this endpoint.
static void authorize(struct mg_connection *conn,
                      const struct mg_request_info *request_info) {
  char user[32], password[32], referer[256];

  if(!strcmp(request_info->request_method, "POST")) {
    char post_data[1024];
    int post_data_len = mg_read(conn, post_data, sizeof(post_data));

    mg_get_var(post_data, post_data_len, "user", user, sizeof(user));
    mg_get_var(post_data, post_data_len, "password", password, sizeof(password));
    mg_get_var(post_data, post_data_len, "referer", referer, sizeof(referer));
  } else {
    // Fetch user name and password.
    get_qsvar(request_info, "user", user, sizeof(user));
    get_qsvar(request_info, "password", password, sizeof(password));
    get_qsvar(request_info, "ref", referer, sizeof(referer));
  }

  /* Referer url must begin with '/' */
  if((referer[0] != '/') || (strcmp(referer, AUTHORIZE_URL) == 0))
    strcpy(referer, "/");

  if(ntop->checkUserPassword(user, password)) {
    char key[256], session_id[64], random[64];

    // Authentication success:
    //   1. create new session
    //   2. set session ID token in the cookie
    //
    // The most secure way is to stay HTTPS all the time. However, just to
    // show the technique, we redirect to HTTP after the successful
    // authentication. The danger of doing this is that session cookie can
    // be stolen and an attacker may impersonate the user.
    // Secure application must use HTTPS all the time.

    snprintf(random, sizeof(random), "%d", rand());

    generate_session_id(session_id, random, user);

    // ntop->getTrace()->traceEvent(TRACE_ERROR, "==> %s\t%s", random, session_id);

    /* http://en.wikipedia.org/wiki/HTTP_cookie */
    mg_printf(conn, "HTTP/1.1 302 Found\r\n"
	      "Set-Cookie: session=%s; path=/; max-age=%u; HttpOnly\r\n"  // Session ID
	      "Set-Cookie: user=%s; path=/; max-age=%u; HttpOnly\r\n"  // Set user, needed by Javascript code
	      "Location: %s%s\r\n\r\n",
	      session_id, HTTP_SESSION_DURATION,
	      user, HTTP_SESSION_DURATION, 
	      ntop->getPrefs()->get_http_prefix(), referer);

    /* Save session in redis */
    snprintf(key, sizeof(key), "sessions.%s", session_id);
    ntop->getRedis()->set(key, user, HTTP_SESSION_DURATION);
    ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Set session sessions.%s", session_id);
  } else {
    // Authentication failure, redirect to login.
    redirect_to_login(conn, request_info);
  }
}
Esempio n. 10
0
bool CManageModule::_HandleConn_Mail(struct mg_connection *conn)
{
	char playerid[MSG_VAR_LEN] = { 0 };
	char mailtitle[MSG_VAR_LEN] = { 0 };
	char item[MSG_VAR_LEN] = { 0 };
	char exp[MSG_VAR_LEN] = { 0 };
	char silver[MSG_VAR_LEN] = { 0 };
	char gold[MSG_VAR_LEN] = { 0 };
	char credit[MSG_VAR_LEN] = { 0 };
	char ap[MSG_VAR_LEN] = { 0 };
	char merit[MSG_VAR_LEN] = { 0 };
	char knight[MSG_VAR_LEN] = { 0 };
	mg_get_var(conn, MSG_VAR_PLAYER, playerid, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILTITLE, mailtitle, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILITEM, item, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILEXP, exp, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILSILVER, silver, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILGOLD, gold, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILCREDIT, credit, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILAP, ap, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILMERIT, merit, MSG_VAR_LEN);
	mg_get_var(conn, MSG_VAR_MAILKNIGHT, knight, MSG_VAR_LEN);

	PersonID pid = atoll(playerid);
	int nType = atoi(mailtitle);
	int nItem = atoi(item);
	int nExp = atoi(exp);
	int nSilver = atoi(silver);
	int nGold = atoi(gold);
	int nCredit = atoi(credit);
	int nAp = atoi(ap);
	int nMerit = atoi(merit);
	int nKnight = atoi(knight);

	if (pid < 1 || nType < 1) {
		Log.Error("Wrong Mail. playerid: %lld, mailtype: %d, item: %d, gold: %d, silver: %d", pid, nType, nItem, nGold, nSilver);
		return false;
	}

	Message::GMManager msg;
	msg.set_playerid(pid);
	msg.set_mailtitle(nType);
	msg.set_item(nItem);
	msg.set_exp(nExp);
	msg.set_silver(nSilver);
	msg.set_gold(nGold);
	msg.set_credit(nCredit);
	msg.set_ap(nAp);
	msg.set_merit(nMerit);
	msg.set_knight(nKnight);

	PACKET_COMMAND pack;
	PROTOBUF_CMD_PACKAGE(pack, msg, B2G_MANAGE_MAIL);
	SendGameMsg(&pack);

	Log.Notice("send mail. player: %s, item: %s, gold: %s, silver: %s", playerid, item, gold, silver);

	return true;
}
Esempio n. 11
0
static void handle_restful_call(struct mg_connection *conn) {
  char n1[100], n2[100];

  // Get form variables
  mg_get_var(conn, "n1", n1, sizeof(n1));
  mg_get_var(conn, "n2", n2, sizeof(n2));

  mg_printf_data(conn, "{ \"result\": %lf }", strtod(n1, NULL) + strtod(n2, NULL));
}
Esempio n. 12
0
void RestfulApi::ApiWrap_Mult(struct mg_connection *conn) {
  char n1[100], n2[100];

  // Get form variables
  mg_get_var(conn, "n1", n1, sizeof(n1));
  mg_get_var(conn, "n2", n2, sizeof(n2));

  mg_printf_data(conn, "{ \"result\": %lf }", strtod(n1, NULL) * strtod(n2, NULL));
}
Esempio n. 13
0
static void check_auth(struct mg_connection *conn) {
	char name[100], password[100];
	// Get form variables
	mg_get_var(conn, "name", name, sizeof(name));
	mg_get_var(conn, "password", password, sizeof(password));
	if (strcmp(name, "1") == 0 && strcmp(password, "1") == 0) {
		mg_send_file(conn, "D:\\Users\\Administrator\\Desktop\\EasyDarwin\\EasyDarwin\\WinNTSupport\\Debug\\index.html", NULL);
	}
	else
	{
		mg_send_file(conn, "D:\\Users\\Administrator\\Desktop\\EasyDarwin\\EasyDarwin\\WinNTSupport\\Debug\\loginerror.html", NULL);
	}
}
Esempio n. 14
0
static void check_auth(struct mg_connection *conn) {
	char name[100], password[100];
	// Get form variables
	mg_get_var(conn, "name", name, sizeof(name));
	mg_get_var(conn, "password", password, sizeof(password));
	if (strcmp(name, "1") == 0 && strcmp(password, "1") == 0) {
		mg_send_file(conn, "index.html", NULL);
	}
	else
	{
		mg_send_file(conn, "loginerror.html", NULL);
	}
}
Esempio n. 15
0
//handler
static int ev_handler(struct mg_connection * conn, enum mg_event ev) {
	struct kvbox * box = 0;
	char key[KEY_MAX_LEN + 1];
	char value[VALUE_MAX_LEN + 1];
	//
	switch(ev) {
		case MG_AUTH:
			return MG_TRUE;
		case MG_REQUEST:
			mg_printf_data(conn, "URI -> %s, QUERY -> %s\n", conn->uri, conn->query_string);
			if(strcmp(conn->uri, "/add.do") == 0) {
				mg_get_var(conn, "key", key, sizeof(key));
				mg_get_var(conn, "value", value, sizeof(value));
				mg_printf_data(conn, "ADD: %s -> %s, %zu\n", key, value, dbox->box_size);
				//
				pthread_mutex_lock(&(dbox->mutex));
				box = dict_add(dbox, key, value);
				pthread_mutex_unlock(&(dbox->mutex));
				//
				if(box) {
					mg_printf_data(conn, "%zu ADD OK\n", dbox->box_size);
				} else {
					mg_printf_data(conn, "%zu ADD FAIL\n", dbox->box_size);
				}
			} else if(strcmp(conn->uri, "/del.do") == 0) {
				mg_get_var(conn, "key", key, sizeof(key));
				//
				pthread_mutex_lock(&(dbox->mutex));
				dict_del(dbox, key);
				pthread_mutex_unlock(&(dbox->mutex));
				//
				mg_printf_data(conn, "DEL %zu %s\n", dbox->box_size, key);
			} else if(strcmp(conn->uri, "/seek.do") == 0) {
				mg_get_var(conn, "key", key, sizeof(key));
				//
				box = dict_seek(dbox, key);
				if(box) {
					mg_printf_data(conn, "SEEK: %s -> %s\n", key, box->value);
				} else {
					mg_printf_data(conn, "SEEK: %s ->\n", key);
				}
			}
			return MG_TRUE;
		default:
			return MG_FALSE;
	}
	//
	return 0;
}
Esempio n. 16
0
void shapefiles_list(struct mg_connection *conn, const struct mg_request_info *ri, void *data)
{
  char * formatc = mg_get_var(conn, "format");
  int json = 0;
  if (formatc != NULL && strcmp(formatc, "json") == 0)
    json = 1;
  free(formatc);
  
  if (json)
  {
    mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nConnection: close\r\n\r\n");
    mg_printf(conn, "[");
  }
  else
  {
    mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n");
    mg_printf(conn, "<table>");
  }
  
  general_count = 0;
  dconn = conn; // dconn used in display_info callback
  int flags = FTW_DEPTH | FTW_PHYS;
  if (nftw(data_path, display_info, 20, flags) == -1) mg_printf(conn, "nftw FAILED\n");
  dconn = NULL;
  
  if (json)
    mg_printf(conn, "\n]\n");
  else
    mg_printf(conn, "</table>");
}
Esempio n. 17
0
    bool Request::readVariable(const char *data, string key, string &output)
    {
        int size = 1024;
        int ret, n;
        char *buffer = new char[size];
        n = strlen(data);

        do {
            ret = mg_get_var(connection, key.c_str(), buffer, size);

            if (ret == -1) {
                return false;
            }

            if (ret == -2) {
                size *= 2;
                delete[] buffer;
                buffer = new char[size];
            }
        } while (ret == -2);

        output = string(buffer);
        delete[] buffer;

        return true;
    }
Esempio n. 18
0
bool CManageModule::OnManageRequest(struct mg_connection *conn)
{
	if (conn == NULL) {
		Log.Error("[ManageModule] conn == NULL.");
		return false;
	}

	if (GetTimeSec() - m_LastOptTime <= MSG_OPT_CIRCLE) {
		return false;
	}

	char mType[MSG_VAR_LEN] = { 0 };
	mg_get_var(conn, MSG_VAR_TYPE, mType, MSG_VAR_LEN);

	switch (atoi(mType))
	{
	case Manage_Msg_Forbid:		return _HandleConn_Forbid(conn);
	case Manage_Msg_Notice:		return _HandleConn_Notice(conn);
	case Manage_Msg_Mail:		return _HandleConn_Mail(conn);
	case Manage_Msg_UnForbid:	return _HandleConn_UnForbid(conn);

	default: 
		Log.Error("[ManageModule] msg type %s wrong.", mType);
		return false;
	}

	Log.Notice("Manage done. ip: %s, port: %d.", conn->remote_ip, conn->remote_port);
}
Esempio n. 19
0
void Server::generateHtml(mg_connection *conn, GUIInterface *inter, sqlite3 *sql, std::string sub, std::string &html)
{
	std::stringstream htmlBuf;

	if (sub == "post")
	{
		char get[256];
		std::vector<int> results;
		// -2 if buffer too small, -1 if not found
		int getResult = mg_get_var(conn, "tags", get, 256);
		if (getResult == -1)
		{
			inter->queryForTags("", results);
		}
		else
		{
			inter->queryForTags(get, results);
		}

		std::vector<std::string> filenames, extensions;
		inter->queryForEntryInfo(results, filenames, extensions);

		htmlBuf << "<html>";
		for (int i = 0; i < filenames.size(); i++)
		{
			std::string &str = filenames[i];
			htmlBuf << "<img src=\"preview/" << str.substr(0, 2) << "/" << str.substr(2, 2) << "/" << str << ".jpg/>";
		}
		htmlBuf << "</html>";
	}

	html = htmlBuf.str();
}
////////////////////////////////////////////////////////////////
///Read post message data and find the value for specified key
void Executive::get_psvar(const char *pdata, const char *name, char *dst, size_t dst_len)
{

	const char *qs = pdata;
	mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);

}
void EquipletScada::mongooseProcessChangeEquipletState(mg_connection* conn, mg_request_info* request_info) {
    char equipletState[64];
    const char* query = request_info->query_string;
    const size_t query_len = strlen(query);

    mg_get_var(query, query_len, "state", equipletState, sizeof(equipletState));

    for(int i = 0; i < STATE_COUNT; i++) {
        std::string testState = equipletState;
        std::transform(testState.begin(), testState.end(), testState.begin(), ::tolower);
        std::replace(testState.begin(), testState.end(),' ', '_');

        std::string equipletStateStr = rexos_statemachine::state_txt[i];
        std::transform(equipletStateStr.begin(), equipletStateStr.end(), equipletStateStr.begin(), ::tolower);
        std::replace(equipletStateStr.begin(), equipletStateStr.end(),' ', '_');

        if(testState == equipletStateStr) {
            actionlib::SimpleActionClient<rexos_statemachine::ChangeStateAction> client(equiplet->getNodeHandle(), equiplet->getEquipletName() + "/change_state");
            rexos_statemachine::ChangeStateGoal goal;
            goal.desiredState = static_cast<rexos_statemachine::State>(i);
            client.sendGoal(goal);

            mg_printf(conn, "%s", ajax_reply_start_success);
            return;
        }
    }

    mg_printf(conn, "%s", ajax_reply_start_failed);
}
Esempio n. 22
0
static int l_conn_get(lua_State *L) {
	int ret;
	const char *key;
	const char *msg;
	static char varbuff[1024];
	struct connection *user_conn;
	user_conn = (struct connection *)luaL_checkudata(L, 1, META_CONN);
	if (!user_conn) {
		msg = "invalid user_conn";
		goto error_ret;
	}
	key = lua_tostring(L, 2);
	if (!key) {
		msg = "invalid param";
		goto error_ret;
	}

	mg_get_var(user_conn->conn, key, varbuff, sizeof(varbuff));
	ret = strlen(varbuff);
	if (!ret)
		lua_pushnil(L);
	else 
		lua_pushlstring(L, varbuff, ret);
	return 1;
error_ret:
	lua_pushnil(L);
	lua_pushfstring(L, "%s", msg);
	return 2;
}
Esempio n. 23
0
// Runs the given 'code' query string in the lua interpreter. 
// Totally not safe, but whatever. 
static void 
eval_script(struct mg_connection *conn,
      const struct mg_request_info *request_info,
      void *user_data) 
{
  char *code = mg_get_var(conn, "code"), *err_str;
  if (code) {
    
    // thread-safe, blocking eval call
    err_str = eval_buffer_write(code);
    if (err_str) {
        mg_printf(conn, "HTTP/1.1 500 Internal Server Error\r\n"
                  "Content-Type: text/plain\r\n\r\n"
                  "Lua error: %s", err_str);
        free(err_str);
    } else {
        mg_printf(conn, "HTTP/1.1 200 OK\r\n"
                  "Content-Type: text/plain\r\n\r\n");        
    }

    mg_free(code);
  } else {
    mg_printf(conn, "HTTP/1.1 400 Bad Request\r\n"
          "Content-Type: text/plain\r\n\r\n"
          "Parameter 'code' not specified");  
  }
}
 std::string ServiceRequest::getParameter(std::string key) {
   char iddata[100];
   memset(&iddata, 0, 100);
   if (_request_info->query_string != NULL) {
     mg_get_var(_request_info->query_string, strlen(_request_info->query_string), key.c_str(), iddata, sizeof (iddata));
   }
   return iddata;
 }
Esempio n. 25
0
int webserver_request_handler(struct mg_connection* conn, enum mg_event ev)
{
	if (ev == MG_REQUEST)	{
		/* check ajax json requests
		 * else just send the file to the client */
		if (strstr(conn->uri, AJAX_HEADER) == conn->uri)	{
			char param1[64];
			char param2[64];

			const char* cmd = conn->uri + strlen(AJAX_HEADER);

			/* read POST data for parameters */
			mg_get_var(conn, "p1", param1, sizeof(param1));
			mg_get_var(conn, "p2", param2, sizeof(param2));

			webserver_runajax(conn, cmd, param1, param2);
		}	else	{
			/* set default 'index.html' for urls with no file references */
			char path[DH_PATH_MAX];
            strcpy(path, WEB_ROOTDIR);
            strcat(path, conn->uri);
			if (util_pathisdir(path))	{
				if (path[strlen(path)-1] != '/')
					strcat(path, "/index.html");
				else
					strcat(path, "index.html");
			}

			/* send back the file to the client */
            file_t f = fio_openmem(mem_heap(), path, FALSE, MID_PRF);
            if (f != NULL)  {
                size_t size;
                void* data = fio_detachmem(f, &size, NULL);
                mg_send_data(conn, data, (uint)size);
                fio_close(f);
            }   else {
                mg_send_status(conn, 404);
            }

		}

        return MG_TRUE;
	}

    return MG_FALSE;
}
Esempio n. 26
0
bool bool_query_param_def(const struct mg_request_info *request_info, const char * param, const bool def) {
    char queryParam[10];
    size_t queryLength = n_strlen(request_info->query_string);
    int res = mg_get_var(request_info->query_string, queryLength, param, queryParam, 10);
    if(res > 0) {
        return (queryParam[0] == '1');
    }
    return def;
}
Esempio n. 27
0
    bool Request::hasVariable(string key)
    {
        const char *dataField;
        char dummy[10];

        // Looking on the query string
        dataField = request->query_string;
        if (dataField != NULL && mg_get_var(dataField, strlen(dataField), key.c_str(), dummy, 1) != -1) {
            return true;
        }

        // Looking on the POST data
        dataField = data.c_str();
        if (dataField != NULL && mg_get_var(dataField, strlen(dataField), key.c_str(), dummy, 1) != -1) {
            return true;
        }

        return false;
    }
Esempio n. 28
0
static void
login_page(struct mg_connection *conn,
		const struct mg_request_info *ri, void *data)
{
	char		*name, *pass, uri[100];
	const char	*cookie;

	name = mg_get_var(conn, "name");
	pass = mg_get_var(conn, "pass");
	cookie = mg_get_header(conn, "Cookie");

	/*
	 * Here user name and password must be checked against some
	 * database - this is step 2 from the algorithm described above.
	 * This is an example, so hardcode name and password to be
	 * admin/admin, and if this is so, set "allow=yes" cookie and
	 * redirect back to the page where we have been redirected to login.
	 */
	if (name != NULL && pass != NULL &&
	    strcmp(name, "admin") == 0 && strcmp(pass, "admin") == 0) {
		if (cookie == NULL || sscanf(cookie, "uri=%99s", uri) != 1)
			(void) strcpy(uri, "/");
		/* Set allow=yes cookie, which is expected by authorize() */
		mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
		    "Location: %s\r\n"
		    "Set-Cookie: allow=yes;\r\n\r\n", uri);
	} else {
		/* Print login page */
		mg_printf(conn, "HTTP/1.1 200 OK\r\n"
		    "content-Type: text/html\r\n\r\n"
		    "Please login (enter admin/admin to pass)<br>"
		    "<form method=post>"
		    "Name: <input type=text name=name></input><br/>"
		    "Password: <input type=password name=pass></input><br/>"
		    "<input type=submit value=Login></input>"
		    "</form>");
	}

	if (name != NULL)
		mg_free(name);
	if (pass != NULL)
		mg_free(pass);
}
Esempio n. 29
0
File: main.c Progetto: undees/cukeup
static void multiply(
    struct mg_connection *conn,
    const struct mg_request_info *request_info,
    void *user_data)
{
    char *multiplier_s   = mg_get_var(conn, "multiplier");
    char *multiplicand_s = mg_get_var(conn, "multiplicand");

    int multiplier   = atol(multiplier_s);
    int multiplicand = atol(multiplicand_s);

    result = multiplier * multiplicand;

    mg_printf(conn,
        "HTTP/1.1 200 OK\r\n\
Content-Type: text/plain\r\n\r\n");

    mg_free(multiplier_s);
    mg_free(multiplicand_s);
}
Esempio n. 30
0
static void
login_page(struct mg_connection *conn,
		const struct mg_request_info *ri, void *data)
{
	char		*name, *pass;

	name = mg_get_var(conn, "UserId");
	pass = mg_get_var(conn, "PassWord");

	/*
	 * Here user name and password must be checked against some
	 * database - this is step 2 from the algorithm described above.
	 * This is an example, so hardcode name and password to be
	 * admin/admin, and if this is so, set "allow=yes" cookie and
	 * redirect back to the page where we have been redirected to login.
	 */
	if (name != NULL && pass != NULL ) {
		/* Print login page */
		mg_printf(conn, "HTTP/1.1 200 OK\r\n"
		    "content-Type: text/html\r\n\r\n"
		    "Name is %s<br>"
            "password is %s<br>",name,pass);
	} else {
		/* Print login page */
		mg_printf(conn, "HTTP/1.1 200 OK\r\n"
		    "content-Type: text/html\r\n\r\n"
		    "Please login (enter admin/admin to pass)<br>"
		    "<form method=post>"
		    "Name: <input type=text name=name></input><br/>"
		    "Password: <input type=password name=pass></input><br/>"
		    "<input type=submit value=Login></input>"
		    "</form>");
	}

	if (name != NULL)
		mg_free(name);
	if (pass != NULL)
		mg_free(pass);

	return ;
}