示例#1
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_writeBuf() {
  int result;
  int fd = KNI_GetParameterAsInt(1);
  int offset = KNI_GetParameterAsInt(3);
  int length = KNI_GetParameterAsInt(4);

  KNI_StartHandles(1);
  KNI_DeclareHandle(buffer_object);
  KNI_GetParameterAsObject(2, buffer_object);
  char *buffer = (char *) SNI_GetRawArrayPointer(buffer_object) + offset;

  result = jvm_send(fd, buffer, length, 0); // We rely on open0() for setting the socket to non-blocking
  KNI_EndHandles();

  if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *) SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_WRITE;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
/* JAVADOC COMMENT ELIDED */
KNIEXPORT KNI_RETURNTYPE_VOID
    Java_com_sun_j2me_location_PlatformLocationProvider_resetImpl() {

    MidpReentryData *info = NULL;
    ProviderInfo *pInfo = NULL;
    jint provider = KNI_GetParameterAsInt(1);
    jsr179_result res;

    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {
        /* reset provider */
        res = jsr179_update_cancel((jsr179_handle)provider);
        switch (res) {
            case JSR179_STATUSCODE_OK:
            case JSR179_STATUSCODE_FAIL:
                break;
            case JSR179_STATUSCODE_INVALID_ARGUMENT:
                /* wrong provider name */
                KNI_ThrowNew(midpIllegalArgumentException, "wrong provider");
                break;
            case JSR179_STATUSCODE_WOULD_BLOCK:
                /* wait for javanotify */
                pInfo = getProviderInfo(provider);
                if(pInfo != NULL) {
                    pInfo->locked = KNI_FALSE;
                }
                lock_thread(JSR179_EVENT_UPDATE_ONCE, provider);
                break;
            default:
                break;
        }
    }

    KNI_ReturnVoid();
}
示例#3
0
/**
 * The function blocks the calling thread if Transaction Store is locked.
 * <p>Java declaration:
 * <pre>
 * private native void lockStore();
 */
KNIEXPORT KNI_RETURNTYPE_VOID
Java_com_sun_j2me_payment_TransactionStorageImpl_lockStore() {
    MidpReentryData *info = NULL;

    KNI_StartHandles(1);
    KNI_DeclareHandle(thisObject);
    KNI_GetThisPointer(thisObject);

    if (locked == KNI_FALSE) {
        locked = KNI_TRUE;
        KNI_GetThisPointer(thisObject);
        getStorageOpenFlag(thisObject)->isOpen = (jboolean)KNI_TRUE;
    } else {
        info = (MidpReentryData*)SNI_GetReentryData(NULL);
        if (info == NULL) {
            info = (MidpReentryData*)
                (SNI_AllocateReentryData(sizeof (MidpReentryData)));
        }
        info->waitingFor = PAYMENT_TRANSACTION_STORE_SIGNAL;
        info->descriptor = 0;
        info->status = KNI_FALSE;
        info->pResult = NULL;

        /* try again later */
        SNI_BlockThread();
    }
    KNI_EndHandles();
    KNI_ReturnVoid();
}
示例#4
0
/**
 * Query native security manager for permission.
 * This call may block if user needs to be asked.
 *
 * Java prototype:
 * <pre>
 * native boolean checkPermission0(String suiteId, String permission);
 * </pre>
 * @param suiteId the MIDlet suite the permission should be checked against
 * @param permission the permission id
 * @return true if permission is granted. Otherwise, false.
 */
