3

--- config.h

extern char userurl[3];
char userurl[3];

--- index.c

include "config.h"

int main(int argc, char *argv[]) {  
    char *req_g="",*req_p="";

    get_arg("g=", &req_g, argc,argv);
    get_arg("p=", &req_p, argc,argv);

    strcat(userurl,req_g);
    strcat(userurl,req_p);
    ..

    xbuf_xcat(reply,"%s",userurl);
    ..

    return 200;
}

Then I used http://127.0.0.1:8080/?index&g=a&p=b

I reload multiple times and the results duplicate: userurl is not freed...

What's the proper way to declare extern or global variables for gwan?

Gil
  • 3,279
  • 1
  • 15
  • 25
stashfree
  • 655
  • 6
  • 22
  • Easy work around: initialize your variable. `userurl[0]='\0'` Also, your code is prone to buffer overflow attacks (and indeed userurl is overflowed) so take care about that. – Nagi Nov 22 '14 at 00:26

1 Answers1

0

Each G-WAN script is compiled separately. As a result, all your variables are static (local to this module) - you cannot share them without using pointers and atomic operations.

In order to ease the use of global variables, G-WAN provides persistent pointers (US_HANDLER_DATA, US_VHOST_DATA, or US_REQUEST_DATA):

void *pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA);
if(pVhost_persistent_ptr)
   printf("%.4s\n", pVhost_persistent_ptr);

// get a pointer on a pointer (to CHANGE the pointer value)
void **pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA);
if(pVhost_persistent_ptr)
   *pVhost_persistent_ptr = strdup("persistent data");

Several examples, like persistence.c or stream3.c illustrate how to proceed with real-life programs.

Gil
  • 3,279
  • 1
  • 15
  • 25
  • not looking for persistence across multiple instance calling in this case. I'm looking for global variable for that particular instance and hope that the instance's global variable is freed (gc) after each run – stashfree Nov 22 '14 at 21:43
  • Please define *"instance"*. The G-WAN persistent pointers are for one single G-WAN instance (but potentially concurrent script runs via several threads). If you need a variable to survive for the time of the request or connection then use **US_REQUEST_DATA** (and allocate the context with **gc_alloc()**). – Gil Nov 23 '14 at 13:45
  • I don't want the variable to survive for the time of the request or connection. I would like it to be "freed" upon client closing the connection. Is what Nagi suggested the proper way to go about it? – stashfree Nov 24 '14 at 08:35
  • 1
    Look at the stream[1,2,3].c example - they just do that (allocating a memory context with G-WAN's garbage collector to "alloc and forget"). – Gil Nov 24 '14 at 13:42