chat.c 12 KB

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