KNIEXPORT KNI_RETURNTYPE_BOOLEAN
Java_com_sun_midp_security_SecurityHandler_checkPermission0() {
    jboolean granted = KNI_FALSE;
    MidpReentryData* info = (MidpReentryData*)SNI_GetReentryData(NULL);

    if (!isListenerRegistered) {
        midpport_security_set_permission_listener(midpPermissionListener);
        isListenerRegistered = 1;
    }

    if (info == NULL) {
        /* initial invocation: send request */
                jint requestHandle;
        jint suiteId = KNI_GetParameterAsInt(1);
        jint permId = KNI_GetParameterAsInt(2);
        jint result = midpport_security_check_permission(suiteId, permId,
                  &requestHandle);

                if (result == 1) {
                  granted = KNI_TRUE;
                } else if (result == -1) {
                  /* Block the caller until the security listener is called */
                  midp_thread_wait(SECURITY_CHECK_SIGNAL, requestHandle, NULL);
                }
    } else {
        /* reinvocation: check result */
        granted = (jboolean)(info->status);
    }

    KNI_ReturnBoolean(granted);
}
示例#5
0
/**
 * Gets a raw IPv4 address for the given hostname.
 * <p>
 * Java declaration:
 * <pre>
 *     static getIpNumber([B)I
 * </pre>
 *
 * @param szHost the hostname to lookup as a 'C' string
 * @return raw IPv4 address or <tt>-1</tt> if there was an error
 */
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_midp_io_j2me_datagram_Protocol_getIpNumber(void) {
    int len;
    int status;
    int ipn = -1;
    unsigned char ipBytes[MAX_ADDR_LENGTH];
    void* context = NULL;
    void* handle;
    MidpReentryData* info;

    KNI_StartHandles(1);
    KNI_DeclareHandle(hostObject);

    KNI_GetParameterAsObject(1, hostObject);

    info = (MidpReentryData*)SNI_GetReentryData(NULL);

    if (info == NULL) {  /* First invocation */
        SNI_BEGIN_RAW_POINTERS;
        status = pcsl_network_gethostbyname_start(
               (char*)JavaByteArray(hostObject),
                ipBytes, MAX_ADDR_LENGTH, &len, &handle, &context);
        SNI_END_RAW_POINTERS;
    } else {  /* Reinvocation after unblocking the thread */
        handle = (void*)info->descriptor;
        /* IMPL NOTE: Please see 6440539 for details. */
        /* All but windows implementations of pcsl_network_gethostbyname_finish */
        /*  ignore context parameter. Windows one expects status code there. */
        context = (void*)info->status;
        status = pcsl_network_gethostbyname_finish(ipBytes, MAX_ADDR_LENGTH,
                                                  &len, handle, context);
    }

    KNI_EndHandles();

    if (status == PCSL_NET_SUCCESS) {
        /*
         * Convert the unsigned char ip bytes array into an integer
         * that represents a raw IP address.
         */
        //ipn = pcsl_network_getRawIpNumber(ipBytes);
        memcpy(&ipn, ipBytes, MAX_ADDR_LENGTH);
    } else if (status == PCSL_NET_WOULDBLOCK) {
        midp_thread_wait(HOST_NAME_LOOKUP_SIGNAL, (int)handle, context);
    } else {
        /* status is either PCSL_NET_IOERROR or PCSL_NET_INVALID */
        ipn = -1;
        REPORT_INFO1(LC_PROTOCOL,
            "datagram::getIpNumber returns PCSL error code %d", status);
        /*
         * IOException is thrown at the Java layer when return value
         * is -1
         */
        //KNI_ThrowNew(midpIOException, "Host name could not be resolved");
    }

    KNI_ReturnInt((jint)ipn);
}
示例#6
0
void initDevice() {
    if (!(state & DEVICE_INITED)) {
        START_REQUEST
            APPEND_DEV_REQ(INIT_DEVICE);
        END_REQUEST
        if (NULL == SNI_GetReentryData(NULL)) {
            /* This condition preserves from calling midp_thread_wait
               twice without unblocking current thread. */
            midp_thread_wait(JSR82_SIGNAL, BTE_SIGNAL_HANDLE, NULL);
        }
    }
示例#7
0
/**
 * Receives an SMS message.
 *
 * @param port The port number to be matched against incoming SMS messages.
 * @param handle The handle to the open SMS message connection.
 * @param messageObject The Java message object to be populated.
 *
 * @return The length of the SMS message (in bytes).
 */
KNIEXPORT KNI_RETURNTYPE_INT
KNIDECL(com_sun_midp_io_j2me_sms_Protocol_receive0) {
#if ENABLE_REENTRY
    MidpReentryData *info = (MidpReentryData*)SNI_GetReentryData(NULL);
#endif
    int port, handle;
    int messageLength = -1;
    SmsMessage *psmsData = NULL;
    /* The midlet suite name for this connection. */
    AppIdType msid = UNUSED_APP_ID;
    jboolean isOpen;

    KNI_StartHandles(6);

    KNI_DeclareHandle(this);
    KNI_DeclareHandle(thisClass);
    KNI_GetThisPointer(this);
    KNI_GetObjectClass(this, thisClass);
    isOpen = KNI_GetBooleanField(this, KNI_GetFieldID(thisClass, "open", "Z"));

    if (isOpen) { /* No close in progress */
        KNI_DeclareHandle(messageClazz);
        KNI_DeclareHandle(messageObject);
        KNI_DeclareHandle(addressArray);
        KNI_DeclareHandle(byteArray);

        port = KNI_GetParameterAsInt(1);
        msid = KNI_GetParameterAsInt(2);
        handle = KNI_GetParameterAsInt(3);
        KNI_GetParameterAsObject(4, messageObject);

        do {
#if ENABLE_REENTRY
            if (!info) {
#endif
                psmsData = jsr120_sms_pool_peek_next_msg((jchar)port);
                if (psmsData == NULL) {
#if ENABLE_REENTRY
                    /* block and wait for a message. */
                    midp_thread_wait(WMA_SMS_READ_SIGNAL, handle, NULL);
#else
        do {
            CVMD_gcSafeExec(_ee, {
                jsr120_wait_for_signal(handle, WMA_SMS_READ_SIGNAL);
            });
            psmsData = jsr120_sms_pool_peek_next_msg((jchar)port);
            isOpen = KNI_GetBooleanField(this, KNI_GetFieldID(thisClass, "open", "Z"));
        } while (psmsData == NULL && isOpen);
#endif
                }
#if ENABLE_REENTRY
            } else {
示例#8
0
/**
 * Block this thread until unblocked.
 * Initialize the reentry data needed to unblock this thread later.
 * Only the waitingFor setting is used.
 * The status is set to STATUS_OK.
 * If canceled the status will be set to cancelled.
 */
static void blockThread() {
    /* Initialize the re-entry data so later this thread can
     * be unblocked.
     */
    MidpReentryData* p = (MidpReentryData*)(SNI_GetReentryData(NULL));
    if (p == NULL) {
        p = (MidpReentryData*)
            (SNI_AllocateReentryData(sizeof (MidpReentryData)));
    }
    p->waitingFor = JSR211_SIGNAL;
    p->status = JSR211_INVOKE_OK;
    SNI_BlockThread();
}
void closePort(int hPort)
{
    javacall_result ret;
    void* context = NULL;
    MidpReentryData* info = (MidpReentryData*)SNI_GetReentryData(NULL);

    if (info == NULL) { //first invocation    
        ret = javacall_serial_close_start((javacall_handle)hPort);
    } else { /* Reinvocation */
        hPort = info->descriptor;
        context = info->pResult;
        ret = javacall_serial_close_finish((javacall_handle)hPort);
    }

    if (JAVACALL_WOULD_BLOCK == ret) {
        midp_thread_wait(COMM_CLOSE_SIGNAL, hPort, context);
    }
}
示例#10
0
/**
 * Gets a raw IPv4 address for the given hostname.
 * <p>
 * Java declaration:
 * <pre>
 *     getIpNumber([B)I
 * </pre>
 *
 * @param szHost the hostname to lookup as a 'C' string
 * @param ipBytes Output parameter that represents an unsigned char
 *                array for an IP address
 * @return len Length of ipBytes
 * 
 */
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_midp_io_j2me_socket_Protocol_getIpNumber0(void) {
    int len = -1;
    int status = PCSL_NET_INVALID;
    unsigned char ipBytes[MAX_ADDR_LENGTH];
    void* context = NULL;
    void* pcslHandle;
    MidpReentryData* info;

    KNI_StartHandles(2);
    KNI_DeclareHandle(hostObject);
    KNI_DeclareHandle(ipAddressObject);
    
    KNI_GetParameterAsObject(1, hostObject);
    KNI_GetParameterAsObject(2, ipAddressObject);

    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {  /* First invocation */
        SNI_BEGIN_RAW_POINTERS;
        status = pcsl_network_gethostbyname_start(
                (char*)JavaByteArray(hostObject), 
                ipBytes, MAX_ADDR_LENGTH, &len, &pcslHandle, &context);
        SNI_END_RAW_POINTERS;
    } else {  /* Reinvocation after unblocking the thread */
        pcslHandle = (void*)info->descriptor;
        /* IMPL NOTE: Please see 6440539 for details. */
        /* All but windows implementations of pcsl_network_gethostbyname_finish */
        /*  ignore context parameter. Windows one expects status code there. */
        context = (void*)info->status;
        status = pcsl_network_gethostbyname_finish(ipBytes, MAX_ADDR_LENGTH,
                                                  &len, pcslHandle, context);
    }

    if (status == PCSL_NET_SUCCESS) {
        KNI_SetRawArrayRegion(ipAddressObject, 0, len, (jbyte *)ipBytes);
    } else if (status == PCSL_NET_WOULDBLOCK) {
        midp_thread_wait(HOST_NAME_LOOKUP_SIGNAL, (int)pcslHandle, context);
    } else { /* must be PCSL_NET_IOERROR or PCSL_NET_INVALID */
        len = -1; 
    }

    KNI_EndHandles();
    KNI_ReturnInt((jint)len);
}
示例#11
0
/**
 * Performs reset of the device.
 * <p>Java declaration:
 * <pre>
 * private native int reset0(byte[] atr);
 * </pre>
 * @param atr ATR bytes
 * @return Length of ATR in case of success, else -1 
 */
KNIEXPORT KNI_RETURNTYPE_INT 
KNIDECL(com_sun_cardreader_PlatformCardDevice_reset0) {
    jint retcode;
    javacall_int32 atr_length;
    char *atr_buffer;
    MidpReentryData* info;
    void *context = NULL;
    javacall_result status_code;
    
    KNI_StartHandles(1);
    KNI_DeclareHandle(atr_handle);

    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    KNI_GetParameterAsObject(1, atr_handle);
    if (KNI_IsNullHandle(atr_handle)) {
        atr_buffer = NULL;
        atr_length = 0;
    } else {
        atr_length = KNI_GetArrayLength(atr_handle);
        atr_buffer = SNI_GetRawArrayPointer(atr_handle);
    }

    if (info == NULL) {
        status_code = javacall_carddevice_reset_start(atr_buffer, &atr_length, &context);
    } else {
        context = info->pResult;
        status_code = javacall_carddevice_reset_finish(atr_buffer, &atr_length, context);
    }

    if (status_code == JAVACALL_WOULD_BLOCK) {
        midp_thread_wait(CARD_READER_DATA_SIGNAL, SIGNAL_RESET, context);
        goto end;
    }

    if (status_code != JAVACALL_OK) {
        retcode = -1;
    } else {
        retcode = atr_length;
    }
end:
    KNI_EndHandles();
    KNI_ReturnInt(retcode);
}
示例#12
0
/**
 * Blocks the current Java thread. The MidpReentryData block for
 * the current Java thread is set to the passed values.
 *
 * @param waitingFor set into MidpReentryData.waitingFor
 * @param descriptor set into  MidpReentryData.descriptor
 * @param pResult set into MidpReentryData.pResult
 */
void
midp_thread_wait(midpSignalType waitingFor, int descriptor, void* pResult)
{
    MidpReentryData* p =
        (MidpReentryData*)SNI_GetReentryData(NULL);

    if (p == NULL) {
        p = (MidpReentryData*)
            (SNI_AllocateReentryData(sizeof (MidpReentryData)));
        if (p == NULL) {
            REPORT_CRIT(LC_CORE,
                        "midp_cond_wait: failed to allocate reentry data");
        }
    }

    p->descriptor = descriptor;
    p->waitingFor = waitingFor;
    p->status = 0;
    p->pResult = pResult;

    SNI_BlockThread();
}
示例#13
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_readBuf() {
  int result;
  int fd = KNI_GetParameterAsInt(1);
  int offset = KNI_GetParameterAsInt(3);
  int length = KNI_GetParameterAsInt(4);

  KNI_StartHandles(1);
  KNI_DeclareHandle(buffer_object);
  KNI_GetParameterAsObject(2, buffer_object);
  char *buffer = (char *) SNI_GetRawArrayPointer(buffer_object) + offset;

  result = jvm_recv(fd, buffer, length, 0); // We rely on open0() for setting the socket to non-blocking
  KNI_EndHandles();

  if (result == 0) {
    // If remote side has shut down the connection gracefully, and all
    // data has been received, recv() will complete immediately with
    // zero bytes received.
    //
    // This is true for Win32/CE and Linux
    result = -1;
  }
  else if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_READ;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
示例#14
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_writeByte() {
  int fd = KNI_GetParameterAsInt(1);
  char byte = (char) KNI_GetParameterAsInt(2);

  // We rely on open0() for setting the socket to non-blocking
  int result = jvm_send(fd, &byte, 1, 0);

  if (result < 0) {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_WRITE;
      }
      SNI_BlockThread();
    }
  }

  KNI_ReturnInt(result);
}
示例#15
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_readByte() {
  jint result = -1;
  unsigned char byte;

  int fd = KNI_GetParameterAsInt(1);
  int n = jvm_recv(fd, (char*)&byte, 1, 0);

  if (n == 1) {
    result = byte; // do not sign-extend
    GUARANTEE(0 <= result && result <= 255, "no sign extension");
  }
  else if (n == 0) {
    // If remote side has shut down the connection gracefully, and all
    // data has been received, recv() will complete immediately with
    // zero bytes received.
    //
    // This is true for Win32/CE and Linux
    result = -1;
  }
  else {
    int err_code = GET_LAST_ERROR();
    if (err_code == EWOULDBLOCK) {
      if (SNI_GetReentryData(NULL) == NULL) {
        BlockingSocket *socket =
            (BlockingSocket *)SNI_AllocateReentryData(sizeof(*socket));
        socket->fd = fd;
        socket->check_flags = CHECK_READ;
      }
      SNI_BlockThread();
    } else {
      result = -1;
    }
  }

  KNI_ReturnInt(result);
}
示例#16
0
/**
 * Checks if this slot is SAT slot. 
 * <p>Java declaration:
 * <pre>
 * private native int isSatSlot0(int slotNumber);
 * </pre>
 * @param slotNumber Slot number
 * @return <code> 1</code> if the slot is dedicated for SAT,
 *         <code> 0</code> if not,
 *         <code>-1</code> if any error occured
 */
KNIEXPORT KNI_RETURNTYPE_INT 
KNIDECL(com_sun_cardreader_PlatformCardDevice_isSatSlot0) {
    jint retcode;
    javacall_bool result;
    MidpReentryData* info;
    javacall_result status_code;
    void *context = NULL;

    int slotIndex = KNI_GetParameterAsInt(1);
    info = (MidpReentryData*)SNI_GetReentryData(NULL);

    if (info == NULL) {
        status_code = javacall_carddevice_is_sat_start(slotIndex, &result, &context);
    } else {
        context = info->pResult;
        status_code = javacall_carddevice_is_sat_finish(slotIndex, &result, context);
    }

    if (status_code == JAVACALL_WOULD_BLOCK) {
        midp_thread_wait(CARD_READER_DATA_SIGNAL, SIGNAL_XFER, context);
        goto end;
    }

    if (status_code != JAVACALL_OK) {
        retcode = -1;
    } else {
        if (result == JAVACALL_FALSE) {
            retcode = 0;
        } else {
            retcode = 1;
        }
    }

end:
    KNI_ReturnInt(retcode);
}
示例#17
0
/**
 * Write to a serial port without blocking.
 *
 * @param hPort handle to a native serial port
 * @param b I/O buffer
 * @param off starting offset for data
 * @param len length of data
 *
 * @return number of bytes that were written
 *
 * @exception  IOException  if an I/O error occurs.
 */
KNIEXPORT KNI_RETURNTYPE_INT
    Java_com_sun_midp_io_j2me_comm_Protocol_native_1writeBytes() {

    int  length = (int)KNI_GetParameterAsInt(4);
    int  offset = (int)KNI_GetParameterAsInt(3);
    int  hPort  = (int)KNI_GetParameterAsInt(1);
    int   bytesWritten = 0;
    int status = PCSL_NET_IOERROR;
    void* context = NULL;
    MidpReentryData* info;

    KNI_StartHandles(1);
    KNI_DeclareHandle(bufferObject);
    KNI_GetParameterAsObject(2, bufferObject);

    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {

        if (hPort < 0) {
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Write to port: handle %d is invalid\n", hPort);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpIllegalArgumentException, gKNIBuffer);
        } else {        		
            SNI_BEGIN_RAW_POINTERS;
            status = writeToPortStart(hPort,
                (char*)&(JavaByteArray(bufferObject)[offset]),
                length, &bytesWritten, &context);
            SNI_END_RAW_POINTERS;
        }
    } else {
        /* reinvocation */
        hPort = info->descriptor;
        context = info->pResult;
        SNI_BEGIN_RAW_POINTERS;
        status = writeToPortFinish(hPort,
            (char*)&(JavaByteArray(bufferObject)[offset]),
            length, &bytesWritten, context);
        SNI_END_RAW_POINTERS;
    }

    switch (status) {
        case PCSL_NET_SUCCESS:			
            /*do nothing and return normally */
            break;
        case PCSL_NET_INTERRUPTED:			
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Writing to port %d has been interrupted\n", hPort);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpInterruptedIOException, gKNIBuffer);
            break;
        case PCSL_NET_WOULDBLOCK:			
            midp_thread_wait(COMM_WRITE_SIGNAL, hPort, context);
            break;
        default:	   
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Writing to  port %d was failed\n", hPort);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpIOException, gKNIBuffer);
    }
    	    
    KNI_EndHandles();
    KNI_ReturnInt((jint)bytesWritten);
    
}
示例#18
0
/**
 * Check if this blocked thread was cancelled.
 */
static jboolean isThreadCancelled() {
    MidpReentryData* p = 
        (MidpReentryData*)(SNI_GetReentryData(NULL));
    return (p != NULL && p->status == JSR211_INVOKE_CANCELLED);
}
/*
 * Performs client connection establishment.
 *
 * Note: the method gets native connection handle directly from
 * <code>handle<code> field of <code>L2CAPConnectionImpl</code> object.
 *
 * @param addr bluetooth address of device to connect to
 * @param psm Protocol Service Multiplexor (PSM) value
 * @return Negotiated ReceiveMTU and TransmitMTU.
 *               16 high bits is ReceiveMTU, 16 low bits is TransmitMTU.
 *
 * @throws IOException if any I/O error occurs
 */
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_jsr082_bluetooth_btl2cap_L2CAPConnectionImpl_connect0(void) {
    unsigned char *address = NULL;
    int psm  = (int)KNI_GetParameterAsInt(2);

    javacall_handle handle = JAVACALL_BT_INVALID_HANDLE;
    int status, i, imtu, omtu, mtus;
    void* context = NULL;
    MidpReentryData* info;
    javacall_bt_address addr;
    jfieldID connHandleID = NULL;

    KNI_StartHandles(3);
    KNI_DeclareHandle(thisHandle);
    KNI_DeclareHandle(arrayHandle);
    KNI_DeclareHandle(classHandle);

    KNI_GetThisPointer(thisHandle);
    KNI_GetClassPointer(classHandle);
    GET_FIELDID(classHandle, "handle", "I", connHandleID)

    KNI_GetParameterAsObject(1, arrayHandle);
    handle = (javacall_handle)KNI_GetIntField(thisHandle, connHandleID);

    REPORT_INFO1(LC_PROTOCOL, "btl2cap::connect handle=%d", handle);

    /* copy address from Java input array */
    SNI_BEGIN_RAW_POINTERS;
    address = JavaByteArray(arrayHandle);
    for (i = 0; i < JAVACALL_BT_ADDRESS_SIZE; i++) {
        addr[i] = address[i];
    }
    SNI_END_RAW_POINTERS;

    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {   /* First invocation */
        // Need revisit: add resource counting
        /*
         * Verify that the resource is available well within limit as per
         * the policy in ResourceLimiter
         */
/*
        if (midpCheckResourceLimit(RSC_TYPE_BT_CLI, 1) == 0) {
            const char* pMsg = "Resource limit exceeded for BT client sockets";
            REPORT_INFO(LC_PROTOCOL, pMsg);
            KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
        } else {
*/
            status = javacall_bt_l2cap_connect(handle, address, psm,
                    &imtu, &omtu);

            if (status == JAVACALL_OK) {
                // Need revisit: add resource counting
/*
                if (midpIncResourceCount(RSC_TYPE_BT_CLI, 1) == 0) {
                    REPORT_INFO(LC_PROTOCOL, "Resource limit update error");
                }
*/
            } else if (status == JAVACALL_FAIL) {
                char* pError;
                javacall_bt_l2cap_get_error(handle, &pError);
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                        "IO error in btl2cap::connect (%s)\n", pError);
                REPORT_INFO(LC_PROTOCOL, gKNIBuffer);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(gKNIBuffer));
            } else if (status == JAVACALL_WOULD_BLOCK) {
                // Need revisit: add bluetooth activity indicator
//                INC_BT_INDICATOR;
                // Need revisit: add resource counting
/*
                if (midpIncResourceCount(RSC_TYPE_BT_CLI, 1) == 0) {
                    REPORT_INFO(LC_PROTOCOL, "Resource limit update error");
                }
*/
                REPORT_INFO1(LC_PROTOCOL,
                    "btl2cap::connect is waiting for complete notify"
                    ", handle = %d\n", handle);
                midp_thread_wait(NETWORK_WRITE_SIGNAL, (int)handle, context);
            } else {
                char* pMsg = "Unknown error during btl2cap::connect";
                REPORT_INFO(LC_PROTOCOL, pMsg);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
            }
//        }
    } else {  /* Reinvocation after unblocking the thread */
        context = info->pResult;

        if ((javacall_handle)info->descriptor != handle) {
            REPORT_CRIT2(LC_PROTOCOL,
                "btl2cap::connect handles mismatched %d != %d\n",
                 handle, (javacall_handle)info->descriptor);
        }

        status = javacall_bt_l2cap_connect(handle, address, psm,
            &imtu, &omtu);

        if (status == JAVACALL_OK) {
            // Need revisit: add bluetooth activity indicator
//            DEC_BT_INDICATOR;
        } else if (status == JAVACALL_WOULD_BLOCK) {
            midp_thread_wait(NETWORK_WRITE_SIGNAL, (int)handle, context);
        } else  {
            char* pError;

            KNI_SetIntField(thisHandle, connHandleID, (jint)JAVACALL_BT_INVALID_HANDLE);

            // Need revisit: add bluetooth activity indicator
//            DEC_BT_INDICATOR;

            // Need revisit: add resource counting
/*
            if (midpDecResourceCount(RSC_TYPE_BT_CLI, 1) == 0) {
                REPORT_INFO(LC_PROTOCOL, "Resource limit update error");
            }
*/
            javacall_bt_l2cap_get_error(handle, &pError);
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "Error in btl2cap::connect (%s)", pError);
            REPORT_INFO(LC_PROTOCOL, gKNIBuffer);
            KNI_ThrowNew(midpConnectionNotFoundException,
                EXCEPTION_MSG(gKNIBuffer));
        }
    }

    mtus = (imtu << 16) & 0xFFFF0000;
    mtus |= omtu & 0xFFFF;

    KNI_EndHandles();
    KNI_ReturnInt(mtus);
}
示例#20
0
/* JAVADOC COMMENT ELIDED */
KNIEXPORT KNI_RETURNTYPE_BOOLEAN
    Java_com_sun_j2me_location_PlatformLocationProvider_waitForNewLocation() {

    jboolean ret = KNI_FALSE;
    MidpReentryData *info = NULL;
    ProviderInfo *pInfo = NULL;
    jsr179_result res;
    jint provider;
    jlong timeout;
    KNI_StartHandles(1);
    provider = KNI_GetParameterAsInt(1);
    timeout = KNI_GetParameterAsLong(2);
    pInfo = getProviderInfo(provider);
    if(pInfo != NULL) {
        info = (MidpReentryData*)SNI_GetReentryData(NULL);
        if (info == NULL) {
            /* First call -request */
            if(pInfo->locked == KNI_TRUE) {
                lock_thread(JSR179_EVENT_UPDATE_ONCE, provider);
            } else {
                /* request new location */
                res = jsr179_update_set((jsr179_handle)provider, timeout);
                switch (res) {
                    case JSR179_STATUSCODE_WOULD_BLOCK:
                        /* wait for javanotify */
                        pInfo->locked = KNI_TRUE;
                        lock_thread(JSR179_EVENT_UPDATE_ONCE, provider);
                        break;
                    case JSR179_STATUSCODE_OK:
                        /* location updated successfully */
                        pInfo->locked = KNI_FALSE;
			            pInfo->newLocationAvailable = KNI_TRUE;
                        ret = KNI_TRUE;
                        break;
                    case JSR179_STATUSCODE_FAIL:
                        /* fail */
                        pInfo->locked = KNI_FALSE;
                        /* wrong provider name */
                        KNI_ThrowNew(midpIllegalArgumentException, 
                                    "wrong provider");
                        break;
                    default:
                        /* fail */
                        pInfo->locked = KNI_FALSE;
                        break;
                }
            }
        } else {
            /* Response */
            if (info->status == JSR179_STATUSCODE_OK) {
                /* location updated successfully */
				pInfo->newLocationAvailable = KNI_TRUE;
                ret = KNI_TRUE;
            } else {
                /* location updated failed */
                ret = KNI_FALSE;
            }
            pInfo->locked = KNI_FALSE;
        }
    }
    KNI_EndHandles();
    KNI_ReturnBoolean(ret);
}
示例#21
0
/* JAVADOC COMMENT ELIDED */
KNIEXPORT KNI_RETURNTYPE_INT
    Java_com_sun_j2me_location_PlatformLocationProvider_open() {

    MidpReentryData *info = NULL;
    ProviderInfo *pInfo = NULL;
    jsr179_result res;
    jsr179_handle pProvider = NULL;
    jint provider = 0;
    
    KNI_StartHandles(1);
    GET_PARAMETER_AS_PCSL_STRING(1, name)
    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {
        res = jsr179_provider_open(name, &pProvider);
        switch (res) {
            case JSR179_STATUSCODE_OK:
                /* handler returned immediatelly */
                provider = (jint)pProvider;
                register_provider(provider);
                break;
            case JSR179_STATUSCODE_INVALID_ARGUMENT:
                /* wrong provider name */
                KNI_ThrowNew(midpIllegalArgumentException, 
                            "wrong provider name");
                break;
            case JSR179_STATUSCODE_FAIL:
                /* fail */
                KNI_ThrowNew(midpIOException, "open failed");
                break;
            case JSR179_STATUSCODE_WOULD_BLOCK:
                /* wait for javanotify */
                provider = (jint)pProvider;
                pInfo = register_provider(provider);
                if (pInfo != NULL) {
                    pInfo->locked = KNI_TRUE;
                }
                lock_thread(JSR179_EVENT_OPEN_COMPLETED, provider);
                break;
            default:
                break;
        }
    } else {
        /* Second call for this thread - finish open */
        if (info->status == JSR179_STATUSCODE_OK) {
            /* Provider opened successfully */
            provider = info->descriptor;
            pInfo = getProviderInfo(provider);
            if (pInfo != NULL) {
                pInfo->locked = KNI_FALSE;
            }
        } else {
            /* Provider open failed*/
            unregister_provider(provider);
            provider = 0;
        }
    }

    RELEASE_PCSL_STRING_PARAMETER
    KNI_EndHandles();
    KNI_ReturnInt(provider);
}
示例#22
0
/**
 * private native void receive0(LinkMessage msg, Link link)
 *         throws ClosedLinkException,
 *                InterruptedIOException,
 *                IOException;
 */
KNIEXPORT KNI_RETURNTYPE_VOID
Java_com_sun_midp_links_Link_receive0(void)
{
    rendezvous *rp;

    KNI_StartHandles(4);
    KNI_DeclareHandle(thisObj);
    KNI_DeclareHandle(recvMessageObj);
    KNI_DeclareHandle(sendMessageObj);
    KNI_DeclareHandle(linkObj);

    KNI_GetThisPointer(thisObj);
    KNI_GetParameterAsObject(1, recvMessageObj);
    KNI_GetParameterAsObject(2, linkObj);

    rp = getNativePointer(thisObj);

    if (rp == NULL) {
        if (SNI_GetReentryData(NULL) == NULL) {
            KNI_ThrowNew(midpClosedLinkException, NULL);
        } else {
            KNI_ThrowNew(midpInterruptedIOException, NULL);
        }
    } else if (JVM_CurrentIsolateID() != rp->receiver) {
        KNI_ThrowNew(midpIllegalArgumentException, NULL);
    } else {
        jboolean ok;

        switch (rp->state) {
            case IDLE:
                rp->state = RECEIVING;
                midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                break;

            case SENDING:
                getReference(rp->msg, "receive0/SENDING",
                    sendMessageObj);
                ok = copy(sendMessageObj, recvMessageObj, linkObj);
                if (ok) {
                    rp->retcode = OK;
                } else {
                    rp->retcode = ERROR;
                    KNI_ThrowNew(midpIOException, NULL);
                }
                rp->state = DONE;
                midp_thread_signal(LINK_READY_SIGNAL, (int)rp, 0);
                break;

            case RENDEZVOUS:
                getReference(rp->msg, "receive0/RENDEZVOUS", sendMessageObj);
                ok = copy(sendMessageObj, recvMessageObj, linkObj);
                if (ok) {
                    rp->retcode = OK;
                } else {
                    rp->retcode = ERROR;
                    KNI_ThrowNew(midpIOException, NULL);
                }
                rp->state = DONE;
                midp_thread_signal(LINK_READY_SIGNAL, (int)rp, 0);

                break;

            case RECEIVING:
            case DONE:
                midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                break;

            case CLOSED:
                setNativePointer(thisObj, NULL);
                rp_decref(rp);
                if (SNI_GetReentryData(NULL) == NULL) {
                    KNI_ThrowNew(midpClosedLinkException, NULL);
                } else {
                    KNI_ThrowNew(midpInterruptedIOException, NULL);
                }
                break;
        }
    }

    KNI_EndHandles();
    KNI_ReturnVoid();
}
示例#23
0
/**
 * Sends an SMS message.
 *
 * @param handle The handle to the open SMS connection.
 * @param messageType The type of message: binary or text.
 * @param address The SMS-formatted address.
 * @param destPort The port number of the recipient.
 * @param sourcePort The port number of the sender.
 * @param messageBuffer The buffer containing the SMS message.
 *
 * @return Always returns <code>0</code>.
 */
KNIEXPORT KNI_RETURNTYPE_INT
KNIDECL(com_sun_midp_io_j2me_sms_Protocol_send0) {
    WMA_STATUS status = WMA_ERR;
    jint messageLength = 0;
    jint messageType;
    jint sourcePort;
    jint destPort;
    jint handle;
    jint msAddress_len;
    jchar* msAddress_data;
    int i;
    unsigned char *pAddress = NULL;
    unsigned char *pMessageBuffer = NULL;
    jboolean stillWaiting = KNI_FALSE;
    jboolean trySend = KNI_FALSE;
    void *pdContext = NULL;
#if ENABLE_REENTRY
    MidpReentryData *info;
    jsr120_sms_message_state_data *messageStateData = NULL;
#endif
    jboolean isOpen;

    KNI_StartHandles(4);

    KNI_DeclareHandle(this);
    KNI_DeclareHandle(thisClass);
    KNI_GetThisPointer(this);
    KNI_GetObjectClass(this, thisClass);
    isOpen = KNI_GetBooleanField(this, KNI_GetFieldID(thisClass, "open", "Z"));
    
    if (isOpen) { /* No close in progress */
        KNI_DeclareHandle(messageBuffer);
        KNI_DeclareHandle(address);

        handle = KNI_GetParameterAsInt(1);
        messageType = KNI_GetParameterAsInt(2);
        KNI_GetParameterAsObject(3, address);
        destPort = KNI_GetParameterAsInt(4);
        sourcePort = KNI_GetParameterAsInt(5);
        KNI_GetParameterAsObject(6, messageBuffer);

        do {
#if ENABLE_REENTRY
            info = (MidpReentryData*)SNI_GetReentryData(NULL);
            if (info == NULL) {	  /* First invocation. */
#endif
                if (KNI_IsNullHandle(address)) {

                    KNI_ThrowNew(midpIllegalArgumentException, NULL);
                    break;
                } else {
                    msAddress_len = KNI_GetStringLength(address);
                    msAddress_data = (jchar *)pcsl_mem_malloc(msAddress_len * sizeof (jchar));
                    if (msAddress_data == NULL) {

                        KNI_ThrowNew(midpOutOfMemoryError, NULL);
                        break;
                    } else {

                        KNI_GetStringRegion(address, 0, msAddress_len, msAddress_data);
                        pAddress = (unsigned char*)pcsl_mem_malloc(msAddress_len + 1);
                        if (pAddress != NULL) {
                            for (i = 0; i < msAddress_len; i++) {
                                pAddress[i] = (unsigned char)msAddress_data[i];
                            }	
                            pAddress[msAddress_len] = 0;
                        }
                        //pAddress = (unsigned char *)midpJcharsToChars(msAddress);
                        pcsl_mem_free(msAddress_data);

                        if (!KNI_IsNullHandle(messageBuffer)) {
                            messageLength = KNI_GetArrayLength(messageBuffer);
                        }
                        if (messageLength >= 0) {
                            if (messageLength > 0) {
                                pMessageBuffer = (unsigned char *)pcsl_mem_malloc(messageLength);
                                memset(pMessageBuffer, 0, messageLength);
                                KNI_GetRawArrayRegion(messageBuffer, 0, messageLength,
                                                      (jbyte *)pMessageBuffer);
                            }

                            trySend = KNI_TRUE;
                        }
                    }
                }
#if ENABLE_REENTRY
            } else { /* Reinvocation after unblocking the thread. */

                if (info->pResult == NULL) {
                    /* waiting for mms_send_completed event */
                    if (info->status == WMA_ERR) {
                        KNI_ThrowNew(midpInterruptedIOException, "Sending SMS");
                    }
                    break;
                }
                messageStateData = info->pResult;
                pMessageBuffer = messageStateData->pMessageBuffer;
                pAddress = messageStateData->pAddress;
                pdContext = messageStateData->pdContext;

                trySend = KNI_TRUE;
            }
#endif

            if (trySend == KNI_TRUE) {
                /* send message. */
                status = jsr120_send_sms((jchar)messageType,
                                         pAddress,
                                         pMessageBuffer,
                                         (jchar)messageLength,
                                         (jchar)sourcePort,
                                         (jchar)destPort,
                                         handle,
                                         &pdContext);

                if (status == WMA_ERR) {
                    KNI_ThrowNew(midpIOException, "Sending SMS");
                    break;
                } 
#if ENABLE_REENTRY
                else if (status == WMA_NET_WOULDBLOCK) {
                    if (messageStateData == NULL) {
                        messageStateData =
                            (jsr120_sms_message_state_data *)pcsl_mem_malloc(
                                sizeof(*messageStateData));
                        messageStateData->pMessageBuffer = pMessageBuffer;
                        messageStateData->pAddress = pAddress;
                    }

                    messageStateData->pdContext = pdContext;

                    /* Block calling Java Thread. */
                    midp_thread_wait(WMA_SMS_WRITE_SIGNAL, handle,
                                     messageStateData);

                    stillWaiting = KNI_TRUE;
                    break;
                } else {
                    /* waiting for sms_send_completed event */
                    midp_thread_wait(WMA_SMS_WRITE_SIGNAL, handle, NULL);
                }
#endif
            }
        } while (0);

        if (!stillWaiting) {
            pcsl_mem_free(pMessageBuffer);
            pcsl_mem_free(pAddress);
        }
    }

    KNI_EndHandles();

    KNI_ReturnInt(0); /* currently ignored. */
}
/*
 * Reads data from a packet received via Bluetooth stack.
 *
 * Note: the method gets native connection handle directly from
 * <code>handle<code> field of <code>L2CAPConnectionImpl</code> object.
 *
 * @param buf the buffer to read to
 * @param offset he start offset in array <code>buf</code>
 *               at which the data to be written
 * @param size the maximum number of bytes to read,
 *             the rest of the packet is discarded.
 * @return total number of bytes read into the buffer or
 *             <code>0</code> if a zero length packet is received
 * @throws IOException if an I/O error occurs
 */
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_jsr082_bluetooth_btl2cap_L2CAPConnectionImpl_receive0(void) {
    int length, offset;
    javacall_handle handle;
    int bytesRead = -1;
    int status = JAVACALL_FAIL;
    void* context = NULL;
    MidpReentryData* info;
    jfieldID connHandleID = NULL;

    offset = (int)KNI_GetParameterAsInt(2);
    length = (int)KNI_GetParameterAsInt(3);

    KNI_StartHandles(3);
    KNI_DeclareHandle(arrayHandle);
    KNI_DeclareHandle(thisHandle);
    KNI_DeclareHandle(classHandle);

    KNI_GetThisPointer(thisHandle);
    KNI_GetClassPointer(classHandle);
    GET_FIELDID(classHandle, "handle", "I", connHandleID)

    handle = (javacall_handle)KNI_GetIntField(thisHandle, connHandleID);
    KNI_GetParameterAsObject(1, arrayHandle);

    REPORT_INFO3(LC_PROTOCOL,
        "btl2cap::receive off=%d len=%d handle=%d\n", offset, length, handle);

    info = (MidpReentryData*)SNI_GetReentryData(NULL);

    // Need revisit: add bluetooth activity indicator
//    START_BT_INDICATOR;

    if (info == NULL) {   /* First invocation */
        if (JAVACALL_BT_INVALID_HANDLE == handle) {
            KNI_ThrowNew(midpIOException, EXCEPTION_MSG(
                "Invalid handle during btl2cap::receive"));
        } else {
            // Need revisit: add bluetooth activity indicator
//            INC_BT_INDICATOR;

            SNI_BEGIN_RAW_POINTERS;
            status = javacall_bt_l2cap_receive(handle,
                (unsigned char*)&(JavaByteArray(arrayHandle)[offset]),
                length, &bytesRead);
            SNI_END_RAW_POINTERS;
        }
    } else {  /* Reinvocation after unblocking the thread */
        if (JAVACALL_BT_INVALID_HANDLE == handle) {
            /* closed by another thread */
            KNI_ThrowNew(midpInterruptedIOException, EXCEPTION_MSG(
                         "Interrupted IO error during btl2cap::receive"));

            // Need revisit: add bluetooth activity indicator
//            DEC_BT_INDICATOR;
        } else {
            if ((javacall_handle)info->descriptor != handle) {
                REPORT_CRIT2(LC_PROTOCOL,
                    "btl2cap::receive handles mismatched %d != %d\n",
                    handle, (javacall_handle)info->descriptor);
            }
            context = info->pResult;
            SNI_BEGIN_RAW_POINTERS;
            status = javacall_bt_l2cap_receive(handle,
                (unsigned char*)&(JavaByteArray(arrayHandle)[offset]),
                length, &bytesRead);
            SNI_END_RAW_POINTERS;
        }
    }

    REPORT_INFO1(LC_PROTOCOL, "btl2cap::receive bytes=%d\n", bytesRead);

    if (JAVACALL_BT_INVALID_HANDLE != handle) {
        if (status == JAVACALL_OK) {
            // Need revisit: add bluetooth activity indicator
//            DEC_BT_INDICATOR;
        } else {
            char* pError;
            javacall_bt_l2cap_get_error(handle, &pError);
            REPORT_INFO1(LC_PROTOCOL, "btl2cap::receive (%s)\n", pError);

            if (status == JAVACALL_WOULD_BLOCK) {
                midp_thread_wait(NETWORK_READ_SIGNAL, (int)handle, context);
            } else if (status == JAVACALL_INTERRUPTED) {
                char* pError;
                javacall_bt_l2cap_get_error(handle, &pError);
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                        "Interrupted IO error during btl2cap::receive (%s)",
                        pError);
                KNI_ThrowNew(midpInterruptedIOException,
                    EXCEPTION_MSG(gKNIBuffer));

                // Need revisit: add bluetooth activity indicator
//                DEC_BT_INDICATOR;
            } else {
                char* pError;
                javacall_bt_l2cap_get_error(handle, &pError);
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "Unknown error during btl2cap::receive (%s)", pError);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(gKNIBuffer));

                // Need revisit: add bluetooth activity indicator
//                DEC_BT_INDICATOR;
            }
        }
    }

    // Need revisit: add bluetooth activity indicator
