Exemplo n.º 1
0
int SendPacket(int fd, GenericPacket* in, int packetSize)
{
    int totalSent = 0;
    do
    {
        int r = send(
                fd, (void*)in + totalSent,
                MAXDATA(packetSize - totalSent),
                0);

        if (r > 0)
        {
            totalSent += r;
        }
        else if (!IS_WOULDBLOCK(GET_ERROR()))
        {
            printf("send error: %d\n", GET_ERROR());
            return GET_ERROR();
        }
        //printf("sent %d / %d\n", totalSent, packetSize);
    }
    while (totalSent < packetSize);

    return 0;
}
Exemplo n.º 2
0
int RecvPacket(int fd, GenericPacket** out)
{
    int sizeofGenericPacket = sizeof(GenericPacket);
    GenericPacket packet;

    {
        // FIXME: Call recv multiple times here if needed.
        int r = recv(fd, (void*)&packet, sizeofGenericPacket, 0);

        if (r == 0)
        {
            return -1;
        }
        else if (r < 0)
        {
            if (IS_WOULDBLOCK(GET_ERROR()))
                return -2;
            else
                return GET_ERROR();
        }
    }

    int totalSize = sizeofGenericPacket + packet.dataSize;
    *out = malloc(totalSize);
    memcpy(*out, (char*)&packet, sizeofGenericPacket);

    if (packet.dataSize == 0)
        return 0;

    {
        int totalReceived = sizeofGenericPacket;
        do
        {
            int r = recv(
                    fd, (void*)*out + totalReceived,
                    MAXDATA(totalSize - totalReceived),
                    0);

            if (r > 0)
            {
                totalReceived += r;
            }
            else if (r == 0)
            {
                free(*out);
                return -1;
            }
            else if (!IS_WOULDBLOCK(GET_ERROR()))
            {
                free(*out);
                return GET_ERROR();
            }
            //printf("received %d / %d\n", totalReceived, totalSize);
        }
        while (totalReceived < totalSize);
    }

    return 0;
}
Exemplo n.º 3
0
	bool Socket::Read( char * dst, uint dst_bytes ) {
		//Output( "Socket::read() %d bytes to 0x%x", dst_bytes, dst);
		int n = dst_bytes;
		while( n > 0 ) {
			int i = (int)recv( s, dst, n, 0 );
			if( i < 0 ) {
#ifdef _WIN32
				int wsaerr = GET_ERROR();
				if( wsaerr == 10035 ) {
					Sleep(1); // no data, recv would block
					continue;	  // wait a msec and try again
				}
				return false;
#else
				if( /*errno == EWOULDBLOCK ||*/ errno == EAGAIN ) {
					i=0;
				} else {
					Output( "r3::Socket::read: recv" );
					return false;
				}
#endif
			} else if ( i == 0 ) {
				Output( "Socket::read(): connection closed on remote end\n");
				return false;
			}
			//Output( "i=%d, n=%d",i,n );
			dst += i;
			n -= i;
		}
		//fprintf(stderr,"Done\n");
		return true;
	}
