How to access environment variables ?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
44 messages Options
123
Reply | Threaded
Open this post in threaded view
|

How to access environment variables ?

Mehul Sanghvi-2

I would like to be able to get at all of the environment variables (whether it
is the shell environment variables or the CGI environment variables or
something else).  What object/class would I use for that ?


cheers,

      mehul



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen

On Jan 14, 2009, at 11:45 AM, Mehul N. Sanghvi wrote:

>
> I would like to be able to get at all of the environment variables  
> (whether it is the shell environment variables or the CGI  
> environment variables or something else).  What object/class would I  
> use for that ?

o wait, i think i know this:

Smalltalk getenv: 'foo'
Smalltalk getenv: 'bar'



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen
In reply to this post by Mehul Sanghvi-2
Paolo,

Where can I find the documentation on this?

Are there docs on all the libgst stuff somewhere that I just haven't  
found?

And to everyone else,

Does the sidebar on smalltalk.gnu.org is confusing?

I never clicked into documentation for 3 days when i start because all  
i though there was going to be was the FAQ because that was all
that was a sub area under it. Perhaps I'm just daft.


On Jan 14, 2009, at 11:45 AM, Mehul N. Sanghvi wrote:

>
> I would like to be able to get at all of the environment variables  
> (whether it is the shell environment variables or the CGI  
> environment variables or something else).  What object/class would I  
> use for that ?
>
>
> cheers,
>
>     mehul
>
>
>
> _______________________________________________
> help-smalltalk mailing list
> [hidden email]
> http://lists.gnu.org/mailman/listinfo/help-smalltalk



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Mehul Sanghvi-2
In reply to this post by SeanTAllen
Sean Allen said the following on 01/14/2009 12:20 PM:

>
> On Jan 14, 2009, at 11:45 AM, Mehul N. Sanghvi wrote:
>
>>
>> I would like to be able to get at all of the environment variables
>> (whether it is the shell environment variables or the CGI environment
>> variables or something else).  What object/class would I use for that ?
>
> o wait, i think i know this:
>
> Smalltalk getenv: 'foo'
> Smalltalk getenv: 'bar'
>
>


Is there something that will get all the environment variables and store it in
an Array or something like that ?   Using the approach above, say in a CGI
environment when I'm trying to debug, I just want it to print every environment
  variable as I probably do not know what I would be looking for but am hoping
that something in the environment will give me some guidance.


Did that make sense ?

Perl, Tcl, and PHP store the environment variables in an associative array
which can then be poked and peeked at (yes the usage of the two words was
intentional use of BASIC).  Scheme also supports this with a recent enhancement
to the language, SRFI-98.

Is there some way to do something similar ? Maybe there is a message
"getenvAll" ?   I couldn't find it and there doesn't seem to be much
documentation for getenv on smalltalk.gnu.org site.

cheers,

      mehul



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen

On Jan 14, 2009, at 3:09 PM, Mehul N. Sanghvi wrote:

> Sean Allen said the following on 01/14/2009 12:20 PM:
>> On Jan 14, 2009, at 11:45 AM, Mehul N. Sanghvi wrote:
>>>
>>> I would like to be able to get at all of the environment variables  
>>> (whether it is the shell environment variables or the CGI  
>>> environment variables or something else).  What object/class would  
>>> I use for that ?
>> o wait, i think i know this:
>> Smalltalk getenv: 'foo'
>> Smalltalk getenv: 'bar'
>
>
> Is there something that will get all the environment variables and  
> store it in an Array or something like that ?   Using the approach  
> above, say in a CGI environment when I'm trying to debug, I just  
> want it to print every environment  variable as I probably do not  
> know what I would be looking for but am hoping
> that something in the environment will give me some guidance.
>
>
> Did that make sense ?
>
> Perl, Tcl, and PHP store the environment variables in an associative  
> array which can then be poked and peeked at (yes the usage of the  
> two words was intentional use of BASIC).  Scheme also supports this  
> with a recent enhancement to the language, SRFI-98.
>
> Is there some way to do something similar ? Maybe there is a message  
> "getenvAll" ?   I couldn't find it and there doesn't seem to be much  
> documentation for getenv on smalltalk.gnu.org site.


i've only been looking at the source for a few days but what i know by  
now ( or think i know, corrections from Paolo appreciated... )

getenv is a call out to C's getenv
you want a call out to environ which doesn't exist right now, someone  
with more experience than i could put in quickly.

you can see everything in kernel/cFuncs.st and libgst/cint.c

if you are feeling adventurous, there is documentation about  
interfacing with C at:

http://www.gnu.org/software/smalltalk/manual/gst.html#C-and-Smalltalk



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen

On Jan 14, 2009, at 5:33 PM, Sean Allen wrote:

>
> On Jan 14, 2009, at 3:09 PM, Mehul N. Sanghvi wrote:
>
>> Sean Allen said the following on 01/14/2009 12:20 PM:
>>> On Jan 14, 2009, at 11:45 AM, Mehul N. Sanghvi wrote:
>>>>
>>>> I would like to be able to get at all of the environment  
>>>> variables (whether it is the shell environment variables or the  
>>>> CGI environment variables or something else).  What object/class  
>>>> would I use for that ?
>>> o wait, i think i know this:
>>> Smalltalk getenv: 'foo'
>>> Smalltalk getenv: 'bar'
>>
>>
>> Is there something that will get all the environment variables and  
>> store it in an Array or something like that ?   Using the approach  
>> above, say in a CGI environment when I'm trying to debug, I just  
>> want it to print every environment  variable as I probably do not  
>> know what I would be looking for but am hoping
>> that something in the environment will give me some guidance.
>>
>>
>> Did that make sense ?
>>
>> Perl, Tcl, and PHP store the environment variables in an  
>> associative array which can then be poked and peeked at (yes the  
>> usage of the two words was intentional use of BASIC).  Scheme also  
>> supports this with a recent enhancement to the language, SRFI-98.
>>
>> Is there some way to do something similar ? Maybe there is a  
>> message "getenvAll" ?   I couldn't find it and there doesn't seem  
>> to be much documentation for getenv on smalltalk.gnu.org site.
>
>
> i've only been looking at the source for a few days but what i know  
> by now ( or think i know, corrections from Paolo appreciated... )
>
> getenv is a call out to C's getenv
> you want a call out to environ which doesn't exist right now,  
> someone with more experience than i could put in quickly.
>
> you can see everything in kernel/cFuncs.st and libgst/cint.c
>
> if you are feeling adventurous, there is documentation about  
> interfacing with C at:
>
> http://www.gnu.org/software/smalltalk/manual/gst.html#C-and-Smalltalk
>

Paolo,

Following up on this as I'm unclear from the docs,

environ returns char **

should the returning part in cFuncs.st be