//    STOP_BT_INDICATOR;

    KNI_EndHandles();
    KNI_ReturnInt((jint)bytesRead);
}
示例#25
0
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_cldc_io_j2me_socket_Protocol_open0() {
  init_sockets();

  SocketOpenParameter *p = (SocketOpenParameter*) SNI_GetReentryData(NULL);
  if (p == NULL) {
    p = (SocketOpenParameter*) SNI_AllocateReentryData(sizeof(*p));
    p->fd = -1;

    struct hostent *phostent;
    KNI_StartHandles(1);
    KNI_DeclareHandle(hostname_object);
    KNI_GetParameterAsObject(1, hostname_object);

    // hostname is always NUL terminated. See socket/Protocol.java for detail.
    char *hostname = (char*) SNI_GetRawArrayPointer(hostname_object);
    phostent = (struct hostent*)jvm_gethostbyname(hostname);
    KNI_EndHandles();

    if (phostent == NULL) {
      KNI_ReturnInt(-1);
    }
    struct sockaddr_in destination_sin;
    destination_sin.sin_family = AF_INET;
    int port = KNI_GetParameterAsInt(2);
    destination_sin.sin_port = jvm_htons(port);
    jvm_memcpy((char *) &destination_sin.sin_addr, phostent->h_addr,
                phostent->h_length);

    p->fd = jvm_socket(AF_INET, SOCK_STREAM, 0);
    if (p->fd < 0) {
       KNI_ReturnInt(-1);
    }
    if (!set_blocking_flags(&p->fd, /*is_blocking*/ KNI_FALSE)) {
      KNI_ReturnInt(-1);
    }

    if (jvm_connect(p->fd, (struct sockaddr *) &destination_sin,
                    sizeof(destination_sin)) < 0) {
      int err_code = GET_LAST_ERROR();
      if (err_code == EINPROGRESS) {
        // When the socket is ready for connect, it becomes *writable*
        // (according to BSD socket spec of select())
        p->check_flags = CHECK_WRITE | CHECK_EXCEPTION;
        SNI_BlockThread();
      } else {
        jvm_shutdown(p->fd, 2);
        closesocket(p->fd);
        p->fd = -1;
      }
    }
    KNI_ReturnInt(p->fd);
  } else {
    // When we come to here, a CheckEvent() call has reported one of the
    // following:
    // [1] connect() has succeeded. In this case we return the socket fd.
    // [2] connect() has failed. In this case CheckEvent has already closed
    //     the socket and set p->fd to -1. So we'd be returning -1.
    KNI_ReturnInt(p->fd);
  }
}
示例#26
0
/*
 * Accepts incoming client connection request.
 *
 * Note: the method gets native connection handle directly from
 * <code>handle<code> field of <code>BTSPPNotifierImpl</code> object.
 *
 * Note: new native connection handle to work with accepted incoming
 * client connection is setted directly to <code>handle</code> field of
 * appropriate <code>RFCOMMConnectionImpl</code> object.
 *
 * @throws IOException if an I/O error occurs
 */