Exemplo n.º 4
0
static INFO_STATUS set_access_token(user_t users) {
#define CONTENT_LEN 512
#define BUF_LEN 1024
    /* Connect */
    int client = make_connect();
    users->comm_hook = (void *)client;
    char content[CONTENT_LEN] = {0};
    int content_size = snprintf(content, CONTENT_LEN, "{\"username\": \"%s\",\"password\": \"%s\"}",
                                              users->username, users->password);

    char send_buf[BUF_LEN] = {0};
    snprintf(send_buf, BUF_LEN, "%sContent-length: %d\r\nConnection: keep-alive\r\n\r\n%s", post_head, content_size, content);
    send(client, send_buf, strnlen(send_buf, BUF_LEN), 0);
    int err = recv(client, send_buf, BUF_LEN, 0);
    fprintf(stderr, "Receive(%d): \n%s\n", err, send_buf);
    /* Parse */
    char * start = find_accecc(send_buf);
    /* Check For Error */
    if (IS_SET_ERROR((int)(start)))
        return GET_ERROR((int)(start));

#define PREFIX_LEN 4
#define ACCESS_TOKEN_LEN 173
    char * access_token = calloc(PREFIX_LEN + ACCESS_TOKEN_LEN+2, 1);
    if (unlikely(access_token == NULL))
        exit(-3);
    int writen = snprintf(access_token, PREFIX_LEN + ACCESS_TOKEN_LEN+1, "JWT %s", start);
    //fprintf(stderr, "Parse Accesstoken is (%d): %s\n", writen, access_token);
    assert(writen == 176);
    /* Store */
    users->access_token = access_token;
    return SET_ACC_TOKEN_SUCCESS;
#undef PREFIX_LEN
#undef ACCESS_TOKEN_LEN
}
Exemplo n.º 5
0
// NOTE: because this does not return the entire PAB back to you,
// if you need data from the DSR other than the error byte
// (ie: RECORD NUMBER), then you have to get it yourself!
unsigned char dsrlnk(struct PAB *pab, unsigned int vdp) {
	unsigned char x;

	// copies your PAB to VDP and then executes the call through dsrlnkraw
	vdpmemcpy(vdp, (const unsigned char*)pab, 9);
	// assumes vdpmemcpy leaves the VDP address in the right place!
	if (pab->NameLength == 0) {
		x = strlen(pab->pName);
	} else {
		x= pab->NameLength;
	}
	VDPWD = x;

	// and the filename itself - note we assume 'x' is valid!
	unsigned char *p = pab->pName;
	while (x--) {
		VDPWD = *(p++);
	}

	// now we can call it
	dsrlnkraw(vdp);

	// now return the result
	return GET_ERROR(vdpreadchar(vdp+1));
}
Exemplo n.º 6
0
int cleanup()
/* Function tries to clean up resources gathered by the library.    *
 *                                                                  *
 * RETURN VALUE                                                     *
 *    0             success                                         *
 *    PSIM_EIO      unlinking or closing the memory file failed     *
 *    other         last pthread_xxx_destroy error encountered      */
{
  int ret = 0, ret2 = 0, buf, i;
  
  GET_ERROR(pthread_mutex_destroy(&data.mutex), buf, ret);
  GET_ERROR(pthread_cond_destroy(&data.max_operations_cond), buf, ret);
  GET_ERROR(pthread_cond_destroy(&data.create_page_cond), buf, ret);
  for(i = 0; i < data.addr_space_size; i++)
    GET_ERROR(pthread_cond_destroy(&data.pages[i].cond), buf, ret);

  if(data.file != -1)
  {
    if(close(data.file) != 0)
      ret2 = PSIM_EIO;
    if(unlink(data.file_name) != 0)
      ret2 = PSIM_EIO;
  }

  if(ret2 != 0)
    return PSIM_EIO;
  
  if(ret != 0)
    return PSIM_ECLEA;

  /* We're freeing memory only if operations on conds and mutex were *
   * successful. Freeing may cause segfault in get/set operation.    */
  page_sim_mem_cleanup();
  
  return 0;
}
Exemplo n.º 7
0
static inline bool mcc_rls(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
{
	struct l2cap_frame *frame = &rfcomm_frame->l2cap_frame;
	struct rfcomm_rls rls;

	if (!l2cap_frame_get_u8(frame, &rls.dlci))
		return false;

	if (!l2cap_frame_get_u8(frame, &rls.error))
		return false;

	print_field("%*cdlci %d error: %d", indent, ' ',
			RFCOMM_GET_DLCI(rls.dlci), GET_ERROR(rls.error));

	return true;
}
Exemplo n.º 8
0
	bool Listener::Listen( int port ) {
		INIT_SOCKET_LIB();

                if ( s == INVALID_SOCKET ) {
		    s = socket(AF_INET, SOCK_STREAM, 0);
#if ! _WIN32
                    unsigned int opt = 1;
                    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))==-1) {
                        perror("setsockopt(s,SOL_SOCKET, SO_REUSEADDR,1)");
                    }
