summaryrefslogtreecommitdiff
path: root/content/fetchers/httplib_kolibri.c
blob: f9a0d953122150bcb49a0fc926c03f8273046a2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#include<libwapcaplet/libwapcaplet.h>
#include<stdlib.h>

#include "utils/url.h"
#include "utils/nsurl.h"
#include "utils/utils.h"
#include "utils/corestrings.h"
#include "utils/nsurl.h"
#include "utils/log.h"

#include "content/fetch.h"
#include "content/fetchers.h"
#include "content/fetchers/httplib_kolibri.h"
#include "frontends/kolibrios/kolibri_http.h"

extern struct fetch;

struct httpfetcher {
  struct http_msg *handle;
  struct fetch *owner;
  bool headercbdone;
  unsigned int datalen_cb_done;

  struct httpfetcher *next;
};

struct httpfetcher *head = NULL;

void add_to_poll(struct httpfetcher *newfetcher) {

  LOG("-=- add: newfetcher 0x%x, newfetcher->handle 0x%x", newfetcher, newfetcher->handle);

  struct httpfetcher *t = head;
  assert(newfetcher->next == NULL);

  if(head == NULL) {
    head = newfetcher;
    assert(head->next == NULL);
  }
  else {
    while(t->next != NULL) {
      t = t->next;
    }
    t->next = newfetcher;
  }
}

void remove_from_poll(struct http_msg *donehttp) {
  struct httpfetcher *t = head, *p = head;
  LOG("-=- remove: (->handle) donehttp 0x%x", donehttp);

  while(t) {
    if (t->handle == donehttp) {
      if(t == head) {
        p = t->next;
        head = p;
        break;
      }
      else {
        p->next = t->next;
        break;
      }
    }

  p = t;
  t = t->next;
  }  
}

bool init_fetcher(lwc_string *scheme) {
  bool supported_scheme; 
  assert(lwc_string_isequal(scheme, corestring_lwc_http, &supported_scheme) == lwc_error_ok);

  LOG("Initializing http library!");
  debug_board_printf("---- [NETSURF] Trying to initialize http library.\n");
  if(kolibri_http_init() == 0) {
    LOG("[INFO] Loaded http.obj library successfully.\n");
    debug_board_printf("---- [NETSURF] Successfully initialized http library.\n");
  }
  else {
    LOG("[ERROR] Could not load http.obj library.\n");
    debug_board_printf("---- [NETSURF] Could not initialize http library. Exiting.\n");
    assert(0 && 1);
    return false;
  }

  return supported_scheme;
}

bool supported_url_check(const struct nsurl *url) {
  bool supported;
  lwc_string *url_scheme = nsurl_get_component(url, NSURL_SCHEME);
  assert(lwc_string_isequal(url_scheme, corestring_lwc_http, &supported) == lwc_error_ok);
  lwc_string_unref(url_scheme);
  return supported;
}

