Exemplo n.º 1
0
 dispatcher wait()
 {
     return dispatcher(&q);
 }
void clientDisplay(void) {


	updateCamera();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
	glDisable(GL_LIGHTING);

	//GL_ShapeDrawer::drawCoordSystem();

	ATTRIBUTE_ALIGNED16(btScalar) m[16];
	int i;
#ifdef USE_GJK
	btGjkEpaPenetrationDepthSolver epa;
	btGjkPairDetector	convexConvex(shapePtr[0],shapePtr[1],&sGjkSimplexSolver,&epa);

	btVector3 seperatingAxis(0.00000000f,0.059727669f,0.29259586f);
	convexConvex.setCachedSeperatingAxis(seperatingAxis);

	btPointCollector gjkOutput;
	btGjkPairDetector::ClosestPointInput input;
	input.m_transformA = tr[0];
	input.m_transformB = tr[1];

	convexConvex.getClosestPoints(input ,gjkOutput,0);

	if (gjkOutput.m_hasResult)
	{
		btVector3 endPt = gjkOutput.m_pointInWorld +
			gjkOutput.m_normalOnBInWorld*gjkOutput.m_distance;

		 glBegin(GL_LINES);
		glColor3f(1, 0, 0);
		glVertex3d(gjkOutput.m_pointInWorld.x(), gjkOutput.m_pointInWorld.y(),gjkOutput.m_pointInWorld.z());
		glVertex3d(endPt.x(),endPt.y(),endPt.z());
		glEnd();

	}
#else //USE_GJK

	
	struct	MyContactResultCallback : public btCollisionWorld::ContactResultCallback
	{
		virtual	btScalar	addSingleResult(btManifoldPoint& cp,	const btCollisionObjectWrapper* colObj0Wrap,int partId0,int index0,const btCollisionObjectWrapper* colObj1Wrap,int partId1,int index1)
		{
			 glBegin(GL_LINES);
			glColor3f(1, 0, 0);
			
			glVertex3d(cp.m_positionWorldOnA.getX(),cp.m_positionWorldOnA.getY(),cp.m_positionWorldOnA.getZ());
			glVertex3d(cp.m_positionWorldOnB.getX(),cp.m_positionWorldOnB.getY(),cp.m_positionWorldOnB.getZ());
			glEnd();

			return 1.f;
		}
	};

	btDefaultCollisionConfiguration collisionConfiguration;
	btCollisionDispatcher				dispatcher(&collisionConfiguration);
	btDbvtBroadphase pairCache;
	btCollisionWorld world (&dispatcher,&pairCache,&collisionConfiguration);
	gContactBreakingThreshold=1e10f;
	
	MyContactResultCallback result;
	btCollisionObject obA;
	obA.setCollisionShape(shapePtr[0]);
	obA.setWorldTransform(tr[0]);
	btCollisionObject obB;
	obB.setCollisionShape(shapePtr[1]);
	obB.setWorldTransform(tr[1]);
	world.contactPairTest(&obA,&obB,result);

#endif//USE_GJK

	btVector3 worldMin(-1000,-1000,-1000);
	btVector3 worldMax(1000,1000,1000);

	for (i=0;i<numObjects;i++)
	{
		
		tr[i].getOpenGLMatrix( m );

		if (debugMode)
		{
			/// for polyhedral shapes
				if (shapePtr[i]->isPolyhedral())
				{
					if (!shapePtr[i]->getUserPointer())
					{
						btConvexHullComputer* convexUtil = new btConvexHullComputer();
						shapePtr[i]->setUserPointer(convexUtil);

						btPolyhedralConvexShape* polyshape = (btPolyhedralConvexShape*) shapePtr[i];

						btAlignedObjectArray<btVector3> vertices;
						vertices.resize(polyshape->getNumVertices());
						for (int i=0;i<polyshape->getNumVertices();i++)
						{
							polyshape->getVertex(i,vertices[i]);
						}
						
						bool useDoublePrecision = false;
						convexUtil->compute(&vertices[0].getX(),sizeof(btVector3), polyshape->getNumVertices(),0,0);
					} 

					if (shapePtr[i]->getUserPointer())
					{
						btConvexHullComputer* convexUtil = (btConvexHullComputer*)shapePtr[i]->getUserPointer();
						//printf("num faces = %d\n",convexUtil->faces.size());
						for (int j=0;j<convexUtil->faces.size();j++)
						{
							int face = convexUtil->faces[j];
							//printf("face=%d\n",face);
							const btConvexHullComputer::Edge*  firstEdge = &convexUtil->edges[face];
							const btConvexHullComputer::Edge*  edge = firstEdge;

							do
							{
								int src = edge->getSourceVertex();
								int targ = edge->getTargetVertex();
								//printf("src=%d target = %d\n", src,targ);
								
								btVector3 wa = tr[i] * convexUtil->vertices[src];
								btVector3 wb = tr[i] * convexUtil->vertices[targ];

								glBegin(GL_LINES);
								glColor3f(1, 1, 1);
								glVertex3f(wa.getX(),wa.getY(),wa.getZ());
								glVertex3f(wb.getX(),wb.getY(),wb.getZ());
								glEnd();

								edge = edge->getNextEdgeOfFace();
							} while (edge!=firstEdge);

						}
					}
				}
		} else
		{
			shapeDrawer.drawOpenGL(m,shapePtr[i],btVector3(1,1,1),debugMode, worldMin, worldMax);
		}


	}

	simplex.setSimplexSolver(&sGjkSimplexSolver);
	btVector3 ybuf[4],pbuf[4],qbuf[4];
	int numpoints = sGjkSimplexSolver.getSimplex(pbuf,qbuf,ybuf);
	simplex.reset();
	
	for (i=0;i<numpoints;i++)
		simplex.addVertex(ybuf[i]);

	btTransform ident;
	ident.setIdentity();
	ident.getOpenGLMatrix(m);
	shapeDrawer.drawOpenGL(m,&simplex,btVector3(1,1,1),debugMode, worldMin,worldMax);


	btQuaternion orn;
	orn.setEuler(yaw,pitch,roll);
	tr[0].setRotation(orn);
	tr[1].setRotation(orn);

	pitch += 0.005f;
	yaw += 0.01f;

	glFlush();
    glutSwapBuffers();
}
Exemplo n.º 3
0
// **********************************************************************
// **********************************************************************
// OS startup
//
// 1. Init OS
// 2. Define reset longjmp vector
// 3. Define global system semaphores
// 4. Create CLI task
// 5. Enter scheduling/idle loop
//
int main(int argc, char* argv[])
{

	// Disable buffering for debugging
	// setbuf(stdout, NULL);
/*
	insertDeltaClock(4, tics10thsec);
	insertDeltaClock(8, tics10thsec);
	insertDeltaClock(1, tics10thsec);
	insertDeltaClock(12, tics10thsec);
	insertDeltaClock(6, tics10thsec);
	insertDeltaClock(1, tics10thsec);
	insertDeltaClock(2, tics10thsec);
	insertDeltaClock(9, tics10thsec);


	dc;
	int i = 0;
	for(i=0; i<deltaClockSize; i++) {
		printf("\n%i: %i seconds - %s", i, dc[i].time, dc[i].sem->name);
	}
*/

	// save context for restart (a system reset would return here...)
	int resetCode = setjmp(reset_context);
	superMode = TRUE;						// supervisor mode

	switch (resetCode)
	{
		case POWER_DOWN_QUIT:				// quit
			powerDown(0);
			printf("\nGoodbye!!");
			return 0;

		case POWER_DOWN_RESTART:			// restart
			powerDown(resetCode);
			printf("\nRestarting system...\n");

		case POWER_UP:						// startup
			break;

		default:
			printf("\nShutting down due to error %d", resetCode);
			powerDown(resetCode);
			return resetCode;
	}

	// output header message
	printf("%s", STARTUP_MSG);

	// initalize OS
	if ( resetCode = initOS()) return resetCode;

	// create global/system semaphores here
	//?? vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

	charReady = createSemaphore("charReady", BINARY, 0);
	inBufferReady = createSemaphore("inBufferReady", BINARY, 0);
	keyboard = createSemaphore("keyboard", BINARY, 1);
	tics1sec = createSemaphore("tics1sec", BINARY, 0);
	tics10thsec = createSemaphore("tics10thsec", BINARY, 0);
	tics10sec = createSemaphore("tics10sec", COUNTING, 0);
	deltaClock = createSemaphore("deltaClock", BINARY, 0);

	//?? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

	// schedule CLI task
	createTask("myShell",			// task name
					P1_shellTask,	// task
					MED_PRIORITY,	// task priority
					argc,			// task arg count
					argv);			// task argument pointers

	/*
	static char* dcArgv[] = {"deltaClock"};
	createTask("deltaClock",
					delta_clock_task,
					HIGH_PRIORITY,
					1,
					dcArgv);
	*/
	// HERE WE GO................

	// Scheduling loop
	// 1. Check for asynchronous events (character inputs, timers, etc.)
	// 2. Choose a ready task to schedule
	// 3. Dispatch task
	// 4. Loop (forever!)

	while(1)									// scheduling loop
	{
		// check for character / timer interrupts
		pollInterrupts();

		// schedule highest priority ready task
		if ((curTask = scheduler()) < 0) continue;

		// dispatch curTask, quit OS if negative return
		if (dispatcher() < 0) break;
	}											// end of scheduling loop

	// exit os
	longjmp(reset_context, POWER_DOWN_QUIT);

	return 0;
} // end main
Exemplo n.º 4
0
void clientDisplay(void) {


	updateCamera();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
	glDisable(GL_LIGHTING);

	//GL_ShapeDrawer::drawCoordSystem();

	float m[16];
	int i;
#ifdef USE_GJK
	btGjkEpaPenetrationDepthSolver epa;
	btGjkPairDetector	convexConvex(shapePtr[0],shapePtr[1],&sGjkSimplexSolver,&epa);

	btVector3 seperatingAxis(0.00000000f,0.059727669f,0.29259586f);
	convexConvex.setCachedSeperatingAxis(seperatingAxis);

	btPointCollector gjkOutput;
	btGjkPairDetector::ClosestPointInput input;
	input.m_transformA = tr[0];
	input.m_transformB = tr[1];

	convexConvex.getClosestPoints(input ,gjkOutput,0);

	if (gjkOutput.m_hasResult)
	{
		btVector3 endPt = gjkOutput.m_pointInWorld +
			gjkOutput.m_normalOnBInWorld*gjkOutput.m_distance;

		 glBegin(GL_LINES);
		glColor3f(1, 0, 0);
		glVertex3d(gjkOutput.m_pointInWorld.x(), gjkOutput.m_pointInWorld.y(),gjkOutput.m_pointInWorld.z());
		glVertex3d(endPt.x(),endPt.y(),endPt.z());
		glEnd();

	}
#else //USE_GJK

	
	struct	MyContactResultCallback : public btCollisionWorld::ContactResultCallback
	{
		virtual	btScalar	addSingleResult(btManifoldPoint& cp,	const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1)
		{
			 glBegin(GL_LINES);
			glColor3f(1, 0, 0);
			
			glVertex3d(cp.m_positionWorldOnA.getX(),cp.m_positionWorldOnA.getY(),cp.m_positionWorldOnA.getZ());
			glVertex3d(cp.m_positionWorldOnB.getX(),cp.m_positionWorldOnB.getY(),cp.m_positionWorldOnB.getZ());
			glEnd();

			return 1.f;
		}
	};

	btDefaultCollisionConfiguration collisionConfiguration;
	btCollisionDispatcher				dispatcher(&collisionConfiguration);
	btDbvtBroadphase pairCache;
	btCollisionWorld world (&dispatcher,&pairCache,&collisionConfiguration);
	world.getDispatchInfo().m_convexMaxDistanceUseCPT = true;
	MyContactResultCallback result;
	btCollisionObject obA;
	obA.setCollisionShape(shapePtr[0]);
	obA.setWorldTransform(tr[0]);
	btCollisionObject obB;
	obB.setCollisionShape(shapePtr[1]);
	obB.setWorldTransform(tr[1]);
	world.contactPairTest(&obA,&obB,result);

#endif//USE_GJK

	btVector3 worldMin(-1000,-1000,-1000);
	btVector3 worldMax(1000,1000,1000);

	for (i=0;i<numObjects;i++)
	{
		
		tr[i].getOpenGLMatrix( m );

		shapeDrawer.drawOpenGL(m,shapePtr[i],btVector3(1,1,1),debugMode, worldMin, worldMax);


	}

	simplex.setSimplexSolver(&sGjkSimplexSolver);
	btVector3 ybuf[4],pbuf[4],qbuf[4];
	int numpoints = sGjkSimplexSolver.getSimplex(pbuf,qbuf,ybuf);
	simplex.reset();
	
	for (i=0;i<numpoints;i++)
		simplex.addVertex(ybuf[i]);

	btTransform ident;
	ident.setIdentity();
	ident.getOpenGLMatrix(m);
	shapeDrawer.drawOpenGL(m,&simplex,btVector3(1,1,1),debugMode, worldMin,worldMax);


	btQuaternion orn;
	orn.setEuler(yaw,pitch,roll);
	tr[0].setRotation(orn);
	tr[1].setRotation(orn);

	pitch += 0.005f;
	yaw += 0.01f;

	glFlush();
    glutSwapBuffers();
}
Exemplo n.º 5
0
 ReportBuilder::ReportBuilder(cppcms::service &srv):Master(srv)
 {
     dispatcher().assign("/?",&ReportBuilder::prepare,this);
     mapper().assign("/"); // default empty url
 }
