basicauthentication.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Feel free to use this example code in any way
  2. you see fit (Public Domain) */
  3. #include <sys/types.h>
  4. #ifndef _WIN32
  5. #include <sys/select.h>
  6. #include <sys/socket.h>
  7. #else
  8. #include <winsock2.h>
  9. #endif
  10. #include <microhttpd.h>
  11. #include <time.h>
  12. #include <string.h>
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #define PORT 8888
  16. static int
  17. answer_to_connection (void *cls, struct MHD_Connection *connection,
  18. const char *url, const char *method,
  19. const char *version, const char *upload_data,
  20. size_t *upload_data_size, void **con_cls)
  21. {
  22. char *user;
  23. char *pass;
  24. int fail;
  25. int ret;
  26. struct MHD_Response *response;
  27. (void)cls; /* Unused. Silent compiler warning. */
  28. (void)url; /* Unused. Silent compiler warning. */
  29. (void)version; /* Unused. Silent compiler warning. */
  30. (void)upload_data; /* Unused. Silent compiler warning. */
  31. (void)upload_data_size; /* Unused. Silent compiler warning. */
  32. if (0 != strcmp (method, "GET"))
  33. return MHD_NO;
  34. if (NULL == *con_cls)
  35. {
  36. *con_cls = connection;
  37. return MHD_YES;
  38. }
  39. pass = NULL;
  40. user = MHD_basic_auth_get_username_password (connection,
  41. &pass);
  42. fail = ( (NULL == user) ||
  43. (0 != strcmp (user, "root")) ||
  44. (0 != strcmp (pass, "pa$$w0rd") ) );
  45. if (NULL != user) MHD_free (user);
  46. if (NULL != pass) MHD_free (pass);
  47. if (fail)
  48. {
  49. const char *page = "<html><body>Go away.</body></html>";
  50. response =
  51. MHD_create_response_from_buffer (strlen (page), (void *) page,
  52. MHD_RESPMEM_PERSISTENT);
  53. ret = MHD_queue_basic_auth_fail_response (connection,
  54. "my realm",
  55. response);
  56. }
  57. else
  58. {
  59. const char *page = "<html><body>A secret.</body></html>";
  60. response =
  61. MHD_create_response_from_buffer (strlen (page), (void *) page,
  62. MHD_RESPMEM_PERSISTENT);
  63. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  64. }
  65. MHD_destroy_response (response);
  66. return ret;
  67. }
  68. int
  69. main (void)
  70. {
  71. struct MHD_Daemon *daemon;
  72. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
  73. &answer_to_connection, NULL, MHD_OPTION_END);
  74. if (NULL == daemon)
  75. return 1;
  76. (void) getchar ();
  77. MHD_stop_daemon (daemon);
  78. return 0;
  79. }