Пример #1
0
/**
 * A main() is provided so that quick testing of this
 * library can be done. 
 */
int main(int argc, char **argv) {
  int ngroups;
  gid_t *groups = NULL;
  char *user = "******";
  if (argc == 2) user = argv[1];
  int error = getGroupIDList(user, &ngroups, &groups);
  if (error != 0) {
    printf("Couldn't obtain grp for user %s", user);
    return;
  }
  int i;
  for (i = 0; i < ngroups; i++) {
    char *grpbuf = NULL;
    error = getGroupDetails(groups[i], &grpbuf);
    printf("grps[%d]: %s ",i, ((struct group*)grpbuf)->gr_name);
    free(grpbuf);
  }
  free(groups);
  return 0;
}
JNIEXPORT jobjectArray JNICALL 
Java_org_apache_hadoop_security_JniBasedUnixGroupsMapping_getGroupForUser 
(JNIEnv *env, jobject jobj, jstring juser) {
  extern int getGroupIDList(const char *user, int *ngroups, gid_t **groups);
  extern int getGroupDetails(gid_t group, char **grpBuf);

  jobjectArray jgroups; 
  int error = -1;

  if (emptyGroups == NULL) {
    jobjectArray lEmptyGroups = (jobjectArray)(*env)->NewObjectArray(env, 0,
            (*env)->FindClass(env, "java/lang/String"), NULL);
    if (lEmptyGroups == NULL) {
      goto cleanup;
    }
    emptyGroups = (*env)->NewGlobalRef(env, lEmptyGroups);
    if (emptyGroups == NULL) {
      goto cleanup;
    }
  }
  char *grpBuf = NULL;
  const char *cuser = (*env)->GetStringUTFChars(env, juser, NULL);
  if (cuser == NULL) {
    goto cleanup;
  }

  /*Get the number of the groups, and their IDs, this user belongs to*/
  gid_t *groups = NULL;
  int ngroups = 0;
  error = getGroupIDList(cuser, &ngroups, &groups);
  if (error != 0) {
    goto cleanup; 
  }

  jgroups = (jobjectArray)(*env)->NewObjectArray(env, ngroups, 
            (*env)->FindClass(env, "java/lang/String"), NULL);
  if (jgroups == NULL) {
    error = -1;
    goto cleanup; 
  }

  /*Iterate over the groupIDs and get the group structure for each*/
  int i = 0;
  for (i = 0; i < ngroups; i++) {
    error = getGroupDetails(groups[i],&grpBuf);
    if (error != 0) {
      goto cleanup;
    }
    jstring jgrp = (*env)->NewStringUTF(env, ((struct group*)grpBuf)->gr_name);
    if (jgrp == NULL) {
      error = -1;
      goto cleanup;
    }
    (*env)->SetObjectArrayElement(env, jgroups,i,jgrp);
    free(grpBuf);
    grpBuf = NULL;
  }

cleanup:
  if (error == ENOMEM) {
    THROW(env, "java/lang/OutOfMemoryError", NULL);
  }
  if (error == ENOENT) {
    THROW(env, "java/io/IOException", "No entry for user");
  }
  if (groups != NULL) {
    free(groups);
  }
  if (grpBuf != NULL) {
    free(grpBuf);
  }
  if (cuser != NULL) {
    (*env)->ReleaseStringUTFChars(env, juser, cuser);
  }
  if (error == 0) {
    return jgroups;
  } else {
    return emptyGroups;
  }
}