#endif 
		    if (s == INVALID_SOCKET) {
			Output( "Error at socket(): %ld\n", (long)GET_ERROR() );
			Close();
			return false;
		    }

		    sockaddr_in service;
		    memset( &service, 0, sizeof( service ) );
	 	    service.sin_family = AF_INET;
		    service.sin_addr.s_addr = INADDR_ANY;
		    service.sin_port = htons(port);

		    if ( bind( s, (SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR ) {
		    	Output( "bind() failed." );
#if ! _WIN32
			perror( "bind error" );
#endif
			Close();
			return false;
		    }

                }
		if ( listen( s, 1 ) == SOCKET_ERROR ) {
			Output( "Error listening on socket." );
#if ! _WIN32
			perror( "bind error" );
#endif
			Close();
			return false;
		}

		//SetNonblocking();
		return true;
	}
Exemplo n.º 9
0
//-1 error
//1  tc
//0 normal
//2 retry
int
check_an_msg(ushort flag, uchar * domain, int *bk)
{
    uint get = 0;
    flag = ntohs(flag);
    //printf("flag is 0x%x\n",flag);
    get = GET_QR(flag);
    if (get == QR_Q)            //query
    {
        printf("answer set Q sign\n");
        return -1;
    }
    get = GET_OPCODE(flag);     //ignore.
    get = GET_AA(flag);         //ignore
    get = GET_TC(flag);
    if (get == 1)
        return 1;               //tc
    get = GET_RD(flag);         //ignore
    get = GET_ERROR(flag);
    if ((get != 0) && (get != NAME_ERROR))      //soa
    {
        switch (get) {
        case SERVER_FAIL:
            //printf("2server fail\n");
            break;
            //case NAME_ERROR: SOA
            //*bk = 1;
            //printf("3name error\n");
            //break;
        case FORMAT_ERROR:
            //*bk = 1;
            //printf("1format error\n");
            break;
        case NOT_IMPL:
            //printf("4not implation\n");
            break;
        case REFUSED:
            //printf("5server refused\n");
            break;
        }
        return 2;
    }
    return 0;
}
Exemplo n.º 10
0
	Socket Listener::Accept() {
		if( s == -1 ) {
			return -1;
		}

		SOCKET client = accept( s, NULL, NULL );
		if ( client == SOCKET_ERROR ) {
#ifdef _WIN32
			int wsaerr = GET_ERROR();
			if( wsaerr != WSAEWOULDBLOCK ) {
				Close();
			} 
#else
                        perror( "Accept failed." );
#endif
			return Socket(-1);
		}
                //Output( "Accept() returning client %d\n", client );
		return Socket( client, ST_Stream );
	}
Exemplo n.º 11
0
	int Socket::ReadPartial( char * dst, uint dst_bytes ) {
		//fprintf(stderr,"r3::Socket::read() %d bytes to 0x%x\n", dst_bytes, dst);
    
		int i = (int)recv( s, dst, dst_bytes, 0 );
		if( i < 0 ) {
#ifdef _WIN32
			int wsaerr = GET_ERROR();
			if( wsaerr == 10035 ) {
				i=0;
			}
#else
			if( errno == EWOULDBLOCK || errno == EAGAIN ) {
				i=0;
			}
			perror("r3::Socket::read: recv");
#endif
		} else if ( i == 0 ) {
			Output( "r3::Socket::Read(): connection closed on remote end" );
			Disconnect();
			i=-1; // we'll use negative return to mean something bad happened...
		}
		return i;
	}
