basicauthentication.c 1.9 KB

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