chat.c 13 KB

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