Debian Codegraph @

doc/examples/basicauthentication.c

raw
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 enum MHD_Result
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 **req_cls)
25 {
26 struct MHD_BasicAuthInfo *auth_info;
27 enum MHD_Result ret;
28 struct MHD_Response *response;
29 (void) cls; /* Unused. Silent compiler warning. */
30 (void) url; /* Unused. Silent compiler warning. */
31 (void) version; /* Unused. Silent compiler warning. */
32 (void) upload_data; /* Unused. Silent compiler warning. */
33 (void) upload_data_size; /* Unused. Silent compiler warning. */
34
35 if (0 != strcmp (method, "GET"))
36 return MHD_NO;
37 if (NULL == *req_cls)
38 {
39 *req_cls = connection;
40 return MHD_YES;
41 }
42 auth_info = MHD_basic_auth_get_username_password3 (connection);
43 if (NULL == auth_info)
44 {
45 static const char *page =
46 "<html><body>Authorization required</body></html>";
47 response = MHD_create_response_from_buffer_static (strlen (page), page);
48 ret = MHD_queue_basic_auth_required_response3 (connection,
49 "admins",
50 MHD_YES,
51 response);
52 }
53 else if ((strlen ("root") != auth_info->username_len) ||
54 (0 != memcmp (auth_info->username, "root",
55 auth_info->username_len)) ||
56 /* The next check against NULL is optional,
57 * if 'password' is NULL then 'password_len' is always zero. */
58 (NULL == auth_info->password) ||
59 (strlen ("pa$$w0rd") != auth_info->password_len) ||
60 (0 != memcmp (auth_info->password, "pa$$w0rd",
61 auth_info->password_len)))
62 {
63 static const char *page =
64 "<html><body>Wrong username or password</body></html>";
65 response = MHD_create_response_from_buffer_static (strlen (page), page);
66 ret = MHD_queue_basic_auth_required_response3 (connection,
67 "admins",
68 MHD_YES,
69 response);
70 }
71 else
72 {
73 static const char *page = "<html><body>A secret.</body></html>";
74 response = MHD_create_response_from_buffer_static (strlen (page), page);
75 ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
76 }
77 if (NULL != auth_info)
78 MHD_free (auth_info);
79 MHD_destroy_response (response);
80 return ret;
81 }
82
83
84 int
85 main (void)
86 {
87 struct MHD_Daemon *daemon;
88
89 daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
90 &answer_to_connection, NULL, MHD_OPTION_END);
91 if (NULL == daemon)
92 return 1;
93
94 (void) getchar ();
95
96 MHD_stop_daemon (daemon);
97 return 0;
98 }