chat.c 14 KB

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