在C中打开LDAP客户端 - 如何替换已弃用的API

时间:2017-05-29 08:54:40

标签: c gcc ldap solaris openldap

我在转换用C编码的小型OpenLDAP客户端时遇到了困难。此程序的原始版本适用于已弃用的API。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ldap.h>


/*-------------------

 gcc -w  -DLDAP_DEPRECATED -o exe/TstLDAPold  sources/TstLDAPold.c -lopenldap

--------------------*/

int main(int argc, char ** argv)
{

  char* pstrDatabaseName = "I36_XXX";
  char * pstrSchemaName = "DEV_XXX";
  char* pstrModuleName = "L8XX";
  char * pstrHostName = "mado";

  // New LDAP Structure

  int version, ldapPort, i, rc, entryCount, NodeFound;
  char *ldapHost, *searchBase;
  char *attribute, *dn, **values;
  const char *sortAttribute = "sn";
  struct timeval timeOut;
  BerElement *ber;
  LDAP *ld;
  LDAPMessage *searchResult, *entry;
  FILE *fp;

  const char * loginDN = "cn=ldap_yyyy,cn=yyyyy,cn=Ixxxxx";
  const char * password = "ldap_xxx";

  ldapHost = (char *) malloc(100);
  searchBase = (char *) malloc(500);                     // New LDAP Structure

  (void) strcpy( (char *) ldapHost, (const char *) "myldapserver");

  char * strLdapPort = (char *) malloc(10);
  if (getenv("LDAP_PORT") != NULL)
  {
    ldapPort = atoi(getenv("LDAP_PORT"));
    strcpy(strLdapPort, getenv("LDAP_PORT"));
  }
  else
  {
    ldapPort = 389;
    strcpy(strLdapPort, "389");
  }

  strcpy(searchBase, "HostName=");  // Change attrib ModuleName in ProgramName
  strcat(searchBase, pstrHostName);
  strcpy(searchBase, "ProgramName="); // Change attrib ModuleName in ProgramName
  strcat(searchBase, pstrModuleName);
  strcat(searchBase, ",SchemaName=");                    // New LDAP Structure
  strcat(searchBase, pstrSchemaName);                    // New LDAP Structure
  strcat(searchBase, ",DatabaseName=");                  // New LDAP Structure
  strcat(searchBase, pstrDatabaseName);                  // New LDAP Structure
  strcat(searchBase, ",cn=RLM,cn=Ixxx");

  /* Set LDAP version to 3 */
  version = LDAP_VERSION3;
  ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &version);

  /* Initialize the LDAP session */
  /* NEW ROUTINE OPEN LDAP 2.4 */

  char * ldapServer = (char *) malloc(200);
  strcpy(ldapServer, (const char *) ldapHost);
  strcat(ldapServer, (const char *) ":");
  strcat(ldapServer, (const char *) strLdapPort);
  printf("LDAP Server : %s\n", ldapServer);
  //LDAP ld1;


   if ((ld = ldap_open(ldapHost, ldapPort)) == NULL)
   {
   printf("\n    LDAP session initialization failed\n");
   return (1);
   } else {
    printf("Open success\n");
   }

  /* Bind to the server */

  rc = ldap_simple_bind_s(ld, loginDN, password);
  if (rc != LDAP_SUCCESS)
  {
    printf(
        "ldap_simple_bind_s: %s\nInformations : Login: %s Password: %s\n",
        ldap_err2string(rc), loginDN, password);

    printf( "Unbind\n" );
    ldap_unbind_s(ld);
    printf( "Unbinding ok\n" );
    return (1);
  }

  rc = ldap_search_s(ld, searchBase, LDAP_SCOPE_ONELEVEL, "(objectclass=*)",
      NULL, 0, &searchResult);




  if (rc != LDAP_SUCCESS)
  {
    printf("ldap_search_ext_s: %s \n", ldap_err2string(rc));
    ldap_unbind_s(ld);
    return (1);
  } else {
    printf("Search Success\n");
  }

/// DISPLAY RESULTS


  NodeFound = 0;
  /* Go through the search results by checking entries */
  for (entry = ldap_first_entry(ld, searchResult);
      entry != NULL & NodeFound == 0; entry = ldap_next_entry(ld, entry))
  {
    if ((dn = ldap_get_dn(ld, entry)) != NULL)
    {
      ldap_memfree(dn);
    }

    for (attribute = ldap_first_attribute(ld, entry, &ber);
        attribute != NULL;
        attribute = ldap_next_attribute(ld, entry, ber))
    {
      /* Get values and print.  Assumes all values are strings. */
      if ((values = ldap_get_values(ld, entry, attribute)) != NULL)
      {
        printf("attribute : %s \n",attribute );
        printf("value : %s\n", values[0] );

        if (strcasecmp(attribute, "HostName") == 0)
        {
          if (strncmp(values[0], pstrHostName, strlen(pstrHostName)) != 0)
          {
            NodeFound = 0;
          } else
          {
            //strcpy(mstrHostName, values[0]);
            NodeFound = 1;
          }
        }

        ldap_value_free(values);
      }
      ldap_memfree(attribute);
    }

  }
  ldap_msgfree(searchResult);
  ldap_unbind_s(ld);

  return (0);
}

此代码有效,它给出了:

属性:ModuleName
值:LIC_058
属性:BeginDate
价值:19970404
attribute:EndDate
价值:20251231
...

然后,我把它改为:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ldap.h>


/*-------------------

 gcc -o exe/TstLDAP  sources/TstLDAP.c -lopenldap

--------------------*/

int main(int argc, char ** argv)
{

  char* pstrDatabaseName = "I36_XXX";
  char * pstrSchemaName = "DEV_XXX";
  char* pstrModuleName = "LXXX";
  char * pstrHostName = "mado";

  // New LDAP Structure

  int version, ldapPort, i, rc, entryCount, NodeFound;
  char *ldapHost, *searchBase;
  char *attribute, *dn, **values;
  const char *sortAttribute = "sn";
  struct timeval timeOut;
  BerElement *ber;
  LDAP *ld;
  LDAPMessage *searchResult, *entry;
  FILE *fp;

  const char * loginDN = "cn=ldap_yyy,cn=yyyy,cn=Ixxxx";
  const char * password = "ldap_xxx";

  ldapHost = (char *) malloc(100);
  searchBase = (char *) malloc(500);                     // New LDAP Structure

  (void) strcpy( (char *) ldapHost, (const char *) "ldap://myldapserver");

  char * strLdapPort = (char *) malloc(10);
  if (getenv("LDAP_PORT") != NULL)
  {
    ldapPort = atoi(getenv("LDAP_PORT"));
    strcpy(strLdapPort, getenv("LDAP_PORT"));
  }
  else
  {
    ldapPort = 389;
    strcpy(strLdapPort, "389");
  }


  strcpy(searchBase, "HostName=");  // Change attrib ModuleName in ProgramName
  strcat(searchBase, pstrHostName);
  strcpy(searchBase, "ProgramName="); // Change attrib ModuleName in ProgramName
  strcat(searchBase, pstrModuleName);
  strcat(searchBase, ",SchemaName=");                    // New LDAP Structure
  strcat(searchBase, pstrSchemaName);                    // New LDAP Structure
  strcat(searchBase, ",DatabaseName=");                  // New LDAP Structure
  strcat(searchBase, pstrDatabaseName);                  // New LDAP Structure
  strcat(searchBase, ",cn=RLM,cn=Ixxx");

  /* Set LDAP version to 3 */
  version = LDAP_VERSION3;
  ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &version);

  /* Initialize the LDAP session */
  /* NEW ROUTINE OPEN LDAP 2.4 */

  char * ldapServer = (char *) malloc(200);
  strcpy(ldapServer, (const char *) ldapHost);
  strcat(ldapServer, (const char *) ":");
  strcat(ldapServer, (const char *) strLdapPort);
  printf("LDAP Server : %s\n", ldapServer);
  //LDAP ld1;

  if (ldap_initialize(&ld, ldapServer))
  {
    //logFile("/tmp/licences_manager.log", "LDAP init failed!", "");
    printf("LDAP Init failed");
  }
  else
  {
    //logFile("/tmp/licences_manager.log", "LDAP init Success!", "");
    printf("LDAP Init Success\n");
  }

  /*
   if ((ld = ldap_open(ldapHost, ldapPort)) == NULL)
   {
   printf("\n    LDAP session initialization failed\n");
   return (1);
   }*/

  /* Bind to the server */

  struct berval cred;
  strcpy(cred.bv_val, password);
  cred.bv_len = strlen(password);
  rc = ldap_sasl_bind_s(ld, loginDN, LDAP_SASL_SIMPLE, &cred, NULL, NULL,  NULL);
  if (rc != LDAP_SUCCESS)
  {
    printf("ldap_sasl_bind_s: %s\nInformations : Login: %s Password: %s\n",
        ldap_err2string(rc), loginDN, password);
    return (1);
  } else {
    printf( "Binding successful\n");
  }


  ////-------------Phase 2

  LDAPControl             **serverctrls;
  LDAPControl             **clientctrls; 
  struct timeval  *timeout;

  rc = ldap_search_ext_s( ld,
   searchBase, 
   LDAP_SCOPE_ONELEVEL, 
   "(objectclass=*)",
      NULL, 
      0,
      NULL, // LDAPControl             **serverctrls, // NEW
      NULL, // LDAPControl             **clientctrls, // NEW 
      NULL, // struct timeval  *timeout,               //NEW
      LDAP_NO_LIMIT,   // int                             sizelimit, // NEW
      &searchResult );

  if (rc != LDAP_SUCCESS)
  {
    printf("ldap_search_ext_s: %s \n", ldap_err2string(rc));
    //ldap_unbind_s(ld);
    return (1);
  } else {
    printf("Search Success\n");
  }

  return (0);
}

第一步似乎有效(初始化,绑定)但在运行搜索时它在第2阶段崩溃:

LDAP服务器:ldap:// myldapserver:389
LDAP初始化成功
记忆错误(coredump)

在Solaris 11上使用GCC 4.8,但我认为它与系统无关。我在搜索API上做错了吗?我已经google了很多,但我找不到它失败的充分理由。

非常感谢。

1 个答案:

答案 0 :(得分:0)

哎呀,似乎绑定也不起作用。我忘了分配cred.bv_val来接收密码。这就是coredump的原因。