Ejemplo n.º 1
0
QPixmap QQLoginCore::getCapImg()
{
    QString captcha_str ="/getimage?uin=%1&vc_type=%2&aid=1003909&r=0.5354663109529408";

    Request req;
    req.create(kGet, captcha_str.arg(CurrLoginAccount::id()).arg(QString(sum_)));
    req.addHeaderItem("Host", "captcha.qq.com");
    req.addHeaderItem("Connection", "Keep-Alive");

    fd_->connectToHost("captcha.qq.com", 80);

    fd_->write(req.toByteArray());

    QByteArray result;
    socketReceive(fd_, result);
    
    int cookie_idx = result.indexOf("Set-Cookie") + 12;
    int idx = result.indexOf(';', cookie_idx)+1;
    CaptchaInfo::instance()->setCookie(result.mid(cookie_idx, idx - cookie_idx));

    QPixmap pix;
    pix.loadFromData(result.mid(result.indexOf("\r\n\r\n") + 4));

    fd_->close();

    return pix;
}
Ejemplo n.º 2
0
int main()
{
	char google[] = "173.194.79.103";
	char message[] = "GET / HTTP/1.1\r\n\r\n";
	char reply[2000];
	int port = 80;
	int ret, sd;
	
	sd = socketCreate();
	printf("Created socket wrapper with descriptor %d.\n", sd);

	ret = socketConnect(sd, google, port);
	printf("Socket wrapper connected to '%s' on port '%d' with return value %d.\n", google, port, ret);

	ret = socketSend(sd, message, -1);
	printf("Socket wrapper sent: \n\n'%s'\n\nto '%s' on port '%d' with return value %d.\n", message, google, port, ret);

	ret = socketReceive(sd, reply, 2000);
	printf("Socket wrapper received: \n\n'%s'\n\nfrom '%s' on port '%d' with return value %d.\n", reply, google, port, ret);

	ret = socketDisconnect(sd);
	printf("Socket wrapper disconnected from '%s' on port '%d' with return value %d.\n", google, port, ret);
	
	return 0;
}
Ejemplo n.º 3
0
QString Protocol::MsgSender::getGroupSig(QString gid, QString to_id)
{
    if ( group_sigs_.contains(gid+to_id) )
        return group_sigs_.value(gid+to_id);

    QString msg_sig_url = "/channel/get_c2cmsg_sig2?id="+ gid +"&to_uin=" + to_id +
        "&service_type=0&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

    QHttpRequestHeader header;
    QString host = "d.web2.qq.com";
    header.setRequest("GET", msg_sig_url);
    header.addValue("Host", host);
    header.addValue("Content-Type", "utf-8");
    header.addValue("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());

    QTcpSocket fd;
    fd.connectToHost(host, 80);
    fd.write(header.toString().toAscii());

    QByteArray result;
    socketReceive(&fd, result);
    fd.close();

    int sig_s_idx = result.indexOf("value")+8;
    int sig_e_idx = result.indexOf('"', sig_s_idx);
    QString sig = result.mid(sig_s_idx, sig_e_idx - sig_s_idx);

    group_sigs_.insert(gid+to_id, sig);

    return sig;
}
Ejemplo n.º 4
0
int_t recv(int_t s, void *data, int_t size, int_t flags)
{
   error_t error;
   size_t received;
   Socket *socket;

   //Make sure the socket descriptor is valid
   if(s < 0 || s >= SOCKET_MAX_COUNT)
   {
      socketError(NULL, ERROR_INVALID_SOCKET);
      return SOCKET_ERROR;
   }

   //Point to the socket structure
   socket = &socketTable[s];

   //Receive data
   error = socketReceive(socket, data, size, &received, flags << 8);

   //Any error to report?
   if(error)
   {
      socketError(socket, error);
      return SOCKET_ERROR;
   }

   //Return the number of bytes received
   return received;
}
void* manageSocketConnection(void* param) {
	Socket* socket = (Socket*) param;
	Boolean connected = TRUE;
	log_info(umclog, "UMC: Gestor de conexiones.");
//while (TRUE) {
	log_info(umclog, "UMC: Esperando el request...");
	SocketBuffer* sb = socketReceive(socket);
	log_info(umclog, "UMC: ...Entro el request.");
	if (sb != NULL) {
		Char id = getStreamId((Stream) sb->data);
		StrKerUmc* sku = NULL;
		StrCpuUmc* scu = NULL;
		StrUmcCpu * suc = NULL;
		StrUmcKer * suk = NULL;
		espacioAsignado aux;
		int thread_socketaux;
		switch (id) {
		case KERNEL_ID:
			//sku = unserializeKerUmc((Stream) sb->data);
			//umcThread();

			pthread_mutex_lock(mutexThreadSockets);
			suk = newStrUmcKer(UMC_ID, HANDSHAKE, "hola", thread_socket, 0, 0);
			newUmcThread();
			//(Char id, Char action, Byte* data, Int32U size, Int32U pid, Int32U cantPage)
			sleep(2);
			pthread_mutex_unlock(mutexThreadSockets);
			sb = serializeUmcKer(suk);
			socketSend(socket, sb);

			break;
		case CPU_ID:
			pthread_mutex_lock(mutexThreadSockets);
			//(Char id, Char action, espacioAsignado pageComienzo, Int32U offset, Int32U dataLen, Byte* data, Int32U pid)
			suc = newStrUmcCpu(UMC_ID, HANDSHAKE, aux, 0, thread_socket, "hola",
					0);
			newUmcThread();
			sleep(2);
			pthread_mutex_unlock(mutexThreadSockets);
			sb = serializeUmcCpu(suc);
			socketSend(socket, sb);

			break;
		default:
			connected = FALSE; //todo loggear algun error.
			break;
		}
	} else {
		log_error(umclog,
				"UMC: Gestor de conexiones: No pudo recibir request, desconectando al cliente.");
		connected = FALSE;
		//	}

	}
	return NULL;
}
Ejemplo n.º 6
0
int LLUdpQWave::receive(uint8_t *buf, int max)
{
	int receivedBytes = socketReceive(m_socketRx, buf, max);
	if (receivedBytes == -1) {
		receivedBytes = 0;
		return 0;
	}

	return receivedBytes;
}
Ejemplo n.º 7
0
error_t ftpReadFile(FtpClientContext *context,
   void *data, size_t size, size_t *length, uint_t flags)
{
   //Invalid context?
   if(context == NULL)
      return ERROR_INVALID_PARAMETER;

   //Receive data from the FTP server
   return socketReceive(context->dataSocket, data, size, length, flags);
}
void finalizarPrograma(int pid) {
	if (tlbHabilitada())
		eliminarProcesoTLB(pid);
	StrUmcSwa*streamUmcSwa;
	espacioAsignado* pagina = newEspacioAsignado();
	streamUmcSwa = newStrUmcSwa(UMC_ID, ELIMINAR_PROCESO, *pagina, NULL,
	NULL,
	NULL, pid);
	SocketBuffer*buffer = serializeUmcSwa(streamUmcSwa);
	if (!socketSend(socketSwap->ptrSocket, buffer))
		puts("error al enviar al swap");
	buffer = socketReceive(socketSwap->ptrSocket);
	StrSwaUmc*desdeUMC = unserializeSwaUmc(buffer);
	espacioAsignado*nodoAReventar;
	int nodoActualAReventar = 0;
	nodoAReventar = list_get(listaEspacioAsignado, nodoActualAReventar);
	while ((nodoAReventar->pid) != pid) {
		nodoActualAReventar++;
		nodoAReventar = list_get(listaEspacioAsignado, nodoActualAReventar);
	}
	int contador;
	int posicion;
	while ((nodoAReventar->pid) == pid) {
		if (nodoAReventar->bitDePresencia == 1) {
			contador = 0;
			posicion = nodoAReventar->IDPaginaInterno * marco_Size;
			while (contador < marco_Size) {
				memoriaReal[posicion] = '\0';
				posicion++;
				contador++;
			}
			bitMap[nodoAReventar->IDPaginaInterno] = 0;
		}
		nodoAReventar = list_remove(listaEspacioAsignado, nodoActualAReventar);
		free(nodoAReventar);
		if (listaEspacioAsignado->elements_count == nodoActualAReventar)
			break;
		nodoAReventar = list_get(listaEspacioAsignado, nodoActualAReventar);
	}
	int j = 0;
	paginasPorPrograma*unaPaginaParaZafar = list_get(listaPaginasPorPrograma,
			j);
	while (unaPaginaParaZafar->pid != pid) {
		j++;
		unaPaginaParaZafar = list_get(listaPaginasPorPrograma, j);
	}
	free(list_remove(listaPaginasPorPrograma, j));
	log_info(umclog, "Programa (PID: %d) eliminado de la UMC", pid);
	free(pagina);
	free(streamUmcSwa);
	free(desdeUMC);
}
Ejemplo n.º 9
0
void tcpDiscardConnectionTask(void *param)
{
   error_t error;
   size_t n;
   size_t byteCount;
   systime_t startTime;
   systime_t duration;
   DiscardServiceContext *context;

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

   //Total number of bytes received
   byteCount = 0;

   //Main loop
   while(1)
   {
      //Throw away any received datagram...
      error = socketReceive(context->socket, context->buffer, DISCARD_BUFFER_SIZE, &n, 0);
      //Any error to report?
      if(error) break;

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

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

   //Debug message
   TRACE_INFO("Discard service: %" PRIuSIZE " bytes "
      "received 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
   osFreeMem(context);

   //Kill ourselves
   osDeleteTask(NULL);
}
Ejemplo n.º 10
0
error_t smtpRead(SmtpClientContext *context, void *data, size_t size, size_t *received, uint_t flags)
{
#if (SMTP_TLS_SUPPORT == ENABLED)
   //Check whether a secure connection is being used
   if(context->tlsContext != NULL)
   {
      //Use SSL/TLS to receive data from the SMTP server
      return tlsRead(context->tlsContext, data, size, received, flags);
   }
   else
#endif
   {
      //Receive data from the SMTP server
      return socketReceive(context->socket, data, size, received, flags);
   }
}
bool inicializarPrograma(int pid, int paginas, char*codigo) {
	SocketBuffer*buffer;
	StrUmcSwa*streamUmcSwap;
	espacioAsignado* pagina = newEspacioAsignado();
	StrSwaUmc * streamSwapUmc;
	pagina->numDePag = 0;
	streamUmcSwap = newStrUmcSwa(UMC_ID, RECIBIR_NUEVO_PROGRAMA, *pagina,
			paginas, codigo, tamanioCodigo(codigo), pid);
	buffer = serializeUmcSwa(streamUmcSwap);
	socketSend(socketSwap->ptrSocket, buffer);

	buffer = socketReceive(socketSwap->ptrSocket);
	streamSwapUmc = unserializeSwaUmc(buffer->data);

	if (streamSwapUmc->action == PROGRAMA_RECIBIDO) {
		int i = 0;
		paginasPorPrograma*pagina = malloc(sizeof(paginasPorPrograma));
		pagina->pid = pid;
		pagina->cantPaginasEnMemoria = 0;
		list_add(listaPaginasPorPrograma, pagina);
		while (i < paginas) {
			espacioAsignado*nuevoMarco = malloc(sizeof(espacioAsignado));
			nuevoMarco->bitDePresencia = 0;
			nuevoMarco->bitModificado = 0;
			nuevoMarco->bitUso = 0;
			nuevoMarco->numDePag = i;
			nuevoMarco->pid = pid;
			if (i == 0)
				nuevoMarco->punteroAPagina = 1;
			else
				nuevoMarco->punteroAPagina = 0;
			list_add(listaEspacioAsignado, nuevoMarco);
			i++;
		}
		log_info(umclog, "Programa inicializado correctamente PID: %d", pid);
		free(streamSwapUmc);
		free(streamUmcSwap);

		return TRUE;
	} else
		log_error(umclog, "No se pudo inicializar el programa PID: %d", pid);
	free(streamSwapUmc);
	free(streamUmcSwap);
	return FALSE;

}
static jbyteArray com_android_nfc_NativeP2pDevice_doReceive(
   JNIEnv *e, jobject o)
{
	uint32_t handle = nfc_jni_get_nfc_socket_handle(e, o);
	bool_t canUse = W_FALSE;

    jclass target_cls = NULL;
    jfieldID f;
	if(IS_SERVER_SOCKET(handle))
	{
		return serverSocketReceive(e, handle);
	}
	else if(IS_CLIENT_SOCKET(handle))
	{
		return socketReceive(e, handle);
	}
	return NULL;
}
Ejemplo n.º 13
0
error_t sntpWaitForResponse(SntpClientContext *context, systime_t timeout)
{
   error_t error;
   size_t length;
   systime_t elapsedTime;

   //Time elapsed since the NTP request was sent
   elapsedTime = 0;

   //Keep listening as long as the retransmission timeout has not been reached
   while(elapsedTime < timeout)
   {
      //Adjust receive timeout
      error = socketSetTimeout(context->socket, timeout - elapsedTime);
      //Any error to report?
      if(error) break;

      //Wait for a response from the NTP server
      error = socketReceive(context->socket, &context->message,
         sizeof(NtpHeader), &length, 0);

      //Any datagram received?
      if(!error)
      {
         //Time at which the response was received
         context->t4 = osGetSystemTime();

         //Parse incoming datagram
         error = sntpParseResponse(context, &context->message, length);
         //Valid NTP response message?
         if(!error) return NO_ERROR;
      }

      //Compute the time elapsed since the NTP request was sent
      elapsedTime = osGetSystemTime() - context->t1;
   }

   //The timeout period elapsed
   return ERROR_TIMEOUT;
}
Ejemplo n.º 14
0
error_t httpReceive(HttpConnection *connection,
   void *data, size_t size, size_t *received, uint_t flags)
{
   error_t error;

#if (HTTP_SERVER_TLS_SUPPORT == ENABLED)
   //Check whether a secure connection is being used
   if(connection->tlsContext != NULL)
   {
      //Use SSL/TLS to receive data from the client
      error = tlsRead(connection->tlsContext, data, size, received, flags);
   }
   else
#endif
   {
      //Receive data from the client
      error = socketReceive(connection->socket, data, size, received, flags);
   }

   //Return status code
   return error;
}
Ejemplo n.º 15
0
error_t tlsIoRead(TlsContext *context, void *data, size_t length)
{
#if (TLS_BSD_SOCKET_SUPPORT == ENABLED)
   //Read as much data as possible
   while(length > 0)
   {
      //Read data
      int_t n = recv(context->socket, data, length, 0);
      //Any error to report?
      if(n <= 0) break;

      //Advance data pointer
      data = (uint8_t *) data + n;
      //Number of bytes remaining to read
      length -= n;
   }

   //Make sure that the requested number of bytes have been read
   if(length != 0) return ERROR_READ_FAILED;

   //Successful read operation
   return NO_ERROR;
#else
   error_t error;
   size_t n;

   //Read data
   error = socketReceive(context->socket, data, length, &n, SOCKET_FLAG_WAIT_ALL);
   //Any error to report?
   if(error) return ERROR_READ_FAILED;

   //Make sure that the requested number of bytes have been read
   if(n != length) return ERROR_READ_FAILED;

   //Successful read operation
   return NO_ERROR;
#endif
}
Ejemplo n.º 16
0
//----------------------------------------------------------------------------//
// QCanDump()                                                                 //
// constructor                                                                //
//----------------------------------------------------------------------------//
QCanDump::QCanDump(QObject *parent) :
    QObject(parent)
{
   //----------------------------------------------------------------
   // get the instance of the main application
   //
   pclAppP = QCoreApplication::instance();

   
   //----------------------------------------------------------------
   // connect signals for socket operations
   //
   QObject::connect(&clCanSocketP, SIGNAL(connected()),
                    this, SLOT(socketConnected()));

   QObject::connect(&clCanSocketP, SIGNAL(disconnected()),
                    this, SLOT(socketDisconnected()));
   
   QObject::connect(&clCanSocketP, SIGNAL(error(QAbstractSocket::SocketError)),
                    this, SLOT(socketError(QAbstractSocket::SocketError)));

   QObject::connect(&clCanSocketP, SIGNAL(framesReceived(uint32_t)),
                    this, SLOT(socketReceive(uint32_t)));
}
Ejemplo n.º 17
0
void icecastClientTask(void *param)
{
   error_t error;
   bool_t end;
   size_t n;
   size_t length;
   size_t received;
   IcecastClientContext *context;

   //Retrieve the Icecast client context
   context = (IcecastClientContext *) param;

   //Main loop
   while(1)
   {
      //Initiate a connection to the Icecast server
      error = icecastClientConnect(context);

      //Connection to server failed?
      if(error)
      {
         //Debug message
         TRACE_ERROR("Connection to Icecast server failed!\r\n");
         //Recovery delay
         osDelay(ICECAST_RECOVERY_DELAY);
         //Try to reconnect...
         continue;
      }

      //Debug message
      TRACE_INFO("Block size = %u\r\n", context->blockSize);

      //Check block size
      if(!context->blockSize)
      {
         socketClose(context->socket);
         continue;
      }

      //Initialize loop condition variable
      end = FALSE;

      //Read as much data as possible...
      while(!end)
      {
         //Process the stream block by block
         length = context->blockSize;

         //Read current block
         while(!end && length > 0)
         {
            //Wait for the buffer to be available for writing
            osEventWait(context->writeEvent, INFINITE_DELAY);

            //Enter critical section
            osMutexAcquire(context->mutex);
            //Compute the number of bytes to read at a time
            n = min(length, context->bufferSize - context->bufferLength);
            //Leave critical section
            osMutexRelease(context->mutex);

            //Check whether the specified data crosses buffer boundaries
            if((context->writeIndex + n) > context->bufferSize)
               n = context->bufferSize - context->writeIndex;

            //Receive data
            error = socketReceive(context->socket, context->streamBuffer +
               context->writeIndex, n, &received, SOCKET_FLAG_WAIT_ALL);

            //Make sure the expected number of bytes have been received
            if(error || received != n)
               end = TRUE;

            //Enter critical section
            osMutexAcquire(context->mutex);

            //Increment write index
            context->writeIndex += n;
            //Wrap around if necessary
            if(context->writeIndex >= context->bufferSize)
               context->writeIndex -= context->bufferSize;

            //Update buffer length
            context->bufferLength += n;
            //Check whether the buffer is available for writing
            if(context->bufferLength < context->bufferSize)
               osEventSet(context->writeEvent);
            //Check whether the buffer is available for reading
            if(context->bufferLength > 0)
               osEventSet(context->readEvent);

            //Leave critical section
            osMutexRelease(context->mutex);

            //Update the total number of bytes that have been received
            context->totalLength += n;
            //Number of remaining data to read
            length -= n;
         }

         //Debug message
         TRACE_DEBUG("Total bytes received = %u\r\n", context->totalLength);

         //Check whether the metadata block should be read
         if(!end)
         {
            //Process the metadata block
            error = icecastClientProcessMetadata(context);
            //Any error to report?
            if(error) end = TRUE;
         }
      }

      //Close connection
      socketClose(context->socket);
   }
}
Ejemplo n.º 18
0
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 almacenarBytes(int pid, int pagina, int offset, int tamanio, char*buffer) {
	usleep(1000 * espera);
	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)) {
		paginaEncontrada = FALSE;
		log_error(umclog,"=================================================\n");
		log_error(umclog,"===========Segmentation fault, PID: %d===========\n", pid);
		log_error(umclog,"=================================================\n");
	} else {
		if (nodoALeer->bitDePresencia == 1) {
			(nodoALeer->bitUso) = 1;
			nodoALeer->bitModificado = 1;
			int lugarDeLaCadena = 0;
			int posicionDeChar = (nodoALeer->IDPaginaInterno) * marco_Size
					+ offset;
			while (lugarDeLaCadena < tamanio) {
				memoriaReal[posicionDeChar] = buffer[lugarDeLaCadena];
				posicionDeChar++;
				lugarDeLaCadena++;
			}
			log_info(umclog, "Bytes almacenados por PID: %d, en pagina %d", pid,
					pagina);
		} 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 = 1;
				nodoALeer->bitDePresencia = 1;
				espacioAsignado pageToSend;
				pageToSend.numDePag = pagina;
				StrUmcSwa*streamUmcSwap = newStrUmcSwa(UMC_ID,
				LEER_UNA_PAGINA, pageToSend, 1,
				NULL, 0, nodoALeer->pid);
				SocketBuffer*buf = serializeUmcSwa(streamUmcSwap);
				if (!socketSend(socketSwap->ptrSocket, buf))
					puts("error al enviar al swap");
				buf = socketReceive(socketSwap->ptrSocket);
				StrSwaUmc* streamSwapUmc = unserializeSwaUmc(buf);
				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 < tamanio) {
					memoriaReal[comCadena] = buffer[lugCad];
					comCadena++;
					lugCad++;
				}
				free(streamSwapUmc);
				free(streamUmcSwap);
				log_info(umclog, "Bytes almacenados por PID: %d, en pagina %d",
						pid, pagina);
			} else {

				int frame = reemplazarPagina(pid, pagina, 1);
				int dondeEscribo = frame * marco_Size + offset;
				int enDondeEstoyDeLoQueMeMandaron = 0;
				int contador = 0;
				while (contador < tamanio) {
					memoriaReal[dondeEscribo] =
							buffer[enDondeEstoyDeLoQueMeMandaron];
					dondeEscribo++;
					enDondeEstoyDeLoQueMeMandaron++;
					contador++;
				}
				log_info(umclog, "Bytes almacenados por PID: %d, en pagina %d",
						pid, pagina);
			}
		}
		if (tlbHabilitada()) {
			llevarPaginaATLB(pid, pagina, NULL);
		}
	}
}
Ejemplo n.º 20
0
error_t icecastClientProcessMetadata(IcecastClientContext *context)
{
   error_t error;
   size_t n;
   size_t length;
   size_t metadataLength;

   //The metadata block begins with a single byte which indicates
   //how many 16-byte segments need to be read
   error = socketReceive(context->socket, context->buffer,
      sizeof(uint8_t), &length, SOCKET_FLAG_WAIT_ALL);

   //Any error to report?
   if(error)
      return error;
   //Make sure the expected number of bytes have been received
   if(length != sizeof(uint8_t))
      return ERROR_INVALID_METADATA;

   //Compute the length of the following metadata block
   metadataLength = context->buffer[0] * 16;
   //Debug message
   TRACE_DEBUG("Icecast metadata length = %u\r\n", metadataLength);

   //Limit the number of bytes to read
   n = min(metadataLength, ICECAST_CLIENT_METADATA_MAX_SIZE - 1);

   //Read the metadata information
   error = socketReceive(context->socket, context->buffer,
      n, &length, SOCKET_FLAG_WAIT_ALL);

   //Any error to report?
   if(error)
      return error;
   //Make sure the expected number of bytes have been received
   if(length != n)
      return ERROR_INVALID_METADATA;

   //Enter critical section
   osMutexAcquire(context->mutex);

   //Save metadata information
   memcpy(context->metadata, context->buffer, n);
   //Terminate the string properly
   context->metadata[n] = '\0';
   //Record the length of the metadata
   context->metadataLength = n;

   //Leave critical section
   osMutexRelease(context->mutex);

   //Debug message
   TRACE_DEBUG("<%s>\r\n", context->metadata);

   //Compute the number of bytes that have not been processed
   metadataLength -= n;

   //Read the complete metadata
   while(metadataLength > 0)
   {
      //Compute the number of data to read at a time
      n = min(metadataLength, ICECAST_CLIENT_METADATA_MAX_SIZE);

      //Drop incoming data...
      error = socketReceive(context->socket, context->buffer,
         n, &length, SOCKET_FLAG_WAIT_ALL);

      //Any error to report?
      if(error)
         return error;
      //Make sure the expected number of bytes have been received
      if(length != n)
         return ERROR_INVALID_METADATA;

      //Update byte counter
      metadataLength -= n;
   }

   //Successful processing
   return NO_ERROR;
}
//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;
}
Ejemplo n.º 22
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);
   }
}
Ejemplo n.º 23
0
void ftpServerReceiveData(FtpServerContext *context, FtpClientConnection *connection)
{
   error_t error;
   bool_t eof;
   size_t n;

   //File transfer in progress?
   if(connection->controlState == FTP_CONTROL_STATE_STOR ||
      connection->controlState == FTP_CONTROL_STATE_APPE)
   {
      //Read incoming data
      error = socketReceive(connection->dataSocket,
         connection->buffer + connection->bufferPos,
         FTP_SERVER_BUFFER_SIZE - connection->bufferLength, &n, 0);

      //Any error to report?
      if(error)
      {
         //Cannot read more data
         eof = TRUE;
      }
      else
      {
         //Successful read operation
         eof = FALSE;

         //Advance data pointer
         connection->bufferPos += n;
         connection->bufferLength += n;
      }

      //Read data until the buffer is full or the end of the file is reached
      if(eof || connection->bufferLength >= FTP_SERVER_BUFFER_SIZE)
      {
         //Any data to be written?
         if(connection->bufferLength > 0)
         {
            //Write data to the specified file
            error = fsWriteFile(connection->file,
               connection->buffer, connection->bufferLength);

            //Any error to report?
            if(error)
            {
               //Close the data connection
               ftpServerCloseDataConnection(connection);

               //Release previously allocated resources
               fsCloseFile(connection->file);
               connection->file = 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;
            }
         }

         //Flush reception buffer
         connection->bufferLength = 0;
         connection->bufferPos = 0;
      }

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

         //Graceful shutdown sequence
         connection->dataState = FTP_DATA_STATE_WAIT_ACK;
      }
   }
   //Invalid state?
   else
   {
      //The FTP server has encountered a critical error
      ftpServerCloseConnection(context, connection);
   }
}
Ejemplo n.º 24
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;
}
Ejemplo n.º 25
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;
}
Ejemplo n.º 26
0
error_t dnsResolve(NetInterface *interface, const char_t *name, IpAddr *ipAddr)
{
   error_t error;
   uint_t i;
   size_t length;
   uint16_t identifier;
   IpAddr serverIpAddr;
   Socket *socket;
   DnsHeader *dnsMessage;

   //Debug message
   TRACE_INFO("Trying to resolve %s...\r\n", name);

   //Use default network interface?
   if(!interface)
      interface = tcpIpStackGetDefaultInterface();

   //Allocate a memory buffer to hold DNS messages
   dnsMessage = memPoolAlloc(DNS_MESSAGE_MAX_SIZE);
   //Failed to allocate memory?
   if(!dnsMessage)
      return ERROR_OUT_OF_MEMORY;

   //Open a UDP socket
   socket = socketOpen(SOCKET_TYPE_DGRAM, SOCKET_PROTOCOL_UDP);

   //Failed to open socket?
   if(!socket)
   {
      //Free previously allocated memory
      osMemFree(dnsMessage);
      //Return status code
      return ERROR_OPEN_FAILED;
   }

#if (IPV4_SUPPORT == ENABLED)
   //IP address of the DNS server
   serverIpAddr.length = sizeof(Ipv4Addr);
   serverIpAddr.ipv4Addr = interface->ipv4Config.dnsServer[0];
#elif (IPV6_SUPPORT == ENABLED)
   //IP address of the DNS server
   serverIpAddr.length = sizeof(Ipv6Addr);
   serverIpAddr.ipv6Addr = interface->ipv6Config.dnsServer[0];
#endif

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

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

   //Connect the newly created socket to the primary DNS server
   error = socketConnect(socket, &serverIpAddr, DNS_PORT);

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

   //An identifier is used by the client to match replies
   //with corresponding requests
   identifier = rand();

   //Try to retransmit the DNS message if the previous query timed out
   for(i = 0; i < DNS_MAX_RETRIES; i++)
   {
      //Send DNS query message
      error = dnsSendQuery(socket, dnsMessage, identifier, name);
      //Failed to send message ?
      if(error) break;

      //Adjust receive timeout
      error = socketSetTimeout(socket, DNS_REQUEST_TIMEOUT);
      //Any error to report?
      if(error) break;

      //Wait for the server response
      error = socketReceive(socket, dnsMessage, DNS_MESSAGE_MAX_SIZE, &length, 0);

      //Any response from the specified DNS server?
      if(!error)
      {
         //Parse DNS response
         error = dnsParseResponse(dnsMessage, length, identifier, ipAddr);
         //DNS response successfully decoded?
         if(!error) break;
      }
   }

   //The maximum number of retransmissions has been reached?
   if(i >= DNS_MAX_RETRIES)
      error = ERROR_TIMEOUT;

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

   //Debug message
   if(!error)
   {
      //Name resolution succeeds
      TRACE_INFO("Host name resolved to %s...\r\n", ipAddrToString(ipAddr, NULL));
   }
   else
   {
      //Report an error
      TRACE_ERROR("DNS resolution failed!\r\n");
   }

   //Return status code
   return error;
}
Ejemplo n.º 27
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;
}
Ejemplo n.º 28
0
int32_t UdpConnection::receiveDataFromRemote(uint32_t size)
{
    unsigned int index;
    unsigned int id;
    unsigned int remote;
    unsigned int ack;
    unsigned int ackBitmap;
    unsigned char * packet = mRcvBuffer;
    
    int bytes_read = socketReceive(&mSock, &mSender, packet, size + UDP_CONNECTION_HEADER_SIZE );
    if ( bytes_read <= 0 )
    {
        return bytes_read;
    }
    
    if ( bytes_read <= UDP_CONNECTION_HEADER_SIZE )
    {
        LOG_ERR2("Not enough bytes for header", bytes_read);
        return 0;
    }
    
    id = (unsigned int)read32bitsFromBuffer(packet);
    
    if (id!=mProtocolId)
    {
        LOG_ERR2("This id is not for this connection",id);
        return 0;
    }
    
    
    uint32_t last = getTicks();
    if (mReceiverLastTime!=0)
    {
        mReceiverDeltaTime = last - mReceiverLastTime;
    }
    
    mReceiverLastTime = last;
    
    
    // read the remote packet number and check if this number is more recent than the current
    remote = (unsigned int)read32bitsFromBuffer(packet+4);
    if (isSequenceMoreRecent(remote,mRemoteSequence)==1)
    {
        // move the ack bitmap and acknowledge the packet received
        mRemoteSequence = remote;
        
        moveAckBitmap(mRemoteAcks);
        
        mRemoteAcks[0] = 1;
    }
    else
    {
        // we receive an old packet
        index = (mRemoteSequence - remote) & (ACK_MAX-1);
        
        mRemoteAcks[index] = 1;
    }
    
    // read the ack (my sequence number from the point of view of the remote)
    ack = (unsigned int)read32bitsFromBuffer(packet+8);
    ackBitmap = (unsigned int)read32bitsFromBuffer(packet+12);
    mSenderDeltaTime = (uint32_t)read32bitsFromBuffer(packet+16);
    
    
    // and check ack and our local sequence number : local - ACK_MAX < ack < local
    //    if (isSequenceMoreRecent(ack, connection->localSequence)==0)
    if ( (int)ack > (int)(mLocalSequence - ACK_MAX) && ack <= mLocalSequence)
    {
        index = (mLocalSequence - ack) & (ACK_MAX-1);
        
        setLocalAckFromBitmap(index,ackBitmap);
    }
    else
    {
        // we receive a packet with a very old ack and we can't check
        
        //LOG("error: Receive ack %d local %d, too old !\n", ack, mLocalSequence);
    }
    
    return (bytes_read - UDP_CONNECTION_HEADER_SIZE);
}
Ejemplo n.º 29
0
void tcpEchoConnectionTask(void *param)
{
   error_t error;
   uint_t n;
   uint_t writeIndex;
   uint_t readIndex;
   uint_t bufferLength;
   uint_t rxByteCount;
   uint_t txByteCount;
   time_t startTime;
   time_t duration;
   SocketEventDesc eventDesc;
   EchoServiceContext *context;

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

   //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 = osGetTickCount() - startTime;

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

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

   //Kill ourselves
   osTaskDelete(NULL);
}
//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;
}