basicauthentication.c 1.8 KB

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