You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.0 KiB

4 years ago
  1. /*
  2. * urlparse.c
  3. *
  4. * Created by Yigit Colakoglu on 07/06/2021.
  5. * Copyright yigit@yigitcolakoglu.com. 2021. All rights reserved.
  6. */
  7. #include "urlparse.h"
  8. #include "linkedlist.h"
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. URL *parseurl(char *url) {
  13. URL *urlp = urlalloc();
  14. urlp->params = NULL;
  15. short stage = 0; /* var to keep track of where we are in url */
  16. int counter = 0;
  17. while (*url != '\0' && *url != '\n') {
  18. switch (*url++) {
  19. case ':':
  20. if (stage == 0) {
  21. urlp->https = *(url - 2) == 's';
  22. if (*(url + 1) == '\0' || *url == '\0' || *url == '\n') /* weird stuff would happen with strings like "http:" */
  23. return NULL;
  24. url += 2; /* Skip the // after the :*/
  25. stage = 1;
  26. counter+=4;
  27. }
  28. break;
  29. case '?':
  30. if (stage == 1) {
  31. urlp->base =
  32. (char *)malloc(counter); /* +1 for the '\0' in the end */
  33. strncpy(urlp->base, url - counter, counter - 1);
  34. stage = 2;
  35. counter = 1;
  36. } else {
  37. return NULL;
  38. }
  39. break;
  40. case '=':
  41. if (stage == 2) {
  42. char *foo;
  43. foo = (char *)malloc(counter);
  44. strncpy(foo, url - counter, counter-1);
  45. counter = 1;
  46. if (urlp->params == NULL){
  47. urlp->params = linkedlistalloc();
  48. urlp->params->data = foo;
  49. }else
  50. urlp->params = linkedlistadd(urlp->params, foo);
  51. while(*url != '&' && *url != '\0' && *url != '\n')
  52. url++;
  53. url++;
  54. } else {
  55. return NULL;
  56. }
  57. break;
  58. default:
  59. counter++;
  60. break;
  61. }
  62. }
  63. switch(stage){
  64. case 0:
  65. return NULL;
  66. break;
  67. case 1:
  68. urlp->base = (char *)malloc(counter); /* +1 for the '\0' in the end */
  69. strncpy(urlp->base, url - (counter-1), counter - 1);
  70. break;
  71. case 2:
  72. break;
  73. default:
  74. return NULL;
  75. }
  76. return urlp;
  77. }
  78. URL *urlalloc(void) { return (URL *)malloc(sizeof(URL)); }