returning: ( #array #string )

what about the size though?

little confused by the docs on that part.





_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Stephen-71
In reply to this post by Mehul Sanghvi-2
Mehul N. Sanghvi wrote:
>
> I would like to be able to get at all of the environment variables
> (whether it is the shell environment variables or the CGI environment
> variables or something else).  What object/class would I use for that ?
>

There is a way of getting it with an OS call...

$ gst
GNU Smalltalk ready

st> | pipe |
st> pipe := FileStream popen: 'set'  dir: FileStream read
<Pipe on set>
st> pipe contents
'AUTO_SYMLINK=no
BASH=/bin/sh
BASH_ARGC=()
BASH_ARGV=()
BASH_EXECUTION_STRING=set
BASH_LINENO=()
BASH_SOURCE=()
....




In code, something like:
     osCall: cmd [
         | pipe |
         pipe := FileStream popen: cmd dir: FileStream read.
         ^pipe contents.
     ]


Then call it like:-

Transcript show: (osCall: 'set').
or
Transcript show: (osCall: 'ls -l').



Stephen


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Paolo Bonzini-2
In reply to this post by Mehul Sanghvi-2

> Is there some way to do something similar ? Maybe there is a message
> "getenvAll" ?

Not yet.

> I couldn't find it and there doesn't seem to be much
> documentation for getenv on smalltalk.gnu.org site.

Yes, the documentation is not searchable.  If anybody knows a Drupal
module to crawl another site and include it in the search results,
please tell me.

Paolo


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Paolo Bonzini-2
In reply to this post by SeanTAllen

> environ returns char **
>
> should the returning part in cFuncs.st be
>
> returning: ( #array #string )
>
> what about the size though?

Returning #(#ptr #string), with some Smalltalk code to convert it to an
OrderedCollection.  Everything else is correct.

Paolo




_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen

On Jan 15, 2009, at 2:59 PM, Paolo Bonzini wrote:

>>
>> environ returns char **
>>
>> should the returning part in cFuncs.st be
>>
>> returning: ( #array #string )
>>
>> what about the size though?
>
> Returning #(#ptr #string), with some Smalltalk code to convert it to  
> an
> OrderedCollection.  Everything else is correct.

Is there anything that does this right now that I could use as an  
exemplar?
Or should I just grep for #ptr #string and see what I find?

Making some progress here learning stuff... god bless knowing C.
The entire time I did C programming it was always "god damn C" and  
now...
ah... finally, worth it.



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Paolo Bonzini-2

> Is there anything that does this right now that I could use as an exemplar?
> Or should I just grep for #ptr #string and see what I find?

There's something somewhere, but I'll just point you to the mailing list
archives.  Look for the exchanges I had with Stephen (Woolerton) about
his LDAP bindings.

> Making some progress here learning stuff... god bless knowing C.
> The entire time I did C programming it was always "god damn C" and now...
> ah... finally, worth it.

I'm glad of it. :-)

Paolo


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

SeanTAllen

On Jan 15, 2009, at 3:49 PM, Paolo Bonzini wrote:

>
>> Is there anything that does this right now that I could use as an  
>> exemplar?
>> Or should I just grep for #ptr #string and see what I find?
>
> There's something somewhere, but I'll just point you to the mailing  
> list
> archives.  Look for the exchanges I had with Stephen (Woolerton) about
> his LDAP bindings.

found those emails... having a hard time digesting...

Stephen... do you any code related to dealing with char ** or anything  
similar,
that I could take a look at.

i'm going to try printing out the emails and cutting them up and  
pasting them together
in a different order, hoping,  that might perhaps ease the absorbing  
of them.


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Stephen-71
Sean Allen wrote:

>
> On Jan 15, 2009, at 3:49 PM, Paolo Bonzini wrote:
>
>>
>>> Is there anything that does this right now that I could use as an
>>> exemplar?
>>> Or should I just grep for #ptr #string and see what I find?
>>
>> There's something somewhere, but I'll just point you to the mailing list
>> archives.  Look for the exchanges I had with Stephen (Woolerton) about
>> his LDAP bindings.
>
> found those emails... having a hard time digesting...
>
> Stephen... do you any code related to dealing with char ** or anything
> similar,
> that I could take a look at.
>
> i'm going to try printing out the emails and cutting them up and pasting
> them together
> in a different order, hoping,  that might perhaps ease the absorbing of
> them.
>
>
> _______________________________________________
> help-smalltalk mailing list
> [hidden email]
> http://lists.gnu.org/mailman/listinfo/help-smalltalk
>
>
I've had a quick look and not all of the correspondence got copied to
the list. I'll copy the missing ones to you.

I've attached a copy of a working C program to do an LDAP lookup - this
is what we were working from; the blueprint so to speak. You should find
this helpful as you can see what the C program was doing and then how it
was implemented in GST.

Secondly, attached is the working script for where we got to.. best to
run it on a 32 bit system, (there was an issue which Paolo fixed on some
not all 64 bit systems).

Also attached is the ldap.h file (from Linux).

I'm just about to head out the door and away for the weekend so by all
means send questions through but you mightn't get a reply for a while.

Regards
Stephen

#!/usr/local/bin/gst -f
"call LDAP API"

DLD addLibrary: 'libldap'.

  CObject extend [
        "Will be in 3.1"
        isNull [ ^self address = 0 ]
  ]

  UndefinedObject extend [
        isNull [ ^true ] ]

  CObject subclass: BER [
        " -----------------------
        LBER_F( void )
        ber_free LDAP_P((
                BerElement *ber,
                int freebuf ));
        ------------------------- "
      free [
        <cCall: 'ber_free' returning: #void args: #(#self #int)>
        ]
  ]

  CObject subclass: LDAPMessage [
      free [
        <cCall: 'ldap_msgfree' returning: #int args: #(#self)>
        ]
  ]

  CObject subclass: LDAP [
      "class variables"
      scopeBase := 0.
      nolimit := 0.

      LDAP class >> openOn: host port: port [
          "Maybe you prefer #open:port: as the selector, of course."
          <cCall: 'ldap_open' returning: #{LDAP} args: #(#string #int)>
      ]

      LDAP class >> on: host port: port [
          "Maybe you prefer #init:port: as the selector, of course."
          <cCall: 'ldap_init' returning: #{LDAP} args: #(#string #int)>
      ]

      LDAP class >> errorString: resultNum [
          "Utility methods might also go on the class side."
          <cCall: 'ldap_err2string' returning: #string args: #(#int)>
      ]

      simpleBindWithDN: who passwd: secret [
          <cCall: 'ldap_simple_bind_s' returning: #int args: #(#self #string #string)>
      ]

        " ldap_search_ext_s C definition --------------
        LDAP_F( int )
      ldap_search_ext_s LDAP_P((
        LDAP                    *ld,
        LDAP_CONST char *base,
        int                             scope,
        LDAP_CONST char *filter,
        char                    **attrs,
        int                             attrsonly,
        LDAPControl             **serverctrls,
        LDAPControl             **clientctrls,
        struct timeval  *timeout,
        int                             sizelimit,
        LDAPMessage             **res ));
        rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
    ""(objectclass=*)"", NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
    LDAP_NO_LIMIT, &result
                                        --------------- "
        "TODO: write a wrapper method which has less parameters and calls this one"
        searchWithBase: baseDN
          scope: aScope
          filter: aFilter
          attributes: theAttribs
          isAttrsOnly: attrsOnly
          serverctrls: serverControl
          clientctrls: clientControl
          timeout: timeval
          sizelimit: numResults
          searchResult: aSearchResult [
           <cCall: 'ldap_search_ext_s' returning: #int args: #(#self #string #int #string #cObject #int #cObject #cObject #cObject #int #cObjectPtr)>
        ]

        " ldap_first_entry C definition --------------
        LDAP_F( LDAPMessage * )
        ldap_first_entry LDAP_P((
                LDAP *ld,
                LDAPMessage *chain ));
                                        --------------"
        firstEntry: searchResult [
                <cCall: 'ldap_first_entry' returning: #cObject args: #(#self #cObject)> ]

        " -------------
        LDAP_F( char * )
        ldap_first_attribute LDAP_P((
                LDAP *ld,
                LDAPMessage *entry,
                BerElement **ber ));
                                -------------"
        firstAttribute: anEntry ber: aBer [
                <cCall: 'ldap_first_attribute' returning: #cObject args: #(#self #cObject #cObjectPtr)> ]

        " -------------
        LDAP_F( char * )
        ldap_next_attribute LDAP_P((
                LDAP *ld,
                LDAPMessage *entry,
                BerElement *ber ));
          -------------"
        nextAttribute: anEntry ber: aBer [
                <cCall: 'ldap_next_attribute' returning: #cObject args: #(#self #cObject #cObject)> ]

        " -------------
        #if LDAP_DEPRECATED
        LDAP_F( char ** )
        ldap_get_values LDAP_P((        /* deprecated, use ldap_get_values_len */
                LDAP *ld,
                LDAPMessage *entry,
                LDAP_CONST char *target ));
                                -------------"
        getValues: anEntry attribute: anAttribute [
                <cCall: 'ldap_get_values' returning: #{CString} args: #(#self #cObject #cObject)> ]

]

| ldapcall ldap resultCode resultCode2 errorMsg hostName baseDN |
Transcript showCr: 'started'.
hostName := '172.21.5.5'.
baseDN := 'ou=Users,dc=shineglobal,dc=com'.
superviserDN := 'uid=sw-sol,ou=Users,dc=shineglobal,dc=com'.

ldap := LDAP openOn: hostName port: 389.
ldap isNil ifTrue: [ File checkError. ObjectMemory quit: 1 ].
resultCode := ldap simpleBindWithDN: superviserDN passwd: 'tlinthcuhn'.
(resultCode > 0) ifTrue: [
        "Transcript showCr: ('%1 is result from bind' % { resultCode })."
        errorCodeMsg := LDAP errorString: resultCode.
        Transcript showCr: 'The LDAP Bind failed with the message: ',errorCodeMsg ].

(resultCode = 0) ifTrue: [
        Transcript showCr: '... about to run the search.'.
        resultCode := ldap searchWithBase: 'uid=stephenw,ou=Users,dc=shineglobal,dc=com'
          scope: 16r0000
          filter: '(objectclass=*)'
          attributes: nil
          isAttrsOnly: 0
          serverctrls: nil
          clientctrls: nil
          timeout: nil
          sizelimit: 0
          searchResult: (searchResult := LDAPMessage new).
        Transcript showCr: '... search completed'.

        (resultCode > 0) ifTrue: [
                "Transcript showCr: ('%1 is result from bind' % { resultCode })."
                errorCodeMsg := LDAP errorString: resultCode.
                Transcript showCr: 'The LDAP search failed with the message: ',errorCodeMsg ].

        entry := ldap firstEntry: searchResult.
        entry isNil ifFalse: [
                ('Found results with base DN: ', baseDN) displayNl.
                aPtr := ldap firstAttribute: entry ber: (ber := BER new).
                ('Found first attribute') displayNl.
                [ aPtr isNil ] whileFalse: [
                        attr := String fromCData: aPtr.
                        aPtr free.

                        vals := ldap getValues: entry attribute: attr.
                        vals isNull ifFalse: [
                                val := vals.
                                [ val value isNil ] whileFalse: [
                                        (attr->val value) printNl.
                                        val incr ].
                                "vals free. "
                        ].
                        vals isNull ifTrue: [
                                Transcript showCr: ('  **  Attribute %1 has null value.' % {attr}) ].
                        aPtr := ldap nextAttribute: entry ber: ber.
                ]
        ]
]



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

/* Adjust these setting for your own LDAP server */
#define HOSTNAME "192.168.0.1"
#define PORT_NUMBER  LDAP_PORT
#define FIND_DN "uid=myaccount,dc=example,dc=com"

int
main( int argc, const char * argv[] )
{
        LDAP         *ld;
        LDAPMessage  *result, *e;
        BerElement   *ber;
        char         *a;
        char         **vals;
        int          i, rc;
       
        /* Get a handle to an LDAP connection. */
        if ( (ld = ldap_init( HOSTNAME, PORT_NUMBER )) == NULL ) {
                perror( "ldap_init" );
                return( 1 );
        }
       
        /* Bind anonymously to the LDAP server. */
        rc = ldap_simple_bind_s( ld, NULL, NULL );
        if ( rc != LDAP_SUCCESS ) {
                fprintf(stderr, "ldap_simple_bind_s: %s\n", ldap_err2string(rc));
                return( 1 );
        }
       
        /* Search for the entry. */
        if ( ( rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
                                                                  "(objectclass=*)", NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
                                                                  LDAP_NO_LIMIT, &result ) ) != LDAP_SUCCESS ) {
                fprintf(stderr, "ldap_search_ext_s: %s\n", ldap_err2string(rc));
                return( 1 );
        }
       
        /* Since we are doing a base search, there should be only
     one matching entry. */
        e = ldap_first_entry( ld, result );
        if ( e != NULL ) {
                printf( "\nFound %s:\n\n", FIND_DN );
               
                /* Iterate through each attribute in the entry. */
                for ( a = ldap_first_attribute( ld, e, &ber );
                         a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
                       
                        /* For each attribute, print the attribute name and values. */
                        if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
                                for ( i = 0; vals[i] != NULL; i++ ) {
                                        printf( "%s: %s\n", a, vals[i] );
                                }
                                ldap_value_free( vals );
                        }
                        ldap_memfree( a );
                }
                if ( ber != NULL ) {
                        ber_free( ber, 0 );
                }
        }
        ldap_msgfree( result );
        ldap_unbind( ld );
        return( 0 );
}


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk

ldap.h.defines (20K) Download Attachment
Reply | Threaded
Open this post in threaded view
|

calling C API example using LDAP API

Stephen-71
In reply to this post by SeanTAllen
Sean Allen wrote:

>
> On Jan 15, 2009, at 3:49 PM, Paolo Bonzini wrote:
>
>>
>>> Is there anything that does this right now that I could use as an
>>> exemplar?
>>> Or should I just grep for #ptr #string and see what I find?
>>
>> There's something somewhere, but I'll just point you to the mailing list
>> archives.  Look for the exchanges I had with Stephen (Woolerton) about
>> his LDAP bindings.
>
> found those emails... having a hard time digesting...
>
> Stephen... do you any code related to dealing with char ** or anything
> similar,
> that I could take a look at.
>
> i'm going to try printing out the emails and cutting them up and pasting
> them together
> in a different order, hoping,  that might perhaps ease the absorbing of
> them.
>
>
> _______________________________________________
> help-smalltalk mailing list
> [hidden email]
> http://lists.gnu.org/mailman/listinfo/help-smalltalk
>
>

I've attached a copy of a working C program to do an LDAP lookup - this
is what we were working from; the blueprint so to speak. You should find
this helpful as you can see what the C program was doing and then how it
was implemented in GST.

The C program was compiled on OS X like so...
   cc -g -o ldaptest main.c /usr/lib/libldap.dylib
It is from the "Advanced OS X Programming" book by dalrymple and hillegrass

Secondly, attached is the working script for where we got to.. best to
run it on a 32 bit system, (there was an issue which Paolo fixed on some
not all 64 bit systems).

Also attached is the ldap.h file (from Linux).

I'm just about to head out the door and away for the weekend so by all
means send questions through but you mightn't get a reply for a while.

Regards
Stephen


#!/usr/local/bin/gst -f
"call LDAP API"

DLD addLibrary: 'libldap'.

  CObject extend [
        "Will be in 3.1"
        isNull [ ^self address = 0 ]
  ]

  UndefinedObject extend [
        isNull [ ^true ] ]

  CObject subclass: BER [
        " -----------------------
        LBER_F( void )
        ber_free LDAP_P((
                BerElement *ber,
                int freebuf ));
        ------------------------- "
      free [
        <cCall: 'ber_free' returning: #void args: #(#self #int)>
        ]
  ]

  CObject subclass: LDAPMessage [
      free [
        <cCall: 'ldap_msgfree' returning: #int args: #(#self)>
        ]
  ]

  CObject subclass: LDAP [
      "class variables"
      scopeBase := 0.
      nolimit := 0.

      LDAP class >> openOn: host port: port [
          "Maybe you prefer #open:port: as the selector, of course."
          <cCall: 'ldap_open' returning: #{LDAP} args: #(#string #int)>
      ]

      LDAP class >> on: host port: port [
          "Maybe you prefer #init:port: as the selector, of course."
          <cCall: 'ldap_init' returning: #{LDAP} args: #(#string #int)>
      ]

      LDAP class >> errorString: resultNum [
          "Utility methods might also go on the class side."
          <cCall: 'ldap_err2string' returning: #string args: #(#int)>
      ]

      simpleBindWithDN: who passwd: secret [
          <cCall: 'ldap_simple_bind_s' returning: #int args: #(#self #string #string)>
      ]

        " ldap_search_ext_s C definition --------------
        LDAP_F( int )
      ldap_search_ext_s LDAP_P((
        LDAP                    *ld,
        LDAP_CONST char *base,
        int                             scope,
        LDAP_CONST char *filter,
        char                    **attrs,
        int                             attrsonly,
        LDAPControl             **serverctrls,
        LDAPControl             **clientctrls,
        struct timeval  *timeout,
        int                             sizelimit,
        LDAPMessage             **res ));
        rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
    ""(objectclass=*)"", NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
    LDAP_NO_LIMIT, &result
                                        --------------- "
        "TODO: write a wrapper method which has less parameters and calls this one"
        searchWithBase: baseDN
          scope: aScope
          filter: aFilter
          attributes: theAttribs
          isAttrsOnly: attrsOnly
          serverctrls: serverControl
          clientctrls: clientControl
          timeout: timeval
          sizelimit: numResults
          searchResult: aSearchResult [
           <cCall: 'ldap_search_ext_s' returning: #int args: #(#self #string #int #string #cObject #int #cObject #cObject #cObject #int #cObjectPtr)>
        ]

        " ldap_first_entry C definition --------------
        LDAP_F( LDAPMessage * )
        ldap_first_entry LDAP_P((
                LDAP *ld,
                LDAPMessage *chain ));
                                        --------------"
        firstEntry: searchResult [
                <cCall: 'ldap_first_entry' returning: #cObject args: #(#self #cObject)> ]

        " -------------
        LDAP_F( char * )
        ldap_first_attribute LDAP_P((
                LDAP *ld,
                LDAPMessage *entry,
                BerElement **ber ));
                                -------------"
        firstAttribute: anEntry ber: aBer [
                <cCall: 'ldap_first_attribute' returning: #cObject args: #(#self #cObject #cObjectPtr)> ]

        " -------------
        LDAP_F( char * )
        ldap_next_attribute LDAP_P((
                LDAP *ld,
                LDAPMessage *entry,
                BerElement *ber ));
          -------------"
        nextAttribute: anEntry ber: aBer [
                <cCall: 'ldap_next_attribute' returning: #cObject args: #(#self #cObject #cObject)> ]

        " -------------
        #if LDAP_DEPRECATED
        LDAP_F( char ** )
        ldap_get_values LDAP_P((        /* deprecated, use ldap_get_values_len */
                LDAP *ld,
                LDAPMessage *entry,
                LDAP_CONST char *target ));
                                -------------"
        getValues: anEntry attribute: anAttribute [
                <cCall: 'ldap_get_values' returning: #{CString} args: #(#self #cObject #cObject)> ]

]

| ldapcall ldap resultCode resultCode2 errorMsg hostName baseDN |
Transcript showCr: 'started'.
hostName := '192.168.0.1'.
baseDN := 'ou=Users,dc=example,dc=com'.
superviserDN := 'uid=myacct,ou=Users,dc=example,dc=com'.

ldap := LDAP openOn: hostName port: 389.
ldap isNil ifTrue: [ File checkError. ObjectMemory quit: 1 ].
resultCode := ldap simpleBindWithDN: superviserDN passwd: 'passwordhere.
(resultCode > 0) ifTrue: [
        "Transcript showCr: ('%1 is result from bind' % { resultCode })."
        errorCodeMsg := LDAP errorString: resultCode.
        Transcript showCr: 'The LDAP Bind failed with the message: ',errorCodeMsg ].

(resultCode = 0) ifTrue: [
        Transcript showCr: '... about to run the search.'.
        resultCode := ldap searchWithBase: 'uid=user2,ou=Users,dc=example,dc=com'
          scope: 16r0000
          filter: '(objectclass=*)'
          attributes: nil
          isAttrsOnly: 0
          serverctrls: nil
          clientctrls: nil
          timeout: nil
          sizelimit: 0
          searchResult: (searchResult := LDAPMessage new).
        Transcript showCr: '... search completed'.

        (resultCode > 0) ifTrue: [
                "Transcript showCr: ('%1 is result from bind' % { resultCode })."
                errorCodeMsg := LDAP errorString: resultCode.
                Transcript showCr: 'The LDAP search failed with the message: ',errorCodeMsg ].

        entry := ldap firstEntry: searchResult.
        entry isNil ifFalse: [
                ('Found results with base DN: ', baseDN) displayNl.
                aPtr := ldap firstAttribute: entry ber: (ber := BER new).
                ('Found first attribute') displayNl.
                [ aPtr isNil ] whileFalse: [
                        attr := String fromCData: aPtr.
                        aPtr free.

                        vals := ldap getValues: entry attribute: attr.
                        vals isNull ifFalse: [
                                val := vals.
                                [ val value isNil ] whileFalse: [
                                        (attr->val value) printNl.
                                        val incr ].
                                "vals free. "
                        ].
                        vals isNull ifTrue: [
                                Transcript showCr: ('  **  Attribute %1 has null value.' % {attr}) ].
                        aPtr := ldap nextAttribute: entry ber: ber.
                ]
        ]
]



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

/* Adjust these setting for your own LDAP server */
#define HOSTNAME "192.168.0.1"
#define PORT_NUMBER  LDAP_PORT
#define FIND_DN "uid=myaccount,dc=example,dc=com"

int
main( int argc, const char * argv[] )
{
        LDAP         *ld;
        LDAPMessage  *result, *e;
        BerElement   *ber;
        char         *a;
        char         **vals;
        int          i, rc;
       
        /* Get a handle to an LDAP connection. */
        if ( (ld = ldap_init( HOSTNAME, PORT_NUMBER )) == NULL ) {
                perror( "ldap_init" );
                return( 1 );
        }
       
        /* Bind anonymously to the LDAP server. */
        rc = ldap_simple_bind_s( ld, NULL, NULL );
        if ( rc != LDAP_SUCCESS ) {
                fprintf(stderr, "ldap_simple_bind_s: %s\n", ldap_err2string(rc));
                return( 1 );
        }
       
        /* Search for the entry. */
        if ( ( rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
                                                                  "(objectclass=*)", NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
                                                                  LDAP_NO_LIMIT, &result ) ) != LDAP_SUCCESS ) {
                fprintf(stderr, "ldap_search_ext_s: %s\n", ldap_err2string(rc));
                return( 1 );
        }
       
        /* Since we are doing a base search, there should be only
     one matching entry. */
        e = ldap_first_entry( ld, result );
        if ( e != NULL ) {
                printf( "\nFound %s:\n\n", FIND_DN );
               
                /* Iterate through each attribute in the entry. */
                for ( a = ldap_first_attribute( ld, e, &ber );
                         a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
                       
                        /* For each attribute, print the attribute name and values. */
                        if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
                                for ( i = 0; vals[i] != NULL; i++ ) {
                                        printf( "%s: %s\n", a, vals[i] );
                                }
                                ldap_value_free( vals );
                        }
                        ldap_memfree( a );
                }
                if ( ber != NULL ) {
                        ber_free( ber, 0 );
                }
        }
        ldap_msgfree( result );
        ldap_unbind( ld );
        return( 0 );
}


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk

ldap.h.defines (20K) Download Attachment
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Mehul Sanghvi-2
In reply to this post by Stephen-71
Stephen said the following on 01/14/2009 10:15 PM:

> Mehul N. Sanghvi wrote:
>>
>> I would like to be able to get at all of the environment variables
>> (whether it is the shell environment variables or the CGI environment
>> variables or something else).  What object/class would I use for that ?
>>
>
> There is a way of getting it with an OS call...
>
> $ gst
> GNU Smalltalk ready
>
> st> | pipe |
> st> pipe := FileStream popen: 'set'  dir: FileStream read
> <Pipe on set>
> st> pipe contents
> 'AUTO_SYMLINK=no
> BASH=/bin/sh
> BASH_ARGC=()
> BASH_ARGV=()
> BASH_EXECUTION_STRING=set
> BASH_LINENO=()
> BASH_SOURCE=()
> ....
>
>
>
>
> In code, something like:
>     osCall: cmd [
>         | pipe |
>         pipe := FileStream popen: cmd dir: FileStream read.
>         ^pipe contents.
>     ]
>
>
> Then call it like:-
>
> Transcript show: (osCall: 'set').
> or
> Transcript show: (osCall: 'ls -l').
>
>
>
> Stephen
>


I am trying to use it in a CGI script and get the entire CGI environment.  The
above works, but it gives me the shell environment variables.  Two different
things.


cheers,

     mehul



_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Stephen-71

>
> I am trying to use it in a CGI script and get the entire CGI
> environment.  The above works, but it gives me the shell environment
> variables.  Two different things.
>
My understanding is that with CGI all the parameters are only available
to the process as environment variables. I googled a BASH script and a
Perl script, and then compared with the simple GST script below. When
run on Linux I can extract the same information with all three scripts.
Are you getting different results on your platform?

--------------------------
PERL demo CGI script
#!/usr/bin/perl
##
##  printenv -- demo CGI program which just prints its environment
##

print "Content-type: text/plain\n\n";
foreach $var (sort(keys(%ENV))) {
    $val = $ENV{$var};
    $val =~ s|\n|\\n|g;
    $val =~ s|"|\\"|g;
    print "${var}=\"${val}\"\n";
}

--------------------
GST demo CGI script

#!/usr/local/bin/gst -f

Transcript showCr: 'Content-type: text/plain'; nl.

cgivars := {'SERVER_SOFTWARE'. 'HTTP_ACCEPT'. 'HTTP_HOST'. 'REQUEST_URI' }.
cgivars do: [ :env |
    Transcript showCr: env,':',(Smalltalk getenv: env)].

Transcript nl; showCr: '==== All Env Vars below ==============';nl.
pipe := FileStream popen: ('set',logFile) dir: FileStream read.
Transcript showCr: pipe contents.
! !

Regards
Stephen




_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Mehul Sanghvi-2
Stephen said the following on 02/10/2009 06:55 AM:

>
>>
>> I am trying to use it in a CGI script and get the entire CGI
>> environment.  The above works, but it gives me the shell environment
>> variables.  Two different things.
>>
> My understanding is that with CGI all the parameters are only available
> to the process as environment variables. I googled a BASH script and a
> Perl script, and then compared with the simple GST script below. When
> run on Linux I can extract the same information with all three scripts.
> Are you getting different results on your platform?
>
> --------------------------
> PERL demo CGI script
> #!/usr/bin/perl
> ##
> ##  printenv -- demo CGI program which just prints its environment
> ##
>
> print "Content-type: text/plain\n\n";
> foreach $var (sort(keys(%ENV))) {
>    $val = $ENV{$var};
>    $val =~ s|\n|\\n|g;
>    $val =~ s|"|\\"|g;
>    print "${var}=\"${val}\"\n";
> }
>
> --------------------
> GST demo CGI script
>
> #!/usr/local/bin/gst -f
>
> Transcript showCr: 'Content-type: text/plain'; nl.
>
> cgivars := {'SERVER_SOFTWARE'. 'HTTP_ACCEPT'. 'HTTP_HOST'. 'REQUEST_URI' }.
> cgivars do: [ :env |
>    Transcript showCr: env,':',(Smalltalk getenv: env)].
>
> Transcript nl; showCr: '==== All Env Vars below ==============';nl.
> pipe := FileStream popen: ('set',logFile) dir: FileStream read.
> Transcript showCr: pipe contents.
> ! !
>
> Regards
> Stephen
>
>
>


====== PERL SCRIPT =======
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD><TITLE>Testing CGI/Perl</TITLE></HEAD>\n";
print "<BODY>\n";
print "<H2>Yo! Perl,   Whats up ? </H2>\n";

print "<tt>\n";
foreach $key (sort keys(%ENV)) {
     print "$key = $ENV{$key} <br>" ;
}

print "</BODY>\n";
print "</HTML>\n";


exit (o);

====== END PERL SCRIPT =====

====== PERL OUTPUT IN WEBPAGE =====
Yo! Perl, Whats up ?
CONTENT_LENGTH = 0
DOCUMENT_ROOT = /var/www/www.sanghvi.org//
GATEWAY_INTERFACE = CGI/1.1
HTTP_ACCEPT = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_CHARSET = ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_ACCEPT_ENCODING = gzip,deflate
HTTP_ACCEPT_LANGUAGE = en
HTTP_CONNECTION = keep-alive
HTTP_HOST = www.sanghvi.org
HTTP_KEEP_ALIVE = 300
HTTP_USER_AGENT = Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko
Galeon/2.0.6 (Debian 2.0.6-2+b1)
REDIRECT_STATUS = 200
REMOTE_ADDR = ::ffff:192.168.70.20
REMOTE_PORT = 54879
REQUEST_METHOD = GET
REQUEST_URI = /~mehul/test-cgi.pl
SCRIPT_FILENAME = /home/mehul/public_html/test-cgi.pl
SCRIPT_NAME = /~mehul/test-cgi.pl
SERVER_ADDR = ::
SERVER_NAME = www.sanghvi.org
SERVER_PORT = 80
SERVER_PROTOCOL = HTTP/1.1
SERVER_SOFTWARE = lighttpd/1.4.19
===== END PERL OUTPUT =====


===== SMALLTALK SCRIPT ====
Transcript showCr: 'Content-type: text/html'; nl .
'' displayNl .
'<HTML>' displayNl .
'<HEAD><TITLE>Testing CGI/Smalltalk</TITLE></HEAD>' displayNl .
'<BODY>' displayNl .
'<H2>Yo! Smalltalk,  Whats up ? </H2>' displayNl .

Transcript nl ; showCr: '==== All Env Vars below ====== <br>'; nl.
pipe := FileStream popen: ('set', logFile) dir: FileStream read .
Transcript showCr: pipe contents .

'</BODY>' displayNl .
'</HTML>' displayNl .
======== END SMALLTALK SCRIPT =======


======= SMALLTALK OUTPUT =======


Yo! Smalltalk, Whats up ?
==== All Env Vars below ======
BASH=/bin/sh BASH_ARGC=() BASH_ARGV=() BASH_EXECUTION_STRING=set BASH_LINENO=()
BASH_SOURCE=() BASH_VERSINFO=([0]="3" [1]="2" [2]="39" [3]="1" [4]="release"
[5]="powerpc-unknown-linux-gnu") BASH_VERSION='3.2.39(1)-release'
CONTENT_LENGTH=0 DIRSTACK=() DOCUMENT_ROOT=/var/www/www.sanghvi.org// EUID=33
GATEWAY_INTERFACE=CGI/1.1 GROUPS=() HOSTNAME=tatooine HOSTTYPE=powerpc
HTTP_ACCEPT='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
HTTP_ACCEPT_CHARSET='ISO-8859-1,utf-8;q=0.7,*;q=0.7'
HTTP_ACCEPT_ENCODING=gzip,deflate HTTP_ACCEPT_LANGUAGE=en
HTTP_CACHE_CONTROL=max-age=0 HTTP_CONNECTION=keep-alive
HTTP_HOST=www.sanghvi.org HTTP_KEEP_ALIVE=300 HTTP_USER_AGENT='Mozilla/5.0
(X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko Galeon/2.0.6 (Debian 2.0.6-2+b1)'
IFS=' ' MACHTYPE=powerpc-unknown-linux-gnu OPTERR=1 OPTIND=1 OSTYPE=linux-gnu
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
POSIXLY_CORRECT=y PPID=8315 PS4='+ ' PWD=/home/mehul/public_html
REDIRECT_STATUS=200 REMOTE_ADDR=::ffff:192.168.70.20 REMOTE_PORT=50171
REQUEST_METHOD=GET REQUEST_URI=/~mehul/test-cgi.st
SCRIPT_FILENAME=/home/mehul/public_html/test-cgi.st
SCRIPT_NAME=/~mehul/test-cgi.st SERVER_ADDR=:: SERVER_NAME=www.sanghvi.org
SERVER_PORT=80 SERVER_PROTOCOL=HTTP/1.1 SERVER_SOFTWARE=lighttpd/1.4.19
SHELL=/bin/sh SHELLOPTS=braceexpand:hashall:interactive-comments:posix SHLVL=1
TERM=dumb UID=33 _=sh

=======  END SMALLTALK SCRIPT ====


There are extra shell variables showing up like PATH, BASH, TERM, etc.  which
do not show up in a CGI environment using any other language that I've used to
write a similar CGI program (Perl, PHP, Lisp, Scheme, C, Tcl).  All of them
print out the same variables as the output of the Perl script.  What we seem to
  be doing in Smalltalk is forking/execing a shell and and then getting the
environment variables so that we end up with variables from a hybrid
environment of CGI and shell.

My platform is also Linux (Debian Testing).

cheers,

     mehul


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Paolo Bonzini-2

> There are extra shell variables showing up like PATH, BASH, TERM, etc.
> which do not show up in a CGI environment using any other language that
> I've used to write a similar CGI program (Perl, PHP, Lisp, Scheme, C,
> Tcl).  All of them print out the same variables as the output of the
> Perl script.  What we seem to  be doing in Smalltalk is forking/execing
> a shell and and then getting the environment variables so that we end up
> with variables from a hybrid environment of CGI and shell.

Yes, you're right that's suboptimal.

What is really needed is a package covering POSIX stuff, from
environment to process creation, in a nice object-oriented way.  Ideally
you could do something like

   redirections := SpawnParameters new
       stdin: (FileStream open: '/dev/null' mode: FileStream write);
       stdout: (FileStream newPipe: FileStream write);
       stderr: FileStream stderr;
       workingDirectory: '/'.
   process := redirections spawn: 'ls -lR'.
   s := [ process stdout readSide contents ] fork.
   process wait

Paolo


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

kaveman
CONTENTS DELETED
The author has deleted this message.
Reply | Threaded
Open this post in threaded view
|

Re: How to access environment variables ?

Paolo Bonzini-2
Krishna wrote:

> On Tue, Feb 10, 2009 at 7:41 PM, Paolo Bonzini <[hidden email]> wrote:
>>> There are extra shell variables showing up like PATH, BASH, TERM, etc.
>>> which do not show up in a CGI environment using any other language that
>>> I've used to write a similar CGI program (Perl, PHP, Lisp, Scheme, C,
>>> Tcl).  All of them print out the same variables as the output of the
>>> Perl script.  What we seem to  be doing in Smalltalk is forking/execing
>>> a shell and and then getting the environment variables so that we end up
>>> with variables from a hybrid environment of CGI and shell.
>
> why not call getenv(3) using the C interface?

He wants *all* the variables, not just one.

Paolo


_______________________________________________
help-smalltalk mailing list
[hidden email]
http://lists.gnu.org/mailman/listinfo/help-smalltalk
123