Пример #1
0
static int
request_test_handler(struct mg_connection *conn, void *cbdata)
{
	int i;
	char chunk_data[32];
	const struct mg_request_info *ri;
	struct mg_context *ctx;
	void *ud, *cud;

	ctx = mg_get_context(conn);
	ud = mg_get_user_data(ctx);
	ri = mg_get_request_info(conn);

	ck_assert(ri != NULL);
	ck_assert(ctx == g_ctx);
	ck_assert(ud == &g_ctx);

	mg_set_user_connection_data(conn, (void *)6543);
	cud = mg_get_user_connection_data(conn);
	ck_assert_ptr_eq((void *)cud, (void *)6543);

	ck_assert_ptr_eq((void *)cbdata, (void *)7);
	strcpy(chunk_data, "123456789A123456789B123456789C");

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

	for (i = 1; i <= 10; i++) {
		mg_printf(conn, "%x\r\n", i);
		mg_write(conn, chunk_data, (unsigned)i);
		mg_printf(conn, "\r\n");
	}

	mg_printf(conn, "0\r\n\r\n");

	return 1;
}
Пример #2
0
// Satisfies the HTTP request from memory, or returns a 404 error. The
// filesystem is never touched.
// Ideally we'd use Mongoose's open_file callback override to implement file
// serving from memory instead, but that method provides no way to disable
// caching or display directory index documents.
static void serve_file_from_memory_or_404(struct mg_connection *connection) {
  const struct mg_request_info *request_info = mg_get_request_info(connection);
  const char *uri = request_info->uri;
  // If the root of the server is requested, display the index instead.
  if (strlen(uri) < 2) {
    uri = "/index.html";
  }
  // Construct the file's full path relative to the document root.
  const int max_path = 2048;
  char file_path[max_path];
  size_t path_length = strlen(uri) + strlen(document_root) + 1;
  const char *file = NULL;
  size_t file_size = 0;
  if (path_length < max_path) {
    snprintf(file_path, path_length, "%s%s", document_root, uri);
    file = get_file(file_path, &file_size);
  }
  if (file) {
    // We've located the file in memory. Serve it with headers to disable
    // caching.
    mg_printf(connection, "HTTP/1.1 200 OK\r\n"
              "Cache-Control: no-cache\r\n"
              "Content-Type: %s\r\n"
              "Content-Length: %lu\r\n"
              "Connection: close\r\n\r\n",
              mg_get_builtin_mime_type(file_path),
              file_size);
    mg_write(connection, file, file_size);
  } else {
    // The file doesn't exist in memory.
    mg_printf(connection, "HTTP/1.1 404 Not Found\r\n"
              "Cache-Control: no-cache\r\n"
              "Content-Type: text/plain; charset=utf-8\r\n"
              "Content-Length: 25\r\n"
              "Connection: close\r\n\r\n"
              "Error 404: File not found");
  }
}
void TMongCliContext::Respond(const PHttpResp& HttpResp) {
	const TMem& Body = HttpResp->GetBodyAsMem();
	TStr ResponseHeader = HttpResp->GetHdStr();
	mg_write(Conn, ResponseHeader.CStr(), ResponseHeader.Len());
	mg_write(Conn, Body.GetBf(), Body.Len());
}
Пример #4
0
bool write_quad_model_as_bmp(struct mg_connection *conn, quad_model* model)
{
    int width = 640;
    int height = 320;

    HWND hWND = CreateWindow(_T("BUTTON"),
                             NULL,
                             WS_OVERLAPPEDWINDOW /*| WS_VISIBLE*/ | CS_OWNDC,
                             0, 0, width, height,
                             NULL, NULL, NULL, NULL);

    HDC hDC = GetDC(hWND);
    int pixelForamt = ChoosePixelFormatEx(hDC, false);
    PIXELFORMATDESCRIPTOR pfd = {0};
    BOOL bRet = SetPixelFormat(hDC, pixelForamt, &pfd);
    HGLRC hRC = wglCreateContext(hDC);

    bRet = wglMakeCurrent(hDC, hRC);

    GLenum err = glewInit( );
    if( GLEW_OK != err )
        return false;

    if( !GLEW_VERSION_2_1 )  // check that the machine supports the 2.1 API.
        return false;
    //
    //    if( !GLEW_ARB_framebuffer_object)  // check that the machine supports the 2.1 API.
    //        return false;

    //if( !GLEW_VERSION_3_1 )  // check that the machine supports the 2.1 API.
    //    return false;


    // create a texture object
    GLuint textureId = 0;
    glGenTextures(1, &textureId);
    glBindTexture(GL_TEXTURE_2D, textureId);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glBindTexture(GL_TEXTURE_2D, 0);

    // create a renderbuffer object to store depth info
    GLuint rboId = 0;
    glGenRenderbuffersEXT(1, &rboId);
    glBindRenderbufferEXT(GL_RENDERBUFFER, rboId);
    glRenderbufferStorageEXT(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
    glBindRenderbufferEXT(GL_RENDERBUFFER, 0);

    // create a framebuffer object
    GLuint fboId = 0;
    glGenFramebuffersEXT(1, &fboId);
    glBindFramebufferEXT(GL_FRAMEBUFFER, fboId);

    // attach the texture to FBO color attachment point
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);

    // attach the renderbuffer to depth attachment point
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboId);

    bool fboUsed = true;
    // check FBO status
    GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
    if(status != GL_FRAMEBUFFER_COMPLETE)
        fboUsed = false;

    glBindFramebufferEXT(GL_FRAMEBUFFER, fboId);

    glViewport(0, 0, width, height);
    glClearColor(1, 1, 0, 1);

    //glPushAttrib(GL_COLOR_BUFFER_BIT | GL_PIXEL_MODE_BIT); // for GL_DRAW_BUFFER and GL_READ_BUFFER
    //glDrawBuffer(GL_BACK);
    //glReadBuffer(GL_BACK);
    assert(0 == glGetError());

    //glClear(GL_FRONT_AND_BACK);
    assert(0 == glGetError());

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    double aspect = width / (double)height;
    glOrtho(-3, 3, -3/aspect, 3/aspect, -1, 1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glTranslated(-1.5, 0, 0);

    //glUseProgram(0);
    DrawQuad();

    glTranslated(1.5, 0, 0);
    //glPopAttrib();

    quad_modelRender qr;
    qr.Setquad_model(model);

    char logbuffer[1024] = "";
    int loglen = ARRAYSIZE(logbuffer);
    qr.Initialize(logbuffer, &loglen);
    assert(0 == glGetError());

    qr.Render();
    assert(0 == glGetError());

    glFinish();

    GLenum error = glGetError();

    int bits = 24;

    std::vector<unsigned char> buffer;
    buffer.resize( width * height * bits / 8 );

    glBindTexture(GL_TEXTURE_2D, textureId);
    glPixelStorei(GL_PACK_ALIGNMENT, 1);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_BGR, GL_UNSIGNED_BYTE, &buffer[0]);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hRC);
    ReleaseDC(hWND, hDC);
    //CloseWindow(hWND);

    BITMAPFILEHEADER bfh = {0};
    bfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + buffer.size();
    bfh.bfType = 0x4D42;
    bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

    BITMAPINFOHEADER bih = {};
    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biWidth= width;
    bih.biHeight= height;
    bih.biPlanes= 1;
    bih.biBitCount= bits;

    // image/bmp
    mg_write(conn, &bfh, sizeof(bfh));
    mg_write(conn, &bih, sizeof(bih));
    mg_write(conn, &buffer[0], buffer.size());
}
Пример #5
0
void MushiRequest::write(char *data){

    mg_write(this->conn,data,strlen(data));
}
Пример #6
0
static int adapt_serve(struct mg_connection* connection) {
    struct mg_request_info* request = mg_get_request_info(connection);
    adapt_serving_context* context = (adapt_serving_context*)request->user_data;
    const char* uri = request->uri;
    // char buf[1024];
    // sprintf(buf, "Requested uri '%s'\n", uri);
    // OutputDebugStringA(buf);
    if (strncmp(uri, context->content_prefix, strlen(context->content_prefix)) == 0) {
        const char* file_name = uri + strlen(context->content_prefix);
        if (context->callback->packaging_type == ADAPT_PACKAGE_ZIP) {
            if (*file_name == '\0') {
                // Special case, query about file structure
                const char * r = strstr(request->query_string, "r=");
                if (r && adapt_serve_zip_metadata(request->request_method, connection, context, r+2)) {
                    return 1;
                }
            } else if (adapt_serve_zip_entry(connection, context, file_name)) {
                return 1;
            }
        } else if (context->callback->packaging_type == ADAPT_PACKAGE_SINGLE_FILE) {
            // plain fb2 file, no external resources
            if (strcmp(file_name, "file.fb2") == 0) {
                char buf[4096];
                size_t p = 0;
                mg_printf(connection,
                          "HTTP/1.1 200 Success\r\n"
                          "Content-Type: text/xml\r\n"
                          "Content-Length: %ld\r\n"
                          "\r\n",
                          context->callback->content_length);
                do {
                    size_t len = context->callback->content_length - p;
                    if (len > sizeof buf) {
                        len = sizeof buf;
                    }
                    context->callback->read_bytes(context->callback, buf, p, len);
                    mg_write(connection, buf, len);
                    p += len;
                } while (p < context->callback->content_length);
                return 1;
            }
        } else if (context->callback->packaging_type == ADAPT_PACKAGE_FILE_SYSTEM) {
            if (*file_name != '\0') {
                return 0;
            }
        }
    } else if (strcmp(uri, context->msg_url) == 0) {
        if (strcmp(request->request_method, "POST") == 0) {
            int len = 0;
            char* buf = adapt_read_connection(connection, &len);
            if (buf) {
                context->callback->process_message(context->callback, buf, len);
                free(buf);
            }
        }
        mg_printf(connection,
                  "HTTP/1.1 200 Success\r\n"
                  "Content-Length: 4\r\n"
                  "\r\nOK\r\n");
        return 1;
    } else if (strncmp(uri, context->html_prefix, strlen(context->html_prefix)) == 0) {
        const char* file_name = uri + strlen(context->html_prefix);
        if (strcmp(file_name, "driver.xhtml") == 0) {
            mg_printf(connection,
                      "HTTP/1.1 200 Success\r\n"
                      "Content-Type: application/xhtml+xml\r\n"
                      "Content-Length: %ld\r\n"
                      "\r\n",
                      strlen(adapt_driver));
            mg_write(connection, adapt_driver, sizeof adapt_driver);
            return 1;
        } else {
            const struct adapt_resource* resource = adapt_resource_find(file_name);
            if (resource) {
                mg_printf(connection,
                          "HTTP/1.1 200 Success\r\n"
                          "Content-Type: %s\r\n"
                          "Content-Length: %d\r\n"
                          "%s"
                          "\r\n",
                          resource->type, resource->size,
                          resource->compressed ? "Content-Encoding: gzip\r\n" : "");
                mg_write(connection, resource->data, resource->size);
                return 1;
            }
        }
    }
    mg_write(connection, adapt_http_error, strlen(adapt_http_error));
    return 1;
}
Пример #7
0
int Response::vprintf(const char *fmt, va_list ap)
{
    char buf[BUFSIZE];
    int len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
    return mg_write(conn, buf, (size_t)len);
}
Пример #8
0
/* *************************
 * GET
 * Mongoose http will call this function for each request.
 * May run in separate thread, will be multithreaded.
 */
