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.

87 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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. urlp->nparams = 0;
  16. short stage = 0; /* var to keep track of where we are in url */
  17. int counter = 0;
  18. while (*url != '\0' && *url != '\n') {
  19. switch (*url++) {
  20. case ':':
  21. counter++;
  22. if (stage == 0) {
  23. urlp->https = *(url - 2) == 's';
  24. if (*(url + 1) == '\0' || *url == '\0' || *url == '\n') /* weird stuff would happen with strings like "http:" */
  25. return NULL;
  26. url += 2; /* Skip the // after the :*/
  27. stage = 1;
  28. counter+=3;
  29. }
  30. break;
  31. case '?':
  32. if (stage == 1) {
  33. urlp->base =
  34. (char *)malloc(counter); /* +1 for the '\0' in the end */
  35. strncpy(urlp->base, url - counter, counter - 1);
  36. stage = 2;
  37. counter = 1;
  38. } else {
  39. return NULL;
  40. }
  41. break;
  42. case '=':
  43. if (stage == 2) {
  44. char *foo;
  45. foo = (char *)malloc(counter);
  46. strncpy(foo, url - counter, counter-1);
  47. counter = 1;
  48. if (urlp->params == NULL){
  49. urlp->params = linkedlistalloc();
  50. urlp->params->data = foo;
  51. }else
  52. urlp->params = linkedlistadd(urlp->params, foo);
  53. urlp->nparams++;
  54. while(*url != '&' && *url != '\0' && *url != '\n')
  55. url++;
  56. url++;
  57. }
  58. break;
  59. default:
  60. counter++;
  61. break;
  62. }
  63. }
  64. switch(stage){
  65. case 0:
  66. return NULL;
  67. break;
  68. case 1:
  69. urlp->base = (char *)malloc(counter); /* +1 for the '\0' in the end */
  70. strncpy(urlp->base, url - (counter-1), counter - 1);
  71. break;
  72. case 2:
  73. break;
  74. default:
  75. return NULL;
  76. }
  77. return urlp;
  78. }
  79. URL *urlalloc(void) { return (URL *)malloc(sizeof(URL)); }