void *setup_fetch(struct fetch *parent_fetch, struct nsurl *url,
               bool only_2xx, bool downgrade_tls, const char *post_urlenc,
               const struct fetch_multipart_data *post_multipart,
               const char **headers) {

  struct http_msg* request = NULL;

  LOG("[SETUP] Our target URL: %s", nsurl_access(url));
  LOG("[SETUP] POST urlencoded data: %s", post_urlenc);
  int i = 0;
  for(i = 0; headers[i] != NULL; i++)
    LOG("[SETUP] -- Headers : %s", headers[i]);


  if(post_multipart != NULL) {
    struct fetch_multipart_data *printer = post_multipart;
    while(printer != NULL) {
      LOG("Multipart POST : (%s = %s)\n", printer->name, printer->value);
      /* debug_board_printf("Multipart POST : (%s = %s)\n", printer->name, printer->value); */
      printer = printer->next;
    }

    LOG("[WARNING] We dont support POST multipart yet!\n");
    LOG("[NETSURF ERROR] We dont support POST multipart yet!\n");
    char *boundary = "--------Netsurf------------KolibriOS----Multipart----";
    int lenb = strlen(boundary);
    char *contenttype = "multipart/form-data; boundary=--------Netsurf------------KolibriOS----Multipart----";

    /* Intermediate boundaries have 2 additional dashes at the beginning */
    char *iboundary = "----------Netsurf------------KolibriOS----Multipart----";
    char *content = NULL;
    int contentlen = 0;

    printer = post_multipart;
    while(printer != NULL) {
      int leninc = strlen(iboundary) + 2 + strlen("Content-Disposition: form-data; name=") + 1 + strlen(printer->name) + 1 + 2 + 2 + strlen(printer->value) + 2;
      contentlen+=leninc;
      printer = printer -> next;
    }

    /* Space for last boundary (which has 2 empty boundary dashes) and CRLF */
    contentlen += strlen(iboundary) + 2 + 2;

    /* Space for terminating NULL */
    contentlen += 1;

    content = realloc(content, contentlen);

    char *tmp = content;
    /* debug_board_printf("Before Loop tmp = %u\n", tmp); */

    printer = post_multipart;
    while(printer != NULL) {
      int i = 0;
      strcpy(tmp, iboundary);
      tmp+=strlen(iboundary);

      /* debug_board_printf("tmp = %u\n", tmp); */

      *tmp++ = '\r';
      *tmp++ = '\n';

      /* debug_board_printf("tmp = %u\n", tmp); */

      strcpy(tmp, "Content-Disposition: form-data; name=\"");
      tmp+= strlen("Content-Disposition: form-data; name=\"");

      /* debug_board_printf("tmp = %u\n", tmp); */

      strcpy(tmp, printer->name);
      tmp += strlen(printer->name);

      /* debug_board_printf("tmp = %u\n", tmp); */

      *tmp++ = '"';
      *tmp++ = '\r';
      *tmp++ = '\n';
      *tmp++ = '\r';
      *tmp++ = '\n';

      /* debug_board_printf("tmp = %u\n", tmp); */

      strcpy(tmp, printer->value);
      tmp += strlen(printer->value);

      /* debug_board_printf("tmp = %u\n", tmp); */

      *tmp++ = '\r';
      *tmp++ = '\n';

      /* debug_board_printf("END OF LOOP tmp = %u\n", tmp); */

      printer = printer->next;
    }

    /* debug_board_printf("AFTER LOOP tmp = %u, content=%u\n", tmp, content); */

    strcpy(tmp, iboundary);
    tmp+=strlen(iboundary);

    strcpy(tmp, "--");
    tmp+=2;

    *tmp++ = '\r';
    *tmp++ = '\n';

    *tmp='\0';

    /* debug_board_printf("TERMINATING NULL tmp = %u\n", tmp); */

    LOG("Multipart request content length : %d", contentlen);
    LOG("Multipart request content: %s", content);

    request = http_post_asm(nsurl_access(url), NULL, 1<<8, *headers, contenttype, contentlen - 1);

    if(request != NULL) {
      int datasent = 0;
      /* debug_board_printf("--- Sending data : %s with length %u\n", content, contentlen); */
      /* LOG("--- Sending data : with length %u\n", contentlen); */
      datasent = http_send_asm(request, content, contentlen - 1);
      /* debug_board_printf("--- Sent %d bytes of data.\n", datasent); */
      LOG("--- Sent %d bytes of multipart post data.\n", datasent);
    }
  }
  else if(post_urlenc) {
    LOG("http_post: %s", nsurl_access(url));
    request = http_post_asm(nsurl_access(url), NULL, 0, *headers, "application/x-www-form-urlencoded", strlen(post_urlenc));
    if(request != NULL) {
      int datasent = 0;
      /* Send all the data here itself. Move this later to polling maybe. */
      /* debug_board_printf("--- Sending data : %s with length %u\n", post_urlenc, strlen(post_urlenc)); */
      datasent = http_send_asm(request, post_urlenc, strlen(post_urlenc));
      LOG("--- Sent %d bytes of urlencoded data.\n", datasent);
    }
  }
  else {
    /* Do a GET */
    LOG("http_get: %s", nsurl_access(url));
    request = http_get_asm(nsurl_access(url), NULL, 0, *headers);
  }

  if(request == NULL) {
    LOG("Failed to allocate http buffer. Could be multiple reasons for failure (like DNS resolution)", request);
    return NULL;
  }

  /* This assert is tricky beacause the http library may fail when it fails to resolve the hostname.
     There is no sane way to understand that the hostname is wrong or needs to be fixed.
     assert leads to a crash for no reason. Disabling it, and the code should handle this from now.
     Returning NuLL from here should just force a BadURL to the user.
  */

  struct httpfetcher *newfetcher = (struct httpfetcher *) malloc(sizeof(struct httpfetcher));
  assert(newfetcher);

  newfetcher->next = NULL;
  newfetcher->handle = request;
  newfetcher->headercbdone = false;
  newfetcher->owner = parent_fetch;
  newfetcher->datalen_cb_done = 0;

  return newfetcher;
}

