Beispiel #1
0
int CHttpServer::processHttpMessage(int nClientFD, message *m)
{
	const char *http_res = 
		"HTTP/1.1 200 OK\r\n"
		"Server: pm_manager\r\n"
		"Date: Wed, 07 Mar 2012 09:43:02 GMT\r\n"
		"Content-Type: application/json; charset=utf-8\r\n"
		"Connection: keep-alive\r\n"

#ifdef NOSETEST
		"Content-Length: 20\r\n\r\n{\"result\":\"success\"}";
#else
		"Content-Length: 15\r\n\r\n{\"result\":true}";
#endif

	if (m->method == HTTP_POST) 
	{
		_DBG("client POST to: %s", m->url);
		_DBG("content: %s", m->body);

		if (strncmp("/event", m->url, 6) == 0)
		{
			//std::string jsonStr = "{\"sn\":123456789,\"component_name\":\"sensor\",\"event\":\"shutdown\",\"hostname\":\"TPE1A0109\"}";
			if (strlen(m->body) == 0) return 1;
			std::string jsonStr(m->body);
			
			Json::Reader reader;  
			Json::Value value;
			if(reader.parse(jsonStr, value))
			{
				char hostname[BUF_SIZE], event[BUF_SIZE];
				
				_DBG("GOT HTTP event: %s", value["event"].asString().c_str());
				
				strcpy(event, value["event"].asString().c_str());

				if (strncmp(event, "poweroff", 8) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());
						_DBG("%s is POWERED OFF !!", hostname);
						if (-1 != m_nEventFilter)
						{
							sendMessage(m_nEventFilter, EVENT_MONITOR_SHUTDOWN, nClientFD, strlen(hostname), hostname);
						}
						else
						{
							sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_SHUTDOWN, nClientFD, strlen(hostname), hostname);
						}
					}
				}
				else if (strncmp(event, "heartbeat", 9) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());

						if (strncmp(status, "heartbeat", 9) == 0)
						{
							if (-1 != m_nEventFilter)
							{
								sendMessage(m_nEventFilter, EVENT_MONITOR_BOOT, nClientFD, strlen(hostname), hostname);
							}
							else
							{
								sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_BOOT, nClientFD, strlen(hostname), hostname);
							}
						}
					}
				}
				else if (strncmp(event, "dead", 4) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());
						_DBG("%s is DEAD !! T_T", hostname);
						if (-1 != m_nEventFilter)
						{
							sendMessage(m_nEventFilter, EVENT_MONITOR_DEAD, nClientFD, strlen(hostname), hostname);
						}
						else
						{
							sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_DEAD, nClientFD, strlen(hostname), hostname);
						}
					}
				}
			}

		}
	}

	socketSend(nClientFD, http_res, strlen(http_res));

	return 0;
}
void ftpServerControlEventHandler(FtpServerContext *context,
   FtpClientConnection * connection, uint_t eventFlags)
{
   error_t error;
   size_t n;

   //Send buffer is available for writing?
   if(eventFlags == SOCKET_EVENT_TX_READY)
   {
      //Send data back to the client
      error = socketSend(connection->controlSocket, connection->response +
         connection->responsePos, connection->responseLength, &n, 0);

      //Failed to send data?
      if(error != NO_ERROR && error != ERROR_TIMEOUT)
      {
         //Close connection with the client
         ftpServerCloseConnection(context, connection);
         //Exit immediately
         return;
      }

      //Advance data pointer
      connection->responsePos += n;
      //Number of bytes still available in the response buffer
      connection->responseLength -= n;
   }
   //Data is pending in the receive buffer?
   else if(eventFlags == SOCKET_EVENT_RX_READY)
   {
      //Read data from the client
      error = socketReceive(connection->controlSocket,
         connection->command + connection->commandLength,
         FTP_SERVER_MAX_LINE_LEN - connection->commandLength, &n, 0);

      //Failed to receive data?
      if(error == ERROR_END_OF_STREAM)
      {
         //Gracefully disconnect from the remote host
         connection->controlState = FTP_CONTROL_STATE_WAIT_ACK;
         //Exit immediately
         return;
      }
      else if(error)
      {
         //Close connection with the client
         ftpServerCloseConnection(context, connection);
         //Exit immediately
         return;
      }

      //Number of bytes available in the command buffer
      connection->commandLength += n;
      //Process incoming command
      ftpServerProcessCmd(context, connection);
   }
   //Data are transmitted and acknowledged?
   else if(eventFlags == SOCKET_EVENT_TX_ACKED)
   {
      //Disable transmission
      socketShutdown(connection->controlSocket, SOCKET_SD_SEND);
      //Next state
      connection->controlState = FTP_CONTROL_STATE_SHUTDOWN_TX;
   }
   //Transmission is shut down?
   else if(eventFlags == SOCKET_EVENT_TX_SHUTDOWN)
   {
      //Disable reception
      socketShutdown(connection->controlSocket, SOCKET_SD_RECEIVE);
      //Next state
      connection->controlState = FTP_CONTROL_STATE_SHUTDOWN_RX;
   }
   //Reception is shut down?
   else if(eventFlags == SOCKET_EVENT_RX_SHUTDOWN)
   {
      //Properly close connection
      ftpServerCloseConnection(context, connection);
   }
}
Beispiel #3
0
void tcpChargenConnectionTask(void *param)
{
   error_t error;
   //size_t i;
   size_t n;
   //size_t offset;
   size_t byteCount;
   systime_t startTime;
   systime_t duration;
   ChargenServiceContext *context;

   //Get a pointer to the context
   context = (ChargenServiceContext *) param;
   //Get current time
   startTime = osGetTickCount();

   //Initialize counters
   byteCount = 0;
   //offset = 0;

   //Once a connection is established a stream of data is sent out
   //the connection (and any data received is thrown away). This
   //continues until the calling user terminates the connection
   while(1)
   {
      //Format output data
      /*for(i = 0; i < CHARGEN_BUFFER_SIZE; i += 95)
      {
         //Calculate the length of the current line
         n = min(CHARGEN_BUFFER_SIZE - i, 95);
         //Copy character pattern
         memcpy(context->buffer + i, pattern + offset, n);
      }

      //Update offset
      offset += CHARGEN_BUFFER_SIZE + 95 - i;
      //Wrap around if necessary
      if(offset >= 95) offset = 0;*/

      //Send data
      error = socketSend(context->socket, context->buffer, CHARGEN_BUFFER_SIZE, &n, 0);
      //Any error to report?
      if(error) break;

      //Total number of bytes sent
      byteCount += n;
   }

   //Graceful shutdown
   socketShutdown(context->socket, SOCKET_SD_BOTH);
   //Compute total duration
   duration = osGetTickCount() - startTime;
   //Avoid division by zero...
   if(!duration) duration = 1;

   //Debug message
   TRACE_INFO("Chargen service: %" PRIuSIZE " bytes "
      "sent in %" PRIu32 " ms (%" PRIu32 " kBps, %" PRIu32 " kbps)\r\n",
      byteCount, duration, byteCount / duration, (byteCount * 8) / duration);

   //Close socket
   socketClose(context->socket);
   //Release previously allocated memory
   osMemFree(context);

   //Kill ourselves
   osTaskDelete(NULL);
}
Beispiel #4
0
error_t httpClientTest(void)
{
   error_t error;
   size_t length;
   IpAddr ipAddr;
   Socket *socket;
   static char_t buffer[256];

   //Debug message
   TRACE_INFO("\r\n\r\nResolving server name...\r\n");

   //Resolve HTTP server name
   error = getHostByName(NULL, CLIENT_SERVER_NAME, &ipAddr, 1, NULL, 0);
   //Any error to report?
   if(error)
   {
      //Debug message
      TRACE_INFO("Failed to resolve server name!\r\n");
      //Exit immedialtely
      return error;
   }

   //Create a new socket to handle the request
   socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_PROTOCOL_TCP);
   //Any error to report?
   if(!socket)
   {
      //Debug message
      TRACE_INFO("Failed to open socket!\r\n");
      //Exit immedialtely
      return error;
   }

   //Start of exception handling block
   do
   {
      //Debug message
      TRACE_INFO("Connecting to HTTP server %s\r\n", ipAddrToString(&ipAddr, NULL));

      //Connect to the HTTP server
      error = socketConnect(socket, &ipAddr, CLIENT_SERVER_PORT);
      //Any error to report?
      if(error) break;

      //Debug message
      TRACE_INFO("Successful connection\r\n");

      //Format HTTP request
      length = sprintf(buffer, "GET %s HTTP/1.0\r\nHost: %s:%u\r\n\r\n",
         CLIENT_REQUEST_URI, CLIENT_SERVER_NAME, CLIENT_SERVER_PORT);

      //Debug message
      TRACE_INFO("\r\nHTTP request:\r\n%s", buffer);

      //Send HTTP request
      error = socketSend(socket, buffer, length, NULL, 0);
      //Any error to report?
      if(error) break;

      //Debug message
      TRACE_INFO("HTTP response header:\r\n");

      //Parse HTTP response header
      while(1)
      {
         //Read the header line by line
         error = socketReceive(socket, buffer, sizeof(buffer) - 1, &length, SOCKET_FLAG_BREAK_CRLF);
         //End of stream?
         if(error) break;

         //Properly terminate the string with a NULL character
         buffer[length] = '\0';
         //Dump current data
         TRACE_INFO("%s", buffer);

         //The end of the header has been reached?
         if(!strcmp(buffer, "\r\n"))
            break;
      }

      //Debug message
      TRACE_INFO("HTTP response body:\r\n");

      //Parse HTTP response body
      while(1)
      {
         //Read response body
         error = socketReceive(socket, buffer, sizeof(buffer) - 1, &length, 0);
         //End of stream?
         if(error) break;

         //Properly terminate the string with a NULL character
         buffer[length] = '\0';
         //Dump current data
         TRACE_INFO("%s", buffer);
      }

      //End of exception handling block
   } while(0);

   //Close the connection
   socketClose(socket);
   //Debug message
   TRACE_INFO("\r\nConnection closed...\r\n");

   //Return status code
   return error;
}
void ftpServerSendData(FtpServerContext *context, FtpClientConnection *connection)
{
   error_t error;
   size_t n;

   //Any data waiting for transmission?
   if(connection->bufferLength > 0)
   {
      //Send more data
      error = socketSend(connection->dataSocket, connection->buffer +
         connection->bufferPos, connection->bufferLength, &n, 0);

      //Failed to send data?
      if(error != NO_ERROR && error != ERROR_TIMEOUT)
      {
         //Close the data connection
         ftpServerCloseDataConnection(connection);

         //Release previously allocated resources
         if(connection->file != NULL)
         {
            fsCloseFile(connection->file);
            connection->file = NULL;
         }
         if(connection->dir != NULL)
         {
            fsCloseDir(connection->dir);
            connection->dir = NULL;
         }

         //Back to idle state
         connection->controlState = FTP_CONTROL_STATE_IDLE;

         //Transfer status
         strcpy(connection->response, "451 Transfer aborted\r\n");
         //Debug message
         TRACE_DEBUG("FTP server: %s", connection->response);

         //Number of bytes in the response buffer
         connection->responseLength = strlen(connection->response);
         connection->responsePos = 0;

         //Exit immediately
         return;
      }

      //Advance data pointer
      connection->bufferPos += n;
      //Number of bytes still available in the buffer
      connection->bufferLength -= n;
   }

   //Empty transmission buffer?
   if(connection->bufferLength == 0)
   {
      //File transfer in progress?
      if(connection->controlState == FTP_CONTROL_STATE_RETR)
      {
         //Read more data
         error = fsReadFile(connection->file,
            connection->buffer, FTP_SERVER_BUFFER_SIZE, &n);

         //End of stream?
         if(error)
         {
            //Close file
            fsCloseFile(connection->file);
            connection->file = NULL;

            //Wait for all the data to be transmitted and acknowledged
            connection->dataState = FTP_DATA_STATE_WAIT_ACK;

            //Exit immediately
            return;
         }
      }
      //Directory listing in progress?
      else if(connection->controlState == FTP_CONTROL_STATE_LIST)
      {
         uint_t perm;
         time_t currentTime;
         time_t modified;
         char_t *path;
         FsDirEntry dirEntry;

         //Read a new entry in the directory
         error = fsReadDir(connection->dir, &dirEntry);

         //End of stream?
         if(error)
         {
            //Close directory
            fsCloseDir(connection->dir);
            connection->dir = NULL;

            //Wait for all the data to be transmitted and acknowledged
            connection->dataState = FTP_DATA_STATE_WAIT_ACK;

            //Exit immediately
            return;
         }

         //Point to the scratch buffer
         path = connection->buffer;

         //Get the pathname of the directory being listed
         strcpy(path, connection->path);
         //Retrieve the full pathname
         pathCombine(path, dirEntry.name, FTP_SERVER_MAX_PATH_LEN);
         pathCanonicalize(path);

         //Get permissions for the specified file
         perm = ftpServerGetFilePermissions(context, connection, path);

         //Enforce access rights
         if(perm & FTP_FILE_PERM_LIST)
         {
            //Format links, owner, group and size fields
            n = sprintf(connection->buffer, "----------   1 owner    group    %10" PRIu32,
               dirEntry.size);

            //Check whether the current entry is a directory
            if(dirEntry.attributes & FS_FILE_ATTR_DIRECTORY)
               connection->buffer[0] = 'd';

            //Read access?
            if(perm & FTP_FILE_PERM_READ)
            {
               connection->buffer[1] = 'r';
               connection->buffer[4] = 'r';
               connection->buffer[7] = 'r';
            }
            //Write access
            if(perm & FTP_FILE_PERM_WRITE)
            {
               connection->buffer[2] = 'w';
               connection->buffer[5] = 'w';
               connection->buffer[8] = 'w';
            }

            //Get current time
            currentTime = getCurrentUnixTime();
            //Get modification time
            modified = convertDateToUnixTime(&dirEntry.modified);

            //Check whether the modification time is within the previous 180 days
            if(currentTime > modified && currentTime < (modified + FTP_SERVER_180_DAYS))
            {
               //The format of the date/time field is Mmm dd hh:mm
               n += sprintf(connection->buffer + n, " %s %02" PRIu8 " %02" PRIu8 ":%02" PRIu8,
                  months[MIN(dirEntry.modified.month, 12)], dirEntry.modified.day,
                  dirEntry.modified.hours, dirEntry.modified.minutes);
            }
            else
            {
               //The format of the date/time field is Mmm dd  yyyy
               n += sprintf(connection->buffer + n, " %s %02" PRIu8 "  %04" PRIu16,
                  months[MIN(dirEntry.modified.month, 12)], dirEntry.modified.day,
                  dirEntry.modified.year);
            }

            //Append filename
            n += sprintf(connection->buffer + n, " %s\r\n", dirEntry.name);
            //Debug message
            TRACE_DEBUG("FTP server: %s", connection->buffer);
         }
         else
         {
            //Insufficient access rights
            n = 0;
         }
      }
      //Invalid state?
      else
      {
         //The FTP server has encountered a critical error
         ftpServerCloseConnection(context, connection);
         //Exit immediately
         return;
      }

      //Number of bytes in the buffer
      connection->bufferPos = 0;
      connection->bufferLength = n;
   }
}
Beispiel #6
0
uint8_t REDFLY::socketSend(uint8_t socket, uint8_t *stream, uint16_t size)
{
  return socketSend(socket, stream, size, 0, 0);
}
//devuelve el nodo del espacio en memoria. 0 lectura 1 escritura
int reemplazarPaginaClockModificado(int pid, int pagina,
bool lectoEscritura) {

	SocketBuffer*buffer;
	StrUmcSwa*streamUmcSwap;
	espacioAsignado pageToSend = espacioAsignadoSinAsterisco();
	int posicionDePaginaLibre;
	espacioAsignado*nodoActual;
	nodoActual = buscarPaginaClockModificado(pid, pagina);
	posicionDePaginaLibre = nodoActual->IDPaginaInterno;
	nodoActual->bitDePresencia = 0;
	if (tlbHabilitada())
		sacarPaginaDeTelebe(nodoActual->pid, nodoActual->numDePag);
	int i = 0;
	espacioAsignado*nodoBuscado = list_get(listaEspacioAsignado, i);
	while (!(nodoBuscado->pid == pid && nodoBuscado->numDePag == pagina)) {
		i++;
		nodoBuscado = list_get(listaEspacioAsignado, i);
	}
	nodoBuscado->bitUso = 1;
	nodoBuscado->bitDePresencia = 1;
	nodoBuscado->IDPaginaInterno = nodoActual->IDPaginaInterno;

	char* paginaAEnviar = malloc(sizeof(char) * marco_Size);
	int inicioLectura = posicionDePaginaLibre * marco_Size;
	int counter = 0;
	while (counter < marco_Size) {
		paginaAEnviar[counter] = memoriaReal[inicioLectura];
		inicioLectura++;
		counter++;
	}
	if (lectoEscritura) {
		pageToSend.IDPaginaInterno = nodoActual->IDPaginaInterno;
		pageToSend.numDePag = nodoActual->numDePag;
		pageToSend.pid = nodoActual->pid;
		streamUmcSwap = newStrUmcSwa(UMC_ID, ESCRIBIR_UNA_PAGINA, pageToSend, 1,
				paginaAEnviar, marco_Size, nodoActual->pid);
		buffer = serializeUmcSwa(streamUmcSwap);
		if (!socketSend(socketSwap->ptrSocket, buffer))
			puts("error al enviar al swap");
		buffer = socketReceive(socketSwap->ptrSocket);
		StrSwaUmc*streamSwUm = unserializeSwaUmc(buffer);
	}
	limpiarPagina(nodoActual->IDPaginaInterno * marco_Size);
	pageToSend.numDePag = pagina;
	streamUmcSwap = newStrUmcSwa(UMC_ID, LEER_UNA_PAGINA, pageToSend, 1,
	NULL, 0, nodoActual->pid);
	buffer = serializeUmcSwa(streamUmcSwap);
	if (!socketSend(socketSwap->ptrSocket, buffer))
		puts("error al enviar al swap");
	buffer = socketReceive(socketSwap->ptrSocket);
	StrSwaUmc* streamSwapUmc = unserializeSwaUmc(buffer);
	inicioLectura = posicionDePaginaLibre * marco_Size;
	counter = 0;
	while (counter < marco_Size) {
		memoriaReal[inicioLectura] = streamSwapUmc->data[counter];
		counter++;
		inicioLectura++;
	}
	nodoBuscado->bitUso = 1;
	nodoBuscado->bitModificado = lectoEscritura;
	log_info(umclog, "Algoritmo CLOCK MODIFICADO realizado correctamente");
	free(streamUmcSwap);
	//free(streamSwUm);
	free(streamSwapUmc);
	return posicionDePaginaLibre;
}
Beispiel #8
0
void streamWAV(void* arg){

	// Fetching cachePackage struct from main thread
	cachePackage* pack = (cachePackage*)arg;
	while(1) {
	
		// Waiting for updateStream event
		svcWaitSynchronization(updateStream, U64_MAX);
		svcClearEvent(updateStream);
		
		// Close the thread if closeStream event received
		if(closeStream){
			closeStream = false;
			svcExitThread();
		}
		
		// Check if the current stream is paused or not
		Music* src = pack->song;
		Socket* Client = pack->client;
		if (src->isPlaying){
		
			// Check if a free buffer is available
			if (src->wavebuf2 == NULL){
			
				// Check if file reached EOF
				if (src->audio_pointer >= src->size){
				
					// Check if playback ended
					if (!ndspChnIsPlaying(src->ch)){
						src->isPlaying = false;
						src->tick = (osGetTime()-src->tick);
					}
					
					continue;
				}
				
				// Swap audiobuffers
				u8* tmp = src->audiobuf;
				src->audiobuf = src->audiobuf2;
				src->audiobuf2 = tmp;
				
				// Create a new block for DSP service
				u32 bytesRead;
				src->wavebuf2 = (ndspWaveBuf*)calloc(1,sizeof(ndspWaveBuf));
				createDspBlock(src->wavebuf2, src->bytepersample, src->mem_size, 0, (u32*)src->audiobuf);
				populatePurgeTable(src, src->wavebuf2);
				ndspChnWaveBufAdd(src->ch, src->wavebuf2);
				socketSend(Client, "exec2:0000");
				u32 processedBytes = 0;
				netSize = 0;
				while (netSize <= 0) heapRecv(Client, 2048);
				while (processedBytes < (src->mem_size / 2)){
					if (netSize <= 0){
							heapRecv(Client, 2048);
							continue;
					}
					if (strncmp((char*)netBuffer, "EOF", 3) == 0) break;
					memcpy(&streamCache[songPointer + processedBytes], netBuffer, netSize);
					processedBytes = processedBytes + netSize;
					heapRecv(Client, 2048);
				}
				memcpy(src->audiobuf, &streamCache[songPointer], src->mem_size);
				if (songPointer == 0) songPointer = src->mem_size / 2;
				else songPointer = 0;
				src->audio_pointer = src->audio_pointer + src->mem_size;
				
				// Changing endianess if Big Endian
				if (src->big_endian){
					u64 i = 0;
					while (i < src->mem_size){
						u8 tmp = src->audiobuf[i];
						src->audiobuf[i] = src->audiobuf[i+1];
						src->audiobuf[i+1] = tmp;
						i=i+2;	
					}
				}
			
			}
			
			// Check if a block playback is finished
			u32 curSample = ndspChnGetSamplePos(src->ch);
			if (src->lastCheck > curSample){
			
				// Prepare next block
				src->wavebuf = src->wavebuf2;
				src->wavebuf2 = NULL;
			
			}
			
			// Update sample position tick
			src->lastCheck = curSample;
		
		}
	}		
}
Beispiel #9
0
// prepareSong: Receive a song with network
Music* prepareSong(Socket* Client, u32 idx)
{
	// Init resources
	u16 audiotype;
	u64 size;
	Music* songFile = (Music*)malloc(sizeof(Music));
	Packet* pkg = NULL;
	
	// Sending command to client
	char cmd[10];
	sprintf(cmd, "exec1:%i", (idx - 1));
	cmd[9] = 0;
	socketSend(Client, cmd);
	
	// Getting file info
	while (pkg == NULL) pkg = socketRecv(Client, 64);
	Songlist* song = getSong(idx);
	
	u64 fileSize = atoi((char*)pkg->message);
	socketSend(Client, "OK");
	if (song->format == WAV_PCM16){
		
		// Getting and parsing header file
		linearFree(pkg->message);
		free(pkg);
		pkg = NULL;
		while (pkg == NULL) pkg = socketRecv(Client, 256);
		socketSend(Client, "OK");
		u8* header = pkg->message;
		u32 header_size = pkg->size;
		u32 samplerate,jump,chunk=0x00000000;
		strcpy(songFile->author,"");
		strcpy(songFile->title,"");
		songFile->big_endian = false;
		u32 pos = 16;
		while (chunk != 0x61746164){
			memcpy(&jump, &header[pos], 4);
			pos=pos+4+jump;
			memcpy(&chunk, &header[pos], 4);
			pos=pos+4;
	
			//Chunk LIST detection
			if (chunk == 0x5453494C){
				u32 chunk_size;
				u32 subchunk;
				u32 subchunk_size;
				u32 sub_pos = pos+4;
				memcpy(&subchunk, &header[sub_pos], 4);
				if (subchunk == 0x4F464E49){
					sub_pos = sub_pos+4;
					memcpy(&chunk_size, &header[pos], 4);
					while (sub_pos < (chunk_size + pos + 4)){
						memcpy(&subchunk, &header[sub_pos], 4);
						memcpy(&subchunk_size, &header[sub_pos + 4], 4);
						if (subchunk == 0x54524149){
							strncpy(songFile->author, (char*)&header[sub_pos + 8], subchunk_size);
							songFile->author[subchunk_size] = 0;
						}else if (subchunk == 0x4D414E49){
							strncpy(songFile->title, (char*)&header[sub_pos + 8], subchunk_size);
							songFile->title[subchunk_size] = 0;
						}
						sub_pos = sub_pos + 8 + subchunk_size;
						u8 checksum;
						memcpy(&checksum, &header[sub_pos], 1);
						if (checksum == 0) sub_pos++;
					}
				}
			}
		
		}
		memcpy(&audiotype, &header[22], 2);
		memcpy(&samplerate, &header[24], 4);
		memcpy(&(songFile->bytepersample), &header[32], 2);
		u16 raw_enc;
		memcpy(&raw_enc, &header[20], 2);
		songFile->wavebuf = NULL;
		songFile->wavebuf2 = NULL;
		if (raw_enc == 0x01) songFile->encoding = CSND_ENCODING_PCM16;
		else if (raw_enc == 0x11) songFile->encoding = CSND_ENCODING_ADPCM;
		songFile->mem_size = fileSize - header_size;
		songFile->size = songFile->mem_size;
		u32 REAL_STREAM_MAX_ALLOC;
		if (audiotype == 1) REAL_STREAM_MAX_ALLOC = STREAM_MAX_ALLOC;
		else REAL_STREAM_MAX_ALLOC = STREAM_MAX_ALLOC * 10;
		while (songFile->mem_size > REAL_STREAM_MAX_ALLOC){
			if ((songFile->mem_size % 2) == 1) songFile->mem_size++;
			songFile->mem_size = songFile->mem_size / 2;
		}
		if ((songFile->mem_size % 2) == 1) songFile->mem_size++;
		linearFree(pkg->message);
		free(pkg);
		pkg = NULL;
		if (raw_enc == 0x11){ // TODO: ADPCM support
		}else if (raw_enc == 0x01){
			if (audiotype == 1){
				while (pkg == NULL) pkg = socketRecv(Client, 32768);
				u32 processedBytes = 0;
				songFile->audiobuf = (u8*)linearAlloc(songFile->mem_size);
				while (processedBytes < songFile->mem_size  - 52000){
					if (pkg == NULL){
						pkg = socketRecv(Client, 32768);
						continue;
					}
					memcpy(&songFile->audiobuf[processedBytes], pkg->message, pkg->size);
					processedBytes = processedBytes + pkg->size;
					linearFree(pkg->message);
					free(pkg);
					pkg = socketRecv(Client, 32768);
				}
				//svcSleepThread(1000000000);
				processedBytes = 0;
				socketSend(Client, "exec2:0000");
				bool secondBlock = false;
				pkg = NULL;
				while (pkg == NULL) pkg = socketRecv(Client, 32768);
				streamCache = (u8*)linearAlloc(songFile->mem_size);
				while (processedBytes < songFile->mem_size){
					if (pkg == NULL){
						pkg = socketRecv(Client, 32768);
						continue;
					}
					memcpy(&streamCache[processedBytes], pkg->message, pkg->size);
					processedBytes = processedBytes + pkg->size;
					if ((!secondBlock) && (processedBytes >= (songFile->mem_size / 2))){
						socketSend(Client, "exec2:0000");
						secondBlock = true;
					}
					linearFree(pkg->message);
					free(pkg);
					pkg = socketRecv(Client, 32768);
				}
				songFile->audiobuf2 = NULL;
			}
		}
		songFile->samplerate = samplerate;
		songFile->isPlaying = false;
		songFile->encoding = CSND_ENCODING_PCM16;
		linearFree(header);
	}
	
	return songFile;
		/*}else{
			// I must reordinate my buffer in order to play stereo sound (Thanks CSND/FS libraries .-.)
			u32 size_tbp;
			if (mem_size){
				wav_file->moltiplier = 1;
				//wav_file->sourceFile = fileHandle;
				wav_file->isPlaying = false;
				wav_file->startRead = (pos+4);
				wav_file->size = size;
				wav_file->mem_size = (size-(pos+4));
				while (wav_file->mem_size > STREAM_MAX_ALLOC * 10){
					wav_file->mem_size = wav_file->mem_size / 2;
				}
				tmp_buf = (u8*)linearAlloc(wav_file->mem_size);
				wav_file->audiobuf = (u8*)linearAlloc(wav_file->mem_size/2);
				wav_file->audiobuf2 = (u8*)linearAlloc(wav_file->mem_size/2);
				//FSFILE_Read(fileHandle, &bytesRead, wav_file->startRead, tmp_buf, wav_file->mem_size);
				size_tbp = wav_file->mem_size;
			}else{
				tmp_buf = (u8*)linearAlloc((size-(pos+4)));
				size_tbp = size-(pos+4);
				wav_file->startRead = 0;
				wav_file->size = (size_tbp)/2;
				//FSFILE_Read(fileHandle, &bytesRead, pos+4, tmp_buf, size-(pos+4));
			}
			u32 off=0;
			u32 i=0;
			u16 z;
			if (raw_enc == 0x01){ //PCM16 Decoding
				wav_file->audiobuf = (u8*)linearAlloc((size-(pos+4))/2);
				wav_file->audiobuf2 = (u8*)linearAlloc((size-(pos+4))/2);
				while (i < size_tbp){
					z=0;
					while (z < (wav_file->bytepersample/2)){
						wav_file->audiobuf[off+z] = tmp_buf[i+z];
						wav_file->audiobuf2[off+z] = tmp_buf[i+z+(wav_file->bytepersample/2)];
						z++;
					}
					i=i+wav_file->bytepersample;
					off=off+(wav_file->bytepersample/2);
				}
			}else if (raw_enc == 0x11){ //ADPCM Decoding
				u32 headers_num = (size_tbp) / wav_file->bytepersample;
				wav_file->audiobuf = (u8*)linearAlloc((size_tbp-headers_num*8)/2);
				wav_file->audiobuf2 = (u8*)linearAlloc((size_tbp-headers_num*8)/2);
				int z=0,i=0;
				while (i < size_tbp){
					wav_file->audiobuf[z] = tmp_buf[i++];
					wav_file->audiobuf2[z++] = tmp_buf[i+3];
					wav_file->audiobuf[z] = tmp_buf[i++];
					wav_file->audiobuf2[z++] = tmp_buf[i+3];
					wav_file->audiobuf[z] = tmp_buf[i++];
					wav_file->audiobuf2[z++] = tmp_buf[i+3];
					wav_file->audiobuf[z] = tmp_buf[i++];
					wav_file->audiobuf2[z++] = tmp_buf[i+3];
					i=i+4;
					if ((i % wav_file->bytepersample) == 0) i=i+8;
				}
			}
		}
		wav_file->magic = 0x4C534E44;*/
}
Beispiel #10
0
void tcpEchoConnectionTask(void *param)
{
   error_t error;
   size_t n;
   size_t writeIndex;
   size_t readIndex;
   size_t bufferLength;
   size_t rxByteCount;
   size_t txByteCount;
   systime_t startTime;
   systime_t duration;
   SocketEventDesc eventDesc;
   EchoServiceContext *context;

   //Get a pointer to the context
   context = (EchoServiceContext *) param;
   //Get current time
   startTime = osGetSystemTime();

   //Initialize variables
   writeIndex = 0;
   readIndex = 0;
   bufferLength = 0;
   rxByteCount = 0;
   txByteCount = 0;

   //Main loop
   while(1)
   {
      //Buffer is empty?
      if(!bufferLength)
      {
         //Get notified when the socket is readable
         eventDesc.socket = context->socket;
         eventDesc.eventMask = SOCKET_EVENT_RX_READY;
      }
      //Buffer is not empty of full?
      else if(bufferLength < ECHO_BUFFER_SIZE)
      {
         //Get notified when the socket is readable or writable
         eventDesc.socket = context->socket;
         eventDesc.eventMask = SOCKET_EVENT_RX_READY | SOCKET_EVENT_TX_READY;
      }
      //Buffer is full?
      else
      {
         //Get notified when the socket is writable
         eventDesc.socket = context->socket;
         eventDesc.eventMask = SOCKET_EVENT_TX_READY;
      }

      //Wait for an event to be fired
      error = socketPoll(&eventDesc, 1, NULL, ECHO_TIMEOUT);
      //Timeout error or any other exception to report?
      if(error) break;

      //The socket is available for reading
      if(eventDesc.eventFlags & SOCKET_EVENT_RX_READY)
      {
         //Read as much data as possible
         n = MIN(ECHO_BUFFER_SIZE - writeIndex, ECHO_BUFFER_SIZE - bufferLength);

         //Read incoming data
         error = socketReceive(context->socket, context->buffer + writeIndex, n, &n, 0);
         //Any error to report?
         if(error) break;

         //Increment write index
         writeIndex += n;
         //Wrap around if necessary
         if(writeIndex >= ECHO_BUFFER_SIZE)
            writeIndex = 0;

         //Increment buffer length
         bufferLength += n;
         //Total number of bytes received
         rxByteCount += n;
      }

      //The socket is available for writing?
      if(eventDesc.eventFlags & SOCKET_EVENT_TX_READY)
      {
         //Write as much data as possible
         n = MIN(ECHO_BUFFER_SIZE - readIndex, bufferLength);

         //Send data back to the client
         error = socketSend(context->socket, context->buffer + readIndex, n, &n, 0);
         //Any error to report?
         if(error && error != ERROR_TIMEOUT) break;

         //Increment read index
         readIndex += n;
         //Wrap around if necessary
         if(readIndex >= ECHO_BUFFER_SIZE)
            readIndex = 0;

         //Update buffer length
         bufferLength -= n;
         //Total number of bytes sent
         txByteCount += n;
      }
   }

   //Adjust timeout value
   socketSetTimeout(context->socket, ECHO_TIMEOUT);
   //Graceful shutdown
   socketShutdown(context->socket, SOCKET_SD_BOTH);
   //Compute total duration
   duration = osGetSystemTime() - startTime;

   //Debug message
   TRACE_INFO("Echo service: %" PRIuSIZE " bytes received, %" PRIuSIZE " bytes sent in %" PRIu32 " ms\r\n",
      rxByteCount, txByteCount, duration);

   //Close socket
   socketClose(context->socket);
   //Release previously allocated memory
   osFreeMem(context);

   //Kill ourselves
   osDeleteTask(NULL);
}
int CSocketServer::runCMPHandler(int nClientFD)
{
	int nFD;
	int result = 0;
	char szTmp[16];
	int nTotalLen = 0;
	int nBodyLen = 0;
	int nCommand = generic_nack;
	int nSequence = 0;

	CMP_PACKET cmpPacket;
	void* pHeader = &cmpPacket.cmpHeader;
	void* pBody;

	CMP_HEADER cmpHeader;
	//void *pHeaderResp = &cmpHeader;
	int nCommandResp;

	/**
	 * clientSockaddr is used for UDP server send packet to client.
	 */
	struct sockaddr_in *clientSockaddr;
	clientSockaddr = new struct sockaddr_in;

	if(externalEvent.isValid() && -1 != externalEvent.m_nEventConnect)
	{
		sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventConnect, nClientFD, 0, 0);
	}

	mapClientThread[nClientFD] = threadHandler->getThreadID();

	while(1)
	{
		memset(&cmpPacket, 0, sizeof(cmpPacket));
		result = socketrecv(nClientFD, sizeof(CMP_HEADER), &pHeader, clientSockaddr);
		if(sizeof(CMP_HEADER) == result)
		{
			nTotalLen = ntohl(cmpPacket.cmpHeader.command_length);
			nCommand = ntohl(cmpPacket.cmpHeader.command_id);
			nSequence = ntohl(cmpPacket.cmpHeader.sequence_number);

			memset(&cmpHeader, 0, sizeof(CMP_HEADER));
			nCommandResp = generic_nack | nCommand;
			cmpHeader.command_id = htonl(nCommandResp);
			cmpHeader.command_status = htonl( STATUS_ROK);
			cmpHeader.sequence_number = htonl(nSequence);
			cmpHeader.command_length = htonl(sizeof(CMP_HEADER));

			if( enquire_link_request == nCommand)
			{
				socketSend(nClientFD, &cmpHeader, sizeof(CMP_HEADER));
				continue;
			}
			nBodyLen = nTotalLen - sizeof(CMP_HEADER);

			if(static_cast<int>(nTotalLen) > MAX_SIZE - 1)
			{
				cmpPacket.cmpBodyUnlimit.cmpdata = new char[nBodyLen + 1];

				pBody = cmpPacket.cmpBodyUnlimit.cmpdata;
				result = socketrecv(nClientFD, nBodyLen, &pBody, clientSockaddr);

				if(result == nBodyLen)
				{
					ServerReceive(nClientFD, static_cast<int>(nTotalLen), &cmpPacket);
					continue;
				}
				else
				{
					socketSend(nClientFD, "Invalid Packet\r\n", strlen("Invalid Packet\r\n"));
					if(externalEvent.isValid() && -1 != externalEvent.m_nEventDisconnect)
					{
						sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventDisconnect, nClientFD, 0, 0);
					}
					socketClose(nClientFD);
					_log("[Socket Server] socket close client: %d , packet length error: %d != %d", nClientFD, nBodyLen,
							result);
					break;
				}

			}
			else
			{
				pBody = &cmpPacket.cmpBody;
			}

			if(0 < nBodyLen)
			{
				result = socketrecv(nClientFD, nBodyLen, &pBody, clientSockaddr);
				if(result != nBodyLen)
				{
					socketSend(nClientFD, "Invalid Packet\r\n", strlen("Invalid Packet\r\n"));
					if(externalEvent.isValid() && -1 != externalEvent.m_nEventDisconnect)
					{
						sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventDisconnect, nClientFD, 0, 0);
					}
					socketClose(nClientFD);
					_log("[Socket Server] socket close client: %d , packet length error: %d != %d", nClientFD, nBodyLen,
							result);
					break;
				}
			}

			if(access_log_request == nCommand)
			{
				socketSend(nClientFD, &cmpHeader, sizeof(CMP_HEADER));
			}
		}
		else if(0 >= result)
		{
			if(externalEvent.isValid() && -1 != externalEvent.m_nEventDisconnect)
			{
				sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventDisconnect, nClientFD, 0, 0);
			}
			socketClose(nClientFD);
			break;
		}
		else
		{
			socketSend(nClientFD, "Control Center: Please use CMP to communicate\r\n",
					strlen("Control Center: Please use CMP to communicate\r\n"));
			_log("[Socket Server] Send Message: Please use CMP to communicate");

			if(externalEvent.isValid() && -1 != externalEvent.m_nEventDisconnect)
			{
				sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventDisconnect, nClientFD, 0, 0);
			}

			socketClose(nClientFD);
			_log("[Socket Server] socket close client: %d , packet header length error: %d", nClientFD, result);
			break;
		}

		if(nClientFD == getSocketfd())
		{
			/**
			 * UDP server receive packet,record client information
			 */
			nFD = ntohs(clientSockaddr->sin_port);
			memset(szTmp, 0, sizeof(szTmp));
			sprintf(szTmp, "%d", nFD);
			udpClientData->setData(szTmp, *clientSockaddr);
		}
		else
		{
			nFD = nClientFD;
		}

		switch(mnPacketHandle)
		{
		case PK_MSQ:
			if(externalEvent.isValid())
			{
				sendMessage(externalEvent.m_nEventFilter, externalEvent.m_nEventRecvCommand, nFD, nTotalLen,
						&cmpPacket);
			}
			else
			{
				sendMessage(m_nInternalFilter, EVENT_COMMAND_SOCKET_SERVER_RECEIVE, nFD, nTotalLen, &cmpPacket);

			}
			break;
		case PK_ASYNC:
			ServerReceive(nFD, nTotalLen, &cmpPacket);
			break;
		}

	} // while

	mapClientThread.erase(nClientFD);

	delete clientSockaddr;

	sendMessage(m_nInternalFilter, EVENT_COMMAND_THREAD_EXIT, threadHandler->getThreadID(), 0, NULL);

	threadHandler->threadSleep(1);
	threadHandler->threadExit();

	return 0;
}
Beispiel #12
0
error_t ping(NetInterface *interface, const IpAddr *ipAddr, time_t timeout, time_t *rtt)
{
   error_t error;
   uint_t i;
   size_t length;
   uint16_t identifier;
   uint16_t sequenceNumber;
   time_t startTime;
   time_t roundTripTime;
   Socket *socket;
   IcmpEchoMessage *message;

   //Debug message
   TRACE_INFO("Pinging %s with 64 bytes of data...\r\n", ipAddrToString(ipAddr, NULL));

   //Length of the complete ICMP message including header and data
   length = sizeof(IcmpEchoMessage) + PING_DATA_SIZE;

   //Allocate memory buffer to hold an ICMP message
   message = osMemAlloc(length);
   //Failed to allocate memory?
   if(!message) return ERROR_OUT_OF_MEMORY;

   //Identifier field is used to help matching requests and replies
   identifier = rand();
   //Sequence Number field is increment each time an Echo Request is sent
   sequenceNumber = osAtomicInc16(&pingSequenceNumber);

   //Format ICMP Echo Request message
   message->type = ICMP_TYPE_ECHO_REQUEST;
   message->code = 0;
   message->checksum = 0;
   message->identifier = identifier;
   message->sequenceNumber = sequenceNumber;

   //Copy data
   for(i = 0; i < PING_DATA_SIZE; i++)
      message->data[i] = i;

#if (IPV4_SUPPORT == ENABLED)
   //Target address is an IPv4 address?
   if(ipAddr->length == sizeof(Ipv4Addr))
   {
      Ipv4Addr srcIpAddr;

      //Select the source IPv4 address and the relevant network
      //interface to use when pinging the specified host
      error = ipv4SelectSourceAddr(&interface, ipAddr->ipv4Addr, &srcIpAddr);

      //Any error to report?
      if(error)
      {
         //Free previously allocated memory
         osMemFree(message);
         //Return the corresponding error code
         return error;
      }

      //ICMP Echo Request message
      message->type = ICMP_TYPE_ECHO_REQUEST;
      //Message checksum calculation
      message->checksum = ipCalcChecksum(message, length);

      //Open a raw socket
      socket = socketOpen(SOCKET_TYPE_RAW, SOCKET_PROTOCOL_ICMP);
   }
   else
#endif
#if (IPV6_SUPPORT == ENABLED)
   //Target address is an IPv6 address?
   if(ipAddr->length == sizeof(Ipv6Addr))
   {
      Ipv6PseudoHeader pseudoHeader;

      //Select the source IPv6 address and the relevant network
      //interface to use when pinging the specified host
      error = ipv6SelectSourceAddr(&interface, &ipAddr->ipv6Addr, &pseudoHeader.srcAddr);

      //Any error to report?
      if(error)
      {
         //Free previously allocated memory
         osMemFree(message);
         //Return the corresponding error code
         return error;
      }

      //ICMPv6 Echo Request message
      message->type = ICMPV6_TYPE_ECHO_REQUEST;
      //Format IPv6 pseudo header
      pseudoHeader.destAddr = ipAddr->ipv6Addr;
      pseudoHeader.length = htonl(length);
      pseudoHeader.reserved = 0;
      pseudoHeader.nextHeader = IPV6_ICMPV6_HEADER;

      //Message checksum calculation
      message->checksum = ipCalcUpperLayerChecksum(
         &pseudoHeader, sizeof(Ipv6PseudoHeader), message, length);

      //Open a raw socket
      socket = socketOpen(SOCKET_TYPE_RAW, SOCKET_PROTOCOL_ICMPV6);
   }
   else
#endif
   //Target address is not valid?
   {
      //Free previously allocated memory
      osMemFree(message);
      //Report an error
      return ERROR_INVALID_ADDRESS;
   }

   //Failed to open socket?
   if(!socket)
   {
      //Free previously allocated memory
      osMemFree(message);
      //Report an error
      return ERROR_OPEN_FAILED;
   }

   //Associate the newly created socket with the relevant interface
   error = socketBindToInterface(socket, interface);

   //Unable to bind the socket to the desired interface?
   if(error)
   {
      //Free previously allocated memory
      osMemFree(message);
      //Close socket
      socketClose(socket);
      //Return status code
      return error;
   }

   //Connect the socket to the target host
   error = socketConnect(socket, ipAddr, 0);

   //Any error to report?
   if(error)
   {
      //Free previously allocated memory
      osMemFree(message);
      //Close socket
      socketClose(socket);
      //Return status code
      return error;
   }

   //Send Echo Request message
   error = socketSend(socket, message, length, NULL, 0);

   //Failed to send message ?
   if(error)
   {
      //Free previously allocated memory
      osMemFree(message);
      //Close socket
      socketClose(socket);
      //Return status code
      return error;
   }

   //Save the time at which the request was sent
   startTime = osGetTickCount();

   //Timeout value exceeded?
   while((osGetTickCount() - startTime) < timeout)
   {
      //Adjust receive timeout
      error = socketSetTimeout(socket, timeout);
      //Any error to report?
      if(error) break;

      //Wait for an incoming ICMP message
      error = socketReceive(socket, message,
         sizeof(IcmpEchoMessage) + PING_DATA_SIZE, &length, 0);
      //Any error to report?
      if(error) break;

      //Check message length
      if(length != (sizeof(IcmpEchoMessage) + PING_DATA_SIZE))
         continue;
      //Verify message type
      if(ipAddr->length == sizeof(Ipv4Addr) && message->type != ICMP_TYPE_ECHO_REPLY)
         continue;
      if(ipAddr->length == sizeof(Ipv6Addr) && message->type != ICMPV6_TYPE_ECHO_REPLY)
         continue;
      //Response identifier matches request identifier?
      if(message->identifier != identifier)
         continue;
      //Make sure the sequence number is correct
      if(message->sequenceNumber != sequenceNumber)
         continue;

      //Loop through data field
      for(i = 0; i < PING_DATA_SIZE; i++)
      {
         //Compare received data against expected data
         if(message->data[i] != i) break;
      }

      //Valid Echo Reply message received?
      if(i == PING_DATA_SIZE)
      {
         //Calculate round-trip time
         roundTripTime = osGetTickCount() - startTime;
         //Debug message
         TRACE_INFO("Echo received (round-trip time = %ums)...\r\n", roundTripTime);

         //Free previously allocated memory
         osMemFree(message);
         //Close socket
         socketClose(socket);

         //Return round-trip time
         if(rtt) *rtt = roundTripTime;

         //No error to report
         return NO_ERROR;
      }
   }

   //Debug message
   TRACE_INFO("No echo received!\r\n");
   //Free previously allocated memory
   osMemFree(message);
   //Close socket
   socketClose(socket);

   //No Echo Reply received from host...
   return ERROR_NO_RESPONSE;
}
Beispiel #13
0
error_t ftpSendCommand(FtpClientContext *context,
   const char_t *command, uint_t *replyCode)
{
   error_t error;
   size_t length;
   char_t *p;

   //Any command line to send?
   if(command)
   {
      //Debug message
      TRACE_DEBUG("FTP client: %s", command);

      //Send the command to the FTP server
      error = socketSend(context->controlSocket, command,
         strlen(command), NULL, SOCKET_FLAG_WAIT_ACK);

      //Failed to send command?
      if(error) return error;
   }

   //Multiline replies are allowed for any command
   while(1)
   {
      //Wait for a response from the server
      error = socketReceive(context->controlSocket, context->buffer,
         FTP_CLIENT_BUFFER_SIZE - 1, &length, SOCKET_FLAG_BREAK_CRLF);

      //The remote server did not respond as expected?
      if(error) return error;

      //Point to the beginning of the buffer
      p = context->buffer;
      //Properly terminate the string with a NULL character
      p[length] = '\0';

      //Remove trailing whitespace from the response
      strRemoveTrailingSpace(p);

      //Debug message
      TRACE_DEBUG("FTP server: %s\r\n", p);

      //Check the length of the response
      if(strlen(p) >= 3)
      {
         //All replies begin with a three digit numeric code
         if(isdigit((uint8_t) p[0]) && isdigit((uint8_t) p[1]) && isdigit((uint8_t) p[2]))
         {
            //A space character follows the response code for the last line
            if(p[3] == ' ' || p[3] == '\0')
            {
               //Get the server response code
               *replyCode = strtoul(p, NULL, 10);
               //Exit immediately
               break;
            }
         }
      }
   }

   //Successful processing
   return NO_ERROR;
}
error_t icecastClientConnect(IcecastClientContext *context)
{
   error_t error;
   size_t length;
   IpAddr serverIpAddr;

   //Icecast request template
   const char_t requestTemplate[] =
      "GET /%s HTTP/1.1\r\n"
      "Host: %s\r\n"
      "User-agent: UserAgent\r\n"
      "Icy-MetaData: 1\r\n"
      "Connection: close\r\n"
      "\r\n";

   //The specified Icecast server can be either an IP or a host name
   error = getHostByName(context->settings.interface,
      context->settings.serverName, &serverIpAddr, 1, NULL, 0);
   //Unable to resolve server name?
   if(error) return error;

   //Open a TCP socket
   context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_PROTOCOL_TCP);
   //Failed to open socket?
   if(!context->socket) return ERROR_OUT_OF_RESOURCES;

   //Start of exception handling block
   do
   {
      //Adjust receive timeout
      error = socketSetTimeout(context->socket, ICECAST_CLIENT_TIMEOUT);
      //Any error to report?
      if(error) return error;

      //Connect to the specified Icecast server
      error = socketConnect(context->socket, &serverIpAddr, context->settings.serverPort);
      //Connection with server failed?
      if(error) return error;

      //Format Icecast request
      length = sprintf(context->buffer, requestTemplate,
         context->settings.resource, context->settings.serverName);

      //Debug message
      TRACE_DEBUG(context->buffer);

      //Send Icecast request
      error = socketSend(context->socket, context->buffer,
         length, NULL, SOCKET_FLAG_WAIT_ACK);

      //Failed to send the request?
      if(error) return error;

      //Parse response header
      while(1)
      {
         char_t *separator;
         char_t *property;
         char_t *value;

         //Read a line from the response header
         error = socketReceive(context->socket, context->buffer,
            ICECAST_CLIENT_METADATA_MAX_SIZE, &length, SOCKET_FLAG_BREAK_CRLF);
         //Failed to read data?
         if(error)
            break;

         //Properly terminate the string with a NULL character
         context->buffer[length] = '\0';

         //The end of the header has been reached?
         if(!strcmp(context->buffer, "\r\n"))
            break;

         //Check whether a separator is present
         separator = strchr(context->buffer, ':');

         //Separator found?
         if(separator)
         {
            //Split the line
            *separator = '\0';

            //Get property name and value
            property = strTrimWhitespace(context->buffer);
            value = strTrimWhitespace(separator + 1);

            //Debug message
            TRACE_INFO("<%s>=<%s>\r\n", property, value);

            //Icy-Metaint property found?
            if(!strcasecmp(property, "Icy-Metaint"))
               context->blockSize = atoi(value);
         }
      }

      //End of exception handling block
   } while(0);

   //Check whether an error occurred
   if(error)
   {
      //Clean up side effects
      socketClose(context->socket);
   }

   //Return status code
   return error;
}
void algoritmoInterbloqueo(int32_t numeroPersonajes)
{
	t_log *log = log_create(logName,"Nivel",FALSE,LOG_LEVEL_INFO);
	t_log *log2 = log_create("matriz.log","matriz",FALSE,LOG_LEVEL_INFO);
	t_list *peticionesActuales, *asignados,*disponibles,*simbolosPersonajes;
	t_list *peticionesPorProceso,*procesoAsignados;
	simboloStruct *unSimbolo;
	void* buffer;
	int32_t nProcesos;
	int32_t socketOrquestador;
	int32_t nRecursos = list_size(nivel.cajas);
	int32_t i;
	colaNoSerializadaStruct colaInterbloqueo;
    int32_t length;
    int16_t size=0;
	unRecursoPaquetizadoStruct *instanciasDisponibles,*instanciasPedidas,*instanciasAsignadas;
	int32_t aux= TRUE, proc,r;
	t_queue *enInterbloqueo;
	if (!listaPersonajes)
			listaPersonajes = list_create();
	nProcesos = numeroPersonajes;
	if (nProcesos > 0)
	{
		disponibles=obtenerMatrizDisponibles();
		asignados=obtenerMatrizAsignados(listaPersonajes,numeroPersonajes);
		peticionesActuales=obtenerPeticionesActuales(listaPersonajes,numeroPersonajes);
		simbolosPersonajes=obtenerListaSimbolos(listaPersonajes,numeroPersonajes);
		mostrarMatrizPeticiones(peticionesActuales,simbolosPersonajes);
		mostrarMatrizASIG(asignados,simbolosPersonajes);
		disponiblesMatriz(disponibles);

		//elimino los que no tienen asignados
		for (proc = 0; proc < nProcesos; proc++)
		{

				procesoAsignados = (t_list *) list_get(asignados,proc);
				 bool condicionCeros(void* recurso) {
						return (((unRecursoPaquetizadoStruct *) recurso)->recurso != 0);
				 }

				if ( list_size(list_filter(procesoAsignados,condicionCeros)) == 0 )
				{
						list_remove_and_destroy_element(peticionesActuales,proc,element_destroyer);
						list_remove_and_destroy_element(asignados,proc,element_destroyer);
						unSimbolo = list_remove(simbolosPersonajes,proc);
						free(unSimbolo);
						nProcesos--;
						proc--;
				}

		}

		aux = TRUE;
		proc = 0;
		if (nProcesos > 0)
		{
			for (proc = 0; proc < nProcesos; proc++ )
		    {
				log_info(log2,"Chequeando proceso %c",((simboloStruct *) list_get(simbolosPersonajes,proc))->simbolo);

			    aux = TRUE;
			    //lista de un solo proceso (como si fuera un arreglo)
			    peticionesPorProceso = (t_list *) list_get(peticionesActuales,proc);
			    procesoAsignados = (t_list *) list_get(asignados,proc);

			    for (r=0; r < nRecursos; r++)
			    {
					instanciasDisponibles = (unRecursoPaquetizadoStruct *) list_get(disponibles,r);
					instanciasPedidas = (unRecursoPaquetizadoStruct *) list_get(peticionesPorProceso,r);
					instanciasAsignadas = (unRecursoPaquetizadoStruct *) list_get(procesoAsignados,r);
					// comprobamos que haya recursos suficientes
					aux = (instanciasPedidas->recurso - instanciasDisponibles->recurso) <= 0;
					if (!aux)
					{
							log_info(log2,"%c todavia necesita %d instancias de %c",((simboloStruct *) list_get(simbolosPersonajes,proc))->simbolo,instanciasPedidas->recurso,((cajaStruct *)list_get(nivel.cajas,r))->simbolo);
							log_info(log2,"hay %d instancias",instanciasDisponibles->recurso);
							break;
					}
			    }

			    if (aux)
			    {
					log_info(log2,"suponemos que %c termina",((simboloStruct *) list_get(simbolosPersonajes,proc))->simbolo);
					aniadirYeliminar(disponibles, asignados, proc);
					//remover indice de maximos

					list_remove_and_destroy_element(peticionesActuales,proc,element_destroyer);
				    unSimbolo = list_remove(simbolosPersonajes,proc);
				    free(unSimbolo);
				    nProcesos--;
				    proc = -1;
				    if (nProcesos == 0)
				    {
						log_info(log,"Es estado seguro");
						log_info(log2,"Es estado seguro");
						log_destroy(log);
						log_destroy(log2);
						list_destroy(disponibles);
						list_destroy(asignados);
						list_destroy(peticionesActuales);
						list_destroy(simbolosPersonajes);
						return;
				    }
			    }
			}
		    log_info(log,"Es Interbloqueo");
		    log_info(log2,"Es Interbloqueo");

		    for (i=0 ; i < list_size(simbolosPersonajes) ; i++)
						   log_info(log,"Personaje en interbloqueo: %c",((simboloStruct *) list_get(simbolosPersonajes,i))->simbolo);

		    if (nivel.recovery == 1)
		    {

				   enInterbloqueo=queue_create();
				   socketOrquestador = socketCreateClient(getIp(nivel.orquestador), getPort(nivel.orquestador));

				   for (i=0 ; i < list_size(simbolosPersonajes) ; i++)
				   {
						   queue_push(enInterbloqueo,list_get(simbolosPersonajes,i));
				   }
				   colaInterbloqueo.cantidadPersonajes=list_size(simbolosPersonajes);
				   colaInterbloqueo.cola = enInterbloqueo;
				   buffer = serializador_interbloqueo(&colaInterbloqueo,&size);
				   length = size + sizeof(header_t);
				   socketSend(socketOrquestador,buffer,length);
				   socketSend(socketOrquestador, &(nivel.nombre), sizeof(char[30]));
				   shutdown(socketOrquestador,2);
				   queue_destroy(enInterbloqueo);
				   free(buffer);
		    }
	    }
		list_destroy(disponibles);
		list_destroy(asignados);
		list_destroy(peticionesActuales);
		list_destroy(simbolosPersonajes);
	}
void notify(int socket, int id, char* message) {
	socketConnect(socket, conf.IP_Orquestador, conf.puertoOrquestador, errorConexionOrquestador);
	t_mensaje* msg = mensaje_create(id, message);
	socketSend(socket, msg, errorConexionOrquestador);
	free(msg);
}
Beispiel #17
0
uint8_t REDFLY::socketSend(uint8_t socket, char *stream, uint8_t *ip, uint16_t port)
{
  return socketSend(socket, (uint8_t*)stream, strlen(stream), ip, port);
}
Beispiel #18
0
int main() {
	luaHello();
	socketSend("socketSend message from client");
}
Beispiel #19
0
uint8_t REDFLY::socketSend(uint8_t socket, char *stream)
{
  return socketSend(socket, (uint8_t*)stream, strlen(stream), 0, 0);
}
void pedirSiguienteTurno(t_personaje* personaje, char* recursoBloqueante) {
	t_mensaje* requestSiguienteTurno = mensaje_create(SIGUIENTE_TURNO, recursoBloqueante);
	socketSend(personaje->connPlanificador, requestSiguienteTurno, handleConnectionError);
}
char* solicitarBytes(int pid, int pagina, int offset, int cantidad) {
	usleep(1000 * espera);
	char *paginaADevolver = malloc(sizeof(char) * cantidad);
	espacioAsignado* nodoALeer;
	int posicionActualDeNodo = 0;
	nodoALeer = list_get(listaEspacioAsignado, posicionActualDeNodo);
	while (!(((nodoALeer->pid) == pid) && (nodoALeer->numDePag == pagina))) {
		posicionActualDeNodo++;
		if (posicionActualDeNodo == list_size(listaEspacioAsignado))
			break;
		nodoALeer = list_get(listaEspacioAsignado, posicionActualDeNodo);

	}
	if (posicionActualDeNodo == list_size(listaEspacioAsignado)) {
		sprintf(paginaADevolver, "%s", "-1");
		paginaEncontrada = FALSE;
		log_error(umclog,"=================================================\n");
		log_error(umclog,"===========Segmentation fault, PID: %d===========\n", pid);
		log_error(umclog,"=================================================\n");
		return paginaADevolver;
	}
	if (nodoALeer->bitDePresencia == 1) {
		(nodoALeer->bitUso) = 1;
		int lugarDeLaCadena = 0;
		int posicionDeChar = (nodoALeer->IDPaginaInterno) * marco_Size + offset;
		while (lugarDeLaCadena < cantidad) {
			paginaADevolver[lugarDeLaCadena] = memoriaReal[posicionDeChar];
			posicionDeChar++;
			lugarDeLaCadena++;
		}
		if (tlbHabilitada()) {
			llevarPaginaATLB(pid, pagina, NULL);
		}
		log_info(umclog, "Bytes leidos por PID: %d Pagina: %d", pid, pagina);
		return (paginaADevolver);

	} else {

		if (paginasOcupadasPorPid(pid) < marco_x_proc
				&& paginasContiguasDeUMC(1) != -1) {
			int contador = 0;
			paginasPorPrograma*paginaAEncontrar = list_get(
					listaPaginasPorPrograma, contador);
			while (paginaAEncontrar->pid != pid) {
				contador++;
				paginaAEncontrar = list_get(listaPaginasPorPrograma, contador);
			}
			paginaAEncontrar->cantPaginasEnMemoria++;
			nodoALeer->IDPaginaInterno = paginasContiguasDeUMC(1);
			bitMap[nodoALeer->IDPaginaInterno] = 1;
			nodoALeer->bitUso = 1;
			nodoALeer->bitModificado = 0;
			nodoALeer->bitDePresencia = 1;
			espacioAsignado pageToSend;
			pageToSend.numDePag = pagina;
			StrUmcSwa*streamUmcSwap = newStrUmcSwa(UMC_ID,
			LEER_UNA_PAGINA, pageToSend, 1,
			NULL, 0, nodoALeer->pid);
			SocketBuffer*buffer = serializeUmcSwa(streamUmcSwap);
			if (!socketSend(socketSwap->ptrSocket, buffer))
				puts("error al enviar al swap");
			buffer = socketReceive(socketSwap->ptrSocket);
			StrSwaUmc* streamSwapUmc = unserializeSwaUmc(buffer);
			int inicioLectura = nodoALeer->IDPaginaInterno * marco_Size;
			int counter = 0;
			while (counter < marco_Size) {
				memoriaReal[inicioLectura] = streamSwapUmc->data[counter];
				counter++;
				inicioLectura++;
			}
			int comCadena = nodoALeer->IDPaginaInterno * marco_Size + offset;
			int lugCad = 0;
			while (lugCad < cantidad) {
				paginaADevolver[lugCad] = memoriaReal[comCadena];
				comCadena++;
				lugCad++;
			}
			if (tlbHabilitada()) {
				llevarPaginaATLB(pid, pagina, NULL);
			}
			log_info(umclog, "Bytes leidos por PID: %d Pagina: %d", pid,
					pagina);
			free(streamSwapUmc);
			free(streamUmcSwap);
			return (paginaADevolver);
		} else {
			int frame = reemplazarPagina(pid, pagina, 1);
			int comienzoDeCadena = frame * marco_Size + offset;
			int lugarDeLaCadena = 0;
			while (lugarDeLaCadena < cantidad) {
				paginaADevolver[lugarDeLaCadena] =
						memoriaReal[comienzoDeCadena];
				comienzoDeCadena++;
				lugarDeLaCadena++;
			}
			if (tlbHabilitada()) {
				llevarPaginaATLB(pid, pagina, NULL);
			}
			log_info(umclog, "Bytes leidos por PID: %d Pagina: %d", pid,
					pagina);
			return (paginaADevolver);

		}
	}
}
//testeada
int inicializarVariables(char* ruta) {

	// LOG
	nucleolog = malloc(sizeof(t_log));
	//nucleolog = log_create("nucleo.log", "NUCLEO", 1, LOG_LEVEL_INFO);

	memcpy(nucleolog, log_create("nucleo.log", "NUCLEO", 1, LOG_LEVEL_INFO),
			sizeof(t_log));

	//tamanioPaginas=pedirTamanioDePagina();

	//Variables de lectura de archivo
	puertoPropio = (char*) malloc(sizeof(puertoPropio));
	cpuPort = (char*) malloc(sizeof(cpuPort));
	quantum = (int) malloc(sizeof(quantum));
	quantumSleep = (int) (sizeof(quantumSleep));
	idSemaforos = (char**) malloc(sizeof(idSemaforos));
	viSemaforos = (char**) malloc(sizeof(viSemaforos));
	cantSemaforos = (int) malloc(sizeof(cantSemaforos)); //No se lee por config
	idIO = (char**) malloc(sizeof(idIO));
	retardoIO = (char**) malloc(sizeof(retardoIO));
	int cantIO = (int) malloc(sizeof(cantIO));	//No se lee por config

	idVariableCompartida = (char**) malloc(sizeof(idVariableCompartida));
	cantVarCompartidas = (int) malloc(sizeof(cantVarCompartidas));
	//variableCompartidaValor=(int*)malloc(sizeof(variableCompartidaValor));
	ipUMC = (char*) malloc((sizeof(ipUMC)));
	UMCPort = (char*) malloc((sizeof(UMCPort)));
	stackSize = (int) malloc((sizeof(stackSize)));
	tamanioPaginas = (int) malloc((sizeof(tamanioPaginas)));

	//Otras Variables
	idProgramas = (int) malloc(sizeof(idProgramas)); //Contador de programa
	primeraLectura = (bool) malloc(sizeof(primeraLectura));

	//Sincronizacion
	//pthread_mutex_t** mutexIO;
	//pthread_mutex_t** mutexVariables;
	mutexQuantum = malloc(sizeof(pthread_mutex_t));

	mutexColaNew = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
	mutexColaReady = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
	mutexColaExit = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
	mutexListaExec = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
	mutexListaBlock = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
	mutexListaCpu = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));

	primeraLectura = true;

	int i;

	//Leo el archivo de configuracion
	leerArchivoDeConfiguracion(ruta);

	//Inicio Semaforos
	cantSemaforos = cantidadPalabrasEnArrayDeStrings(idSemaforos);
	char* valorInicial;
	//char algo;
	unsigned int algo2 = 0;

	//sem_t semaforoPrueba;
	//sem_init(&semaforoPrueba, 0, 4);

	//semaforosAnsisop=malloc(sizeof(pthread_mutex_t)*cantSemaforos);

	for (i = 0; i < cantSemaforos; i++) {
		valorInicial = viSemaforos[i];
		//algo=*valorInicial;
		algo2 = atoi(valorInicial);
		semaforosAnsisop[i] = malloc(sizeof(sem_t));
		if (sem_init((semaforosAnsisop[i]), 0, algo2) != 0) {
			printf("\n init semaforoAnsisop %d fallo\n", i);
			return -1;
		}
	}

	//Inicio Semaforos de Sincro

	//inicio cantIO
	cantidadDispositivosIO = malloc(sizeof(int));
	cantIO = cantidadPalabrasEnArrayDeStrings(idIO);
	memcpy(cantidadDispositivosIO,&cantIO,sizeof(int));
	//mutexIO=malloc(sizeof(pthread_mutex_t)*cantIO);

	for (i = 0; i < cantIO; i++) {

		mutexIO[i] = malloc(sizeof(pthread_mutex_t));
		if (pthread_mutex_init(mutexIO[i], NULL) != 0) {
			printf("\n init mutexIO %d fallo\n", i);
			return -1;
		}
	}

	//inicio cantVarsCompartidas
	cantVarCompartidas = cantidadPalabrasEnArrayDeStrings(idVariableCompartida);

	variableCompartidaValor = (int*) malloc(sizeof(int) * cantVarCompartidas);

	for (i = 0; i < cantVarCompartidas; i++) {
		variableCompartidaValor[i] = 0;
	}
	//mutexVariables=malloc(sizeof(pthread_mutex_t)*cantVarCompartidas);
	for (i = 0; i < cantVarCompartidas; i++) {
		mutexVariables[i] = malloc(sizeof(pthread_mutex_t));
		if (pthread_mutex_init(mutexVariables[i], NULL) != 0) {
			printf("\n init mutexVariables %d fallo\n", i);
			return -1;
		}
	}

	if (pthread_mutex_init(mutexListaCpu, NULL) != 0) {
		printf("\n init mutexListaCpu fallo\n");
		return -1;
	}

	if (pthread_mutex_init(mutexQuantum, NULL) != 0) {
		printf("\n init mutexQuamtum fallo\n");
		return -1;
	}

	if (pthread_mutex_init(mutexColaNew, NULL) != 0) {
		printf("\n init mutexCOlaNew fallo\n");
		return -1;
	}
	if (pthread_mutex_init(mutexColaReady, NULL) != 0) {
		printf("\n init mutexColaReady fallo\n");
		return -1;
	}
	if (pthread_mutex_init(mutexColaExit, NULL) != 0) {
		printf("\n init mutexColaExit fallo\n");
		return -1;
	}
	if (pthread_mutex_init(mutexListaBlock, NULL) != 0) {
		printf("\n init mutexListaBlock fallo\n");
		return -1;
	}
	if (pthread_mutex_init(mutexListaExec, NULL) != 0) {
		printf("\n init mutexListaExec fallo\n");
		return -1;
	}

	//inicio El contador de ids
	idProgramas = 0;

	//InicioLasColas
	listaNew = list_create();
	//colaNew = queue_create();
	listaReady = list_create();
	//colaReady = queue_create();
	listaExec = list_create();
	listaBlock = list_create();
	listaExit = list_create();
	//colaExit = queue_create();
	listaCpu = list_create();

	umcServer = socketCreateClient();
	do {
		puts("**********************************");
		puts("Intentando conectar con la UMC ppal.");
		printf("IP: %s, PUERTO: %d\n", ipUMC, atoi(UMCPort));
		sleep(3);
	} while (!socketConnect(umcServer, ipUMC, atoi(UMCPort)));
	StrKerUmc* out_umc_msg = newStrKerUmc(KERNEL_ID, HANDSHAKE, NULL, 0, 0, 0,
			0, 0, 0);
	SocketBuffer* sb = serializeKerUmc(out_umc_msg);
	socketSend(umcServer->ptrSocket, sb);
	puts("Mensaje enviado a la UMC ppal.");

	sb = socketReceive(umcServer->ptrSocket);
	StrUmcKer* in_umc_msg = unserializeUmcKer(sb);

	printf("Nuevo UMC es %d.\n", in_umc_msg->size);

	int nuevoPuertoUmc = in_umc_msg->size;
	tamanioPaginas = pedirTamanioDePagina(nuevoPuertoUmc);

	return 0;
}