예제 #1
0
int WebController::HandleJsonRequest(struct mg_connection *conn, const char *object, const char *func) {

  json_token *data = NULL;
  json_token *paramtoken;
  char *content;
  int params;
  int ret;

  content = strndup(conn->content, conn->content_len);
  debug("%s",content);

  free(content);

  data = parse_json2(conn->content, conn->content_len);
  if (data == NULL) {
    debug("parsing api request failed");
    return MG_FALSE;
  }

  params = 0;

  paramtoken = find_json_token(data, "params");
  if (paramtoken != NULL) {
    if (paramtoken->type == JSON_TYPE_OBJECT) {
      params = 1;

    } else if (paramtoken->type == JSON_TYPE_ARRAY) {
      params = paramtoken->num_desc;
    } else {
      params = 1;
    }
  }

  //Reset global response string
  gp_response[0] = '\0';
  //gp_response = (char*) malloc(sizeof(char) * ( MAX_LINE));
  ret = 0;
  if (!strcmp("kmx", object)) {
    if (FUNC_SIGP("loadGlobalFile", 2)) {
      int fileType = -1;
      char * file = NULL;
      toki(paramtoken + 1, &fileType);
      toks(paramtoken + 2, &file, 0);
      if (file != NULL) {
        if(strlen(file) > 0){
          if(fileType == 1){
            this->LoadGcode(file);
          } else if(fileType == 2){
            this->LoadMachineConfiguration(file);
          }
        }
        free(file);
      }
    } else if(FUNC_SIGP("listDir", 1)){
      ListDir(paramtoken);
    } else if (FUNC_SIGP("jog", 2)) {
      int axis;
      int speed;
      toki(paramtoken + 1, &axis);
      toki(paramtoken + 2, &speed);
      this->Jog(axis, speed);
    } else if (FUNC_SIGP("onFeedhold", 0)) {
      this->Feedhold();
    } else if (FUNC_SIGP("onSimulate", 0)) {
      this->Simulate();
    } else if (FUNC_SIGP("onEmergencyStop", 0)) {
      this->EmergencyStop();
    } else if (FUNC_SIGP("onHalt", 0)) {
      this->Halt();
    } else if (FUNC_SIGP("onStep", 0)) {
      this->Step();
    } else if (FUNC_SIGP("onReset", 0)) {
      this->Reset();
    } else if (FUNC_SIGP("onCycleStart", 0)) {
      this->CycleStart();
    } else if(FUNC_SIGP("onUpdateMotionParams", 0)) {
      this->UpdateMotionParams();
    } else if (FUNC_SIGP("onInvokeAction", 1)) {
      BOOL FlushBeforeUnbufferedOperation = FALSE;
      int action;
      toki(paramtoken + 1, &action);
      ret = this->InvokeAction(action,FlushBeforeUnbufferedOperation);
    } else if (FUNC_SIGP("onDoErrorMessage", 1)) {
      char *p1 = NULL;
      toks(paramtoken, &p1, 0);
      this->DoErrorMessage(p1);
      EMIT_RESPONSE("[S]", p1);
      free(p1);
    } else {
      log_info("Function request is not part of API %s",func);
    }
  } else {
    log_info("API not implemented %s",object);
  }

  mg_send_header(conn, "Content-Type", "application/json");

  //Need to send some data or connection will not be closed
  if (gp_response[0] == '\0') {
    EMIT_RESPONSE("N");
  }

  mg_printf_data(conn, "%s", gp_response);

  //free(gp_response);
  free(data);

  return MG_TRUE;
}
예제 #2
0
/* Serve a Cortex object */
static int web_serveObject(struct mg_connection *conn) {
    cx_object o = NULL;

    /* Resolve object based on URI */
    o = cx_resolve(NULL, (cx_string)conn->uri + 2);

    if (!o) {
        mg_send_status(conn, 404);
        mg_printf_data(conn, "404: resource '%s' not found\n", conn->uri);
    } else {
        char option[6];
        cx_bool value = 0;
        cx_bool meta = 0;
        cx_bool scope = 0;

        /* Set correct content type */
        mg_send_header(conn, "Content-Type", "application/json; charset=utf-8");

        /* Determine what to show */
        mg_get_var(conn, "value", option, sizeof(option));
        if (!strcmp(option, "true")) { value = TRUE; }

        mg_get_var(conn, "meta", option, sizeof(option));
        if (!strcmp(option, "true")) { meta = TRUE; }

        mg_get_var(conn, "scope", option, sizeof(option));
        if (!strcmp(option, "true")) { scope = TRUE; }

        if (!(value || meta || scope)) {
            value = TRUE;
        }

        {
            /* Serialize object-value to JSON */
            struct cx_serializer_s serializer = cx_json_ser(CX_PRIVATE, CX_NOT, CX_SERIALIZER_TRACE_NEVER);

            if ((cx_typeof(o)->kind == CX_VOID) && (!meta && !scope)) {
                mg_printf_data(conn, "\n");
            } else {
                mg_printf_data(conn, "[");

                /* Serialize metadata of parents */
                if (meta) {
                    if (web_printParents(conn, cx_parentof(o))) {
                        mg_printf_data(conn, ",");
                    }
                }

                /* Serialize value */              
                {
                    cx_json_ser_t jsonData = {NULL, NULL, 0, 0, 0, meta, value, scope, TRUE};
                    cx_serialize(&serializer, o, &jsonData);
                    mg_printf_data(conn, "%s", jsonData.buffer);
                    cx_dealloc(jsonData.buffer);
                }
                mg_printf_data(conn, "]\n");
            }
        }

        cx_free(o);
    }

    return MG_TRUE;
}
예제 #3
0
void WebController::HandleUploadRequest(struct mg_connection *conn){
  FILE *fp = (FILE *) conn->connection_param;
  if (fp != NULL) {

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

    // Temp file will be destroyed after fclose(), do something with the
    // data here -- for example, parse it and extract uploaded files.
    // As an example, we just echo the whole POST buffer back to the client.
    rewind(fp);
    MappedFile mmFile;
    if(mmapFile(mmFile, fp)){
      debug("Failed to read setup file");
      return;
    }
    size_t filesize=0;

    const char *data;
    int data_len, ofs = 0;
    char var_name[100], file_name[100];
    while ((ofs = mg_parse_multipart(mmFile.addr + ofs, mmFile.mapsize - ofs,
                                     var_name, sizeof(var_name),
                                     file_name, sizeof(file_name),
                                     &data, &data_len)) > 0) {

      FILE * pFile;
      //Add one to skip first slash and make path relative
      if(file_name[0] == '/'){
        pFile = fopen (file_name+1, "w+");
      } else {
        pFile = fopen (file_name, "w+");
      }
      //ConsoleHandler("Writing to file");
      //ConsoleHandler(file_name);
      if(pFile){
        size_t written = fwrite (data , sizeof(char), data_len, pFile);
        if(written != data_len){
          this->DoErrorMessage("Error writing to file");
          //ErrMsgHandler(strerror(errno));
        } else{
          filesize += written;
        }
        if(fclose (pFile) == EOF){
          this->DoErrorMessage("Error closing file");
        }
      } else {
        this->DoErrorMessage("Error saving file");
        this->DoErrorMessage(strerror(errno));
      }

    }

    if(filesize == 0 /*filesize != tmpfilesize*/){
      char msg[256];
      snprintf(msg,256, "Bytes written %ld of %ld",filesize, mmFile.filesize);
      this->DoErrorMessage(msg);
    }
    //need to send response back to client to avoid wating connection
    mg_printf_data(conn,
        "Written %ld bytes to file: %s\n\n",
        filesize,
        file_name);
  } else {
    mg_printf_data(conn, "%s", "Had no data to write...");
  }
  //MG_CLOSE event is not raised by mongoose as expected. Need to close file
  OnEventClose(conn);
}
예제 #4
0
파일: webengine.c 프로젝트: relimited/mame
// This function will be called by mongoose on every new request.
int web_engine::begin_request_handler(struct mg_connection *conn)
{
	astring file_path(mg_get_option(m_server, "document_root"), PATH_SEPARATOR, conn->uri);
	if (filename_endswith(file_path.c_str(), ".lp"))
	{
		FILE *fp = NULL;
		if ((fp = fopen(file_path.c_str(), "rb")) != NULL) {
		fseek (fp, 0, SEEK_END);
		size_t size = ftell(fp);
		fseek (fp, 0, SEEK_SET);
		char *data = (char*)mg_mmap(fp,size);

		lua_State *L = luaL_newstate();
		prepare_lua_environment(conn, L);
		lsp(conn, data, (int) size, L);
		if (L != NULL) lua_close(L);
		mg_munmap(data,size);
		fclose(fp);
		return MG_TRUE;
		} else {
		return MG_FALSE;
		}
	}
	else if (!strncmp(conn->uri, "/json/",6))
	{
		if (!strcmp(conn->uri, "/json/game"))
		{
			return json_game_handler(conn);
		}
		if (!strcmp(conn->uri, "/json/slider"))
		{
			return json_slider_handler(conn);
		}
	}
	else if (!strncmp(conn->uri, "/keypost",8))
	{
		// Is there any sane way to determine the length of the buffer before getting it?
		// A request for a way was previously filed with the mongoose devs,
		// but it looks like it was never implemented.

		// For now, we'll allow a paste buffer of 32k.
		// To-do: Send an error if the paste is too big?
		char cmd_val[32768];

		int pastelength = mg_get_var(conn, "val", cmd_val, sizeof(cmd_val));
		if (pastelength > 0) {
			machine().ioport().natkeyboard().post_utf8(cmd_val);
		}
		// Send HTTP reply to the client
		mg_printf(conn,
			"HTTP/1.1 200 OK\r\n"
			"Content-Type: text/plain\r\n"
			"Content-Length: 2\r\n"        // Always set Content-Length
			"\r\n"
			"OK");

		// Returning non-zero tells mongoose that our function has replied to
		// the client, and mongoose should not send client any more data.
		return MG_TRUE;
	}
	else if (!strncmp(conn->uri, "/keyupload",8))
	{
		char *upload_data;
		int data_length, ofs = 0;
		char var_name[100], file_name[255];
		while ((ofs = mg_parse_multipart(conn->content + ofs, conn->content_len - ofs, var_name, sizeof(var_name), file_name, sizeof(file_name), (const char **)&upload_data, &data_length)) > 0) {
				mg_printf_data(conn, "File: %s, size: %d bytes", file_name, data_length);
		}

		// That upload_data contains more than we need. It also has the headers.
		// We'll need to strip it down to just what we want.

		if ((&data_length > 0) && (sizeof(file_name) > 0))
		{
			// MSVC doesn't yet support variable-length arrays, so chop the string the old-fashioned way
			upload_data[data_length] = '\0';

			// Now paste the stripped down paste_data..
			machine().ioport().natkeyboard().post_utf8(upload_data);
		}
		return MG_TRUE;
	}
	else if (!strncmp(conn->uri, "/cmd",4))
	{
		char cmd_name[64];
		mg_get_var(conn, "name", cmd_name, sizeof(cmd_name));

		if(!strcmp(cmd_name,"softreset"))
		{
			m_machine->schedule_soft_reset();
		}
		else if(!strcmp(cmd_name,"hardreset"))
		{
			m_machine->schedule_hard_reset();
		}
		else if(!strcmp(cmd_name,"exit"))
		{
			m_machine->schedule_exit();
		}
		else if(!strcmp(cmd_name,"togglepause"))
		{
			if (m_machine->paused())
				m_machine->resume();
		else
				m_machine->pause();
		}
		else if(!strcmp(cmd_name,"savestate"))
		{
			char cmd_val[64];
			mg_get_var(conn, "val", cmd_val, sizeof(cmd_val));
			char *filename = websanitize_statefilename(cmd_val);
			m_machine->schedule_save(filename);
		}
		else if(!strcmp(cmd_name,"loadstate"))
		{
			char cmd_val[64];
			mg_get_var(conn, "val", cmd_val, sizeof(cmd_val));
			char *filename = cmd_val;
			m_machine->schedule_load(filename);
		}
		else if(!strcmp(cmd_name,"loadauto"))
		{
			// This is here to just load the autosave and only the autosave.
			m_machine->schedule_load("auto");
		}

		// Send HTTP reply to the client
		mg_printf(conn,
				"HTTP/1.1 200 OK\r\n"
				"Content-Type: text/plain\r\n"
				"Content-Length: 2\r\n"        // Always set Content-Length
				"\r\n"
				"OK");

		// Returning non-zero tells mongoose that our function has replied to
		// the client, and mongoose should not send client any more data.
		return MG_TRUE;
	}
	else if (!strncmp(conn->uri, "/slider",7))
	{
		char cmd_id[64];
		char cmd_val[64];
		mg_get_var(conn, "id", cmd_id, sizeof(cmd_id));
		mg_get_var(conn, "val", cmd_val, sizeof(cmd_val));
		int cnt = 0;
		int id = atoi(cmd_id);
		const slider_state *curslider;
		for (curslider = machine().ui().get_slider_list(); curslider != NULL; curslider = curslider->next)
		{
			if (cnt==id)
				(*curslider->update)(machine(), curslider->arg, NULL, atoi(cmd_val));
			cnt++;
		}
		for (curslider = (slider_state*)machine().osd().get_slider_list(); curslider != NULL; curslider = curslider->next)
		{
			if (cnt==id)
				(*curslider->update)(machine(), curslider->arg, NULL, atoi(cmd_val));
			cnt++;
		}

		// Send HTTP reply to the client
		mg_printf(conn,
				"HTTP/1.1 200 OK\r\n"
				"Content-Type: text/plain\r\n"
				"Content-Length: 2\r\n"        // Always set Content-Length
				"\r\n"
				"OK");

		// Returning non-zero tells mongoose that our function has replied to
		// the client, and mongoose should not send client any more data.
		return MG_TRUE;
	}
	else if (!strncmp(conn->uri, "/screenshot.png",15))
	{
		screen_device_iterator iter(m_machine->root_device());
		screen_device *screen = iter.first();

		if (screen == NULL)
		{
			return 0;
		}

		astring fname("screenshot.png");
		emu_file file(m_machine->options().snapshot_directory(), OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS);
		file_error filerr = file.open(fname.c_str());

		if (filerr != FILERR_NONE)
		{
			return 0;
		}

		m_machine->video().save_snapshot(screen, file);
		astring fullpath(file.fullpath());
		file.close();
		mg_send_header(conn, "Cache-Control", "no-cache, no-store, must-revalidate");
		mg_send_header(conn, "Pragma", "no-cache");
		mg_send_header(conn, "Expires", "0");
		mg_send_file(conn, fullpath.c_str(), NULL);
		return MG_MORE; // It is important to return MG_MORE after mg_send_file!
	}
	return 0;
}
예제 #5
0
파일: oc8top.c 프로젝트: sousa-lucas/ec8top
static int ev_handler(struct mg_connection *conn, 
                      enum mg_event ev) {
  char buffer[tamanho_buffer];
  buffer[0] = '\x0';

  switch (ev) {
    case MG_AUTH:
	return MG_MORE;
    case MG_REQUEST:
    //PAGE REQUEST
    //EVERY REQUEST, EITHER BY TYPING URL
    //OR CALL CSS OR JAVASCRIPT
    //ENABLE THIS FUNCTION
    //printf("[%d] %s\n", strlen(conn->uri), conn->uri);
	
	//IF THE URL IS THE NAME OF THE FUNCTIONS, THE MOONGOSE RETURNS THE HTML REFERS TO THEM
	if (strcmp (conn->uri, "/dinamic_versaoso") == 0){

		mg_send_header(conn, "Content-Type", "text/html");

		//ADDS INFORMATIONS O.S
		versaoso(buffer, sizeof(buffer));
		
		mg_printf_data(conn, buffer);
		return MG_TRUE;

	}

        if (strcmp (conn->uri, "/dinamic_numprocessos") == 0){

		mg_send_header(conn, "Content-Type", "text/html");

		//ADDS INFORMATIONS ABOUT THE CṔU USAGE
		cpu_resultado(buffer, sizeof(buffer));

		//ADDS INFORMATIONS ABOUT THE LOAD AVERAGE
		load_average(buffer, sizeof(buffer));

		//ADDS INFORMATIONS ON THE NUMBER OS PROCESSES RUNNING
		numprocessos(buffer, sizeof(buffer));
		
		mg_printf_data(conn, buffer);
		return MG_TRUE;
	}

        if (strcmp (conn->uri, "/dinamic_infomemoria") == 0){

		mg_send_header(conn, "Content-Type", "text/html");

		//ADDS INFORMATIONS FROM MEMORY RAM 
		infomemoria(buffer, sizeof(buffer));

		mg_printf_data(conn, buffer);
		return MG_TRUE;
	}

	if (strcmp (conn->uri, "/dinamic_bateria") == 0){

		mg_send_header(conn, "Content-Type", "text/html");

		//ADDS BATTERY INFORMATION
		bateria(buffer, sizeof(buffer));

		mg_printf_data(conn, buffer);
		return MG_TRUE;
	}

	//IF YOU HAVE NOTHING IN THE URL IT PEFORMS THIS TEXT, OTHERWISE EXECUTE THE URL
	if(strlen(conn->uri)<=1){
		mg_send_header(conn, "Content-Type", "text/html");

		segmento_inicial(buffer, sizeof(buffer));

		segmento_final(buffer, sizeof(buffer));

    		mg_printf_data(conn, buffer);

    		return MG_TRUE;
    	}
    default: return MG_FALSE;
  }
}
예제 #6
0
파일: web.c 프로젝트: hmflash/tikitank
static
void effects_post(struct mg_connection* conn) {
	int len1;
	int len2;
	char kind[256];
	char arg1[256];
	char arg2[256];
	struct channel* channel;

	settings_load();

	len1 = mg_get_var(conn, KIND, kind, sizeof(kind));
	if (len1 < 0) {
		mg_printf_data(conn, "Missing field: " KIND);
		mg_send_status(conn, 400);
		return;
	}

	if(!strncmp(kind, "treads", sizeof(kind))) {
		channel = &channel_treads;
	} else if(!strncmp(kind, "barrel", sizeof(kind))) {
		channel = &channel_barrel;
	} else if(!strncmp(kind, "panels", sizeof(kind))) {
		channel = &channel_panels;
	} else {
		mg_printf_data(conn, "Invalid kind");
		mg_send_status(conn, 400);
		return;
	}
	
	len1 = mg_get_var(conn, ACTIVE, arg1, sizeof(arg1));
	if (len1 > 0) {
		long idx;

		LOG(("selectEffect: kind=%s active=%s\n", kind, arg1));

		idx = strntol(arg1, len1, 10);
		if (idx >= 0 && idx < channel->num_effects) {
			channel->active = idx;
			effects_post_reply(conn);
			return;
		}

		mg_printf_data(conn, "Invalid effect");
		mg_send_status(conn, 400);
		return;
	}

	len1 = mg_get_var(conn, IS_SSAVER, arg1, sizeof(arg1));
	if (len1 > 0) {
		LOG(("setEffectScreenSaver: %s\n", arg1));
		if (!strncmp(arg1, "true", sizeof(arg1))) {
			channel->effects[channel->active]->screen_saver = 1;
		} else {
			channel->effects[channel->active]->screen_saver = 0;
		}
		effects_post_reply(conn);
		return;
	}

	len1 = mg_get_var(conn, COLOR, arg1, sizeof(arg1));
	len2 = mg_get_var(conn, ARGUMENT, arg2, sizeof(arg2));

	if (len1 > 0 && len2 > 0) {
		long idx = strntol(arg2, len2, 10);
		long color = strntol(arg1+1, len1-1, 16);
		LOG(("setEffectParameters: %ld, %lx\n", idx, color));
		if (idx < NUM_PANELS/3) {
			channel->effects[channel->active]->color_arg.colors[idx].value = color;
		}
		effects_post_reply(conn);
		return;
	} else if (len1 > 0) {
		long color = strntol(arg1+1, len1-1, 16);
		LOG(("setEffectColor: %lx\n", color));
		channel->effects[channel->active]->color_arg.color.value = color;
		effects_post_reply(conn);
		return;
	} else if (len2 > 0) {
		long value = strntol(arg2, len2, 10);
		LOG(("setEffectArgument: %ld\n", value));
		channel->effects[channel->active]->argument = value;
		effects_post_reply(conn);
		return;
	}

	mg_printf_data(conn, "Invalid data");
	mg_send_status(conn, 400);
}
예제 #7
0
파일: common.c 프로젝트: toha/DCAF
int http_send_error(struct mg_connection *conn, int status_code, char *msg) {
    mg_send_status(conn, status_code);
    mg_printf_data(conn, msg);
    return MG_TRUE;
}
예제 #8
0
파일: checkip.c 프로젝트: Papafox/checkip
static void checkip_sitemap(struct mg_connection *conn) {
    const char* remote_ip = conn->remote_ip;
    send_headers(conn);
    mg_printf_data(conn, sitemap);
    log_msg(daemon_mode, "sitemap.xml sent to %s", remote_ip);
}
예제 #9
0
파일: expand.cpp 프로젝트: FreshMa/chann
        void render(mg_connection* conn, int id, bool reverse){
            ConfigManager configs;
            // int id = cc_extract_uri_num(conn);

            int limit, count;
            auto r = unq_read_thread_sp(pDb, 0); // get the root thread
            count = r.get()->childCount;
            limit = count - configs.global().get<int>("user::viewable_threads");
            // delete r;

            if (id < 0 || (id < limit && limit != 0) || id > count){
                views::info::render(conn, templates.invoke("misc").toggle("invalid_thread_no").build_destory().c_str());
                return;
            }

            r = unq_read_thread_sp(pDb, id); // get the root thread
            int pid = unq_thread_parent(pDb, r.get());
            
            if ((pid == -1) && !is_admin(conn)){
                views::info::render(conn, templates.invoke("misc").toggle("invalid_thread_no").build_destory().c_str());
                // delete r;
                return;
            }
            
            templates.invoke("site_header").toggle("thread_page").toggle("is_admin", is_admin(conn)) \
                .var("THREAD_NO", id).var("THREAD_TITLE", r.get()->author).pipe_to(conn).destory();

            templates.invoke("single_thread_header").toggle("homepage", !pid).var("THREAD_NO", id) \
                .var("PARENT_NO", pid).toggle("thread", strstr(conn->uri, "/thread/")).pipe_to(conn).destory();
            
            clock_t startc = clock();

            // bool reverse = strstr(conn->uri, "/daerht/");
            bool admin_view = is_admin(conn);
            string username = cck_verify_ssid(conn);

            views::each_thread(conn, r.get(), 0, admin_view);
            mg_printf_data(conn, "<hr>");

            char iid[10];
            strcpy(iid, r.get()->ssid);

            if(!configs.global().get<bool>("archive"))
                templates.invoke("post_form") \
                    .var("THREAD_NO", to_string(id)).toggle("reply_to_thread"). \
                    toggle("is_admin", admin_view || !is_assist(conn).empty()).pipe_to(conn).destory();
                
            if (r.get()->childThread) {
                // int r_childThread = r->childThread;
                // delete r;

                int limit = configs.global().get<int>("user::collapse_image");

                r = unq_read_thread_sp(pDb, r.get()->childThread); // beginning of the circle
                int rid = r.get()->threadID; //the ID
                bool too_many_replies = (r.get()->childCount > limit);

                int di = 1;

                if(reverse)
                {
                    int n_rid = r.get()->prevThread;
                    // delete r;
                    r = unq_read_thread_sp(pDb, r.get()->prevThread);

                    views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK, admin_view, iid, username.c_str());

                    while (r.get()->prevThread != n_rid){
                        di++;
                        // int r_prevThread = r->prevThread;

                        // delete r;
                        r = unq_read_thread_sp(pDb, r.get()->prevThread);

                        if(too_many_replies && (di > limit))
                            views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK + SEND_CUT_IMAGE, admin_view, iid, username.c_str());
                        else
                            views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK, admin_view, iid, username.c_str());
                    }
                }
                else
                {
                    views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK, admin_view, iid, username.c_str());

                    while (r.get()->nextThread != rid){
                        // int r_nextThread = r->nextThread;
                        // delete r;

                        r = unq_read_thread_sp(pDb, r.get()->nextThread);
                        di++;

                        //views::each_thread(conn, r, true, true, false, too_many_replies && (di > 20), admin_view, iid);
                        if(too_many_replies && (di > limit))
                            views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK + SEND_CUT_IMAGE, admin_view, iid, username.c_str());
                        else
                            views::each_thread(conn, r.get(), SEND_IS_REPLY + SEND_SHOW_REPLY_LINK, admin_view, iid, username.c_str());
                    }

                    // if(r) delete r;
                } 
            }

            clock_t endc = clock();

            // site_footer(conn, (float)(endc-startc)/CLOCKS_PER_SEC);
            templates.invoke("site_footer").var("TIME", (int)((endc-startc) * 1000 / CLOCKS_PER_SEC)).pipe_to(conn).destory();
        }