KNIEXPORT KNI_RETURNTYPE_VOID
Java_com_sun_jsr082_bluetooth_btspp_BTSPPNotifierImpl_accept0(void) {
    javacall_handle handle = JAVACALL_BT_INVALID_HANDLE;
    javacall_handle peer_handle = JAVACALL_BT_INVALID_HANDLE;
    MidpReentryData* info;
    int status = JAVACALL_FAIL;
    int processStatus = KNI_FALSE;
    void *context = NULL;
    javacall_bt_address peer_addr;
    jfieldID notifHandleID = NULL;
    jfieldID peerHandleID  = NULL;
    jfieldID peerAddrID    = NULL;
    jfieldID pushHandleID  = NULL;

    KNI_StartHandles(3);
    KNI_DeclareHandle(thisHandle);
    KNI_DeclareHandle(arrayHandle);
    KNI_DeclareHandle(classHandle);
    KNI_GetClassPointer(classHandle);

    GET_FIELDID(classHandle, "handle", "I", notifHandleID)
    GET_FIELDID(classHandle, "peerHandle", "I", peerHandleID)
    GET_FIELDID(classHandle, "peerAddress", "[B", peerAddrID)
    GET_FIELDID(classHandle, "pushHandle", "I", pushHandleID)
    KNI_GetThisPointer(thisHandle);
    handle = (javacall_handle)KNI_GetIntField(thisHandle, notifHandleID);
    KNI_GetObjectField(thisHandle, peerAddrID, arrayHandle);

    if (handle == JAVACALL_BT_INVALID_HANDLE) {
        REPORT_ERROR(LC_PROTOCOL,
            "RFCOMM notifier was closed before btspp_notif::accept");
        KNI_ThrowNew(midpInterruptedIOException, EXCEPTION_MSG(
            "RFCOMM notifier was closed"));
    } else {
#ifndef NO_PUSH
        bt_pushid_t pushid = KNI_GetIntField(thisHandle, pushHandleID);
        if (pushid != BT_INVALID_PUSH_HANDLE) {
            if (bt_push_checkout_client(pushid, &peer_handle, peer_addr,
                    NULL, NULL) == JAVACALL_OK) {
                pushcheckoutaccept((int)handle);
                processStatus = KNI_TRUE;
                status = JAVACALL_OK;
            }
        }
#endif
        if (peer_handle == JAVACALL_BT_INVALID_HANDLE) {

        info = (MidpReentryData*)SNI_GetReentryData(NULL);
		if (info == NULL) {   /* First invocation */
            REPORT_INFO1(LC_PROTOCOL,
                "btspp_notif::accept handle=%d\n", handle);

            // Need revisit: add resource counting
            /*
             * An incoming socket connection counts against the client socket
             * resource limit.
             */
/*
            if (midpCheckResourceLimit(RSC_TYPE_BT_CLI, 1) == 0) {
                const char* pMsg =
                    "Resource limit exceeded for BT client sockets";
                REPORT_INFO(LC_PROTOCOL, pMsg);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
*/
//            } else {
                status = javacall_bt_rfcomm_accept(
                    handle, &peer_handle, &peer_addr);
				processStatus = KNI_TRUE;
//            }
		} else {  /* Reinvocation after unblocking the thread */
			if ((javacall_handle)info->descriptor != handle) {
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "btspp_notif::accept handles mismatched %d != %d\n",
                    handle, info->descriptor);
                REPORT_CRIT(LC_PROTOCOL, gKNIBuffer);
                KNI_ThrowNew(midpIllegalStateException, EXCEPTION_MSG(
                    "Internal error in btspp_notif::accept"));
            } else {
                // Need revisit: add resource counting
/*
                if (midpCheckResourceLimit(RSC_TYPE_BT_CLI, 1) == 0) {
                    const char* pMsg =
                        "Resource limit exceeded for BT client sockets"
                    REPORT_INFO(LC_PROTOCOL, pMsg);
                    KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
                } else {
*/
                    context = info->pResult;
				    status = javacall_bt_rfcomm_accept(
                        handle, &peer_handle, &peer_addr);
					processStatus = KNI_TRUE;
//                }
            }
        }

        }

        if (processStatus) {
            REPORT_INFO1(LC_PROTOCOL,
                "btspp_notif::accept server handle=%d\n", handle);
            if (status == JAVACALL_OK) {

                // Need revisit: add resource counting
/*
                if (midpIncResourceCount(RSC_TYPE_BT_CLI, 1) == 0) {
                    REPORT_INFO(LC_PROTOCOL,
                        "btspp_notif: Resource limit update error");
                }
*/

                // store client native connection handle for temporary storing
                KNI_SetIntField(thisHandle, peerHandleID, (jint)peer_handle);

                // copy address to Java object field
                KNI_SetRawArrayRegion(arrayHandle, 0, JAVACALL_BT_ADDRESS_SIZE, (jbyte*) peer_addr);

                REPORT_INFO(LC_PROTOCOL,
                    "btspp_notif::accept incoming connection accepted!");
            } else if (status == JAVACALL_WOULD_BLOCK) {
                midp_thread_wait(NETWORK_READ_SIGNAL, (int)handle, context);
            } else if (status == JAVACALL_FAIL) {
                char* pError;
                javacall_bt_rfcomm_get_error(handle, &pError);
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "IO error in btspp_notif::accept (%s)\n", pError);
                REPORT_INFO(LC_PROTOCOL, gKNIBuffer);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(gKNIBuffer));

            } else {
                char* pMsg = "Unknown error during btspp_notif::accept";
                REPORT_INFO(LC_PROTOCOL, pMsg);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
            }
        }
    }

    KNI_EndHandles();
    KNI_ReturnVoid();
}
示例#27
0
/**
 * Performs data transfer to the device.
 * <p>Java declaration:
 * <pre>
 * private native int cmdXfer0(byte[] request, byte[] response);
 * </pre>
 * @param request Buffer with request data
 * @param response Buffer for response data
 * @return Length of response in case of success, else -1
 */