void get(struct mg_connection *conn, const struct mg_request_info *ri, void *user_data) 
{
	size_t isize;
	size_t size;
	FILE *fp;
	char *data;
	int res;
    int SN;
    int modulus=1;
	
	printf("Request: %s\n",ri->query_string);
	printf("Uri: -->%s<--\n",ri->uri);

    if ( str_eq(ri->uri, "/status.html") ) {
        mg_printf(conn, "HTTP/1.1 200 OK\r\n");
		mg_printf(conn, "Content-Type: text/html\r\n\r\n");
		mg_printf(conn, STATUS_PAGE, SN1_par, SN2_par, SN3_par );
        mg_printf(conn, FORM_PAGE);
        
        return;
    }
    
    if ( str_eq(ri->uri, "/SET_STATUS") ) {
        
        getServerStatus( ri->query_string );
        
        mg_printf(conn, "HTTP/1.1 200 OK\r\n");
		mg_printf(conn, "Content-Type: text/html\r\n\r\n");
		mg_printf(conn, STATUS_PAGE, SN1_par, SN2_par, SN3_par );
        mg_printf(conn, FORM_PAGE);
        
        return;
        
    }
    
	if ( str_eq( ri->uri, "/favicon.ico") ) {
		data  = (char *) malloc( MAXDATASIZE );
		
		struct stat st;
		stat("favicon.ico", &st);
		size = st.st_size;	
		
		fp = fopen("favicon.ico","rb" );
		if (fp == NULL) {
			isize = 0;
			goto finis;			
		} 		
		isize = fread( data, sizeof( char ), size, fp ); 
		
		fclose( fp );
		
	finis:		
		// printf("Sending data if size %d as image \n", (int)size );
		
		mg_printf(conn, "HTTP/1.1 200 OK\r\n");
		mg_printf(conn, "Content-Type: image/png\r\n");
		mg_printf(conn, "Content-Length: %d\r\n\r\n",(int)size );
		
		res = mg_write(conn, data, (int)size);
		return;
		
	}

	if (ri->query_string == NULL) {
		mg_printf(conn, "HTTP/1.1 400 NO DATA RETURNED\r\n");
		mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
		mg_printf(conn, "NULL Query. No answer\r\n");
	    return;
	}
	
	// Else return YES or NO
	//
	
	mg_printf(conn, "HTTP/1.1 200 OK\r\n");
	mg_printf(conn, "Content-Type: text/plain\r\n\r\n");
	helper_num++;
    
    SN = getServerNr(ri->query_string);
    
    SN = SN % 3;  // if someone does not read the assignment correctly
    
    if ( SN == 0 ){
        helper1++;
        if (SN1_par == 0 ) {
            mg_printf(conn, "NO\r\n");				            
        } else if (SN1_par == 100 ) {
            mg_printf(conn, "YES\r\n");				
        } else {
            modulus = 10;
            if ( (helper1 % modulus) <= (SN1_par/10) ) {
                mg_printf(conn, "YES\r\n");				
            } else {
                mg_printf(conn, "NO\r\n");				
            }

        }
    }else if ( SN == 1 ) {
        helper2++;
        if (SN2_par == 0 ) {
            mg_printf(conn, "NO\r\n");				            
        } else if (SN2_par == 100 ) {
            mg_printf(conn, "YES\r\n");				
        } else {
            modulus = 10;
            if ( (helper2 % modulus) <= (SN2_par/10) ) {
                mg_printf(conn, "YES\r\n");				
            } else {
                mg_printf(conn, "NO\r\n");				
            }
            
        }
        
    } else {
        helper3++;
        if (SN3_par == 0 ) {
            mg_printf(conn, "NO\r\n");				            
        } else if (SN3_par == 100 ) {
            mg_printf(conn, "YES\r\n");				
        } else {
            modulus = 10;
            if ( (helper3 % modulus) <= (SN3_par/10) ) {
                mg_printf(conn, "YES\r\n");				
            } else {
                mg_printf(conn, "NO\r\n");				
            }
            
        }
        
    }

	return;
}
Пример #9
0
int HttpConnection::write(core::data const& da)
{
    use<mg_connection> cnt = connection;
    return mg_write(cnt, da.bytes(), da.length());
}
Пример #10
0
static void *mongoose_callback(enum mg_event event, struct mg_connection *conn) {
  const struct mg_request_info *request_info = mg_get_request_info(conn);

  if (event == MG_INIT0)
  {
    verify_document_root(mg_get_conn_option(conn, "document_root"));
    return (void *)1;
  }

#if defined(_WIN32)
  if (event == MG_EVENT_LOG &&
      strstr(request_info->log_message, "cannot bind to") &&
      !strcmp(request_info->log_severity, "error"))
  {
    if (!error_dialog_shown_previously)
    {
      MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
      error_dialog_shown_previously = 1;
    }
    return 0;
  }
#endif

#if USE_BEL2125_TEST_NR_18_EVENT_HANDLER
  {
    int contentLength = 0;
    int dataRead = 0;
    char postData[BUFFER_SIZE] = { 0 };
    const char* contentType = NULL;

    if (event == MG_NEW_REQUEST)
    {
        if (strstr(request_info->uri, "/echo") == request_info->uri)
        {
            int ie_hack = 0;  // testing an assumption; turns out it doesn't matter whether headers make it into TCP stack before you expect to fetch all input data at once.
            int ie_hack2 = 0;

            contentLength = atoi(mg_get_header(conn, "Content-Length"));
            assert(contentLength <= BUFFER_SIZE);

            mg_set_response_code(conn, 200);

            if (ie_hack2) mg_connection_must_close(conn);  // the stackoverflow suggested fix: http://stackoverflow.com/questions/3731420/why-does-ie-issue-random-xhr-408-12152-responses-using-jquery-post

            contentType = mg_get_header(conn, "Content-Type");

            if (ie_hack)
            {
                //mg_add_response_header(conn, 0, "Connection", mg_suggest_connection_header(conn)); -- not needed any longer
                mg_add_response_header(conn, 0, "Content-Type", contentType);
                mg_add_response_header(conn, 0, "Content-Length", "%d", contentLength);
                mg_write_http_response_head(conn, 0, 0);  // let the previous mg_set_response_code() decide for us
            }

            dataRead = mg_read(conn, postData, contentLength);
            if (dataRead > 0)
            {
                assert(dataRead == contentLength);

                if (!ie_hack)
                {
                    //mg_add_response_header(conn, 0, "Connection", mg_suggest_connection_header(conn)); -- not needed any longer
                    mg_add_response_header(conn, 0, "Content-Type", contentType);
                    mg_add_response_header(conn, 0, "Content-Length", "%d", dataRead);
                    mg_write_http_response_head(conn, 0, 0);  // let the previous mg_set_response_code() decide for us
                }

                if (mg_write(conn, postData, dataRead) != contentLength)
                {
                    mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)contentLength); // internal error in our custom handler or client closed connection prematurely
                }

                return (void*)1;
            }
            else
            {
                mg_send_http_error(conn, 500, NULL, "I/O failure during mg_read() from connection: %s", mg_strerror(ERRNO));
            }
        }
    }
  }