Exemplo n.º 12
0
KS_E_ERROR ks_file_write(KS_FILE_PTR file_ptr,
                         LongWord position,
                         LongWord data_size,
                         Pointer data_buffer)
{
    /* ************************************************************** *
     *  Local declarations:                                           *
     * ************************************************************** */

    KS_E_ERROR   error;            /* Holds error codes for subroutine*/
                                   /*  calls                          */
    LongWord     data_offset;      /* Offset into the buffer to return*/
    LongWord     remaining_space;  /* Space remaining in file buffer  */
    LongWord     buffer_request;   /* Size of each copy from the      */
                                   /*  file buffer                    */


    ROUTINE_ENTER();


    /* ************************************************************** *
     *  Verify the structure ID passed in is the correct one.         *
     * ************************************************************** */

    if (file_ptr->struct_id != KS_FILE_ID)
        {
        KS_ERROR(KS_E_INVALID_STRUCT_ID, KS_FILE_ID);
        };


    /* ************************************************************** *
     *  Zero the number of bytes transfered in the KS_FILE structure. *
     * ************************************************************** */

    file_ptr->data_size = 0;


    /* ************************************************************** *
     *  If there is a buffer, then lets put data into the file buffer.*
     * ************************************************************** */

    if (file_ptr->buffer_size != NULL)
        {

        /* ********************************************************** *
         *  Loop till we satisfy the request (or take an error)       *
         * ********************************************************** */

        data_offset = 0;

        while (data_size > 0)
            {

            /* ****************************************************** *
             *  Calculate the remaining space in the buffer.  If      *
             *  there is any space left in the buffer then lets copy  *
             *  as much as we need to into the file buffer.           *
             * ****************************************************** */

            remaining_space = (file_ptr->buffer_available) -
                              (file_ptr->buffer_offset);

            if (remaining_space > 0)
                {
                buffer_request = MIN(data_size,
                                     remaining_space);

                COPY_BYTES(data_buffer,
                           data_offset,
                           file_ptr->buffer,
                           file_ptr->buffer_offset,
                           buffer_request);

                /* ************************************************** *
                 *  Now modify the parameters of the buffers by:      *
                 *                                                    *
                 *  1) Adding the size of the request to the file     *
                 *  buffer ofset and the data offset (IE: Indices to  *
                 *  the file buffer and the read request buffer).     *
                 *                                                    *
                 *  2) Subtracting the request size from the read     *
                 *  request size and the remaining number of          *
                 *  characters in the file buffer.                    *
                 * ************************************************** */

                file_ptr->buffer_offset = file_ptr->buffer_offset +
                                          buffer_request;

                data_offset = data_offset + buffer_request;

                file_ptr->data_size = data_offset; 

                data_size = data_size - buffer_request;

                remaining_space = remaining_space - buffer_request;
                };


            /* ****************************************************** *
             *  If the file buffer is full, then we have to write it  *
             *  to disk.  The problem is that the buffer size may     *
             *  have changed due to what our user wants (users are    *
             *  bound to be the end of all computing...).  This means *
             *  that we'll junp through a few hoops if we must change *
             *  buffer sizes - so expect some weirdness here.         *
             * ****************************************************** */

            if (remaining_space == 0)
                {

                /* ************************************************** *
                 *  Issue a Read to the file into our buffer.         *
                 * ************************************************** */

                KSf_pkts.IO.pCount = 4;
                KSf_pkts.IO.refNum = file_ptr->refNum;
                KSf_pkts.IO.dataBuffer = TO_POINTER(file_ptr->buffer);
                KSf_pkts.IO.requestCount = file_ptr->buffer_size;

                WriteGS(&KSf_pkts.IO);

                if ((error = GET_ERROR()) != KS_E_SUCCESS)
                    {
                    goto EXIT_NOW;
                    };

                file_ptr->buffer_available = file_ptr->buffer_size;
                file_ptr->buffer_offset = 0;


                /* ************************************************** *
                 *  This is the above mentioned weirdness - if the    *
                 *  user specified a different size buffer we will    *
                 *  no comply with their wishes.                      *
                 * ************************************************** */

                if (file_ptr->buffer_size != KSf_FileBufferSize)
                    {
                    KS_MEMORY_DEALLOCATE(file_ptr->buffer_handle,
                                         error);

                    if (error != KS_E_SUCCESS)
                        {
                        goto EXIT_NOW;
                        };

                    KS_MEMORY_ALLOCATE(attrFixed + attrLocked,
                                       KSf_FileBufferSize,
                                       BUFFER_USERID,
                                       file_ptr->buffer_handle,
                                       error);

                    if (error != KS_E_SUCCESS)
                        {
                        goto EXIT_NOW;
                        };

                    file_ptr->buffer = (Byte *)
                                         *(file_ptr->buffer_handle);

                    file_ptr->buffer_size = KSf_FileBufferSize;

                    file_ptr->buffer_available = KSf_FileBufferSize;
                    };

                };  /* End if there is no remaining buffer space      */

            };  /* End while there are characters to be read...       */

        KS_SUCCESS();

        };  /* End if we are doing buffer I/O from the file           */




    /* ************************************************************** *
     *  Ok, we've done enough buffering... lets do some real output...*
     *                                                                *
     *  Position the 'mark' (where we will write to) in the file.     *
     *  Note: We'll move the mark only if our user asks us to.        *
     * ************************************************************** */

    if (position != KS_NEXT_FILE_POSITION)
        {
        KSf_pkts.position.pCount = 3;
        KSf_pkts.position.refNum = file_ptr->refNum;
        KSf_pkts.position.base = startPlus;
        KSf_pkts.position.displacement = position;

        SetMarkGS(&KSf_pkts.position);

        if ((error = GET_ERROR()) != KS_E_SUCCESS)
            {
            goto EXIT_NOW;
            };

        };  /* End if we must change the file position                */


    /* ************************************************************** *
     *  Setup the I/O packet and write what our user is asking for.   *
     * ************************************************************** */

    KSf_pkts.IO.pCount = 4;
    KSf_pkts.IO.refNum = file_ptr->refNum;
    KSf_pkts.IO.dataBuffer = data_buffer;
    KSf_pkts.IO.requestCount = data_size;

    WriteGS(&KSf_pkts.IO);

    if ((error = GET_ERROR()) != KS_E_SUCCESS)
        {
        goto EXIT_NOW;
        };


    /* ************************************************************** *
     *  Save the number of bytes transfered in the KS_FILE structure. *
     * ************************************************************** */

    file_ptr->data_size = KSf_pkts.IO.transferCount;


    /* ************************************************************** *
     *  Return the status back to our caller.                         *
     * ************************************************************** */

EXIT_NOW:

    if (error != KS_E_SUCCESS)
        {
        KS_ERROR(error, KS_FILE_ID);
        };

    KS_SUCCESS();

}   /* End of ks_file_write()                                         */
Exemplo n.º 13
0
/*
 * Asynchronous object call for
 * operation 'odbcas_ASSvc_WouldLikeToLive'
 */