bool start_fetch(void *httpf) {
  LOG("-=- start_fetch : httpf: 0x%x", httpf);

  add_to_poll((struct httpfetcher *) httpf);
  return true;
}

bool abort_fetch(void *httpf) {
  LOG("aborting fetch 0x%x", ((struct httpfetcher *)httpf)->owner);
  http_disconnect_asm(((struct httpfetcher *)httpf)->handle);
  remove_from_poll(((struct httpfetcher *) httpf)->handle);
  fetch_remove_from_queues(((struct httpfetcher *)httpf)->owner);
  /* fetch_free(((struct httpfetcher *)httpf)->owner); */
  return true;
}

bool free_fetch(void *httpf) {
  LOG("Freeing fetch 0x%x", ((struct httpfetcher *)httpf)->owner);
  http_free_asm((((struct httpfetcher *)httpf)->handle));
  free((struct httpfetcher *)httpf);

  return true;
}

void poll_fetch(lwc_string *scheme) {
  bool supported_scheme;
  assert(lwc_string_isequal(scheme, corestring_lwc_http, &supported_scheme) == lwc_error_ok);
  assert(supported_scheme);

  struct httpfetcher *t = head;

  while(t != NULL) {
    LOG("-- Polling for t 0x%x, http_msg 0x%x, fetch 0x%x [ hcbdone = %s ]", t, t->handle, t->owner, t->headercbdone == true ? "true" : "false");
    LOG("---  http_msg struct at : %x", t->handle);
    LOG("---  Header starts at : %x", &(t->handle->http_header));
    LOG("---  Header Length: %d", t->handle->header_length);
    LOG("---  Content starts at : %x", &(t->handle->content_ptr));
    LOG("---  Content Length (received / total): %d / %d", t->handle->content_received, t->handle->content_length);

    int ret = http_receive_asm(t->handle);

    if(t->handle->flags & HTTP_ERRORS) {
      fetch_msg msg;
      msg.type = FETCH_ERROR;
      LOG("---- [ERROR] http_msg -> flags = 0x%x", t->handle->flags);
      msg.data.header_or_data.buf = (const uint8_t *) "HTTPLIB ERROR";
      msg.data.header_or_data.len = strlen("HTTPLIB ERROR");
      fetch_send_callback(&msg, t->owner);
      t->headercbdone = true;
    }

    if(t->headercbdone == false) {
      if (t->handle->flags & HTTP_GOT_HEADER) {
        LOG("---- Received all HTTP Headers.");
        LOG("---- response status code = %d", t->handle->status);
        fetch_set_http_code(t->owner, t->handle->status);

        if(t->handle->status >= 200 && t->handle->status < 300) {
          fetch_msg msg;
          int plen = 0;
          char *ptr = &(t->handle->http_header);

          while(plen < t->handle->header_length) {
            int j = plen;

            for(;;j++) { 
              if(*(ptr + j) == '\r')
                break;
            }

            msg.type = FETCH_HEADER;
            msg.data.header_or_data.buf = (const uint8_t *)(ptr + plen);
            msg.data.header_or_data.len = j - plen;

            char *xx = (char *) malloc(j - plen + 1);
            strncpy(xx, ptr + plen, j-plen);
            xx[j-plen] = '\0';
            LOG("Headerline: %s", xx);
            fetch_send_callback(&msg, t->owner);
            free(xx);

            plen = j + 2;
          }

          t->headercbdone = true;
        }
        else if(t->handle->status >= 300 && t->handle->status < 400) {
          if(t->handle->status == 304) {
            fetch_msg msg;
            msg.type = FETCH_NOTMODIFIED;
            fetch_send_callback(&msg, t->owner);
            remove_from_poll(t->handle);
            /* t = t->next; */
            t = head;
            continue;
          }
          else {
            fetch_msg msg;
            int lenloc = 0;
            char *tmp = http_find_header_field_asm(t->handle, "location");
            while(!isspace(*(tmp + lenloc))) lenloc++;

            msg.type = FETCH_REDIRECT;
            char *newlocation = malloc(lenloc + 1);
            strncpy(newlocation, tmp, lenloc);
            newlocation[lenloc]='\0';
            msg.data.redirect = newlocation;

            LOG("---- [3xx] : Redirect to %s", msg.data.redirect);
            fetch_send_callback(&msg, t->owner);
            t->headercbdone = true;
            remove_from_poll(t->handle);
            /* t = t->next; */
            t = head;
            continue;
          }
        }
        else {
          fetch_msg msg;
          msg.type = FETCH_ERROR;
          LOG(" ---- [ERROR] Unhandled HTTP Code : %d", t->handle->status);
          fetch_send_callback(&msg, t->owner);
          t->headercbdone = true;
          remove_from_poll(t->handle);
          fetch_remove_from_queues(t->owner);
          /* fetch_free(t->owner); */
          /* t = t->next; */
          t = head;
          continue;
        }
      }
      else {
        LOG("---- Headers not received yet.");
      }
    }
    else if(ret == -1) {
      /* If data was received send it to netsurf core with FETCH_DATA */
      LOG("Doing a data callback; so far : %u vs %u!", t->datalen_cb_done, t->handle->content_received);

      if(t->handle->content_received > t->datalen_cb_done) {
        fetch_msg msg;
        msg.type = FETCH_DATA;
        msg.data.header_or_data.buf = (const uint8_t *) (t->handle->content_ptr + t->datalen_cb_done);
        msg.data.header_or_data.len = t->handle->content_received - t->datalen_cb_done;
        fetch_send_callback(&msg, t->owner);
        t->datalen_cb_done = t->handle->content_received;
      }
    }
    else if(ret == 0) {
      if(t->handle->content_received > t->datalen_cb_done) {
        /* Callback any remaining data before finishing off */
        fetch_msg msg;
        msg.type = FETCH_DATA;
        msg.data.header_or_data.buf = (const uint8_t *) (t->handle->content_ptr + t->datalen_cb_done);
        msg.data.header_or_data.len = t->handle->content_received - t->datalen_cb_done;
        fetch_send_callback(&msg, t->owner);
        t->datalen_cb_done = t->handle->content_received;
      }

      fetch_msg msg;

      msg.type = FETCH_FINISHED;
      msg.data.header_or_data.buf = NULL;
      msg.data.header_or_data.len = 0;
      fetch_send_callback(&msg, t->owner);
      LOG("---- FETCH_FINISHED for fetch 0x%x", t->owner);

      struct httpfetcher *tnext = t->next;
      remove_from_poll(t->handle);
      fetch_remove_from_queues(t->owner);
      /* fetch_free(t->owner); */
      t = head;
      /* t = tnext; */
      continue;
    }

    LOG("Main loop: t going from 0x%x to 0x%x", t->owner, t->next != NULL ? t->next->owner : NULL);
    t = t->next;
  }

  LOG("=Returning from %s", __func__);
}

void finalize_fetcher(lwc_string *scheme) {
  bool supported_scheme;
  assert(lwc_string_isequal(scheme, corestring_lwc_http, &supported_scheme) == lwc_error_ok);
  lwc_string_unref(scheme);
}

static struct fetcher_operation_table fetcher_ops = {
  .initialise = init_fetcher,
  .acceptable = supported_url_check,
  .setup = setup_fetch,
  .start = start_fetch,
  .abort = abort_fetch,
  .free = free_fetch,
  .poll = poll_fetch,
  .finalise = finalize_fetcher
};

nserror fetch_httplib_kolibri_register(void) {
    lwc_string *scheme = lwc_string_ref(corestring_lwc_http);
    return fetcher_add(scheme, &fetcher_ops);
}