basicauthentication.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 enum MHD_Result
  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. enum MHD_Result 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)
  46. MHD_free (user);
  47. if (NULL != pass)
  48. MHD_free (pass);
  49. if (fail)
  50. {
  51. const char *page = "<html><body>Go away.</body></html>";
  52. response =
  53. MHD_create_response_from_buffer (strlen (page), (void *) page,
  54. MHD_RESPMEM_PERSISTENT);
  55. ret = MHD_queue_basic_auth_fail_response (connection,
  56. "my realm",
  57. response);
  58. }
  59. else
  60. {
  61. const char *page = "<html><body>A secret.</body></html>";
  62. response =
  63. MHD_create_response_from_buffer (strlen (page), (void *) page,
  64. MHD_RESPMEM_PERSISTENT);
  65. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  66. }
  67. MHD_destroy_response (response);
  68. return ret;
  69. }
  70. int
  71. main (void)
  72. {
  73. struct MHD_Daemon *daemon;
  74. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
  75. &answer_to_connection, NULL, MHD_OPTION_END);
  76. if (NULL == daemon)
  77. return 1;
  78. (void) getchar ();
  79. MHD_stop_daemon (daemon);
  80. return 0;
  81. }