basicauthentication.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if (0 != strcmp (method, "GET"))
  28. return MHD_NO;
  29. if (NULL == *con_cls)
  30. {
  31. *con_cls = connection;
  32. return MHD_YES;
  33. }
  34. pass = NULL;
  35. user = MHD_basic_auth_get_username_password (connection, &pass);
  36. fail = ( (user == NULL) ||
  37. (0 != strcmp (user, "root")) ||
  38. (0 != strcmp (pass, "pa$$w0rd") ) );
  39. if (user != NULL) free (user);
  40. if (pass != NULL) free (pass);
  41. if (fail)
  42. {
  43. const char *page = "<html><body>Go away.</body></html>";
  44. response =
  45. MHD_create_response_from_buffer (strlen (page), (void *) page,
  46. MHD_RESPMEM_PERSISTENT);
  47. ret = MHD_queue_basic_auth_fail_response (connection,
  48. "my realm",
  49. response);
  50. }
  51. else
  52. {
  53. const char *page = "<html><body>A secret.</body></html>";
  54. response =
  55. MHD_create_response_from_buffer (strlen (page), (void *) page,
  56. MHD_RESPMEM_PERSISTENT);
  57. ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  58. }
  59. MHD_destroy_response (response);
  60. return ret;
  61. }
  62. int
  63. main ()
  64. {
  65. struct MHD_Daemon *daemon;
  66. daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL,
  67. &answer_to_connection, NULL, MHD_OPTION_END);
  68. if (NULL == daemon)
  69. return 1;
  70. (void) getchar ();
  71. MHD_stop_daemon (daemon);
  72. return 0;
  73. }