chat.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * This file is part of the Mongoose project, http://code.google.com/p/mongoose
  3. * It implements an online chat server. For more details,
  4. * see the documentation on the project web site.
  5. * To test the application,
  6. * 1. type "make" in the directory where this file lives
  7. * 2. point your browser to http://127.0.0.1:8081
  8. *
  9. * NOTE(lsm): this file follows Google style, not BSD style as the rest of
  10. * Mongoose code.
  11. */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #include <string.h>
  16. #include <time.h>
  17. #include <pthread.h>
  18. #include "mongoose.h"
  19. #define MAX_USER_LEN 20
  20. #define MAX_MESSAGE_LEN 100
  21. #define MAX_MESSAGES 5
  22. #define MAX_SESSIONS 2
  23. #define SESSION_TTL 120
  24. static const char *login_url = "/login.html";
  25. static const char *authorize_url = "/authorize";
  26. static const char *web_root = "./html";
  27. static const char *http_ports = "8081,8082s";
  28. static const char *ssl_certificate = "ssl_cert.pem";
  29. static const char *ajax_reply_start =
  30. "HTTP/1.1 200 OK\r\n"
  31. "Cache: no-cache\r\n"
  32. "Content-Type: application/x-javascript\r\n"
  33. "\r\n";
  34. // Describes single message sent to a chat. If user is empty (0 length),
  35. // the message is then originated from the server itself.
  36. struct message {
  37. long id; // Message ID
  38. char user[MAX_USER_LEN]; // User that have sent the message
  39. char text[MAX_MESSAGE_LEN]; // Message text
  40. time_t timestamp; // Message timestamp, UTC
  41. };
  42. // Describes web session.
  43. struct session {
  44. char session_id[33]; // Session ID, must be unique
  45. char random[20]; // Random data used for extra user validation
  46. char user[MAX_USER_LEN]; // Authenticated user
  47. time_t expire; // Expiration timestamp, UTC
  48. };
  49. static struct message messages[MAX_MESSAGES]; // Ringbuffer for messages
  50. static struct session sessions[MAX_SESSIONS]; // Current sessions
  51. static long last_message_id;
  52. // Protects messages, sessions, last_message_id
  53. static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
  54. // Get a get of messages with IDs greater than last_id and transform them
  55. // into a JSON string. Return that string to the caller. The string is
  56. // dynamically allocated, caller must free it. If there are no messages,
  57. // NULL is returned.
  58. static char *messages_to_json(long last_id) {
  59. const struct message *message;
  60. int max_msgs, len;
  61. char buf[sizeof(messages)]; // Large enough to hold all messages
  62. // Read-lock the ringbuffer. Loop over all messages, making a JSON string.
  63. pthread_rwlock_rdlock(&rwlock);
  64. len = 0;
  65. max_msgs = sizeof(messages) / sizeof(messages[0]);
  66. // If client is too far behind, return all messages.
  67. if (last_message_id - last_id > max_msgs) {
  68. last_id = last_message_id - max_msgs;
  69. }
  70. for (; last_id < last_message_id; last_id++) {
  71. message = &messages[last_id % max_msgs];
  72. if (message->timestamp == 0) {
  73. break;
  74. }
  75. // buf is allocated on stack and hopefully is large enough to hold all
  76. // messages (it may be too small if the ringbuffer is full and all
  77. // messages are large. in this case asserts will trigger).
  78. len += snprintf(buf + len, sizeof(buf) - len,
  79. "{user: '%s', text: '%s', timestamp: %lu, id: %lu},",
  80. message->user, message->text, message->timestamp, message->id);
  81. assert(len > 0);
  82. assert((size_t) len < sizeof(buf));
  83. }
  84. pthread_rwlock_unlock(&rwlock);
  85. return len == 0 ? NULL : strdup(buf);
  86. }
  87. // If "callback" param is present in query string, this is JSONP call.
  88. // Return 1 in this case, or 0 if "callback" is not specified.
  89. // Wrap an output in Javascript function call.
  90. static int handle_jsonp(struct mg_connection *conn,
  91. const struct mg_request_info *request_info) {
  92. char cb[64];
  93. mg_get_qsvar(request_info, "callback", cb, sizeof(cb));
  94. if (cb[0] != '\0') {
  95. mg_printf(conn, "%s(", cb);
  96. }
  97. return cb[0] == '\0' ? 0 : 1;
  98. }
  99. // A handler for the /ajax/get_messages endpoint.
  100. // Return a list of messages with ID greater than requested.
  101. static void ajax_get_messages(struct mg_connection *conn,
  102. const struct mg_request_info *request_info) {
  103. char last_id[32], *json;
  104. int is_jsonp;
  105. mg_printf(conn, "%s", ajax_reply_start);
  106. is_jsonp = handle_jsonp(conn, request_info);
  107. mg_get_qsvar(request_info, "last_id", last_id, sizeof(last_id));
  108. if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) {
  109. mg_printf(conn, "[%s]", json);
  110. free(json);
  111. }
  112. if (is_jsonp) {
  113. mg_printf(conn, "%s", ")");
  114. }
  115. }
  116. // A handler for the /ajax/send_message endpoint.
  117. static void ajax_send_message(struct mg_connection *conn,
  118. const struct mg_request_info *request_info) {
  119. struct message *message;
  120. char text[sizeof(message->text) - 1];
  121. int is_jsonp;
  122. mg_printf(conn, "%s", ajax_reply_start);
  123. is_jsonp = handle_jsonp(conn, request_info);
  124. (void) mg_get_qsvar(request_info, "text", text, sizeof(text));
  125. if (text[0] != '\0') {
  126. // We have a message to store. Write-lock the ringbuffer,
  127. // grab the next message and copy data into it.
  128. pthread_rwlock_wrlock(&rwlock);
  129. message = &messages[last_message_id %
  130. (sizeof(messages) / sizeof(messages[0]))];
  131. // TODO(lsm): JSON-encode all text strings
  132. strncpy(message->text, text, sizeof(text));
  133. strncpy(message->user, "joe", sizeof(message->user));
  134. message->timestamp = time(0);
  135. message->id = last_message_id++;
  136. pthread_rwlock_unlock(&rwlock);
  137. }
  138. mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true");
  139. if (is_jsonp) {
  140. mg_printf(conn, "%s", ")");
  141. }
  142. }
  143. // Redirect user to the login form. In the cookie, store the original URL
  144. // we came from, so that after the authorization we could redirect back.
  145. static void redirect_to_login(struct mg_connection *conn,
  146. const struct mg_request_info *request_info) {
  147. const char *host;
  148. host = mg_get_header(conn, "Host");
  149. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  150. "Set-Cookie: original_url=%s://%s%s\r\n"
  151. "Location: %s\r\n\r\n",
  152. request_info->is_ssl ? "https" : "http",
  153. host ? host : "127.0.0.1",
  154. request_info->uri,
  155. login_url);
  156. }
  157. // Return 1 if username/password is allowed, 0 otherwise.
  158. static int check_password(const char *user, const char *password) {
  159. // In production environment we should ask an authentication system
  160. // to authenticate the user.
  161. // Here however we do trivial check that user and password are not empty
  162. return (user[0] && password[0]);
  163. }
  164. // Allocate new session object
  165. static struct session *new_session(void) {
  166. int i;
  167. time_t now = time(NULL);
  168. pthread_rwlock_wrlock(&rwlock);
  169. for (i = 0; i < MAX_SESSIONS; i++) {
  170. if (sessions[i].expire == 0 || sessions[i].expire < now) {
  171. sessions[i].expire = time(0) + SESSION_TTL;
  172. break;
  173. }
  174. }
  175. pthread_rwlock_unlock(&rwlock);
  176. return i == MAX_SESSIONS ? NULL : &sessions[i];
  177. }
  178. // Generate session ID. buf must be 33 bytes in size.
  179. static void generate_session_id(char *buf, const char *random,
  180. const char *user, const struct mg_request_info *request_info) {
  181. char remote_ip[20], remote_port[20];
  182. snprintf(remote_ip, sizeof(remote_ip), "%ld", request_info->remote_ip);
  183. snprintf(remote_port, sizeof(remote_port), "%d", request_info->remote_port);
  184. mg_md5(buf, random, user, remote_port, remote_ip, NULL);
  185. }
  186. // A handler for the /authorize endpoint.
  187. // Login page form sends user name and password to this endpoint.
  188. static void authorize(struct mg_connection *conn,
  189. const struct mg_request_info *request_info) {
  190. char user[MAX_USER_LEN], password[MAX_USER_LEN], original_url[200];
  191. struct session *session;
  192. // Fetch user name and password.
  193. mg_get_qsvar(request_info, "user", user, sizeof(user));
  194. mg_get_qsvar(request_info, "password", password, sizeof(password));
  195. mg_get_cookie(conn, "original_url", original_url, sizeof(original_url));
  196. if (check_password(user, password) && (session = new_session()) != NULL) {
  197. // Authentication success:
  198. // 1. create new session
  199. // 2. set session ID token in the cookie
  200. // 3. remove original_url from the cookie - not needed anymore
  201. // 4. redirect client back to the original URL
  202. //
  203. // The most secure way is to stay HTTPS all the time. However, just to
  204. // show the technique, we redirect to HTTP after the successful
  205. // authentication. The danger of doing this is that session cookie can
  206. // be stolen and an attacker may impersonate the user.
  207. // Secure application must use HTTPS all the time.
  208. strlcpy(session->user, user, sizeof(session->user));
  209. snprintf(session->random, sizeof(session->random), "%d", rand());
  210. generate_session_id(session->session_id, session->random,
  211. session->user, request_info);
  212. printf("New session, user: %s, id: %s, redirecting to %s\n",
  213. session->user, session->session_id, original_url);
  214. mg_printf(conn, "HTTP/1.1 302 Found\r\n"
  215. "Set-Cookie: session=%s; max-age=3600; http-only\r\n" // Session ID
  216. "Set-Cookie: user=%s\r\n" // Set user, needed by Javascript code
  217. "Set-Cookie: original_url=/; max-age=0\r\n" // Delete original_url
  218. "Location: %s\r\n\r\n",
  219. session->session_id,
  220. session->user,
  221. original_url[0] == '\0' ? "/" : original_url);
  222. } else {
  223. // Authentication failure, redirect to login.
  224. redirect_to_login(conn, request_info);
  225. }
  226. }
  227. // Return 1 if request is authorized, 0 otherwise.
  228. static int is_authorized(const struct mg_connection *conn,
  229. const struct mg_request_info *request_info) {
  230. char valid_id[33], received_id[33];
  231. int i, authorized = 0;
  232. mg_get_cookie(conn, "session", received_id, sizeof(received_id));
  233. if (received_id[0] != '\0') {
  234. pthread_rwlock_rdlock(&rwlock);
  235. for (i = 0; i < MAX_SESSIONS; i++) {
  236. if (sessions[i].expire != 0 &&
  237. sessions[i].expire > time(NULL) &&
  238. strcmp(sessions[i].session_id, received_id) == 0) {
  239. break;
  240. }
  241. }
  242. if (i < MAX_SESSIONS) {
  243. generate_session_id(valid_id, sessions[i].random,
  244. sessions[i].user, request_info);
  245. if (strcmp(valid_id, received_id) == 0) {
  246. sessions[i].expire = time(0) + SESSION_TTL;
  247. authorized = 1;
  248. }
  249. }
  250. pthread_rwlock_unlock(&rwlock);
  251. }
  252. printf("session: %s, uri: %s, authorized: %s, cookie: %s\n",
  253. received_id, request_info->uri, authorized ? "yes" : "no", mg_get_header(conn, "Cookie"));
  254. return authorized;
  255. }
  256. // Return 1 if authorization is required for requested URL, 0 otherwise.
  257. static int must_authorize(const struct mg_request_info *request_info) {
  258. return (strcmp(request_info->uri, login_url) != 0 &&
  259. strcmp(request_info->uri, authorize_url) != 0);
  260. }
  261. static enum mg_error_t process_request(struct mg_connection *conn,
  262. const struct mg_request_info *request_info) {
  263. enum mg_error_t processed = MG_SUCCESS;
  264. if (must_authorize(request_info) &&
  265. !is_authorized(conn, request_info)) {
  266. // If user is not authorized, redirect to the login form.
  267. redirect_to_login(conn, request_info);
  268. } else if (strcmp(request_info->uri, authorize_url) == 0) {
  269. authorize(conn, request_info);
  270. } else if (strcmp(request_info->uri, "/ajax/get_messages") == 0) {
  271. ajax_get_messages(conn, request_info);
  272. } else if (strcmp(request_info->uri, "/ajax/send_message") == 0) {
  273. ajax_send_message(conn, request_info);
  274. } else {
  275. // No suitable handler found, mark as not processed. Mongoose will
  276. // try to serve the request.
  277. processed = MG_ERROR;
  278. }
  279. return processed;
  280. }
  281. int main(void) {
  282. struct mg_context *ctx;
  283. // Initialize random number generator. It will be used later on for
  284. // the session identifier creation.
  285. srand((unsigned) time(0));
  286. // Start and setup Mongoose
  287. ctx = mg_start();
  288. mg_set_option(ctx, "root", web_root);
  289. mg_set_option(ctx, "ssl_cert", ssl_certificate); // Must be set before ports
  290. mg_set_option(ctx, "ports", http_ports);
  291. mg_set_option(ctx, "dir_list", "no"); // Disable directory listing
  292. mg_set_callback(ctx, MG_EVENT_NEW_REQUEST, &process_request);
  293. // Wait until enter is pressed, then exit
  294. printf("Chat server started on ports %s, press enter to quit.\n", http_ports);
  295. getchar();
  296. mg_stop(ctx);
  297. printf("%s\n", "Chat server stopped.");
  298. return EXIT_SUCCESS;
  299. }
  300. // vim:ts=2:sw=2:et