/* request.c */ // This code is provided "as is" with NO WARRANTY expressed or // implied. You may use it freely at your own risk. #include char *action = "/darkspell/cgi-bin/request.cgi"; char *params[] = { "name=John Byrd", "game=Java One", "job=Java Two and three", "monkey=Perl", "what=this and that" }; const char *headerStuff = "HTTP/1.0\r\nContent-type: application/x-www-form-urlencode\r\nContent-length: "; void die(char *s) { printf("%s\n", s); exit(1); } char *getHost(char *host, int *port, char *arg) { char *p; p = (char *)strtok(arg, ":"); if (p == NULL) *port = 80; strcpy(host, p); p = (char *)strtok(NULL, " "); if (p) *port = atoi(p); return host; } char *urlEncode(char *s, char *param) { char *c; strcpy(s, param); c = s; while (*c != '\0') { if (*c == ' ') *c = '+'; c++; } return s; } char *formContent() { int i, len = 0; int numParams; char s[128]; char *newStr; numParams = sizeof(params) / sizeof(char *); for (i = 0; i< numParams; i++) len += strlen(urlEncode(s, params[i])); len += numParams; if ((newStr = (char *)malloc(len)) == NULL) die("Out of memory"); strcpy(newStr, urlEncode(s, params[0])); strcat(newStr, "&"); for (i=1; i< numParams; i++) { strcat(newStr, urlEncode(s, params[i])); strcat(newStr, "&"); } newStr[len-1] = '\0'; return newStr; } char *formRequest() { char *post; int len; char cLen[32]; char *protocol = "POST "; char *request; int i; post = formContent(); len = strlen(post); sprintf(cLen, "%d", len); len = 0; len += strlen(protocol); len += strlen(action) + 1; len += strlen(headerStuff); len += strlen(cLen) + 6; len += strlen(post); if ((request = (char *)malloc(len)) == NULL) die("Out of memory"); strcpy(request, protocol); strcat(request, action); strcat(request, " "); strcat(request, headerStuff); strcat(request, cLen); strcat(request, "\r\n\r\n"); strcat(request, post); strcat(request, "\r\n"); free(post); return request; }