KNIEXPORT KNI_RETURNTYPE_INT 
KNIDECL(com_sun_cardreader_PlatformCardDevice_cmdXfer0) {
    jint retcode;
    javacall_int32 tx_length, rx_length;
    char *tx_buffer, *rx_buffer;
    MidpReentryData* info;
    void *context = NULL;
    javacall_result status_code;
    
    KNI_StartHandles(2);
    KNI_DeclareHandle(request_handle);
    KNI_DeclareHandle(response_handle);
    
    info = (MidpReentryData*)SNI_GetReentryData(NULL);

    KNI_GetParameterAsObject(1, request_handle);
    if (KNI_IsNullHandle(request_handle)) {
        tx_buffer = NULL;
        tx_length = 0;
        retcode = -1;
        goto end;
    } else {
        tx_length = KNI_GetArrayLength(request_handle);
        tx_buffer = SNI_GetRawArrayPointer(request_handle);
    }
    
    KNI_GetParameterAsObject(2, response_handle);
    if (KNI_IsNullHandle(response_handle)) {
        rx_buffer = NULL;
        rx_length = 0;
        retcode = -1;
        goto end;
    } else {
        rx_length = KNI_GetArrayLength(response_handle);
        rx_buffer = SNI_GetRawArrayPointer(response_handle);
    }
    
    if (tx_length > 5) {
        jsize apdu_len = 5 + (tx_buffer[4]&0xFF) + 1;
        if (tx_length > apdu_len) {
            tx_length = apdu_len;
        }
    }

    if (info == NULL) {
        status_code = javacall_carddevice_xfer_data_start(tx_buffer, 
                                                          tx_length, 
                                                          rx_buffer, 
                                                          &rx_length, &context);
    } else {
        context = info->pResult;
        status_code = javacall_carddevice_xfer_data_finish(tx_buffer, 
                                                           tx_length, 
                                                           rx_buffer, 
                                                           &rx_length, context);
    }

    if (status_code == JAVACALL_WOULD_BLOCK) {
        midp_thread_wait(CARD_READER_DATA_SIGNAL, SIGNAL_XFER, context);
        goto end;
    }

    if (status_code != JAVACALL_OK) {
        retcode = -1;
    } else {
        retcode = rx_length;
    }

end:
    KNI_EndHandles();
    KNI_ReturnInt(retcode);
}
示例#28
0
/**
 * Open a serial port by system dependent device name.
 *
 * @param name device name of the port
 * @param baud baud rate to set the port at
 * @param flags options for the serial port
 *
 * @return handle to a native serial port
 *
 * @exception  IOException  if an I/O error occurs.
 */