#endif // USE_BEL2125_TEST_NR_18_EVENT_HANDLER

  if (event != MG_NEW_REQUEST) {
    // This callback currently only handles new requests
    return NULL;
  }

  {
    int file_found;
    struct mgstat fst;

    assert(request_info->phys_path);
    file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
    if (file_found) {
      return NULL; // let mongoose handle the default of 'file exists'...
    }

#ifdef _WIN32
    // Send the systray icon as favicon
    if (!strcmp("/favicon.ico", request_info->uri)) {
      HMODULE module;
      HRSRC icon;
      DWORD len;
      void *data;

      module = GetModuleHandle(NULL);

      icon = FindResource(module, MAKEINTRESOURCE(IDR_FAVICON), RT_RCDATA);
      data = LockResource(LoadResource(module, icon));
      len = SizeofResource(module, icon);

      mg_add_response_header(conn, 0, "Content-Type", "image/x-icon");
      mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
      mg_add_response_header(conn, 0, "Content-Length", "%u", (unsigned int)len);
      //mg_add_response_header(conn, 0, "Connection", suggest_connection_header(conn)); -- not needed any longer
      mg_write_http_response_head(conn, 200, NULL);

      if ((int)len != mg_write(conn, data, len)) {
        mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
      }
      return (void *)1;
    }
#endif
  }

  return NULL;
}
Пример #11
0
/**
 * Mongoose callback. Run in an arbitrary thread (possibly concurrently with other requests).
 */
