对于我的一个项目,我想实现一个完整的PAM Java实现(应用程序端和模块端)。
现在,我在申请方面。我以jpam为基础,但我偶然发现了一个问题,经过几个小时的搜索,我仍然找不到解决问题的方法:/
这是当前代码:
JNIEXPORT jint JNICALL Java_org_eel_kitchen_pam_PamHandle_authenticate(
JNIEnv *pEnv, jobject pObj, jstring pServiceName, jstring pUsername,
jstring pPassword, jboolean debug)
{
pam_handle_t *pamh = NULL;
int retval;
/*
* TODO: unclear, see what's what
*
* With my first tests, it appears that GetStringUTFChars() makes the JVM
* crash if memory cannot be allocated... But an array copy was made. See
* what happens if the JVM decides NOT to make a copy. Right now it is
* assumed that allocations succeed. And the JNI spec says
* GetStringUTFChars() does NOT throw an OOM on failure.
*/
service_name = (*pEnv)->GetStringUTFChars(pEnv, pServiceName, NULL);
username = (*pEnv)->GetStringUTFChars(pEnv, pUsername, NULL);
password = (*pEnv)->GetStringUTFChars(pEnv, pPassword, NULL);
/* Get a handle to a PAM instance */
retval = pam_start(service_name, username, &PAM_converse, &pamh);
if (retval != PAM_SUCCESS) {
pr_debug("pam_start failed for service %s: %s\n", service_name,
pam_strerror(NULL, retval));
goto out_nohandle;
}
pam_set_item(pamh, PAM_AUTHTOK, password);
retval = pam_authenticate(pamh, 0);
/* Is user permitted access? */
if (retval != PAM_SUCCESS) {
pr_debug("failed to authenticate user %s: %s\n", username,
pam_strerror(NULL, retval));
goto out_free;
}
retval = pam_acct_mgmt(pamh, 0);
if (retval != PAM_SUCCESS)
pr_debug("failed to setup account for user %s: %s\n", username,
pam_strerror(NULL, retval));
out_free:
/* Clean up our handles and variables */
if (pam_end(pamh, retval) != PAM_SUCCESS) {
pamh = NULL;
pr_debug("Fuchs! Failed to release PAM handle\n");
}
out_nohandle:
(*pEnv)->ReleaseStringUTFChars(pEnv, pServiceName, service_name);
(*pEnv)->ReleaseStringUTFChars(pEnv, pUsername, username);
(*pEnv)->ReleaseStringUTFChars(pEnv, pPassword, password);
return retval;
}
我想在这里为
pamh
的所有实例保留对PamHandle
的引用。怎么做到的?编辑:好的,我有答案了,现在是清理部分:我是使用
finalize()
调用本机清理方法然后super.finalize();
,还是有一个JNI函数由GC触发,我可以/必须实现它? 最佳答案
使用long存储指向pam_handle_t的指针。
Java端看起来像
long handle = Pam.create();
Pam.DoSomething(handle,arg1,arg2);
当然,您可以将其封装在类中,这样就可以拥有接口。
PamHandle p = new PamHandle();
p.DoSomething(arg1,arg2);
C面应该是这样的:
JNIEXPORT jlong JNICALL Java_org_Create(
JNIEnv *pEnv)
{
pam_handle_t *pamh = createNew pam_handle somehow
jlong result = (jlong) pamh;
return result;
}
JNIEXPORT jint JNICALL Java_org_Blah_Blah_blah(
JNIEnv *pEnv, jlong handle, jstring arg1,jstring arg2)
{
pam_handle_t *pamh = (pam_handle_t*)handle;
// ... Do rest of stuff
}
这将允许每个实例有一个pam_handle_t。
每次手动传递整数,而不是传递对象,然后必须访问对象的字段,这样做的性能也更高。
编辑
另外,如果您担心jlong不能正确地保存指针,那么jlong保证是64位的。因此,jlong将一直适用于这种情况,直到我们开始获得128位整数(一段很长的路要走)。