KNIEXPORT KNI_RETURNTYPE_INT
    Java_com_sun_midp_io_j2me_comm_Protocol_native_1openByName() {

    int    flags = (int)KNI_GetParameterAsInt(3);
    int    baud = (int)KNI_GetParameterAsInt(2);
    int    nameLen;
    char   szName[MAX_NAME_LEN];
    jchar* temp;
    int    hPort = (int)INVALID_HANDLE;
    int    i;
    int status = PCSL_NET_IOERROR;
    void* context = NULL;
    MidpReentryData* info;

    KNI_StartHandles(1);
    KNI_DeclareHandle(nameObject);
    KNI_GetParameterAsObject(1, nameObject);
    
    info = (MidpReentryData*)SNI_GetReentryData(NULL);
    if (info == NULL) {
        nameLen = KNI_GetStringLength(nameObject);
        if (nameLen > MAX_NAME_LEN) {
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Serial device name has wrong length: %d\n", nameLen);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpIllegalArgumentException, gKNIBuffer);
        } else {
            temp = (jchar*)szName;
            KNI_GetStringRegion(nameObject, 0, nameLen, temp);

            /* device names are in ASCII */
            for (i = 0; i < nameLen; i++) {
                szName[i] = (char)temp[i];
            }
            szName[nameLen] = 0;
		
            status = openPortByNameStart(szName, baud, flags, &hPort, &context);
        }
    } else {
        /* reinvocation */
        hPort = info->descriptor;
        context = info->pResult;
        status = openPortByNameFinish(szName, baud, flags, &hPort, context);	
    }

    switch (status) {
        case PCSL_NET_SUCCESS:			
            /* do nothing and return normally */
            break;
        case PCSL_NET_INTERRUPTED:			
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Opening port %s has been interrupted\n", szName);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpInterruptedIOException, gKNIBuffer);
            break;
        case PCSL_NET_WOULDBLOCK:			
            midp_thread_wait(COMM_OPEN_SIGNAL, hPort, context);
            break;
        default:	   
            midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                "Opening port %s was failed\n", szName);
            REPORT_INFO1(LC_PROTOCOL, "%s\n", gKNIBuffer);
            KNI_ThrowNew(midpIOException, gKNIBuffer);
    }

    KNI_EndHandles();
    KNI_ReturnInt((jint)hPort);
}
示例#29
0
/**
 * Accepts incoming client connection request.
 *
 * Note: the method gets native connection handle directly from
 * <code>handle<code> field of <code>L2CAPNotifierImpl</code> object.
 *
 * Note: new native connection handle to work with accepted incoming
 * client connection is setted directly to <code>handle</code> field of
 * appropriate <code>L2CAPConnectionImpl</code> object.
 *
 * @return Negotiated ReceiveMTU and TransmitMTU.
 *               16 high bits is ReceiveMTU, 16 low bits is TransmitMTU.
 * @throws IOException if an I/O error occurs
 */