static void* MgCallback(mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info)
{
	CProfiler2* profiler = (CProfiler2*)request_info->user_data;
	ENSURE(profiler);

	void* handled = (void*)""; // arbitrary non-NULL pointer to indicate successful handling

	const char* header200 =
		"HTTP/1.1 200 OK\r\n"
		"Access-Control-Allow-Origin: *\r\n" // TODO: not great for security
		"Content-Type: text/plain; charset=utf-8\r\n\r\n";

	const char* header404 =
		"HTTP/1.1 404 Not Found\r\n"
		"Content-Type: text/plain; charset=utf-8\r\n\r\n"
		"Unrecognised URI";

	const char* header400 =
		"HTTP/1.1 400 Bad Request\r\n"
		"Content-Type: text/plain; charset=utf-8\r\n\r\n"
		"Invalid request";

	switch (event)
	{
	case MG_NEW_REQUEST:
	{
		std::stringstream stream;

		std::string uri = request_info->uri;
		if (uri == "/overview")
		{
			profiler->ConstructJSONOverview(stream);
		}
		else if (uri == "/query")
		{
			if (!request_info->query_string)
			{
				mg_printf(conn, "%s (no query string)", header400);
				return handled;
			}

			// Identify the requested thread
			char buf[256];
			int len = mg_get_var(request_info->query_string, strlen(request_info->query_string), "thread", buf, ARRAY_SIZE(buf));
			if (len < 0)
			{
				mg_printf(conn, "%s (no 'thread')", header400);
				return handled;
			}
			std::string thread(buf);

			const char* err = profiler->ConstructJSONResponse(stream, thread);
			if (err)
			{
				mg_printf(conn, "%s (%s)", header400, err);
				return handled;
			}
		}
		else
		{
			mg_printf(conn, "%s", header404);
			return handled;
		}

		mg_printf(conn, "%s", header200);
		std::string str = stream.str();
		mg_write(conn, str.c_str(), str.length());
		return handled;
	}

	case MG_HTTP_ERROR:
		return NULL;

	case MG_EVENT_LOG:
		// Called by Mongoose's cry()
		LOGERROR("Mongoose error: %s", request_info->log_message);
		return NULL;

	case MG_INIT_SSL:
		return NULL;

	default:
		debug_warn(L"Invalid Mongoose event type");
		return NULL;
	}
};
Пример #12
0
static int wiringAdmin_callback(struct mg_connection *conn) {
    int result = 0; // zero means: let civetweb handle it further, any non-zero value means it is handled by us...

    const struct mg_request_info *request_info = mg_get_request_info(conn);

    if (request_info->uri != NULL) {
        wiring_admin_pt admin = request_info->user_data;

        if (hashMap_size(admin->wiringReceiveServices) == 0) {
            printf("%s: No wiringReceiveServices available\n", TAG);
        }

        if (strcmp("POST", request_info->request_method) == 0) {

            celixThreadMutex_lock(&admin->exportedWiringEndpointLock);

            uint64_t datalength = request_info->content_length;
            char* data = malloc(datalength + 1);
            mg_read(conn, data, datalength);
            data[datalength] = '\0';

            char *response = NULL;

            hash_map_iterator_pt iter = hashMapIterator_create(admin->wiringReceiveServices);
            while (hashMapIterator_hasNext(iter)) {
                array_list_pt wiringReceiveServiceList = hashMapIterator_nextValue(iter);

                if (arrayList_size(wiringReceiveServiceList) > 0) {
                    //		printf("WIRING_ADMIN: size of wiringReceiveServiceList is %d\n", arrayList_size(wiringReceiveServiceList));
                    // TODO: we do not support mulitple wiringReceivers?
                    wiring_receive_service_pt wiringReceiveService = (wiring_receive_service_pt) arrayList_get(wiringReceiveServiceList, 0);
                    if (wiringReceiveService->receive(wiringReceiveService->handle, data, &response) != CELIX_SUCCESS) {
                        response = NULL;
                    }

                    break;
                } else {
                    printf("%s: wiringReceiveServiceList is empty\n", TAG);
                }
            }
            hashMapIterator_destroy(iter);

            if (response != NULL) {
                mg_write(conn, data_response_headers, strlen(data_response_headers));
                mg_write(conn, response, strlen(response));

                free(response);
            } else {
                mg_write(conn, no_content_response_headers, strlen(no_content_response_headers));
            }
            result = 1;

            free(data);
        } else {
            printf("%s: Received HTTP Request, but no RSA_Inaetics callback is installed. Discarding request.\n", TAG);
        }

        celixThreadMutex_unlock(&admin->exportedWiringEndpointLock);
    } else {
        printf("%s: Received URI is NULL\n", TAG);
    }

    return result;
}
Пример #13
0
static int mongoose_begin_request_callback(struct mg_connection *connection) {
    const struct mg_request_info *request_info = mg_get_request_info(connection);
    uint8_t magic_pattern[pattern_magic_bytes];
    if (is_latency_test_request(request_info, magic_pattern)) {
        // This is an XMLHTTPRequest made by JavaScript to measure latency in a
        // browser window. magic_pattern has been filled in with a pixel pattern to
        // look for.
        report_latency(connection, magic_pattern);
        return 1;  // Mark as processed
    } else if (strcmp(request_info->uri, "/keepServerAlive") == 0) {
        __sync_fetch_and_add(&keep_alives, 1);
        mg_printf(connection, "HTTP/1.1 200 OK\r\n"
                  "Access-Control-Allow-Origin: *\r\n"
                  "Content-Type: application/octet-stream\r\n"
                  "Cache-Control: no-cache\r\n"
                  "Transfer-Encoding: chunked\r\n\r\n");
        const int chunk_size = 6;
        char *chunk0 = "1\r\n0\r\n";
        char *chunk1 = "1\r\n1\r\n";
        char *chunk = latency_tester_available() ? chunk1 : chunk0;
        const int warmup_chunks = 2048;
        for (int i = 0; i < warmup_chunks; i++) {
            mg_write(connection, chunk, chunk_size);
        }
        while(true) {
            chunk = latency_tester_available() ? chunk1 : chunk0;
            if (!mg_write(connection, chunk, chunk_size)) break;
            usleep(1000 * 1000);
        }
        __sync_fetch_and_add(&keep_alives, -1);
        return 1;
    } else if(strcmp(request_info->uri, "/runControlTest") == 0) {
        uint8_t *test_pattern = (uint8_t *)malloc(pattern_bytes);
        memset(test_pattern, 0, pattern_bytes);
        for (int i = 0; i < pattern_magic_bytes; i++) {
            test_pattern[i] = rand();
        }
        open_native_reference_window(test_pattern);
        report_latency(connection, test_pattern);
        close_native_reference_window();
        return 1;
    } else if (strcmp(request_info->uri, "/oculusLatencyTester") == 0) {
        const char *result_or_error = "Unknown error";
        if (run_hardware_latency_test(&result_or_error)) {
            debug_log("hardware latency test succeeded");
            mg_printf(connection, "HTTP/1.1 200 OK\r\n"
                      "Access-Control-Allow-Origin: *\r\n"
                      "Cache-Control: no-cache\r\n"
                      "Content-Type: text/plain\r\n\r\n"
                      "%s", result_or_error);
        } else {
            debug_log("hardware latency test failed");
            mg_printf(connection, "HTTP/1.1 500 Internal Server Error\r\n"
                      "Access-Control-Allow-Origin: *\r\n"
                      "Cache-Control: no-cache\r\n"
                      "Content-Type: text/plain\r\n\r\n"
                      "%s", result_or_error);
        }
        return 1;
    } else {
#ifdef NDEBUG
        // In release mode, we embed the test files in the executable and serve
        // them from memory. This makes the test easier to distribute as it is
        // a standalone executable file with no other dependencies.
        serve_file_from_memory_or_404(connection);
        return 1;
#else
        // In debug mode, we serve the test files directly from the filesystem for
        // ease of development. Mongoose handles file serving for us.
        return 0;
#endif
    }
}
Пример #14
0
	static int inline mg_write(struct mg_connection* conn, const StringT& string)
	{
		return mg_write(conn, string.c_str(), string.size());
	}