Exemplo n.º 6
0
//-------------------------------------------------------------------------------------
bool Componentbridge::findInterfaces()
{
	int8 findComponentTypes[] = {UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE, 
								UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE, UNKNOWN_COMPONENT_TYPE};

	switch(componentType_)
	{
	case CELLAPP_TYPE:
		findComponentTypes[0] = DBMGR_TYPE;
		findComponentTypes[1] = CELLAPPMGR_TYPE;
		findComponentTypes[2] = BASEAPPMGR_TYPE;
		findComponentTypes[3] = MESSAGELOG_TYPE;
		//findComponentTypes[4] = RESOURCEMGR_TYPE;
		break;
	case BASEAPP_TYPE:
		findComponentTypes[0] = DBMGR_TYPE;
		findComponentTypes[1] = BASEAPPMGR_TYPE;
		findComponentTypes[2] = CELLAPPMGR_TYPE;
		findComponentTypes[3] = MESSAGELOG_TYPE;
		findComponentTypes[4] = RESOURCEMGR_TYPE;
		break;
	case BASEAPPMGR_TYPE:
		findComponentTypes[0] = DBMGR_TYPE;
		findComponentTypes[1] = CELLAPPMGR_TYPE;
		findComponentTypes[2] = MESSAGELOG_TYPE;
		break;
	case CELLAPPMGR_TYPE:
		findComponentTypes[0] = DBMGR_TYPE;
		findComponentTypes[1] = BASEAPPMGR_TYPE;
		findComponentTypes[2] = MESSAGELOG_TYPE;
		break;
	case LOGINAPP_TYPE:
		findComponentTypes[0] = DBMGR_TYPE;
		findComponentTypes[1] = BASEAPPMGR_TYPE;
		findComponentTypes[2] = MESSAGELOG_TYPE;
		break;
	case DBMGR_TYPE:
		findComponentTypes[0] = MESSAGELOG_TYPE;
		break;
	default:
		break;
	};

	int ifind = 0;
	srand(KBEngine::getSystemTime());
	uint16 nport = KBE_PORT_START + (rand() % 1000);

	while(findComponentTypes[ifind] != UNKNOWN_COMPONENT_TYPE)
	{
		if(dispatcher().isBreakProcessing())
			return false;

		int8 findComponentType = findComponentTypes[ifind];

		INFO_MSG("Componentbridge::process: finding %s...\n",
			COMPONENT_NAME[findComponentType]);
		
		Mercury::BundleBroadcast bhandler(networkInterface_, nport);
		if(!bhandler.good())
		{
			KBEngine::sleep(10);
			nport = KBE_PORT_START + (rand() % 1000);
			continue;
		}

		if(bhandler.pCurrPacket() != NULL)
		{
			bhandler.pCurrPacket()->resetPacket();
		}

		bhandler.newMessage(MachineInterface::onFindInterfaceAddr);
		MachineInterface::onFindInterfaceAddrArgs6::staticAddToBundle(bhandler, getUserUID(), getUsername(), 
			componentType_, findComponentType, networkInterface_.intaddr().ip, bhandler.epListen().addr().port);

		if(!bhandler.broadcast())
		{
			ERROR_MSG("Componentbridge::process: broadcast error!\n");
			return false;
		}
	
		MachineInterface::onBroadcastInterfaceArgs8 args;
		if(bhandler.receive(&args, 0))
		{
			if(args.componentType == UNKNOWN_COMPONENT_TYPE)
			{
				//INFO_MSG("Componentbridge::process: not found %s, try again...\n",
				//	COMPONENT_NAME[findComponentType]);
				
				KBEngine::sleep(1000);
				
				// 如果是这些辅助组件没找到则跳过
				if(findComponentType == MESSAGELOG_TYPE || findComponentType == RESOURCEMGR_TYPE)
				{
					WARNING_MSG("Componentbridge::process: not found %s!\n",
						COMPONENT_NAME[findComponentType]);

					findComponentTypes[ifind] = -1; // 跳过标志

					ifind++;
				}

				continue;
			}

			INFO_MSG("Componentbridge::process: found %s, addr:%s:%u\n",
				COMPONENT_NAME[args.componentType], inet_ntoa((struct in_addr&)args.intaddr), ntohs(args.intaddr));

			Componentbridge::getComponents().addComponent(args.uid, args.username.c_str(), 
				(KBEngine::COMPONENT_TYPE)args.componentType, args.componentID, args.intaddr, args.intport, args.extaddr, args.extport);
			
			// 防止接收到的数据不是想要的数据
			if(findComponentType == args.componentType)
			{
				ifind++;
			}
			else
			{
				ERROR_MSG("Componentbridge::process: %s not found. receive data is error!\n", COMPONENT_NAME[findComponentType]);
			}
		}
		else
		{
			ERROR_MSG("Componentbridge::process: receive error!\n");
			return false;
		}
	}
	
	ifind = 0;

	// 开始注册到所有的组件
	while(findComponentTypes[ifind] != UNKNOWN_COMPONENT_TYPE)
	{
		if(dispatcher().isBreakProcessing())
			return false;

		int8 findComponentType = findComponentTypes[ifind++];
		
		if(findComponentType == -1)
			continue;

		INFO_MSG("Componentbridge::process: register self to %s...\n",
			COMPONENT_NAME[findComponentType]);

		if(getComponents().connectComponent(static_cast<COMPONENT_TYPE>(findComponentType), getUserUID(), 0) != 0)
		{
			ERROR_MSG("Componentbridge::register self to %s is error!\n",
			COMPONENT_NAME[findComponentType]);

			dispatcher().breakProcessing();
			return false;
		}
	}

	return true;
}
Exemplo n.º 7
0
int superFormula(const char* szClassName, int x, int y, int width, int height)
{
  docgl::GLDirectContext context;
  SuperFormula superFormula(context);
  OpenGLWindow window(context);

  if (!window.create(superFormula, x, y, width, height, szClassName))
  {
    printf("Error: Unable to create OpenGL Window.\n");
    jassertfalse;
    return 1;
  }

  if (context.initialize().hasErrors())
  {
    window.destroy();
    jassertfalse;
    fprintf(stderr, "GLContext initialize error\n");
    return 2;
  }

#ifdef DOCGL4_1
  printf("max subroutines per shader stage: %u\n", superFormula.context.getMaxSubRoutines());
  printf("max subroutines uniform locations per stage: %u\n", superFormula.context.getMaxSubRoutinesUniformLocation());
#endif // !DOCGL4_1
  printf("SuperFormula HELP:\n");
  printf("[A]/[Q] +- a\n");
  printf("[Z]/[S] +- b\n");
  printf("[E]/[D] +- m\n");
  printf("[R]/[F] +- n1\n");
  printf("[T]/[G] +- n2\n");
  printf("[Y]/[H] +- n3\n");
  printf("Moving Help:\n");
  printf("[8]/[2] Rotate around X axis\n");
  printf("[4]/[6] Rotate around Y axis\n");
  printf("Rendering Help:\n");
  printf("[+] cicle primitives\n");
  printf("[-] switch orientations\n");
  printf("[/] cull face on/off\n");
  printf("[.] depth test on/off\n");
#ifdef DOCGL4_1
  printf("[0] invert color on/off\n");
#endif // !DOCGL4_1
  printf("[ESC] exit\n");

  superFormula.SetupRC();
  superFormula.resized(width, height);

  OpenGLWindow* windowsLists = &window;
  EventDispatcher dispatcher(&windowsLists, 1);
  while (superFormula.running)
  {
    if (!dispatcher.dispatchNextEvent())
    {
      if (window.isVisible() && superFormula.running)
      {
        superFormula.draw(); // no message to dispatch: render the scene.
        window.swapBuffers(); // Flush drawing commands
      }
    }
  }

  superFormula.ShutdownRC();
  window.destroy();

  printf("exit\n");
  return 0;
}
Exemplo n.º 8
0
void TextureConverter::DecodeTexture(VkCommandBuffer command_buffer,
                                     TextureCache::TCacheEntry* entry, u32 dst_level,
                                     const u8* data, size_t data_size, TextureFormat format,
                                     u32 width, u32 height, u32 aligned_width, u32 aligned_height,
                                     u32 row_stride, const u8* palette, TLUTFormat palette_format)
{
  VKTexture* destination_texture = static_cast<VKTexture*>(entry->texture.get());
  auto key = std::make_pair(format, palette_format);
  auto iter = m_decoding_pipelines.find(key);
  if (iter == m_decoding_pipelines.end())
    return;

  struct PushConstants
  {
    u32 dst_size[2];
    u32 src_size[2];
    u32 src_offset;
    u32 src_row_stride;
    u32 palette_offset;
  };

  // Copy to GPU-visible buffer, aligned to the data type
  auto info = iter->second;
  u32 bytes_per_buffer_elem =
      TextureConversionShader::GetBytesPerBufferElement(info.base_info->buffer_format);

  // Calculate total data size, including palette.
  // Only copy palette if it is required.
  u32 total_upload_size = static_cast<u32>(data_size);
  u32 palette_size = iter->second.base_info->palette_size;
  u32 palette_offset = total_upload_size;
  bool has_palette = palette_size > 0;
  if (has_palette)
  {
    // Align to u16.
    if ((total_upload_size % sizeof(u16)) != 0)
    {
      total_upload_size++;
      palette_offset++;
    }

    total_upload_size += palette_size;
  }

  // Allocate space for upload, if it fails, execute the buffer.
  if (!m_texel_buffer->ReserveMemory(total_upload_size, bytes_per_buffer_elem))
  {
    Util::ExecuteCurrentCommandsAndRestoreState(true, false);
    if (!m_texel_buffer->ReserveMemory(total_upload_size, bytes_per_buffer_elem))
      PanicAlert("Failed to reserve memory for encoded texture upload");
  }

  // Copy/commit upload buffer.
  u32 texel_buffer_offset = static_cast<u32>(m_texel_buffer->GetCurrentOffset());
  std::memcpy(m_texel_buffer->GetCurrentHostPointer(), data, data_size);
  if (has_palette)
    std::memcpy(m_texel_buffer->GetCurrentHostPointer() + palette_offset, palette, palette_size);
  m_texel_buffer->CommitMemory(total_upload_size);

  // Determine uniforms.
  PushConstants constants = {
      {width, height},
      {aligned_width, aligned_height},
      texel_buffer_offset / bytes_per_buffer_elem,
      row_stride / bytes_per_buffer_elem,
      static_cast<u32>((texel_buffer_offset + palette_offset) / sizeof(u16))};

  // Determine view to use for texel buffers.
  VkBufferView data_view = VK_NULL_HANDLE;
  switch (iter->second.base_info->buffer_format)
  {
  case TextureConversionShader::BUFFER_FORMAT_R8_UINT:
    data_view = m_texel_buffer_view_r8_uint;
    break;
  case TextureConversionShader::BUFFER_FORMAT_R16_UINT:
    data_view = m_texel_buffer_view_r16_uint;
    break;
  case TextureConversionShader::BUFFER_FORMAT_R32G32_UINT:
    data_view = m_texel_buffer_view_r32g32_uint;
    break;
  default:
    break;
  }

  // Dispatch compute to temporary texture.
  ComputeShaderDispatcher dispatcher(command_buffer,
                                     g_object_cache->GetPipelineLayout(PIPELINE_LAYOUT_COMPUTE),
                                     iter->second.compute_shader);
  m_decoding_texture->TransitionToLayout(command_buffer, Texture2D::ComputeImageLayout::WriteOnly);
  dispatcher.SetPushConstants(&constants, sizeof(constants));
  dispatcher.SetStorageImage(m_decoding_texture->GetView(), m_decoding_texture->GetLayout());
  dispatcher.SetTexelBuffer(0, data_view);
  if (has_palette)
    dispatcher.SetTexelBuffer(1, m_texel_buffer_view_r16_uint);
  auto groups = TextureConversionShader::GetDispatchCount(iter->second.base_info, aligned_width,
                                                          aligned_height);
  dispatcher.Dispatch(groups.first, groups.second, 1);

  // Copy from temporary texture to final destination.
  Texture2D* vulkan_tex_identifier = destination_texture->GetRawTexIdentifier();
  m_decoding_texture->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
  vulkan_tex_identifier->TransitionToLayout(command_buffer, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
  VkImageCopy image_copy = {{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
                            {0, 0, 0},
                            {VK_IMAGE_ASPECT_COLOR_BIT, dst_level, 0, 1},
                            {0, 0, 0},
                            {width, height, 1}};
  vkCmdCopyImage(command_buffer, m_decoding_texture->GetImage(),
                 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vulkan_tex_identifier->GetImage(),
                 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy);
}
Exemplo n.º 9
0
void RfbClient::execute()
{
  // Initialized by default message that will be logged on normal way
  // of disconnection.
  StringStorage peerStr;
  getPeerHost(&peerStr);
  StringStorage sysLogMessage;
  sysLogMessage.format(_T("The client %s has disconnected"),
                       peerStr.getString());

  ServerConfig *config = Configurator::getInstance()->getServerConfig();

  WindowsEvent connClosingEvent;

  SocketStream sockStream(m_socket);

  RfbOutputGate output(&sockStream);
  RfbInputGate input(&sockStream);

  FileTransferRequestHandler *fileTransfer = 0;

  RfbInitializer rfbInitializer(&sockStream, m_extAuthListener, this,
                                !m_isOutgoing);

  try {
    // First initialization phase
    try {
      m_log->info(_T("Entering RFB initialization phase 1"));
      rfbInitializer.authPhase();
      setClientState(IN_AUTH);
      m_log->debug(_T("RFB initialization phase 1 completed"));

      m_shared = rfbInitializer.getSharedFlag();
      m_log->debug(_T("Shared flag = %d"), (int)m_shared);
      m_viewOnlyAuth = rfbInitializer.getViewOnlyAuth();
      m_log->debug(_T("Initial view-only state = %d"), (int)m_viewOnly);
      m_log->debug(_T("Authenticated with view-only password = %d"), (int)m_viewOnlyAuth);
      m_viewOnly = m_viewOnly || m_viewOnlyAuth;

      // Let RfbClientManager handle new authenticated connection.
      m_desktop = m_extAuthListener->onClientAuth(this);

      m_log->info(_T("View only = %d"), (int)m_viewOnly);
    } catch (Exception &e) {
      m_log->error(_T("Error during RFB initialization: %s"), e.getMessage());
      throw;
    }
    _ASSERT(m_desktop != 0);

    m_constViewPort.initDesktopInterface(m_desktop);
    m_dynamicViewPort.initDesktopInterface(m_desktop);

    RfbDispatcher dispatcher(&input, &connClosingEvent);
    m_log->debug(_T("Dispatcher has been created"));
    CapContainer srvToClCaps, clToSrvCaps, encCaps;
    RfbCodeRegistrator codeRegtor(&dispatcher, &srvToClCaps, &clToSrvCaps,
                                  &encCaps);
    // Init modules
    // UpdateSender initialization
    m_updateSender = new UpdateSender(&codeRegtor, m_desktop,
                                      &output, m_id, m_log);
    m_log->debug(_T("UpdateSender has been created"));
    PixelFormat pf;
    Dimension fbDim;
    m_desktop->getFrameBufferProperties(&fbDim, &pf);
    Rect viewPort = getViewPortRect(&fbDim);
    m_updateSender->init(&Dimension(&viewPort), &pf);
    m_log->debug(_T("UpdateSender has been initialized"));
    // ClientInputHandler initialization
    m_clientInputHandler = new ClientInputHandler(&codeRegtor, this,
                                                  m_viewOnly);
    m_log->debug(_T("ClientInputHandler has been created"));
    // ClipboardExchange initialization
    m_clipboardExchange = new ClipboardExchange(&codeRegtor, m_desktop, &output,
                                                m_viewOnly, m_log);
    m_log->debug(_T("ClipboardExchange has been created"));

    // FileTransfers initialization
    if (config->isFileTransfersEnabled() &&
        rfbInitializer.getTightEnabledFlag()) {
      fileTransfer = new FileTransferRequestHandler(&codeRegtor, &output, m_desktop, m_log, !m_viewOnly);
      m_log->debug(_T("File transfer has been created"));
    } else {
      m_log->info(_T("File transfer is not allowed"));
    }

    // Second initialization phase
    // Send and receive initialization information between server and viewer
    m_log->debug(_T("View port: (%d,%d) (%dx%d)"), viewPort.left,
                                                 viewPort.top,
                                                 viewPort.getWidth(),
                                                 viewPort.getHeight());
    m_log->info(_T("Entering RFB initialization phase 2"));
    rfbInitializer.afterAuthPhase(&srvToClCaps, &clToSrvCaps,
                                  &encCaps, &Dimension(&viewPort), &pf);
    m_log->debug(_T("RFB initialization phase 2 completed"));

    // Start normal phase
    setClientState(IN_NORMAL_PHASE);

    m_log->info(_T("Entering normal phase of the RFB protocol"));
    dispatcher.resume();

    connClosingEvent.waitForEvent();
  } catch (Exception &e) {
    m_log->error(_T("Connection will be closed: %s"), e.getMessage());
    sysLogMessage.format(_T("The client %s has been")
                         _T(" disconnected for the reason: %s"),
                         peerStr.getString(), e.getMessage());
  }

  disconnect();
  m_newConnectionEvents->onDisconnect(&sysLogMessage);

  // After this call, we are guaranteed not to be used by other threads.
  notifyAbStateChanging(IN_PENDING_TO_REMOVE);

  if (fileTransfer)         delete fileTransfer;
  if (m_clipboardExchange)  delete m_clipboardExchange;
  if (m_clientInputHandler) delete m_clientInputHandler;
  if (m_updateSender)       delete m_updateSender;

  // Let the client manager remove us from the client lists.
  notifyAbStateChanging(IN_READY_TO_REMOVE);
}
Exemplo n.º 10
0
/* ------------------------------------------------------------------------
   Name - startup
   Purpose - Initializes semaphores, process lists and interrupt vector.
             Start up sentinel process and the P2_Startup process.
   Parameters - none, called by USLOSS
   Returns - nothing
   Side Effects - lots, starts the whole thing
   ----------------------------------------------------------------------- */
void startup()
{
  Check_Your_Privilege();
  // int_disable();
  int i;
  /* initialize the process table here */
  for(i = 0; i < P1_MAXPROC; i++){
      PCB dummy;
      procTable[i]=dummy;
      //USLOSS_Context DummyCon;
      procTable[i].priority = -1;
      //procTable[i].context=DummyCon;
  }

  /* Initialize the Ready list, Blocked list, etc. here */
  readyHead.prevPCB=NULL;
  readyHead.nextPCB=NULL;
  blockedHead.prevPCB=NULL;
  blockedHead.nextPCB=NULL;
  quitListHead.nextPCB=NULL;
  quitListHead.prevPCB=NULL;
  /* Initialize the interrupt vector here */
  USLOSS_IntVec[USLOSS_CLOCK_INT] = &clockHandler;
  USLOSS_IntVec[USLOSS_ALARM_INT] = &tempAlarmHandler;
  USLOSS_IntVec[USLOSS_DISK_INT] = &tempDiskHandler;
  USLOSS_IntVec[USLOSS_TERM_INT] = &tempTermHandler;
  USLOSS_IntVec[USLOSS_MMU_INT] = &tempMMUHandler;
  USLOSS_IntVec[USLOSS_SYSCALL_INT] = &tempSyscallHandler;
  /* Initialize the semaphores here */
  

/*initialize the semaphore table*/
  for(i=0; i< P1_MAXSEM; i++){
    Semaphore *dummy = malloc(sizeof(Semaphore));
    PCB listHead;
    dummy->queue=&listHead;
    semTable[i] = *dummy;
    semTable[i].value = -1;
    semTable[i].valid = 0;
    semTable[i].queue = malloc(sizeof(PCB));
  }

  /*Fork Semaphore*/
  P1_SemCreate(1);
  /* semaphores for the processes */
  for(i=1; i < 50; i++){
    P1_SemCreate(0);
  }
  /* semaphores for the 6 devices */
  for(i=0; i < 6; i++){
    P1_SemCreate(0);
  }

 
  /* startup a sentinel process */
  /* HINT: you don't want any forked processes to run until startup is finished.
   * You'll need to do something in your dispatcher to prevent that from happening.
   * Otherwise your sentinel will start running right now and it will call P1_Halt. 
   */
  P1_Fork("sentinel", sentinel, NULL, USLOSS_MIN_STACK, 6);

  /* start the P2_Startup process */
  P1_Fork("P2_Startup", P2_Startup, NULL, 4 * USLOSS_MIN_STACK, 1);

  // int_enable();
  // USLOSS_Console("Startup finished\n");
  dispatcher();

  /* Should never get here (sentinel will call USLOSS_Halt) */

  return;
} /* End of startup */
Exemplo n.º 11
0
/* ------------------------------------------------------------------------
   Name - P1_Fork
   Purpose - Gets a new process from the process table and initializes
             information of the process.  Updates information in the
             parent process to reflect this child process creation.
   Parameters - the process procedure address, the size of the stack and
                the priority to be assigned to the child process.
   Returns - the process id of the created child or an error code.
   Side Effects - ReadyList is changed, procTable is changed, Current
                  process information changed
   ------------------------------------------------------------------------ */
int P1_Fork(char *name, int (*f)(void *), void *arg, int stacksize, int priority)
{
    /*Check current Mode. If not Kernel Mode return error*/
    Check_Your_Privilege();
    // USLOSS_Console("Proc %s passed Privilege Check\n",name);
    //free the available spots
    free_Procs();

    /*Check Priority and Stack Size*/
    if(priority<1||priority>6){//is priority # valid
      return -3;
    }
    if(stacksize<USLOSS_MIN_STACK){//is stacksize valid
      return -2;
    }
    // P1_Semaphore sema=&semTable[0];
    //find PID
    int newPid = 0;
    while(procTable[newPid].priority!=-1){
      newPid++;
      if(newPid>=P1_MAXPROC){
        return -1;
      }
    }

    int_disable();
    /* stack = allocated stack here */
    // void* newStack=malloc(stacksize*sizeof(char));
    procTable[newPid].stack=malloc(stacksize*sizeof(char));
    procTable[newPid].notFreed=1;

    /*set PCB fields*/
    procTable[newPid].PID=newPid;
    procTable[newPid].cpuTime=0;
    procTable[newPid].lastStartedTime=FIRST_RUN;
    procTable[newPid].state=1;//0=running 1=ready,2=killed,3=quit,4=waiting

    procTable[newPid].status=DEFAULT;
    procTable[newPid].isOrphan= 0;
    if(currPid==-1){
      // USLOSS_Console("Start up %s Orphan\n",name);
      procTable[newPid].isOrphan=1;
    }   
    
    procTable[newPid].parent=currPid;
    procTable[currPid].numChildren++;//increment parents numChildren
    procTable[newPid].numChildren=0;
    procTable[newPid].priority=priority;
    procTable[newPid].waitingOnDevice=0;
    procTable[newPid].name=strdup(name);
    procTable[newPid].startFunc = f;
    procTable[newPid].startArg = arg;
    
    /*PCB Fields are set*/

    // USLOSS_Console("proc %s forked to PID %d\n",name,newPid);
    /*add to ready list*/
    addToReadyList(newPid);    

    /*increment numProcs*/
    numProcs++;
    
    /*initialize context*/
    USLOSS_ContextInit(&(procTable[newPid].context), USLOSS_PsrGet(), procTable[newPid].stack, 
        stacksize, launch);
    int_enable();

    
    /*Run dispatcher if forking higher priority process*/
    if(currPid != -1&&priority<procTable[currPid].priority){
      dispatcher();
    }
    //USLOSS_Console("In Fork PID -- after:  %d\n", currPid);

    return newPid;
} /* End of fork */
Exemplo n.º 12
0
int main(void) {
    void *handler;
    void *handler2;
    void* theqtdp=NULL;
    void* compcall=NULL;
    void* compcallws=NULL;
    ComponentResult (*dispatcher)(ComponentParameters *params, Globals glob);
    ComponentResult ret;
    ComponentParameters *params;
    ComponentDescription desc;
    void *globals=NULL;
    //unsigned int esp=0;
    //int i;

    mp_msg_init();
    //mp_msg_set_level(10);

    Setup_LDT_Keeper();
    printf("loading qts\n");
//    handler = LoadLibraryA("/root/.wine/fake_windows/Windows/System/QuickTime.qts");
    handler = LoadLibraryA("QuickTime.qts");
    theqtdp = GetProcAddress(handler, "theQuickTimeDispatcher");
    compcall = GetProcAddress(handler, "CallComponent");
    compcallws = GetProcAddress(handler, "CallComponentFunctionWithStorage");

    InitializeQTML = 0x6299e590;//GetProcAddress(handler, "InitializeQTML");
    InitializeQTML(6+16);

    printf("loading svq3\n");
    handler2= LoadLibraryA("/root/.wine/fake_windows/Windows/System/QuickTime/QuickTimeEssentials.qtx");
    printf("done\n");
    dispatcher = GetProcAddress(handler2, "SMD_ComponentDispatch");
//    handler = expLoadLibraryA("/usr/local/lib/codecs/On2_VP3.qtx");
//    dispatcher = GetProcAddress(handler, "CDComponentDispatcher");
    printf("handler: %p, dispatcher: %p  theqtdp: %p\n", handler, dispatcher, theqtdp);

//    printf("theQuickTimeDispatcher = %p\n",GetProcAddress(handler, "theQuickTimeDispatcher"));

    // patch svq3 dll:
    *((void**)0x63214c98) = NULL;
    *((void**)0x63214c9c) = theqtdp; // theQt...
    *((void**)0x63214ca0) = compcall; //0xdeadbeef; //dispatcher; // CallCOmponent_ptr
    *((void**)0x63214ca4) = compcallws; //0xdeadbef2; //dispatcher; // CallComponentWithStorage_ptr

    desc.componentType=0;
    desc.componentSubType=0;
    desc.componentManufacturer=0;
    desc.componentFlags=0;
    desc.componentFlagsMask=0;

    params = malloc(sizeof(ComponentParameters)+2048);

    params->flags = 0;
    params->paramSize = 4;
    params->what = kComponentOpenSelect;
    params->params[0] = 0x830000; //0x820000|i; //(i<<16)|0x24; //0x820024;
    ret = dispatcher(params, &globals);
    printf("!!! CDComponentDispatch() => 0x%X  glob=%p\n",ret,globals);

//    memset(x_table,12,4*0x00001837);

//for(i=0;i<=255;i++){

    // params->what = kComponentVersionSelect;
    // params->what = kComponentRegisterSelect;
    // params->what = kComponentOpenSelect;
    // params->what = kComponentCanDoSelect;

    printf("params: flags: %d, paramSize: %d, what: %d, params[0] = %x\n",
        params->flags, params->paramSize, params->what, params->params[0]);

//    __asm__ volatile ("movl %%esp, %0\n\t" : "=a" (esp) :: "memory" );
//    printf("ESP=%p\n",esp);

    *((void**)0x62b7d640) = &x_table[0]; //malloc(0x00001837 * 4); // ugly hack?

    printf("params=%p  &glob=%p  x_table=%p\n",params,&globals, &x_table[0]);

    ret = dispatcher(params, &globals);

//    __asm__ volatile ("movl %%esp, %0\n\t" : "=a" (esp) :: "memory" );
//    printf("ESP=%p\n",esp);

    printf("!!! CDComponentDispatch() => %d  glob=%p\n",ret,globals);
//    if(ret!=-3000) break;
//}

//    for(i=0;i<0x00001837;i++)
//	if(x_table[i]) printf("x_table[0x%X] = %p\n",i,x_table[i]);

    exit(0);
    //return 0;
}
void TWebSocketWorker::execute(int opcode, const QByteArray &payload)
{
    bool sendTask = false;
    QString es = TUrlRoute::splitPath(_requestPath).value(0).toLower() + "endpoint";
    TDispatcher<TWebSocketEndpoint> dispatcher(es);
    TWebSocketEndpoint *endpoint = dispatcher.object();

    if (!endpoint) {
        return;
    }

    try {
        tSystemDebug("Found endpoint: %s", qPrintable(es));
        tSystemDebug("TWebSocketWorker opcode: %d", opcode);

        endpoint->sessionStore = _socket->session(); // Sets websocket session
        endpoint->uuid = _socket->socketUuid();
        // Database Transaction
        setTransactionEnabled(endpoint->transactionEnabled());

        switch (_mode) {
        case Opening: {
            bool res = endpoint->onOpen(_httpSession);
            if (res) {
                // For switch response
                endpoint->taskList.prepend(qMakePair((int)TWebSocketEndpoint::OpenSuccess, QVariant()));

                if (endpoint->keepAliveInterval() > 0) {
                    endpoint->startKeepAlive(endpoint->keepAliveInterval());
                }
            } else {
                endpoint->taskList.prepend(qMakePair((int)TWebSocketEndpoint::OpenError, QVariant()));
            }
            break; }

        case Closing:
            if (!_socket->closing.exchange(true)) {
                endpoint->onClose(Tf::GoingAway);
                endpoint->unsubscribeFromAll();
            }
            break;

        case Receiving: {

            switch (opcode) {
            case TWebSocketFrame::TextFrame:
                endpoint->onTextReceived(QString::fromUtf8(payload));
                break;

            case TWebSocketFrame::BinaryFrame:
                endpoint->onBinaryReceived(payload);
                break;

            case TWebSocketFrame::Close: {
                quint16 closeCode = Tf::GoingAway;
                if (payload.length() >= 2) {
                    QDataStream ds(payload);
                    ds.setByteOrder(QDataStream::BigEndian);
                    ds >> closeCode;
                }

                if (!_socket->closing.exchange(true)) {
                    endpoint->onClose(closeCode);
                    endpoint->unsubscribeFromAll();
                }
                endpoint->close(closeCode);  // close response or disconnect
                break; }

            case TWebSocketFrame::Ping:
                endpoint->onPing(payload);
                break;

            case TWebSocketFrame::Pong:
                endpoint->onPong(payload);
                break;

            default:
                tSystemWarn("Invalid opcode: 0x%x  [%s:%d]", (int)opcode, __FILE__, __LINE__);
                break;
            }
            break; }

        default:
            break;
        }

        // Sets session to the websocket
        _socket->setSession(endpoint->session());

        for (auto &p : endpoint->taskList) {
            const QVariant &taskData = p.second;

            switch (p.first) {
            case TWebSocketEndpoint::OpenSuccess:
                _socket->sendHandshakeResponse();
                break;

            case TWebSocketEndpoint::OpenError:
                _socket->closing = true;
                _socket->closeSent = true;
                _socket->disconnect();
                goto open_error;
                break;

            case TWebSocketEndpoint::SendText:
                _socket->sendText(taskData.toString());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendBinary:
                _socket->sendBinary(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendClose:
                if (_socket->closing.load() && _socket->closeSent.load()) {
                    // close-frame sent and received
                    _socket->disconnect();
                } else {
                    uint closeCode = taskData.toUInt();
                    _socket->sendClose(closeCode);
                    sendTask = true;
                }
                break;

            case TWebSocketEndpoint::SendPing:
                _socket->sendPing(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendPong:
                _socket->sendPong(taskData.toByteArray());
                sendTask = true;
                break;

            case TWebSocketEndpoint::SendTextTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendText(lst[1].toString());
                }
                break; }

            case TWebSocketEndpoint::SendBinaryTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendBinary(lst[1].toByteArray());
                }
                break; }

            case TWebSocketEndpoint::SendCloseTo: {
                QVariantList lst = taskData.toList();
                TAbstractWebSocket *websocket = _socket->searchPeerSocket(lst[0].toByteArray());
                if (websocket) {
                    websocket->sendClose(lst[1].toInt());
                }
                break; }

            case TWebSocketEndpoint::Subscribe: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->subscribe(lst[0].toString(), lst[1].toBool(), _socket);
                break; }

            case TWebSocketEndpoint::Unsubscribe:
                TPublisher::instance()->unsubscribe(taskData.toString(), _socket);
                break;

            case TWebSocketEndpoint::UnsubscribeFromAll:
                TPublisher::instance()->unsubscribeFromAll(_socket);
                break;

            case TWebSocketEndpoint::PublishText: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->publish(lst[0].toString(), lst[1].toString(), _socket);
                break; }

            case TWebSocketEndpoint::PublishBinary: {
                QVariantList lst = taskData.toList();
                TPublisher::instance()->publish(lst[0].toString(), lst[1].toByteArray(), _socket);
                break; }

            case TWebSocketEndpoint::StartKeepAlive:
                _socket->startKeepAlive(taskData.toInt());
                break;

            case TWebSocketEndpoint::StopKeepAlive:
                _socket->stopKeepAlive();
                break;

            default:
                tSystemError("Invalid logic  [%s:%d]",  __FILE__, __LINE__);
                break;
            }
        }

        if (!sendTask) {
            // Receiving but not sending, so renew keep-alive
            _socket->renewKeepAlive();
        }

    open_error:
        // transaction
        if (Q_UNLIKELY(endpoint->rollbackRequested())) {
            rollbackTransactions();
        } else {
            // Commits a transaction to the database
            commitTransactions();
        }

    } catch (ClientErrorException &e) {
Exemplo n.º 14
0
Arquivo: main.cpp Projeto: Ape/xboxdrv
int main(int argc, char** argv)
{
  enum {
    OPTION_HELP,
    OPTION_DEVICE
  };

  gtk_init(&argc, &argv);

  ArgParser argp;
  argp
    .add_usage("[OPTION]...")
    .add_text("Virtual Keyboard")
    .add_newline()
 
    .add_option(OPTION_HELP,   'h', "help", "", "display this help and exit")
    .add_option(OPTION_DEVICE, 'd', "device", "DEVICE", "read events from device");

  ArgParser::ParsedOptions parsed = argp.parse_args(argc, argv);
  std::string device;
  for(ArgParser::ParsedOptions::const_iterator i = parsed.begin(); i != parsed.end(); ++i)
  {
    const ArgParser::ParsedOption& opt = *i;

    switch (i->key)
    {
      case OPTION_HELP:
        argp.print_help(std::cout);
        exit(EXIT_SUCCESS);
        break;

      case OPTION_DEVICE:
        device = opt.argument;
        break;
    }
  }

  StatusIcon status_icon;
  KeyboardDescriptionPtr keyboard_desc = KeyboardDescription::create_us_layout(); 
  VirtualKeyboard virtual_keyboard(keyboard_desc);

  if (!device.empty())
  {
    UInput uinput(false);
    KeyboardDispatcher dispatcher(virtual_keyboard, uinput);
    KeyboardController controller(virtual_keyboard, uinput, device);
    uinput.finish();

    virtual_keyboard.show();
    gtk_main();
  }
  else
  { 
    {
      std::cout << "--device DEVICE option not given, starting in test mode" << std::endl;
    
      // non-interactive test mode
      virtual_keyboard.show();
      gtk_main();
    }

    return EXIT_SUCCESS;
  }
}
Exemplo n.º 15
0
void TaskDispatcher4StdThread::createAndRun( ThreadPtrPromise* promise) {
	// hide ot the promise would work with an packaged_task, see http://www.boost.org/doc/libs/1_55_0/doc/html/thread/synchronization.html#thread.synchronization.futures
	std::shared_ptr<TaskDispatcher4StdThread> dispatcher(create());
	promise->set_value(dispatcher);
	dispatcher->run();
}
Exemplo n.º 16
0
 void operator()(U&& u) {
     std::lock_guard<std::mutex> lock(mutex);
     msgs.push(std::forward<U>(u));
     dispatcher();
 }
Exemplo n.º 17
0
std::shared_ptr<TaskDispatcher4StdThread>
TaskDispatcher4StdThread::create() {
	std::shared_ptr<TaskDispatcher> dispatcher( new TaskDispatcher4StdThread());
	::initCurrentThread(dispatcher);
	return std::static_pointer_cast<TaskDispatcher4StdThread> (dispatcher);
}
Exemplo n.º 18
0
reply::reply(cppcms::service &srv) : thread_shared(srv)
{
	dispatcher().assign(".*",&reply::prepare,this,0);
	mapper().assign("{1}");
}
Exemplo n.º 19
0
 MailList::MailList(cppcms::service &srv):Master(srv)
 {
     dispatcher().assign("/?",&MailList::prepare,this);
     mapper().assign("/"); // default empty url
 }
Exemplo n.º 20
0
flat_thread::flat_thread(cppcms::service &s) : thread_shared(s)
{
	dispatcher().assign(".*",&flat_thread::prepare,this,0);
	mapper().assign("{1}");
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    char logfile[FILENAME_MAX] = "";
    char switchifname[IFNAMSIZ] = {0};
    int c, err;
    int pid = 0;
    FILE *pidfp = NULL;

    // Default some globals
    strncpy(configfile, NPD6_CONF, FILENAME_MAX);
    strncpy( interfacestr, NULLSTR, sizeof(NULLSTR));
    memset( prefixaddrstr, 0, sizeof(prefixaddrstr));
    interfaceIdx = -1;
    daemonize = 0;
    // Default black/whitelisting to OFF
    listType = NOLIST;
    // Default config file values as required
    naLinkOptFlag = 0;
    nsIgnoreLocal = 1;
    naRouter = 1;
    debug = 0;
    maxHops = MAXMAXHOPS;

    /* Parse the args */
    while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, NULL)) > 0)
    {
        if (c==-1)
            break;

        switch (c) {
        case 'c':
            strcpy(configfile, optarg);
            break;
        case 'l':
            strcpy(logfile, optarg);
            break;
        case 'd':
            debug=1;
            break;
        case 'D':
            debug=2;
            break;
        case 'b':
            daemonize=1;
            break;
        case 'v':
            showVersion();
            return 0;
            break;
        case 'h':
            showUsage();
            return 0;
            break;
        }
    }
    
	/* Seems like about the right time to daemonize (or not) */
    if (daemonize)
    {
        if (daemon(0, 0) < 0 )
        {
            flog(LOG_ERR, "Failed to daemonize. Error: %s", strerror(errno) );
            exit(1);
        }
    }
	
	pid = getpid();
	if ((pidfp = fopen(NDP6PROXY_PIDFILE, "w")) != NULL) {
		fprintf(pidfp, "%d\n", pid);
		fclose(pidfp);
	}
    else
    {
        printf("**************** Open Pid file faild *********************** \r\n");
    }
	
    while (0 >= strlen(prefixaddrstr))
    {
        addr6match(NULL, NULL, 0);
        sleep(1);
    }
    /* Sort out where to log */
    if ( strlen(logfile) )
    {
        if (strlen(logfile) == 1 && (logfile[0]='-')  )
            logging = USE_STD;
        else
            logging = USE_FILE;
    }
    else
    {
        logging = USE_SYSLOG;
    }

    /* Open the log and config*/
    if ( (logging == USE_FILE) && (openLog(logfile) < 0)  )
    {
        printf("Exiting. Error in setting up logging correctly.\n");
        exit (1);
    }
    flog(LOG_INFO, "*********************** npd6 *****************************");

    if ( readConfig(configfile) )
    {
        flog(LOG_ERR, "Error in config file: %s", configfile);
        return 1;
    }

    flog(LOG_INFO, "Using normalised prefix %s/%d", prefixaddrstr, prefixaddrlen);
    flog(LOG_DEBUG2, "ifIndex for %s is: %d", interfacestr, interfaceIdx);

    err = init_sockets();
    if (err) {
        flog(LOG_ERR, "init_sockets: failed to initialise one or both sockets.");
        exit(1);
    }

    /* Set allmulti on the interface */
    while (0 > npd6getwan(switchifname))
    {
        sleep(1);
    }
    if_allmulti(switchifname, TRUE);
    if_allmulti(interfacestr, TRUE);
    /* Set up signal handlers */
    signal(SIGUSR1, usersignal);
    signal(SIGUSR2, usersignal);
    signal(SIGHUP, usersignal);
    signal(SIGINT, usersignal);
    signal(SIGTERM, usersignal);    // Typically used by init.d scripts

    /* And off we go... */
    dispatcher();

    flog(LOG_ERR, "Fell back out of dispatcher... This is impossible.");
    return 0;
}
Exemplo n.º 22
0
int main( int argc, char** argv )
{

#if 0
	CommandDispatcher dispatcher( argc, argv );

	if( dispatcher.hadErrors() )
	{
		for( const auto& error : dispatcher.getErrors() )
		{
			std::cout << error << "\n";
		}
	}
#else
	const std::string path = "C:/Users/alexandru.merisanu/Documents/GitHub/PackageManager/PackageManager/source";
	/*
	std::cout	<< "Is dir: " << utils::Filesystem::isDirectory(path)
				<< "\nIs file: " << utils::Filesystem::isFile(path)
				<< std::endl;
	*/

	namespace fs = utils::Filesystem;

	auto results = fs::recursiveFind< fs::AllResults >(path, "*.cpp");

	for( const auto& i : results )
		std::cout << i << std::endl;
#endif


	// Copy folders
	/*
	Process("xcopy").arg("/E")
					.arg("/I")
					.arg("/Y")
					.arg("external")
					.arg("internal")
					.redirect(StdError, "logs/whatever.txt", Append)
					.run();
	*/

	// Copy files
	/*
	Process("copy")	.arg("/Y")
					.arg("input.xml")
					.arg("output.xml")
					.redirect(StdError, "logs/whatever.txt", Append)
					.run();
					*/
	
	/*
	using namespace utils;

	std::string str = "Testing string replacer";

	std::cout <<	Strings::Mutate(str).replace(' ', '-')
										.replace("string","NOT A STRING")
										.toupper() << "\n";

	std::cout <<	Strings::Keep("Another test of string replacer").replace(' ', '=')
																	.replace("test","NOT A TEST")
																	.tolower() << "\n";
	*/

	//FileDownloader::download( "https://github.com/R3AL/test/raw/master/node/node.exe", "node.exe" );
	std::cin.get();
}
Exemplo n.º 23
0
Pages::Pages(cppcms::service& serv) : Controller(serv) {
    dispatcher().assign("", &Pages::homepage, this);
}
Exemplo n.º 24
0
forums::forums(cppcms::service &srv) : master(srv)
{
	mapper().assign("{1}"); // with id
	mapper().assign("");    // default
	dispatcher().assign(".*",&forums::prepare,this,0);
}
Exemplo n.º 25
0
void    svc( SYSTEM_CALL_DATA *SystemCallData ) {
    short               call_type;
    static short        do_print = 10;
    short               i;
    int                 Time;
    int                 ID;
    int                 k=0,m=0,n=0;
    int                 PR;
    int                 sid,tid,mlen;
    int                 actual_length;
    long                tmp;
    INT32               diskstatus;
    long                tmpid;
    void                *next_context;
    char                *tmpmsg;
    PCB                 *head;
    PCB                 *head1;
    PCB *pcb = (PCB *)malloc(sizeof(PCB));


    call_type = (short)SystemCallData->SystemCallNumber;
    if ( do_print > 0 ) {
        printf( "SVC handler: %s\n", call_names[call_type]);
        for (i = 0; i < SystemCallData->NumberOfArguments - 1; i++ ) {
            //Value = (long)*SystemCallData->Argument[i];
            printf( "Arg %d: Contents = (Decimal) %8ld,  (Hex) %8lX\n", i,
                    (unsigned long )SystemCallData->Argument[i],
                    (unsigned long )SystemCallData->Argument[i]);
        }
    }
    switch(call_type) {
    case SYSNUM_GET_TIME_OF_DAY:
        MEM_READ(Z502ClockStatus, &Time);
        //Z502_REG1=Time;
        *SystemCallData->Argument[0]=Time;
        break;

    case SYSNUM_TERMINATE_PROCESS:
        tmpid = (long)SystemCallData->Argument[0];
        if(tmpid>=0) {
            os_delete_process_ready(tmpid);
            Z502_REG9 = ERR_SUCCESS;
        }
        else if(tmpid == -1)
        {
            head =Running;
            Running = NULL;
            while(readyfront==NULL&&timerfront==NULL) {
                Z502Halt();
            }
            //free(head);
            dispatcher();
            Z502SwitchContext( SWITCH_CONTEXT_SAVE_MODE, &(Running->context) );
        }
        else
            Z502Halt();
        break;
    //the execution of sleep();
    case SYSNUM_SLEEP:
        start_timer( (int)SystemCallData->Argument[0] );

        break;
    case SYSNUM_GET_PROCESS_ID:
        *SystemCallData->Argument[1] = os_get_process_id((char *)SystemCallData->Argument[0]);
        break;
    case SYSNUM_CREATE_PROCESS:
        strcpy(pcb->Processname , (char *)SystemCallData->Argument[0]);
        pcb->Priority = (long)SystemCallData->Argument[2];
        head = readyfront;
        head1 = readyfront;
        if(Pid < 20) {
            if(pcb->Priority >0) {
                if(readyfront == NULL&&readyrear == NULL) {
                    readyfront = pcb;
                    readyrear = pcb;
                    //*SystemCallData->Argument[4] = ERR_SUCCESS;
                    Z502_REG9 = ERR_SUCCESS;
                    pcb->pid = Pid;
                    pcb->next=NULL;
                    Toppriority = pcb->Priority;
                    *SystemCallData->Argument[3] = Pid;
                    //pcb->context = (void *)SystemCallData->Argument[1];
                    Z502MakeContext( &next_context, (void *)SystemCallData->Argument[1], USER_MODE );
                    pcb->context = next_context;
                    Pid++;
                }
                else if(readyfront!=NULL&&readyrear!=NULL) {

                    if(checkPCBname(pcb) == 1) {

                        if(pcb->Priority < Toppriority) {
                            Z502_REG9 = ERR_SUCCESS;
                            pcb->next = readyfront;
                            readyfront = pcb;
                            pcb->pid = Pid;
                            pcb->next=NULL;
                            Z502MakeContext( &next_context, (void *)SystemCallData->Argument[1], USER_MODE );
                            pcb->context = next_context;
                            *SystemCallData->Argument[3] = Pid;
                            Pid++;
                        }
                        else {
                            while(head->next!=NULL) {
                                if(pcb->Priority < head->Priority)
                                    break;
                                else
                                    head = head->next;
                            }

                            if(head->next!=NULL) {
                                while(head1->next!=head)
                                {
                                    head1=head1->next;
                                }
                                Z502_REG9 = ERR_SUCCESS;
                                head1->next = pcb;
                                pcb->next=head;
                                pcb->pid = Pid;
                                Z502MakeContext( &next_context, (void *)SystemCallData->Argument[1], USER_MODE );
                                pcb->context = next_context;
                                *SystemCallData->Argument[3] = Pid;
                                Pid++;
                            }
                            else {
                                if(pcb->Priority < head->Priority) {
                                    while(head1->next!=head)
                                    {
                                        head1=head1->next;
                                    }
                                    Z502_REG9 = ERR_SUCCESS;
                                    head1->next=pcb;
                                    pcb->next=head;
                                    pcb->pid = Pid;
                                    Z502MakeContext( &next_context, (void *)SystemCallData->Argument[1], USER_MODE );
                                    pcb->context = next_context;
                                    *SystemCallData->Argument[3] = Pid;
                                    Pid++;
                                }
                                else {
                                    Z502_REG9 = ERR_SUCCESS;
                                    head->next = pcb;
                                    readyrear = pcb;
                                    pcb->next=NULL;
                                    pcb->pid = Pid;
                                    Z502MakeContext( &next_context, (void *)SystemCallData->Argument[1], USER_MODE );
                                    pcb->context = next_context;
                                    *SystemCallData->Argument[3] = Pid;
                                    Pid++;
                                }
                            }

                        }
                    }
                    else free(pcb);
                }
            } else free(pcb);
        }
        else {
            Z502_REG9++;
            free(pcb);
        }
        break;

    case SYSNUM_SUSPEND_PROCESS:
        ID = (int)SystemCallData->Argument[0];
        head = suspendfront;
        while(head!=NULL) {
            if(head->pid == ID) {
                n = 1;
                break;
            }
            else
                head = head->next;
        }

        if(n!=1) {
            head = readyfront;
            while(head!=NULL) {
                if(head->pid == ID) {
                    Z502_REG9 = ERR_SUCCESS;
                    suspend_process_ready(head);
                    k = 1;
                    break;
                }
                else
                    head = head->next;
            }

            if(k == 0) {
                head = timerfront;
                while(head!=NULL) {
                    if(head->pid == ID) {
                        Z502_REG9 = ERR_SUCCESS;
                        suspend_process_timer(head);
                        m = 1;
                        break;
                    }
                    else
                        head=head->next;
                }
                if(m == 0&&k == 0) {
                    printf("illegal PID\n");
                }
            }
        }
        if(n == 1) {
            printf("can not suspend suspended process\n");
        }
        break;

    case SYSNUM_RESUME_PROCESS:
        ID = (int)SystemCallData->Argument[0];
        head = suspendfront;
        while(head!=NULL) {
            if(head->pid == ID) {
                k=1;
                break;
            }
            else
                head=head->next;
        }
        if(k==1)
            resume_process(head);
        else
            printf("error\n");
        break;
    case SYSNUM_CHANGE_PRIORITY:
        ID = (int)SystemCallData->Argument[0];
        PR = (int)SystemCallData->Argument[1];
        if(ID == -1) {
            Running->Priority = PR;
            Z502_REG9 = ERR_SUCCESS;
        }
        else {
            if(PR < 100) {
                if(checkReady(ID) == 1) {
                    head = readyfront;
                    while(head->pid != ID)
                        head=head->next;
                    change_priority_ready(head,PR);
                    Z502_REG9 = ERR_SUCCESS;
                }
                else if(checkTimer(ID) == 1) {
                    head = timerfront;
                    while(head->pid != ID)
                        head=head->next;
                    change_priority_timer(head,PR);
                    Z502_REG9 = ERR_SUCCESS;
                }
                else if(checkSuspend(ID) == 1) {
                    head = suspendfront;
                    while(head->pid != ID)
                        head = head->next;
                    change_priority_suspend(head,PR);
                    Z502_REG9 = ERR_SUCCESS;
                }
                else {
                    printf("ID ERROR!\n");
                }
            }
            else {
                printf("illegal Priority");
            }
        }
        break;
    case SYSNUM_SEND_MESSAGE:
        sid = Running->pid;
        tid = (int)SystemCallData->Argument[0];
        tmpmsg =(char *)SystemCallData->Argument[1];
        mlen = (int)SystemCallData->Argument[2];
        if(maxbuffer < 8) {
            if(tid < 100) {
                if(mlen < 100)
                {
                    if(tid>0)
                    {   send_message(sid,tid,mlen,tmpmsg);
                        maxbuffer++;
                    }
                    else if(tid == -1) {
                        send_message_to_all(sid,mlen,tmpmsg);
                        maxbuffer++;
                    }
                }
                else {
                    printf("illegal length!\n");
                }
            } else
                printf("illegal id!\n");
        }
        else
        {   printf("no space!\n");
            Z502_REG9++;
        }
        break;
    case  SYSNUM_RECEIVE_MESSAGE:
        sid = (int)SystemCallData->Argument[0];
        mlen = (int)SystemCallData->Argument[2];

        if(sid < 100) {
            if(mlen < 100) {
                if(sid == -1) {

                    receive_message_fromall();
                    if(msgnum>0) {
                        actual_length = strlen(checkmsg->msg_buffer);
                        if(mlen >actual_length) {
                            msg_out_queue(checkmsg);
                            *SystemCallData->Argument[3] = actual_length;
                            *SystemCallData->Argument[4] = checkmsg->source_pid;
                            strcpy((char *)SystemCallData->Argument[1] ,checkmsg->msg_buffer);
                            Z502_REG9 = ERR_SUCCESS;
                        }
                        else {
                            printf("small buffer!\n");
                        }
                    }
                }
                else {
                    receive_message_fromone(sid);
                    if(msgnum>0) {
                        actual_length = strlen(checkmsg->msg_buffer);
                        if(mlen >actual_length) {
                            msg_out_queue(checkmsg);
                            *SystemCallData->Argument[3] = actual_length;
                            *SystemCallData->Argument[4] = checkmsg->source_pid;
                            strcpy((char *)SystemCallData->Argument[1], checkmsg->msg_buffer);
                            Z502_REG9 = ERR_SUCCESS;
                        }
                        else {
                            printf("small buffer!\n");
                        }
                    }
                }
            }
            else
                printf("illegal length!\n");
        }
        else
            printf("illegal id!\n");
        break;
    case  SYSNUM_DISK_READ:
        disk_read(SystemCallData->Argument[0],SystemCallData->Argument[1],SystemCallData->Argument[2]);

        break;
    case SYSNUM_DISK_WRITE:
        disk_write(SystemCallData->Argument[0],SystemCallData->Argument[1],SystemCallData->Argument[2]);
        break;
    default:
        printf("call_type %d cannot be recognized\n",call_type);
        break;
    }

    do_print--;
}
Exemplo n.º 26
0
int main()
{
    odil::Association association;
    association.receive_association(boost::asio::ip::tcp::v4(), 11112);

    std::cout
        << "Received association from "
        << association.get_peer_host() << ":" << association.get_peer_port()
        << "\n";

    auto const & contexts =
        association.get_negotiated_parameters().get_presentation_contexts();
    std::cout << "Presentation contexts (" << contexts.size() << ")\n";
    for(auto const & context: contexts)
    {
        std::cout
            << "    "
            << odil::registry::uids_dictionary.at(context.abstract_syntax).name
            << ": "
            << odil::registry::uids_dictionary.at(context.transfer_syntaxes[0]).name
            << ", "
            << (context.scu_role_support?"SCU":"")
            << ((context.scu_role_support & context.scp_role_support)?"/":"")
            << (context.scp_role_support?"SCP":"")
            << std::endl;
    }

    auto echo_scp = std::make_shared<odil::EchoSCP>(association, echo);
    auto find_scp = std::make_shared<odil::FindSCP>(
        association, std::make_shared<FindGenerator>());
    auto store_scp = std::make_shared<odil::StoreSCP>(association, store);

    odil::SCPDispatcher dispatcher(association);
    dispatcher.set_scp(odil::message::Message::Command::C_ECHO_RQ, echo_scp);
    dispatcher.set_scp(odil::message::Message::Command::C_FIND_RQ, find_scp);
    dispatcher.set_scp(
        odil::message::Message::Command::C_STORE_RQ, store_scp);

    bool done = false;
    while(!done)
    {
        try
        {
            dispatcher.dispatch();
        }
        catch(odil::AssociationReleased const &)
        {
            std::cout << "Peer released association" << std::endl;
            done = true;
        }
        catch(odil::AssociationAborted const & e)
        {
            std::cout
                << "Peer aborted association, "
                << "source: " << int(e.source) << ", "
                << "reason: " << int(e.reason)
                << std::endl;
            done = true;
        }
    }
}
Exemplo n.º 27
0
int main(int argc, char* argv[])
{
    if(!CommandLine::Instance().Parse(argc,argv))
    {
        return -1;
    }

    try
    {
        Safir::Dob::Connection connection;
        SimpleDispatcher dispatcher(connection);

        std::wstring name = L"Entity";
        if (CommandLine::Instance().Owner())
        {
            name += L"Owner";
        }
        else if (CommandLine::Instance().Subscriber())
        {
            name += L"Subscriber";
        }


        for(int instance = 0;;++instance)
        {
            try
            {
                connection.Open(name,
                                boost::lexical_cast<std::wstring>(instance),
                                0, // Context
                                &dispatcher,
                                &dispatcher);
                break;
            }
            catch(const Safir::Dob::NotOpenException &)
            {

            }
        }

        std::wcout << "Started as " << Safir::Dob::ConnectionAspectMisc(connection).GetConnectionName() << std::endl;

        bool done = false;
        if (CommandLine::Instance().Owner())
        {
            Owner owner;
            while (!done)
            {
                if (!CommandLine::Instance().NoSleep())
                {
                    const bool dispatch = dispatcher.Wait(CommandLine::Instance().SleepTime());
                    if (dispatch)
                    {
                        connection.Dispatch();
                    }
                }
                for (int i = 0; i < CommandLine::Instance().BatchSize(); ++i)
                {
                    owner.Set();
                }
            }
        }
        else if (CommandLine::Instance().Subscriber())
        {
            Subscriber subscriber;
            bool started = false;
            while (!done)
            {
                const bool dispatch = dispatcher.Wait(10000);

                if(dispatch)
                {
                    started = true;
                    connection.Dispatch();
                }
                else if (started)
                {
                    std::wcout << "No dispatch event in 10s, printing statistics and exiting" << std::endl;
                    subscriber.PrintStatistics();
                    if (CommandLine::Instance().ExtraDispatch())
                    {
                        std::wcout << "Performing an extra dispatch, and then printing statistics again:" << std::endl;
                        connection.Dispatch();
                        subscriber.PrintStatistics();
                    }
                    break;
                }

            }
        }

    }
    catch(std::exception & e)
    {
        std::wcout << "Caught std::exception! Contents of exception is:" << std::endl
            << e.what()<<std::endl;
        std::cin.get();
    }
    catch (...)
    {
        std::wcout << "Caught ... exception!" << std::endl;
        std::cin.get();
    }

    return 0;
}
Exemplo n.º 28
0
int main(int argc, char* argv[])
{
    if(!CommandLine::Instance().Parse(argc,argv))
    {
        return -1;
    }

    try
    {
        Safir::Dob::Connection connection;
        SimpleDispatcher dispatcher(connection);

        std::wstring name = L"Message";
        if (CommandLine::Instance().Sender())
        {
            name += L"Sender";
        }
        else
        {
            name += L"Receiver";
        }


        for(int instance = 0;;++instance)
        {
            try
            {
                connection.Open(name,
                                boost::lexical_cast<std::wstring>(instance),
                                0, // Context
                                &dispatcher,
                                &dispatcher);
                break;
            }
            catch(const Safir::Dob::NotOpenException &)
            {

            }
        }

        std::wcout << "Started as " << Safir::Dob::ConnectionAspectMisc(connection).GetConnectionName() << std::endl;


        bool done = false;

        if(CommandLine::Instance().Sender()) //We are a sender
        {
            Sender sender;
            while (!done)
            {
                const bool dispatch = dispatcher.Wait(10);

                if(dispatch)
                {
                    connection.Dispatch();
                }
                else
                {
                    sender.SendSome();
                }
            }
        }
        else //no, a receiver
        {
            Subscriber subscriber;
            while (!done)
            {
                const bool dispatch = dispatcher.Wait(10);

                if(dispatch)
                {
                    connection.Dispatch();
                }
            }
        }


    }
    catch(std::exception & e)
    {
        std::wcout << "Caught std::exception! Contents of exception is:" << std::endl
            << e.what()<<std::endl;
        std::cin.get();
    }
    catch (...)
    {
        std::wcout << "Caught ... exception!" << std::endl;
        std::cin.get();
    }

    return 0;
}
Exemplo n.º 29
0
int main( int argc, char * argv[] )
{
	int port = 8080, maxThreads = 10;
	char * dstHost = "66.249.89.99";
	int dstPort = 80;

	extern char *optarg ;
	int c ;

	while( ( c = getopt ( argc, argv, "p:t:r:v" )) != EOF ) {
		switch ( c ) {
			case 'p' :
				port = atoi( optarg );
				break;
			case 't':
				maxThreads = atoi( optarg );
				break;
			case 'r':
			{
				dstHost = strdup( optarg );
				char * pos = strchr( dstHost, ':' );
				if( NULL != pos ) {
					dstPort = atoi( pos + 1 );
					*pos = '\0';
				}
				break;
			}
			case '?' :
			case 'v' :
				printf( "Usage: %s [-p <port>] [-t <threads>] [-r <backend>]\n", argv[0] );
				exit( 0 );
		}
	}

#ifdef LOG_PERROR
	sp_openlog( "sptunnel", LOG_CONS | LOG_PID | LOG_PERROR, LOG_USER );
#else
	sp_openlog( "sptunnel", LOG_CONS | LOG_PID, LOG_USER );
#endif

	if( 0 != sp_initsock() ) assert( 0 );

	sp_syslog( LOG_NOTICE, "Backend server - %s:%d", dstHost, dstPort );

	int maxConnections = 100, reqQueueSize = 100;
	const char * refusedMsg = "System busy, try again later.";

	int listenFd = -1;
	if( 0 == SP_IOUtils::tcpListen( "", port, &listenFd ) ) {

		SP_MyDispatcher dispatcher( new SP_DefaultCompletionHandler(), maxThreads );

		dispatcher.setTimeout( 60 );
		dispatcher.dispatch();

#ifdef	OPENSSL
		SP_OpensslChannelFactory * sslFactory = new SP_OpensslChannelFactory();
#else
		SP_MatrixsslChannelFactory * sslFactory = new SP_MatrixsslChannelFactory();
#endif

#ifdef WIN32
		char basePath[ 256 ] = { 0 }, crtPath[ 256 ] = { 0 }, keyPath[ 256 ] = { 0 };
		spwin32_pwd( basePath, sizeof( basePath ) );
		snprintf( crtPath, sizeof( crtPath ), "%s\\..\\..\\..\\sptunnel\\demo.crt", basePath );
		snprintf( keyPath, sizeof( keyPath ), "%s\\..\\..\\..\\sptunnel\\demo.key", basePath );
		sslFactory->init( crtPath, keyPath );
#else
		sslFactory->init( "demo.crt", "demo.key" );
#endif

		for( ; ; ) {
			struct sockaddr_in addr;
			socklen_t socklen = sizeof( addr );
			int fd = accept( listenFd, (struct sockaddr*)&addr, &socklen );

			if( fd > 0 ) {
				if( dispatcher.getSessionCount() >= maxConnections
						|| dispatcher.getReqQueueLength() >= reqQueueSize ) {
					write( fd, refusedMsg, strlen( refusedMsg ) );
					close( fd );
				} else {
					SP_TunnelHandler * handler = new SP_TunnelHandler(
							&dispatcher, dstHost, dstPort );
					dispatcher.push( fd, handler, sslFactory->create() );

					// for non-ssl tunnel
					//dispatcher.push( fd, handler, new SP_DefaultIOChannel() );
				}
			} else {
				break;
			}
		}
	}

	sp_closelog();

	return 0;
}
Exemplo n.º 30
0
// **********************************************************************
// **********************************************************************
// OS startup
//
// 1. Init OS
// 2. Define reset longjmp vector
// 3. Define global system semaphores
// 4. Create CLI task
// 5. Enter scheduling/idle loop
//
int main(int argc, char* argv[])
{
	// All the 'powerDown' invocations must occur in the 'main'
	// context in order to facilitate 'killTask'.  'killTask' must
	// free any stack memory associated with current known tasks.  As
	// such, the stack context must be one not associated with a task.
	// The proper method is to longjmp to the 'reset_context' that
	// restores the stack for 'main' and then invoke the 'powerDown'
	// sequence.

	// save context for restart (a system reset would return here...)
	int resetCode = setjmp(reset_context);
	superMode = TRUE;						// supervisor mode

	switch (resetCode)
	{
	case POWER_DOWN_QUIT:				// quit
		powerDown(0);
		printf("\nGoodbye!!");
		return 0;

	case POWER_DOWN_RESTART:			// restart
		powerDown(resetCode);
		printf("\nRestarting system...\n");
		break;

	case POWER_UP:						// startup
		break;

	default:
		printf("\nShutting down due to error %d", resetCode);
		powerDown(resetCode);
		return 0;
	}

	// output header message
	printf("%s", STARTUP_MSG);

	// initalize OS
	initOS();

	// create global/system semaphores here
	//?? vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

	charReady = createSemaphore("charReady", BINARY, 0);
	inBufferReady = createSemaphore("inBufferReady", BINARY, 0);
	keyboard = createSemaphore("keyboard", BINARY, 1);
	tics1sec = createSemaphore("tics1sec", COUNTING, 0);
	tics10thsec = createSemaphore("tics10thsec", COUNTING, 0);
	tics10sec = createSemaphore("tics10sec", COUNTING, 0);
	dcChange = createSemaphore("dcChange", BINARY, 0);

	//?? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

	// schedule CLI task
	createTask("myShell",			// task name
			P1_shellTask,	// task
			MED_PRIORITY	,	// task priority
			argc,			// task arg count
			argv);			// task argument pointers

	// HERE WE GO................

	// Scheduling loop
	// 1. Check for asynchronous events (character inputs, timers, etc.)
	// 2. Choose a ready task to schedule
	// 3. Dispatch task
	// 4. Loop (forever!)

	while(1)									// scheduling loop
	{
		// check for character / timer interrupts
		pollInterrupts();

		// schedule highest priority ready task
		if ((curTask = scheduler()) < 0) continue;

		// dispatch curTask, quit OS if negative return
		if (dispatcher() < 0) break;
	}											// end of scheduling loop

	// exit os
	longjmp(reset_context, POWER_DOWN_QUIT);
	return 0;
} // end main