chat.c 13 KB

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