Пример #15
0
	static void* TransportRESTCallback(enum mg_event event, struct mg_connection* conn)
	{
		// Serving a new request
		if (event == MG_NEW_REQUEST)
		{
			// Retrieving information associated to the current connection
			// The method from mongoose directly return a pointer from within
			// the mg_connection struct, thus it can not fail.
			const mg_request_info& reqinfo = *mg_get_request_info(conn);
			assert(reqinfo.user_data != NULL and "invalid user data");

			// retrieving the request method first
			// and directly aborting if invalid
			RequestMethod rqmd = StringToRequestMethod(reqinfo.request_method);
			if (rqmd == rqmdInvalid)
				return ReturnSimpleHTTPCode404(conn);

			// server data
			Server::ServerData* serverdata = (Server::ServerData*) reqinfo.user_data;

			// Decision Tree
			// For thread safety reasons, we must keep a smart pointer of the decision tree
			// until the request is served.
			DecisionTree::Ptr dectreeptr = serverdata->decisionTree;
			assert(!(!dectreeptr));
			const DecisionTree::UrlDictionary& urls = dectreeptr->requestMethods[rqmd];

			// invoking the user's callback according the decision tree
			DecisionTree::UrlDictionary::const_iterator mi = urls.find(reqinfo.uri);
			if (mi == urls.end())
			{
				// the url has not been found
				return ReturnSimpleHTTPCode404(conn);
			}
			// alias to the method handler
			const DecisionTree::MethodHandler& mhandler = mi->second;


			// Original service instance
			Service& service = *(serverdata->service);
			assert(serverdata->service != NULL and "invalid reference to Messaging::Service");
			// Message context
			Messaging::Context context(service);

			// reading / checking for parameters
			if (not mhandler.parameters.empty())
			{
				// copying all default parameters
				context.params = mhandler.parameters;

				// reading parameters from the url query
				// ignoring unknown parameters
				if (reqinfo.query_string and reqinfo.query_string[0] != '\0')
				{
					if (not DecodeURLQuery(context.params, reqinfo.query_string))
						return ReturnSimpleHTTPCode<400>(conn, context);
				}
			}

			// resetting context
			context.method = mhandler.name;
			context.schema = mhandler.schema;
			context.httpStatus = 200;
			context.remotePort = (uint)reqinfo.remote_port;
			// response
			Marshal::Object response;

			// Invoke user callback
			mhandler.invoke(context, response);


			// sending the response
			uint statusCode = context.httpStatus;
			if  (statusCode >= 200 and statusCode <= context.httpStatusCode.max2xx)
			{
				Clob& body = context.clob;
				# ifndef NDEBUG
				response.toJSON(body, true);
				# else
				response.toJSON(body, false); // reduce size output
				# endif

				Clob& out  = context.buffer;
				out = context.httpStatusCode.header2xx[statusCode - 200];
				out += "Content-Type: application/json\r\nContent-Length: ";
				out += body.size();
				out += "\r\n\r\n";
				out += body;
				mg_write(conn, out.c_str(), out.size());

				// reducing memory usage for some Memory-hungry apps
				context.autoshrink();
			}
			else if (statusCode >= 400 and statusCode <= context.httpStatusCode.max4xx)
			{
				// reducing memory usage for some Memory-hungry apps
				context.autoshrink();
				// response
				mg_write(conn, context.httpStatusCode.response4xx[statusCode - 400]);
			}
			else
			{
				// not handled by default
				mg_write(conn, context.httpStatusCode.response5xx[500 - 500]);
			}

			return (void*)"ok";
		}

		return nullptr;
	}
Пример #16
0
	static inline void* ReturnSimpleHTTPCode404(struct mg_connection* conn)
	{
		static const AnyString msg("HTTP/1.1 404 Not found\r\n\r\nNot found");
		mg_write(conn, msg);
		return (void*)"ok"; // the request has been managed
	}
Пример #17
0
    void Request::writeResponse(Response *response)
    {
        string data = response->getData();

        mg_write(connection, data.c_str(), data.size());
    }
Пример #18
0
  static int begin_request(struct mg_connection *conn)
  {
    const struct mg_request_info *request_info = mg_get_request_info(conn);

    HTrace(request_info->request_method ? request_info->request_method : "", " ",
           request_info->uri            ? request_info->uri            : "",
           request_info->query_string   ?                        "?"   : "",
           request_info->query_string   ? request_info->query_string   : "");

    if (!strcmp("/favicon.ico",request_info->uri))
    {
      string http = print_string(
                "HTTP/1.1 200 OK\r\n"
                "Content-Type: image/x-icon\r\n"
                "Content-Length: ", sizeof(favicon), "\r\n"
                "\r\n");

      mg_write(conn,http.c_str(),http.length());
      mg_write(conn,favicon,sizeof(favicon));
      return 1;
    }

    string body;

    if (!strcmp("/log",request_info->uri))
    {
      Logging::getLogMessagesHTML(body);
    }
    else if (!strcmp("/glEnable",request_info->uri))
    {
           if (!strcmp("GL_LOG_INFO_REGAL",    request_info->query_string)) Logging::enableError    = true;
      else if (!strcmp("GL_LOG_WARNING_REGAL", request_info->query_string)) Logging::enableWarning  = true;
      else if (!strcmp("GL_LOG_ERROR_REGAL",   request_info->query_string)) Logging::enableInfo     = true;
      else if (!strcmp("GL_LOG_APP_REGAL",     request_info->query_string)) Logging::enableApp      = true;
      else if (!strcmp("GL_LOG_DRIVER_REGAL",  request_info->query_string)) Logging::enableDriver   = true;
      else if (!strcmp("GL_LOG_INTERNAL_REGAL",request_info->query_string)) Logging::enableInternal = true;
      else if (!strcmp("GL_LOG_HTTP_REGAL",    request_info->query_string)) Logging::enableHttp     = true;

      else if (!strcmp("REGAL_FRAME_TIME",     request_info->query_string)) Logging::frameTime      = true;

      else if (!strcmp("REGAL_MD5_COLOR",      request_info->query_string)) Config::frameMd5Color    = true;
      else if (!strcmp("REGAL_MD5_STENCIL",    request_info->query_string)) Config::frameMd5Stencil  = true;
      else if (!strcmp("REGAL_MD5_DEPTH",      request_info->query_string)) Config::frameMd5Depth    = true;
      else if (!strcmp("REGAL_SAVE_COLOR",     request_info->query_string)) Config::frameSaveColor   = true;
      else if (!strcmp("REGAL_SAVE_STENCIL",   request_info->query_string)) Config::frameSaveStencil = true;
      else if (!strcmp("REGAL_SAVE_DEPTH",     request_info->query_string)) Config::frameSaveDepth   = true;

      body += print_string("glEnable(", request_info->query_string, ");",br,br);
      body += print_string("<a href=\"/glDisable?",request_info->query_string,"\">toggle</a>");
    }
    else if (!strcmp("/glDisable",request_info->uri))
    {
           if (!strcmp("GL_LOG_INFO_REGAL",    request_info->query_string)) Logging::enableError    = false;
      else if (!strcmp("GL_LOG_WARNING_REGAL", request_info->query_string)) Logging::enableWarning  = false;
      else if (!strcmp("GL_LOG_ERROR_REGAL",   request_info->query_string)) Logging::enableInfo     = false;
      else if (!strcmp("GL_LOG_APP_REGAL",     request_info->query_string)) Logging::enableApp      = false;
      else if (!strcmp("GL_LOG_DRIVER_REGAL",  request_info->query_string)) Logging::enableDriver   = false;
      else if (!strcmp("GL_LOG_INTERNAL_REGAL",request_info->query_string)) Logging::enableInternal = false;
      else if (!strcmp("GL_LOG_HTTP_REGAL",    request_info->query_string)) Logging::enableHttp     = false;

      else if (!strcmp("REGAL_FRAME_TIME",     request_info->query_string)) Logging::frameTime      = false;

      else if (!strcmp("REGAL_MD5_COLOR",      request_info->query_string)) Config::frameMd5Color    = false;
      else if (!strcmp("REGAL_MD5_STENCIL",    request_info->query_string)) Config::frameMd5Stencil  = false;
      else if (!strcmp("REGAL_MD5_DEPTH",      request_info->query_string)) Config::frameMd5Depth    = false;
      else if (!strcmp("REGAL_SAVE_COLOR",     request_info->query_string)) Config::frameSaveColor   = false;
      else if (!strcmp("REGAL_SAVE_STENCIL",   request_info->query_string)) Config::frameSaveStencil = false;
      else if (!strcmp("REGAL_SAVE_DEPTH",     request_info->query_string)) Config::frameSaveDepth   = false;

      body += print_string("glDisable(", request_info->query_string, ");",br,br);
      body += print_string("<a href=\"/glEnable?",request_info->query_string,"\">toggle</a>");
    }
    else
    {
      ::REGAL_NAMESPACE_INTERNAL::Init::getContextListingHTML(body);
    }

    string html = print_string(
      "<html><body>\n",
      body,
      "</body></html>\n");

    string http = print_string(
              "HTTP/1.1 200 OK\r\n"
              "Content-Type: text/html\r\n"
              "Content-Length: ", html.length(), "\r\n"
              "\r\n",
              html);

    mg_write(conn,http.c_str(),http.length());
    return 1;  // Mark as handled for civetweb
  }
