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