KNIEXPORT KNI_RETURNTYPE_INT
Java_com_sun_midp_io_j2me_btl2cap_L2CAPNotifierImpl_accept0(void) {
    javacall_handle handle = BT_INVALID_HANDLE;
    javacall_handle peer_handle = BT_INVALID_HANDLE;
    MidpReentryData* info;
    int status = JAVACALL_FAIL;
    int processStatus = KNI_FALSE;
    int imtu, omtu, mtus;
    void *context = NULL;
    javacall_bt_address peer_addr;
    unsigned char *address = NULL;

    KNI_StartHandles(2);
    KNI_DeclareHandle(thisHandle);
    KNI_DeclareHandle(arrayHandle);
    KNI_GetThisPointer(thisHandle);
    handle = (javacall_handle)KNI_GetIntField(thisHandle, notifHandleID);
    KNI_GetObjectField(thisHandle, peerAddrID, arrayHandle);

    if (handle == BT_INVALID_HANDLE) {
        REPORT_ERROR(LC_PROTOCOL,
            "L2CAP server socket was closed before btl2cap_notif::accept");
        KNI_ThrowNew(midpInterruptedIOException, EXCEPTION_MSG(
            "L2CAP notifier was closed"));
    } else {
        bt_pushid_t pushid = KNI_GetIntField(thisHandle, pushHandleID);
        if (pushid != BT_INVALID_PUSH_HANDLE) {
            if (bt_push_checkout_client(pushid, &peer_handle, peer_addr,
                    &imtu, &omtu) == JAVACALL_OK) {
                pushcheckoutaccept((int)handle);
                processStatus = KNI_TRUE;
                status = JAVACALL_OK;
            }
        }
        if (peer_handle == BT_INVALID_HANDLE) {

        info = (MidpReentryData*)SNI_GetReentryData(NULL);
        if (info == NULL) {   /* First invocation */
            REPORT_INFO1(LC_PROTOCOL,
                "btl2cap_notif::accept handle=%d\n", handle);

            // Need revisit: add resource counting
            /*
             * An incoming socket connection counts against the client socket
             * resource limit.
             */
/*
            if (midpCheckResourceLimit(RSC_TYPE_BT_CLI, 1) == 0) {
                const char* pMsg =
                    "Resource limit exceeded for BT client sockets";
                REPORT_INFO(LC_PROTOCOL, pMsg);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
*/
//            } else {
                status = javacall_bt_l2cap_accept(
                    handle, &peer_handle, &peer_addr, &imtu, &omtu);
                processStatus = KNI_TRUE;
//            }
        } else {  /* Reinvocation after unblocking the thread */
            if ((javacall_handle)info->descriptor != handle) {
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "btl2cap_notif::accept handles mismatched %d != %d\n",
                    handle, info->descriptor);
                REPORT_CRIT(LC_PROTOCOL, gKNIBuffer);
                KNI_ThrowNew(midpIllegalStateException, EXCEPTION_MSG(
                    "Internal error in btl2cap_notif::accept"));
            } else {
                // Need revisit: add resource counting
/*
                if (midpCheckResourceLimit(RSC_TYPE_BT_CLI, 1) == 0) {
                    const char* pMsg =
                        "Resource limit exceeded for BT client sockets"
                    REPORT_INFO(LC_PROTOCOL, pMsg);
                    KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
                } else {
*/
                    status = javacall_bt_l2cap_accept(
                        handle, &peer_handle, &peer_addr, &imtu, &omtu);
                    processStatus = KNI_TRUE;
//                }
            }
        }

        }

        if (processStatus) {
            REPORT_INFO1(LC_PROTOCOL,
                "btl2cap_notif::accept server handle=%d\n", handle);
            if (status == JAVACALL_OK) {
                int i;

                // Need revisit: add resource counting
/*
                if (midpIncResourceCount(RSC_TYPE_BT_CLI, 1) == 0) {
                    REPORT_INFO(LC_PROTOCOL,
                        "btl2cap_notif: Resource limit update error");
                }
*/

                // store client native connection handle for temporary storing
                KNI_SetIntField(thisHandle, peerHandleID, (jint)peer_handle);

                // copy address to Java object field
                SNI_BEGIN_RAW_POINTERS;
                address = JavaByteArray(arrayHandle);
                for (i = 0; i < BT_ADDRESS_SIZE; i++) {
                    address[i] = peer_addr[i];
                }
                SNI_END_RAW_POINTERS;

                REPORT_INFO(LC_PROTOCOL,
                    "btl2cap_notif::accept incoming connection accepted!");
            } else if (status == JAVACALL_WOULD_BLOCK) {
                midp_thread_wait(NETWORK_READ_SIGNAL, (int)handle, context);
            } else if (status == JAVACALL_FAIL) {
                char* pError;
                javacall_bt_l2cap_get_error(handle, &pError);
                midp_snprintf(gKNIBuffer, KNI_BUFFER_SIZE,
                    "IO error in btl2cap_notif::accept (%s)\n", pError);
                REPORT_INFO(LC_PROTOCOL, gKNIBuffer);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(gKNIBuffer));

            } else {
                char* pMsg = "Unknown error during btl2cap_notif::accept";
                REPORT_INFO(LC_PROTOCOL, pMsg);
                KNI_ThrowNew(midpIOException, EXCEPTION_MSG(pMsg));
            }
        }
    }

    mtus = (imtu << 16) & 0xFFFF0000;
    mtus |= omtu & 0xFFFF;

    KNI_EndHandles();
    KNI_ReturnInt(mtus);
}
示例#30
0
/**
 * private native void send0(LinkMessage msg)
 *     throws ClosedLinkException,
 *            InterruptedIOException,
 *            IOException;
 */