Пример #19
0
void ofxWSRequestHandler::httpResponseData(char *data, int length) {
	mg_write(conn, (const void *)data, length);
}
 int ServiceOutputStream::write(std::string data){
   return mg_write(_conn, data.c_str(), data.length());
 }
Пример #21
0
  static void *callback(enum mg_event event, struct mg_connection *conn)
  {
    const struct mg_request_info *request_info = mg_get_request_info(conn);

    switch (event)
    {
      case MG_EVENT_LOG:
      {
        HTrace(request_info->ev_data ? static_cast<const char *>(request_info->ev_data) : "");
        break;
      }

      case MG_NEW_REQUEST:
      {
        HTrace(request_info->request_method ? request_info->request_method : "", " ",
               request_info->uri            ? request_info->uri            : "",
               request_info->query_string   ?                        "?"   : "",
               request_info->query_string   ? request_info->query_string   : "");

        if (!strcmp("/favicon.ico",request_info->uri))
        {
          string http = print_string(
                    "HTTP/1.1 200 OK\r\n"
                    "Content-Type: image/x-icon\r\n"
                    "Content-Length: ", sizeof(favicon), "\r\n"
                    "\r\n");

          mg_write(conn,http.c_str(),http.length());
          mg_write(conn,favicon,sizeof(favicon));
          return (void *) true;
        }

        string body;

        if (!strcmp("/log",request_info->uri))
        {
          if (Logging::buffer)
            for (list<string>::const_iterator i = Logging::buffer->begin(); i!=Logging::buffer->end(); ++i)
              body += print_string(*i,br);
        }
        else if (!strcmp("/glEnable",request_info->uri))
        {
               if (!strcmp("GL_LOG_INFO_REGAL",    request_info->query_string)) Logging::enableError    = true;
          else if (!strcmp("GL_LOG_WARNING_REGAL", request_info->query_string)) Logging::enableWarning  = true;
          else if (!strcmp("GL_LOG_ERROR_REGAL",   request_info->query_string)) Logging::enableInfo     = true;
          else if (!strcmp("GL_LOG_APP_REGAL",     request_info->query_string)) Logging::enableApp      = true;
          else if (!strcmp("GL_LOG_DRIVER_REGAL",  request_info->query_string)) Logging::enableDriver   = true;
          else if (!strcmp("GL_LOG_INTERNAL_REGAL",request_info->query_string)) Logging::enableInternal = true;
          else if (!strcmp("GL_LOG_HTTP_REGAL",    request_info->query_string)) Logging::enableHttp     = true;

          else if (!strcmp("REGAL_FRAME_TIME",     request_info->query_string)) Logging::frameTime      = true;

          else if (!strcmp("REGAL_MD5_COLOR",      request_info->query_string)) Config::frameMd5Color    = true;
          else if (!strcmp("REGAL_MD5_STENCIL",    request_info->query_string)) Config::frameMd5Stencil  = true;
          else if (!strcmp("REGAL_MD5_DEPTH",      request_info->query_string)) Config::frameMd5Depth    = true;
          else if (!strcmp("REGAL_SAVE_COLOR",     request_info->query_string)) Config::frameSaveColor   = true;
          else if (!strcmp("REGAL_SAVE_STENCIL",   request_info->query_string)) Config::frameSaveStencil = true;
          else if (!strcmp("REGAL_SAVE_DEPTH",     request_info->query_string)) Config::frameSaveDepth   = true;

          body += print_string("glEnable(", request_info->query_string, ");",br,br);
          body += print_string("<a href=\"/glDisable?",request_info->query_string,"\">toggle</a>");
        }
        else if (!strcmp("/glDisable",request_info->uri))
        {
               if (!strcmp("GL_LOG_INFO_REGAL",    request_info->query_string)) Logging::enableError    = false;
          else if (!strcmp("GL_LOG_WARNING_REGAL", request_info->query_string)) Logging::enableWarning  = false;
          else if (!strcmp("GL_LOG_ERROR_REGAL",   request_info->query_string)) Logging::enableInfo     = false;
          else if (!strcmp("GL_LOG_APP_REGAL",     request_info->query_string)) Logging::enableApp      = false;
          else if (!strcmp("GL_LOG_DRIVER_REGAL",  request_info->query_string)) Logging::enableDriver   = false;
          else if (!strcmp("GL_LOG_INTERNAL_REGAL",request_info->query_string)) Logging::enableInternal = false;
          else if (!strcmp("GL_LOG_HTTP_REGAL",    request_info->query_string)) Logging::enableHttp     = false;

          else if (!strcmp("REGAL_FRAME_TIME",     request_info->query_string)) Logging::frameTime      = false;

          else if (!strcmp("REGAL_MD5_COLOR",      request_info->query_string)) Config::frameMd5Color    = false;
          else if (!strcmp("REGAL_MD5_STENCIL",    request_info->query_string)) Config::frameMd5Stencil  = false;
          else if (!strcmp("REGAL_MD5_DEPTH",      request_info->query_string)) Config::frameMd5Depth    = false;
          else if (!strcmp("REGAL_SAVE_COLOR",     request_info->query_string)) Config::frameSaveColor   = false;
          else if (!strcmp("REGAL_SAVE_STENCIL",   request_info->query_string)) Config::frameSaveStencil = false;
          else if (!strcmp("REGAL_SAVE_DEPTH",     request_info->query_string)) Config::frameSaveDepth   = false;

          body += print_string("glDisable(", request_info->query_string, ");",br,br);
          body += print_string("<a href=\"/glEnable?",request_info->query_string,"\">toggle</a>");
        }
        else
        {
          for (map<Thread::Thread, RegalContext *>::const_iterator i = th2rc.begin(); i!=th2rc.end(); ++i)
          {
            RegalContext *ctx = i->second;

            // Need a per-context read-lock?

            body += print_string("ctx = ",ctx,br);
            body += br;
            if (ctx)
            {
              if (ctx->info)
              {
                body += print_string("<b>Vendor     </b>:",ctx->info->regalVendor,br);
                body += print_string("<b>Renderer   </b>:",ctx->info->regalRenderer,br);
                body += print_string("<b>Version    </b>:",ctx->info->regalVersion,br);
                body += print_string("<b>Extensions </b>:",ctx->info->regalExtensions,br);
                body += br;
              }

#if REGAL_EMULATION
              if (ctx->ppa)
              {
                body += print_string("<b>GL_STENCIL_BIT</b><br/>",ctx->ppa->State::Stencil::toString(br),br);
                body += print_string("<b>GL_DEPTH_BIT</b><br/>",  ctx->ppa->State::Depth::toString(br),br);
                body += print_string("<b>GL_POLYGON_BIT</b><br/>",ctx->ppa->State::Polygon::toString(br),br);
                body += br;
              }
#endif
            }
          }
        }

        string html = print_string(
          "<html><body>\n",
          body,
          "</body></html>\n");

        string http = print_string(
                  "HTTP/1.1 200 OK\r\n"
                  "Content-Type: text/html\r\n"
                  "Content-Length: ", html.length(), "\r\n"
                  "\r\n",
                  html);

        mg_write(conn,http.c_str(),http.length());
        break;
      }

      default:
        return NULL;
    }

    return (void *) true;  // Mark as handled for Mongoose
  }