예제 #10
0
파일: single.cpp 프로젝트: FreshMa/chann
    void each_thread(mg_connection* conn, struct Thread* r, char display_state, bool admin_view, 
        const char* iid,
        const char* uid){
        time_t now = time(NULL);

        string thread_post_time = cc_timestamp_to_time(r->date);
        int diff_day = cc_timestamp_diff_day(now, r->date);

        const char* content = unq_read_string(pDb, r->content);
        string thread_content(content);
        delete [] content;

        if((display_state & SEND_CUT_LONG_COMMENT) && thread_content.size() > 1024) 
            thread_content = thread_content.substr(0, 1024) + templates.invoke("misc").toggle("more_contents").build_destory();
            //+ "<font color='red'><b>&#128065;" + STRING_MORE + "</b></font>";

        HTMLTemplate *ht = templates.invoke_pointer("single_thread");

        map<string, bool> stats;
        map<string, string> vars;

        ConfigManager c;

        stats["reply"]                      = display_state & SEND_IS_REPLY;
        stats["show_reply"]                 = display_state & SEND_SHOW_REPLY_LINK;
        stats["archive"]                    = c.global().get<bool>("archive");
        stats["normal_display"]             = r->state & NORMAL_DISPLAY || admin_view;
        stats["thread_poster_is_admin"]     = (strcmp(r->ssid, "Admin") == 0);
        stats["thread_poster_is_sameone"]   = (strcmp(r->ssid, iid) == 0);
        stats["is_sameone"]                 = (strcmp(r->ssid, uid) == 0);
        stats["sage"]                       = (r->state & SAGE_THREAD && !stats["reply"]);
        stats["lock"]                       = (r->state & LOCKED_THREAD);
        stats["delete"]                     = !(r->state & NORMAL_DISPLAY);
        stats["show_admin"]                 = admin_view;
        if (strlen(r->imgSrc) >= 4){
            string fname(r->imgSrc);
            vars["THREAD_IMAGE"]            = fname;

            if (!cc_valid_image_ext(fname).empty()){
                stats["image_attached"]     = true;
                if(display_state & SEND_CUT_IMAGE){
                    struct stat st;
                    stat(("images/" + fname).c_str(), &st);
                    stats["show_size_only"] = true;
                    vars["THREAD_IMAGE_SIZE"] = to_string((int)(st.st_size / 1024));
                }
                else{
                    stats["show_full_image"] = true;
                    vars["THREAD_THUMB_PREFIX"] = c.global().get("image::thumb_prefix");
                }
            }else{
                stats["file_attached"]      = true;
            }
        }
        if(r->childThread && !(display_state & SEND_CUT_REPLY_COUNT)){
            struct Thread* c = unq_read_thread(pDb, r->childThread);
            const char *first_reply = unq_read_string(pDb, c->content);
            string display_reply = (c->state & NORMAL_DISPLAY) ? string(first_reply) : "";

            stats["show_num_replies"]       = true;
            vars["NUM_REPLIES"]             = to_string(c->childCount);
            vars["FIRST_REPLY"]             = cc_smart_shorten(display_reply);// display_reply.substr(0, display_reply.find_first_of("<")).substr(0,15);

            delete c;
            delete[] first_reply;
        }

        vars["THREAD_POSTER"]               = string(r->ssid);
        vars["THREAD_NO"]                   = to_string(r->threadID);
        vars["THREAD_CONTENT"]              = thread_content;

        // stats["show_title"]					= !stats["reply"] || strcmp(r->author, STRING_UNTITLED) != 0;
        vars["THREAD_TITLE"]                = string(r->author);

        vars["THREAD_IP"]                   = string(r->email);
        vars["THREAD_POST_TIME"]            = thread_post_time;
        vars["THREAD_STATE"]                = to_string(r->state);

        if(diff_day >= 0 && diff_day <= 2){
            stats["show_easy_date"]         = true;
            vars["THREAD_POST_DATE"]        = to_string(diff_day);
        }else{
            char timetmp[64];
            struct tm post_date;
            localtime_r(&(r->date), &post_date);

            strftime(timetmp, 64, "%Y-%m-%d", &post_date);
            vars["THREAD_POST_DATE"]        = string(timetmp);
        }

        map<string, queue<string>> loops; //nothing

        mg_printf_data(conn, "%s", ht->build(vars, stats, loops).c_str());

        // if(content) delete [] content;
        delete ht;
    }