KNIEXPORT KNI_RETURNTYPE_VOID
Java_com_sun_midp_links_Link_send0(void)
{
    rendezvous *rp;
    KNI_StartHandles(3);
    KNI_DeclareHandle(thisObj);
    KNI_DeclareHandle(messageObj);
    KNI_DeclareHandle(otherMessageObj);

    KNI_GetThisPointer(thisObj);
    KNI_GetParameterAsObject(1, messageObj);

    rp = getNativePointer(thisObj);

    if (rp == NULL) {
        if (SNI_GetReentryData(NULL) == NULL) {
            KNI_ThrowNew(midpClosedLinkException, NULL);
        } else {
            KNI_ThrowNew(midpInterruptedIOException, NULL);
        }
    } else if (JVM_CurrentIsolateID() != rp->sender) {
        KNI_ThrowNew(midpIllegalArgumentException, NULL);
    } else {
        switch (rp->state) {
            case IDLE:
                rp->msg = SNI_AddStrongReference(messageObj);
                rp->state = SENDING;
                midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                break;

            case RECEIVING:
                rp->msg = SNI_AddStrongReference(messageObj);
                rp->state = RENDEZVOUS;
                midp_thread_signal(LINK_READY_SIGNAL, (int)rp, 0);
                midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                break;

            case SENDING:
            case RENDEZVOUS:
                midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                break;

            case DONE:
                getReference(rp->msg, "send0/DONE", otherMessageObj);
                if (KNI_IsSameObject(messageObj, otherMessageObj)) {
                    /* it's our message, finish processing */
                    SNI_DeleteReference(rp->msg);
                    rp->msg = INVALID_REFERENCE_ID;
                    rp->state = IDLE;
                    midp_thread_signal(LINK_READY_SIGNAL, (int)rp, 0);
                    if (rp->retcode != OK) {
                        KNI_ThrowNew(midpIOException, NULL);
                    }
                } else {
                    /* somebody else's message, just go back to sleep */
                    midp_thread_wait(LINK_READY_SIGNAL, (int)rp, NULL);
                }

                break;
            case CLOSED:
                setNativePointer(thisObj, NULL);
                if (rp->msg != INVALID_REFERENCE_ID) {
                    /* a message was stranded in the link; clean it out */
                    SNI_DeleteReference(rp->msg);
                    rp->msg = INVALID_REFERENCE_ID;
                }
                rp_decref(rp);
                if (SNI_GetReentryData(NULL) == NULL) {
                    KNI_ThrowNew(midpClosedLinkException, NULL);
                } else {
                    KNI_ThrowNew(midpInterruptedIOException, NULL);
                }
                break;
        }
    }

    KNI_EndHandles();
    KNI_ReturnVoid();
}