Пример #22
0
static int io_mg_write(void *context, const void *buffer, int size)
{
	return mg_write((struct mg_connection *)context, buffer, size);
}
Пример #23
0
void* CDebuggingServer::MgDebuggingServerCallback(mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info)
{
	void* handled = (void*)""; // arbitrary non-NULL pointer to indicate successful handling

	const char* header200 =
		"HTTP/1.1 200 OK\r\n"
		"Access-Control-Allow-Origin: *\r\n" // TODO: not great for security
		"Content-Type: text/plain; charset=utf-8\r\n\r\n";

	const char* header404 =
		"HTTP/1.1 404 Not Found\r\n"
		"Content-Type: text/plain; charset=utf-8\r\n\r\n"
		"Unrecognised URI";

	switch (event)
	{
	case MG_NEW_REQUEST:
	{
		std::stringstream stream;
		std::string uri = request_info->uri;
		
		if (uri == "/GetThreadDebuggerStatus")
		{
			GetThreadDebuggerStatus(stream);
		}
		else if (uri == "/EnumVfsJSFiles")
		{
			EnumVfsJSFiles(stream);
		}
		else if (uri == "/GetAllCallstacks")
		{
			GetAllCallstacks(stream);
		}
		else if (uri == "/Continue")
		{
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
				return handled;
			// TODO: handle the return value
			SetNextDbgCmd(threadDebuggerID, DBG_CMD_CONTINUE);	
		}
		else if (uri == "/Break")
		{
			SetBreakRequestedByUser(true);
		}
		else if (uri == "/SetSettingSimultaneousThreadBreak")
		{
			std::string strEnabled;
			bool bEnabled = false;
			if (!GetWebArgs(conn, request_info, "enabled", strEnabled))
				return handled;
			// TODO: handle the return value
			if (strEnabled == "true")
				bEnabled = true;
			else if (strEnabled == "false")
				bEnabled = false;
			else
				return handled; // TODO: return an error state
			SetSettingSimultaneousThreadBreak(bEnabled);
		}
		else if (uri == "/GetSettingSimultaneousThreadBreak")
		{
			stream << "{ \"Enabled\" : " << (GetSettingSimultaneousThreadBreak() ? "true" : "false") << " } ";
		}
		else if (uri == "/SetSettingBreakOnException")
		{
			std::string strEnabled;
			bool bEnabled = false;
			if (!GetWebArgs(conn, request_info, "enabled", strEnabled))
				return handled;
			// TODO: handle the return value
			if (strEnabled == "true")
				bEnabled = true;
			else if (strEnabled == "false")
				bEnabled = false;
			else
				return handled; // TODO: return an error state
			SetSettingBreakOnException(bEnabled);
		}
		else if (uri == "/GetSettingBreakOnException")
		{
			stream << "{ \"Enabled\" : " << (GetSettingBreakOnException() ? "true" : "false") << " } ";
		}
		else if (uri == "/Step")
		{
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
				return handled;
			// TODO: handle the return value
			SetNextDbgCmd(threadDebuggerID, DBG_CMD_SINGLESTEP);
		}
		else if (uri == "/StepInto")
		{
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
				return handled;
			// TODO: handle the return value
			SetNextDbgCmd(threadDebuggerID, DBG_CMD_STEPINTO);
		}
		else if (uri == "/StepOut")
		{
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
				return handled;
			// TODO: handle the return value
			SetNextDbgCmd(threadDebuggerID, DBG_CMD_STEPOUT);
		}
		else if (uri == "/GetStackFrame")
		{
			uint nestingLevel;
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "nestingLevel", nestingLevel) || 
				!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
			{
				return handled;
			}
			GetStackFrameData(stream, nestingLevel, threadDebuggerID, STACK_INFO_LOCALS);
		}
		else if (uri == "/GetStackFrameThis")
		{
			uint nestingLevel;
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "nestingLevel", nestingLevel) || 
				!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
			{
				return handled;
			}
			GetStackFrameData(stream, nestingLevel, threadDebuggerID, STACK_INFO_THIS);
		}
		else if (uri == "/GetCurrentGlobalObject")
		{
			uint threadDebuggerID;
			if (!GetWebArgs(conn, request_info, "threadDebuggerID", threadDebuggerID))
			{
				return handled;
			}
			GetStackFrameData(stream, 0, threadDebuggerID, STACK_INFO_GLOBALOBJECT);
		}
		else if (uri == "/ToggleBreakpoint")
		{
			std::string filename;
			uint line;
			if (!GetWebArgs(conn, request_info, "filename", filename) ||
				!GetWebArgs(conn, request_info, "line", line))
			{
				return handled;
			}
			ToggleBreakPoint(filename, line);
		}
		else if (uri == "/GetFile")
		{
			std::string filename;
			if (!GetWebArgs(conn, request_info, "filename", filename))
				return handled;
			GetFile(filename, stream);
		}
		else
		{
			mg_printf(conn, "%s", header404);
			return handled;
		}

		mg_printf(conn, "%s", header200);
		std::string str = stream.str();
		mg_write(conn, str.c_str(), str.length());
		return handled;
	}

	case MG_HTTP_ERROR:
		return NULL;

	case MG_EVENT_LOG:
		// Called by Mongoose's cry()
		LOGERROR(L"Mongoose error: %hs", request_info->log_message);
		return NULL;

	case MG_INIT_SSL:
		return NULL;

	default:
		debug_warn(L"Invalid Mongoose event type");
		return NULL;
	}
};
Пример #24
0
static void *mongoose_callback(enum mg_event event, struct mg_connection *conn) {
  const struct mg_request_info *request_info = mg_get_request_info(conn);

  if (event == MG_INIT0)
  {
    verify_document_root(mg_get_conn_option(conn, "document_root"));
    return (void *)1;
  }

#if defined(_WIN32)
  if (event == MG_EVENT_LOG &&
      strstr(request_info->log_message, "cannot bind to") &&
      !strcmp(request_info->log_severity, "error"))
  {
    if (!error_dialog_shown_previously)
    {
      MessageBoxA(NULL, request_info->log_message, "Error", MB_OK);
      error_dialog_shown_previously = 1;
    }
    return 0;
  }
#endif

  if (event != MG_NEW_REQUEST) {
    // This callback currently only handles new requests
    return NULL;
  }

  {
    int file_found;
    struct mgstat fst;

    assert(request_info->phys_path);
    file_found = (0 == mg_stat(request_info->phys_path, &fst) && !fst.is_directory);
    if (file_found) {
      return NULL; // let mongoose handle the default of 'file exists'...
    }

#ifdef _WIN32
    // Send the systray icon as favicon
    if (!strcmp("/favicon.ico", request_info->uri)) {
      HMODULE module;
      HRSRC icon;
      DWORD len;
      void *data;

      module = GetModuleHandle(NULL);

      icon = FindResource(module, MAKEINTRESOURCE(IDR_FAVICON), RT_RCDATA);
      data = LockResource(LoadResource(module, icon));
      len = SizeofResource(module, icon);

      mg_add_response_header(conn, 0, "Content-Type", "image/x-icon");
      mg_add_response_header(conn, 0, "Cache-Control", "no-cache");
      mg_add_response_header(conn, 0, "Content-Length", "%u", (unsigned int)len);
      //mg_add_response_header(conn, 0, "Connection", suggest_connection_header(conn)); -- not needed any longer
      mg_write_http_response_head(conn, 200, NULL);

      if ((int)len != mg_write(conn, data, len)) {
        mg_send_http_error(conn, 580, NULL, "not all data was written to the socket (len: %u)", (unsigned int)len); // internal error in our custom handler or client closed connection prematurely
      }
      return (void *)1;
    }
#endif
  }

  return NULL;
}
Пример #25
0
static void adapt_sink_connection_write(struct adapt_sink* sink, size_t file_offset,
                                        const unsigned char* buf, size_t length) {
    if (length > 0) {
        mg_write(((struct adapt_sink_connection*)sink)->connection, buf, length);
    }
}
Пример #26
0
void MushiRequest::write(QString data){
    mg_write(this->conn,data.toStdString().c_str(),data.length());
}
Пример #27
0
void*
FileServer::mongooseCallback(enum mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info) {
    if (event != MG_NEW_REQUEST) {
        return NULL;
    }
    assert(FileServer::s_self != NULL);
    if (FileServer::s_self == NULL) {
        return NULL;
    }
    std::string id(request_info->uri);
    bplus::service::Service::log(BP_INFO, "request.url.path = " + id);
    // drop the leading /
    id = id.substr(1, id.length() - 1);
    // if we can find a slash '/', in the url, we'll drop everything after it.
    size_t slashLoc = id.find('/');
    if (slashLoc != std::string::npos) {
        id = id.substr(0, slashLoc);
    }
    bplus::service::Service::log(BP_INFO, "token '" + id + "' extracted from request path: " + request_info->uri);
    boost::filesystem::path path;
    {
        bplus::sync::Lock lck(FileServer::s_self->m_lock);
        std::map<std::string,boost::filesystem::path>::const_iterator it;
        it = FileServer::s_self->m_paths.find(id);
        if (it == FileServer::s_self->m_paths.end()) {
            bplus::service::Service::log(BP_WARN, "Requested id not found.");
            mg_printf(conn, "HTTP/1.0 404 Not Found\r\n\r\n");
            return conn;
        }
        path = it->second;
    }
    // read file and output to connection
    std::ifstream ifs;
    if (!bp::file::openReadableStream(ifs, path.string(), std::ios::binary)) {
        bplus::service::Service::log(BP_WARN, "Couldn't open file for reading " + path.string());
        mg_printf(conn, "HTTP/1.0 500 Internal Error\r\n\r\n");
        return conn;
    }
    // get length of file:
    long len = 0;
    try {
        ifs.seekg(0, std::ios::end);
        len = ifs.tellg();
        ifs.seekg(0, std::ios::beg);
    } catch (...) {
        len = -1;
    }
    if (len < 0) {
        bplus::service::Service::log(BP_WARN, "Couldn't determine file length: " + path.string());
        mg_printf(conn, "HTTP/1.0 500 Internal Error\r\n\r\n");
        return conn;
    }
    mg_printf(conn, "HTTP/1.0 200 OK\r\n");
    mg_printf(conn, "Content-Length: %ld\r\n", len);
    mg_printf(conn, "Server: FileAccess BrowserPlus service\r\n");
    // set mime type header
    {
        std::vector<std::string> mts;
        mts = bp::file::mimeTypes(path);
        if (mts.size() > 0) {
            mg_printf(conn, "Content-Type: %s\r\n", mts.begin()->c_str());
        }
    }
    mg_printf(conn, "\r\n");    
    char buf[1024 * 32];
    while (!ifs.eof()) {
        size_t rd = 0;
        ifs.read(buf, sizeof(buf));
        rd = ifs.gcount();
        if (rd != (size_t) mg_write(conn, buf, rd)) {
            bplus::service::Service::log(BP_WARN, "partial write detected!  client left?");
            ifs.close();
            return conn;
        }
    }
    bplus::service::Service::log(BP_DEBUG, "Request processed.");
    return conn;
}
Пример #28
0
void MushiRequest::write(std::string data){

    mg_write(this->conn,data.c_str(),data.length());
}
Пример #29
0
void Response::write(char const * buf, size_t size)
{
    checkHeadersSent();
    mg_write(conn, buf, size);
}
Пример #30
0
static int remoteServiceAdmin_callback(struct mg_connection *conn) {
    int result = 1; // zero means: let civetweb handle it further, any non-zero value means it is handled by us...

    const struct mg_request_info *request_info = mg_get_request_info(conn);
    if (request_info->uri != NULL) {
        remote_service_admin_pt rsa = request_info->user_data;


        if (strncmp(request_info->uri, "/service/", 9) == 0 && strcmp("POST", request_info->request_method) == 0) {

            // uri = /services/myservice/call
            const char *uri = request_info->uri;
            // rest = myservice/call

            const char *rest = uri+9;
            char *interfaceStart = strchr(rest, '/');
            int pos = interfaceStart - rest;
            char service[pos+1];
            strncpy(service, rest, pos);
            service[pos] = '\0';
            long serviceId = atol(service);

            celixThreadMutex_lock(&rsa->exportedServicesLock);

            //find endpoint
            export_registration_pt export = NULL;
            hash_map_iterator_pt iter = hashMapIterator_create(rsa->exportedServices);
            while (hashMapIterator_hasNext(iter)) {
                hash_map_entry_pt entry = hashMapIterator_nextEntry(iter);
                array_list_pt exports = hashMapEntry_getValue(entry);
                int expIt = 0;
                for (expIt = 0; expIt < arrayList_size(exports); expIt++) {
                    export_registration_pt check = arrayList_get(exports, expIt);
                    export_reference_pt  ref = NULL;
                    exportRegistration_getExportReference(check, &ref);
                    endpoint_description_pt  checkEndpoint = NULL;
                    exportReference_getExportedEndpoint(ref, &checkEndpoint);
                    if (serviceId == checkEndpoint->serviceId) {
                        export = check;
                        free(ref);
                        break;
                    }
                    free(ref);
                }
            }
            hashMapIterator_destroy(iter);

            if (export != NULL) {

                uint64_t datalength = request_info->content_length;
                char* data = malloc(datalength + 1);
                mg_read(conn, data, datalength);
                data[datalength] = '\0';

                char *response = NULL;
                int responceLength = 0;
                int rc = exportRegistration_call(export, data, -1, &response, &responceLength);
                if (rc != CELIX_SUCCESS) {
                    RSA_LOG_ERROR(rsa, "Error trying to invoke remove service, got error %i\n", rc);
                }

                if (rc == CELIX_SUCCESS && response != NULL) {
                    mg_write(conn, data_response_headers, strlen(data_response_headers));
                    mg_write(conn, response, strlen(response));
                    free(response);
                } else {
                    mg_write(conn, no_content_response_headers, strlen(no_content_response_headers));
                }
                result = 1;

                free(data);
            } else {