예제 #11
0
int Server::eventHandler(mg_connection *conn, mg_event event)
{
	std::vector<std::string> path;
	switch (event)
	{
	case MG_POLL: return MG_FALSE;
	case MG_AUTH: return MG_TRUE;
	case MG_REQUEST:
		byte buffer[1024];
		int length;
		std::string newUri = conn->uri;
		newUri = newUri.substr(1); // Get rid of the first slash
		
		std::vector<std::string> path;
		splitString(newUri, '/', path);
		if (path.size() == 0)
		{
			mg_send_header(conn, "Content-Type", "text/plain");
			std::stringstream html;
			html << "This is going to be the home screen.\nIncoming IP: " << conn->remote_ip << "\nLocal IP: " << conn->local_ip;
			mg_printf_data(conn, html.str().c_str());
			return MG_TRUE;
		}
		else if (path[0] == "admin")
		{
			if (!(strcmp(conn->remote_ip, "127.0.0.1") == 0))
			{
				mg_send_header(conn, "Content-Type", "text/plain");
				mg_printf_data(conn, "You are not authorized to view this page.");
				return MG_TRUE;
			}
			mg_send_header(conn, "Content-Type", "text/plain");
			mg_printf_data(conn, "Admin page here.");
			return MG_TRUE;
		}
		else if (path[0] == "post")
		{
			mg_send_header(conn, "Content-Type", "text/html");
			std::string html;
			generateHtml(conn, static_cast<serveArgs*>(conn->server_param)->inter, static_cast<serveArgs*>(conn->server_param)->sql, "post", html);

			mg_printf_data(conn, html.c_str());
			return MG_TRUE;
		}
		else if (path[0] == "images" || path[0] == "preview" || path[0] == "movies")
		{
			FILE *f = fopen(newUri.c_str(), "rb");
			if (f)
			{
				std::string ext;
				getExtension(newUri, ext);
				std::string mime = getMimeType(ext.c_str());
				mg_send_header(conn, "Content-Type", mime.c_str());
				length = fread(buffer, 1, sizeof(buffer), f);
				while (length > 0)
				{
					mg_send_data(conn, buffer, length);
					length = fread(buffer, 1, sizeof(buffer), f);
				}
				fclose(f);
				return MG_TRUE;
			}
			else
			{
				mg_send_header(conn, "Content-Type", "text/plain");
				mg_printf_data(conn, "Error: couldn't find file [%s].\n", newUri.c_str());
				return MG_TRUE;
			}
		}
	}
}
예제 #12
0
static int handle_request(struct mg_connection *conn)
{
    char * json_data;
    cJSON *root;
    char *json;
    char *title;
    char *description;
    int completed;
    if (!strcmp(conn->request_method, "POST") && !strncmp(conn->uri, "/api/v1",strlen("/api/v1"))) 
    {
        printf("api v1\n");
        json_data = get_post_data(conn);
        if(json_data == NULL)
        {
            printf("Error json data: NULL\n");
            mg_printf_data(conn, "%s","Error jason data:NULL");
            free(json_data);
            return MG_TRUE;   // Tell mongoose to close this connection
        }
        printf("input json data: %s\n", json_data);
        root = cJSON_Parse(json_data);
        if (root == NULL)
        {
            mg_printf_data(conn, "%s","Error jason data:Wrong format");
            free(json_data);
            return MG_TRUE;
        }

        if (!strncmp(conn->uri,"/api/v1/cars", strlen("/api/v1/cars")))
        {   
            int id;
            char *name;
            int price;
            sqlite3 *db;
            char *err_msg = 0; 
            id = cJSON_GetObjectItem(root,"Id")->valueint;
            name = cJSON_GetObjectItem(root,"Name")->valuestring;
            price = cJSON_GetObjectItem(root,"Price")->valueint;
            printf("id = %d,Name = %s, Price=%d",id,name,price);
            int rc = sqlite3_open("quanta.db", &db);
            if (rc != SQLITE_OK) 
            {
            
                fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
                sqlite3_close(db);        
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            char sql[100];
            sprintf(sql,"INSERT INTO Cars VALUES(%d, '%s', %d);",id,name,price);
            rc = sqlite3_exec(db, sql, 0, 0, &err_msg);
            if (rc != SQLITE_OK ) {
        
                fprintf(stderr, "SQL error: %s\n", err_msg);
        
                sqlite3_free(err_msg);        
                sqlite3_close(db);
        
                return MG_TRUE;   // Tell mongoose to close this connection
            } 
            sqlite3_free(err_msg);        
            sqlite3_close(db);
        }
        else
        {
            description = cJSON_GetObjectItem(root,"description")->valuestring; 
            title = cJSON_GetObjectItem(root,"title")->valuestring; 
            completed = cJSON_GetObjectItem(root,"completed")->valueint; 
            printf("title = %s,description = %s, completed = %d\n",title,description,completed);
        }
        json = cJSON_PrintUnformatted(root);
        write_json_result(conn, 0, json);
        free(json_data);
        return MG_TRUE;   // Tell mongoose to close this connection
    }
    else if (!strcmp(conn->request_method, "GET") && !strncmp(conn->uri, "/api/v1",strlen("/api/v1"))) 
    {
        sqlite3 *db;
        char *err_msg = 0; 
        char sql[100];
        int id;
        char response_buff[100];
        printf("get api v1\n");
        if(!strncmp(conn->uri,"/api/v1/cars",strlen("/api/v1/cars")))
        {
            sscanf(conn->uri,"/api/v1/cars/%d/",&id);
            int rc = sqlite3_open("quanta.db", &db);
            if (rc != SQLITE_OK) 
            {
            
                fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
                sqlite3_close(db);        
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            sprintf(sql,"SELECT * FROM Cars WHERE Id = %d",id);
            rc = sqlite3_exec(db,sql, callback, response_buff, &err_msg);
        
            if (rc != SQLITE_OK ) {
                
                fprintf(stderr, "Failed to select data\n");
                fprintf(stderr, "SQL error: %s\n", err_msg);

                sqlite3_free(err_msg);
                sqlite3_close(db);
                
                return MG_TRUE;   // Tell mongoose to close this connection
            } 
            else
            {
                mg_printf_data(conn,"%s",response_buff);
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            sqlite3_close(db);
        }
        else
        {
            mg_printf_data(conn, "%s","Not Support");
            return MG_TRUE;   // Tell mongoose to close this connection
        }
    }
    else if (!strcmp(conn->request_method, "DELETE") && !strncmp(conn->uri, "/api/v1/cars/",strlen("/api/v1/cars/"))) 
    {
        char sql[100];
        int id;
        sqlite3 *db;
        char *err_msg = 0; 
        sscanf(conn->uri,"/api/v1/cars/%d",&id);
        if (id != 0)
        {
            int rc = sqlite3_open("quanta.db", &db);
            if (rc != SQLITE_OK) 
            {
            
                fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
                sqlite3_close(db);        
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            sprintf(sql,"DELETE FROM Cars WHERE ID = %d;",id);
            rc = sqlite3_exec(db,sql, 0, 0, &err_msg);
            if (rc != SQLITE_OK ) {
                
                fprintf(stderr, "Failed to select data\n");
                fprintf(stderr, "SQL error: %s\n", err_msg);

                sqlite3_free(err_msg);
                sqlite3_close(db);
                
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            sqlite3_free(err_msg);        
            sqlite3_close(db);

            mg_printf_data(conn, "Delete %d record from Cars table",id);
            return MG_TRUE;   // Tell mongoose to close this connection
        }
    }
    else if (!strcmp(conn->request_method, "PUT") && !strncmp(conn->uri, "/api/v1/cars/",strlen("/api/v1/cars/"))) 
    {
        char sql[100];
        int id;
        sqlite3 *db;
        char *err_msg = 0; 
        char *json_data;
        sscanf(conn->uri,"/api/v1/cars/%d",&id);
        if (id != 0)
        {
            json_data = get_post_data(conn);
            if(json_data == NULL)
            {
                printf("Error json data: NULL\n");
                mg_printf_data(conn, "%s","Error jason data:NULL");
                free(json_data);
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            printf("input json data: %s\n", json_data);
            root = cJSON_Parse(json_data);
            if (root == NULL)
            {
                mg_printf_data(conn, "%s","Error jason data:Wrong format");
                free(json_data);
                return MG_TRUE;
            }
            char *name;
            int price;
            name = cJSON_GetObjectItem(root,"Name")->valuestring;
            price = cJSON_GetObjectItem(root,"Price")->valueint;
            printf("id = %d,Name = %s, Price=%d",id,name,price);
            int rc = sqlite3_open("quanta.db", &db);
            if (rc != SQLITE_OK) 
            {
            
                fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
                sqlite3_close(db);        
                return MG_TRUE;   // Tell mongoose to close this connection
            }
            char sql[100];
            sprintf(sql,"UPDATE Cars SET Name = '%s', Price = %d WHERE ID = %d;",name,price,id);
            rc = sqlite3_exec(db, sql, 0, 0, &err_msg);
            if (rc != SQLITE_OK ) {
        
                fprintf(stderr, "SQL error: %s\n", err_msg);
        
                sqlite3_free(err_msg);        
                sqlite3_close(db);
        
                return MG_TRUE;   // Tell mongoose to close this connection
            } 
            sqlite3_free(err_msg);        
            sqlite3_close(db);

            mg_printf_data(conn, "UPDATE Cars table %d record",id);
            free(json_data);
            return MG_TRUE;   // Tell mongoose to close this connection
        }
    }
    else 
    {
        printf("else %d\n",__LINE__);
        mg_printf_data(conn, "%s","Not Support");
        return MG_TRUE;   // Tell mongoose to close this connection
    }
    return MG_TRUE;   // Tell mongoose to close this connection
}