extern CEE_status
odbcas_ASSvc_WouldLikeToLive_pst_(
    /* In    */ const CEE_handle_def *ph_
  , /* In    */ CEE_tag_def tag_
  , /* In    */ odbcas_ASSvc_WouldLikeToLive_cct_ rtn_
  , /* In    */ IDL_long srvrType
  , /* In    */ const IDL_char *srvrObjRef
  )
{
	CEE_status retcode = CEE_SUCCESS;
	bool sts;
	long wlength,rlength;
	char* wbuffer, *rbuffer;

	CFSystemDrvr* FileSystem = GTransport.m_FSystemDrvr_list->ins_node();
	if (FileSystem == NULL)
		return CEE_ALLOCFAIL;

	FileSystem->odbcAPI = AS_API_WOULDLIKETOLIVE;
	FileSystem->dialogueId = 0;
	FileSystem->dwTimeout = 0;
//
// do marshaling of input parameters
//
	retcode = odbcas_ASSvc_WouldLikeToLive_param_pst_(
		  FileSystem
		, wbuffer
		, wlength
		, srvrType
		, srvrObjRef);

	if (retcode != CEE_SUCCESS)
		goto bailout;

	sts = OpenIO (FileSystem,srvrGlobal->ASProcessName);
	if (sts == false)
	{
		retcode = GET_ERROR((long)FileSystem);
		goto bailout;
	}

	sts = DoIO (FileSystem, wbuffer, wlength, rbuffer, rlength);
	if (sts == false)
	{
		retcode = GET_ERROR((long)FileSystem);
		goto bailout;
	}

	CloseIO (FileSystem);
//
// process output parameters
//
	long* param[2];
	retcode = decodeParameters(2, param, rbuffer, rlength);
	if (retcode != CEE_SUCCESS)
	{
//LCOV_EXCL_START
		strcpy( errStrBuf2, "odbcas_drvr.cpp");
		strcpy( errStrBuf3, "SRVR-odbcas_ASSvc_WouldLikeToLive_pst_");
		strcpy( errStrBuf4, "buffer overflow");
		sprintf( errStrBuf5, "retcode <%d>", retcode);
		logError( PROGRAM_ERROR, SEVERITY_MAJOR, CAPTURE_ALL + PROCESS_STOP );
		SRVR::exitServerProcess();
//LCOV_EXCL_STOP
	}

    {
	void *pv_[3] = {0};
	pv_[1] = (void *)param[0];
	pv_[2] = (void *)param[1];
	odbcas_ASSvc_WouldLikeToLive_ccw_(
	    /* In    */ (void *) rtn_
	  , /* In    */ tag_
	  , /* In    */ pv_);
    }
bailout:
	GTransport.m_FSystemDrvr_list->del_node(FileSystem);

	return retcode;
}
Exemplo n.º 14
0
int execute_arguments(char *program_name, struct hash_map_t *arguments) {
    /* allocates space for the possible argument
    to be executed from the arguments map */
    void *value;

    /* allocates the value to be used to verify the
    exitence of error from the function */
    ERROR_CODE return_value;

    /* sets space for the flag that will control if
    the service should be run or not, this is used
    for certain situations (mostyle test) where the
    service is not meant to be run */
    char run_service = TRUE;

    /* tries to retrieve the help argument from the arguments
    map in case the value exists prints the help value and then
    exits the current system */
    get_value_string_hash_map(arguments, (unsigned char *) "help", &value);
    if(value != NULL) {
        return help();
    }

    /* tries to retrieve the version argument from the arguments
    map in case the value exists prints the version value and then
    exits the current system */
    get_value_string_hash_map(arguments, (unsigned char *) "version", &value);
    if(value != NULL) {
        return version();
    }

    /* retrieves the test argument value from the arguments map
    and in case it's set starts the test process runing a series
    of test functions in sequence */
    get_value_string_hash_map(arguments, (unsigned char *) "test", &value);
    if(value != NULL) {
        return test();
    }

    /* retrieves the speed argument value from the arguments map
    and in case it's set starts the speed measuring and disables
    the runnig of the service */
    get_value_string_hash_map(arguments, (unsigned char *) "speed", &value);
    if(value != NULL) {
        return speed();
    }

    /* tries to retrieve the daemon argument from the
    arguments map in case the value is set daemonizes
    the current process so that it remains in background
    and returns to the caller process immediately, otherwise
    prints the viriatum information into the standard
    output "file", the label should be standard */
    get_value_string_hash_map(arguments, (unsigned char *) "daemon", &value);
    if(value != NULL) {
        daemonize();
    }
    else {
        print_information();
    }

    /* tries to retrieve the local argument from the arguments
    map in case the value exists localizes the current service
    so that any file read is read from the current directory */
    get_value_string_hash_map(arguments, (unsigned char *) "local", &value);
    if(value != NULL) {
        localize();
    }

    /* in cas the flag that control if the service must be run is
    unset the control flow must be returned immediately (avoids
    running service) */
    if(run_service == FALSE) {
        RAISE_NO_ERROR;
    }

    /* runs the service, with the given arguments, this call
    should block the program control flow until an event
    stop the running of the main loop */
    return_value = run_service_s(program_name, arguments);

    /* tests the error code for error in case it exists
    prints a message indicating the problem that occurred */
    if(IS_ERROR_CODE(return_value)) {
        V_ERROR_F("Problem running service (%s)\n", (char *) GET_ERROR());
        RAISE_AGAIN(return_value);
    }

    /* returns the normal result value as no problems has
    occured during the execution of the command */
    RAISE_NO_ERROR;
}