Advertisement
Guest User

Untitled

a guest
May 11th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.83 KB | None | 0 0
  1. //#include <iostream>
  2. //#include "base64.h"
  3. //#include "xmlParser.h"
  4. //
  5. //using namespace std;
  6. //
  7. //int main() {
  8. //  cout << base64_decode("dGVzdDp0ZXN0") << "\n";
  9. //  system("sleep 1");
  10. //}
  11.  
  12.  
  13. /***** inetserver.cpp *****/
  14. #include <iostream>
  15. #include <sstream>
  16. #include <stdio.h>
  17. #include <unistd.h>
  18. #include <stdlib.h>        /* for getenv */
  19. #include <sys/types.h>
  20. #include <sys/socket.h>
  21. #include <netinet/in.h>    /* Internet domain header */
  22. #include <ctype.h>
  23. #include <mysql.h>
  24. #include <mysql++/mysql++.h>
  25. //#include <result.h>
  26. //#include "xmlParse.h"
  27.  
  28. #include "base64.h"
  29.  
  30. #define SERVER_PORT  32650
  31. #define Debug 1
  32.  
  33. using namespace std;
  34. using namespace mysqlpp;
  35.  
  36. template <class T>
  37. inline std::string to_string (const T& t) {
  38.     std::stringstream ss;
  39.     ss << t;
  40.     return ss.str();
  41. }
  42.  
  43. void pingdb(Connection&); //fw declaration for connectdb
  44.  
  45. void connectdb(Connection& conn) {
  46.     // connect to mysql
  47.     // mysqlpp::Connection(const char *db, coregex.hnst char *server=0, const char *user=0, const char *password=0, unsigned int port=0)
  48.     try {
  49.         conn.connect("skalin01", "pdc-amd01.poly.edu", "skalin01", "p0344698");
  50.     } catch(Exception& e) {
  51.         // probably wrong db parameter, fail gracefully here.
  52.         // clean up, then
  53.         cerr << "Connection to DB interrupted - trying to reconnect\n";
  54.         pingdb(conn);
  55.     }
  56. }
  57.  
  58.  
  59. void pingdb(Connection& conn) {
  60.     // check connection & reconnect if disconnected
  61.     // conn.ping() returns a bool.
  62.     // retry until connectted again.
  63.     while(!conn.ping()) {
  64.         sleep(10);
  65.         connectdb(conn);
  66.     }
  67.  
  68. }
  69.  
  70. bool is_numeric(const char *p) {
  71.     if (*p) {
  72.         char c;
  73.         while ((c=*p++)) {
  74.             if (!isdigit(c)) return 0;
  75.         }
  76.         return true;
  77.     }
  78.     return false;
  79. }
  80.  
  81.  
  82.  
  83. struct sockaddr_in self = {AF_INET,
  84.     0
  85. };
  86. int main() {
  87.     // connect to mysql
  88.     // mysqlpp::Connection(const char *db, const char *server=0, const char *user=0, const char *password=0, unsigned int port=0)
  89.     mysqlpp::Connection conn(true);
  90.     try {
  91.         conn.connect("skalin01", "pdc-amd01.poly.edu", "skalin01", "p0344698");
  92.     } catch(Exception& e) {
  93.         // probably wrong db parameter, fail gracefully here.
  94.         // clean up, then
  95.         cerr << "Could not connect to DB to begin with!\nExiting.\n";
  96.         exit(1);
  97.     }
  98.  
  99.  
  100.  
  101.  
  102.  
  103.     int soc, ns, k;
  104.     char buf[1024];
  105.     struct sockaddr_in peer = {AF_INET};
  106.     self.sin_port = htons(SERVER_PORT);
  107.     socklen_t peer_len = sizeof(peer);
  108.     int val;
  109.  
  110.     /* set up listening socket soc */
  111.     soc = socket(AF_INET, SOCK_STREAM, 0);
  112.     if (soc < 0) {
  113.         perror("server:socket");
  114.         exit(1);
  115.     }
  116.     val = 1;
  117.     if (setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &val, sizeof val) != 0) {
  118.         perror("server:setsockopt");
  119.         exit(1);
  120.     }
  121.     if (bind(soc, (struct sockaddr *)&self, sizeof(self)) == -1) {
  122.         perror("server:bind");
  123.         close(soc);
  124.         exit(1);
  125.     }
  126.     listen(soc, 1);
  127.     /* accept connection request */
  128.     ns = accept(soc, (struct sockaddr *)&peer, &peer_len);
  129.     if (ns < 0) {
  130.         perror("server:accept");
  131.         close(soc);
  132.         exit(1);
  133.     }
  134.     /* data transfer on connected socket ns */
  135.     k = read(ns, buf, sizeof(buf) - 1);
  136.     buf[k] = '\0';          /* null-terminate string */
  137.  
  138.     //debug
  139.     //printf("SERVER RECEIVED: %s\n",buf);
  140.  
  141.     string buffer(buf);
  142.  
  143.  
  144.     int request_url_begin(buffer.find_first_of("T ")+2), request_url_end(buffer.find(" HTTP/1.1"));
  145.     //initialize request url
  146.     string request_url(buffer.substr(request_url_begin, request_url_end-request_url_begin));
  147.  
  148.     int page_begin(request_url.find_last_of("/")+1), page_end(request_url.find(".xml"));
  149.     string page_requested(request_url.substr(page_begin, page_end-page_begin));
  150.     string action_url(request_url.substr(0, page_begin-1));
  151.     int action_begin(action_url.find_last_of("/")+1), action_end(action_url.size());
  152.     string action(action_url.substr(action_begin, action_end-action_begin));
  153.  
  154.  
  155.     /*
  156.     now, --action-- is the directory the xml file resides in, and
  157.     --page_requsted-- is the xml file
  158.     */
  159.  
  160.     string replyToClient; //this is what we will send back
  161.  
  162.     //here come the if/else
  163.     if (page_requested == "register") {
  164.         //register the user here
  165.         int regline_begin(buffer.find("screen_name=")), regline_end(buffer.find_last_of("\r"));
  166.         string regline(buffer.substr(regline_begin, regline_end-regline_begin));
  167.         int screen_name_begin(regline.find_first_of("screen_name=")+12), screen_name_end(regline.find_first_of("&"));
  168.         string screen_name(regline.substr(screen_name_begin, screen_name_end-screen_name_begin));
  169.         int password_begin(regline.find("password=")+9), password_end(regline.size());
  170.         string password(regline.substr(password_begin, password_end-password_begin));
  171. #ifdef Debug
  172.         cout << "\nregline = " << regline << "\nscreen_name = " << screen_name << "; password = " << password << "\n";
  173. #endif
  174.         //MYSQL request here
  175.         //check if user exists
  176.         string sql("SELECT name FROM user WHERE name='" + screen_name + "'");
  177.         Query query = conn.query(sql);
  178. #ifdef Debug
  179.         cout << "\n\n\n"<< query << endl;
  180. #endif
  181.         StoreQueryResult checkuser = query.store();
  182. #ifdef Debug
  183.         cout << "numrows = " << checkuser << endl;
  184. #endif
  185.         int username_exist = checkuser.num_rows();
  186.  
  187.         if(username_exist > 0) {
  188.             //echo "The username you specified has already been taken. Please try again:\n\n";
  189.             //send error 403 to client, username taken
  190.             replyToClient = "HTTP/1.1 403 Forbidden\n";
  191.             replyToClient += "Content-Type: application/xml; charset=utf-8\n";
  192.             replyToClient += "Connection: close\r\n\r\n";
  193.             replyToClient += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  194.             replyToClient += "<hash>\n<request>";
  195.             replyToClient += request_url;
  196.             replyToClient += "</request>\n<error>The username you specified has already been taken.</error>\n</hash>\r\n\r\n";
  197.             //send reply
  198.             //debug
  199.             cout << replyToClient;
  200.         } else {
  201.             sql = "SELECT MAX(id) FROM user";
  202.             Query query = conn.query(sql);
  203.             UseQueryResult res = query.use();
  204.             Row row = res.fetch_row();
  205. #ifdef Debug
  206.             cout << "\nCurrent max id: " << row["MAX(id)"] << "\n";
  207. #endif
  208.             int next_id = row["MAX(id)"];
  209.             next_id++;
  210. #ifdef Debug
  211.             cout << "\nNext id: " << next_id << "\n";
  212. #endif
  213.             sql = "INSERT INTO user(id, name, password) VALUES('"+to_string(next_id)+"', '"+screen_name+"', SHA1('"+password+"'))";
  214. #ifdef Debug
  215.             cout << "\nQuery: " << sql << endl;
  216. #endif
  217.             while (query.more_results()) {
  218.                 query.store_next();
  219.             }
  220.  
  221.             query = conn.query(sql);
  222.             if(!query.exec()) {
  223.                 std::cerr << "Failed adding a user.\n" << std::endl;
  224.             }
  225.  
  226.  
  227.             replyToClient = "HTTP/1.1 201 Created\n";
  228.             replyToClient += "Content-Type: application/xml; charset=utf-8\n";
  229.             replyToClient += "Connection: close\r\n\r\n";
  230.             replyToClient += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  231.             replyToClient += "<user>\n<id>";
  232.             replyToClient += to_string(next_id);
  233.             replyToClient += "</id>\n<screen_name>";
  234.             replyToClient += screen_name;
  235.             replyToClient += "</screen_name>\n</user>\r\n\r\n";
  236.             //send reply
  237.             //debug
  238.             cout << replyToClient;
  239.         }
  240.  
  241.  
  242.     } else if (action == "create") {
  243.         //follow the friend
  244.         if (is_numeric(page_requested.c_str())) {
  245.             //it's a userid
  246.             //MYSQL request here
  247.  
  248.         } else {
  249.             //it's a username
  250.             //MYSQL request here
  251.         }
  252.     } else if (action == "statuses") {
  253.         if (page_requested == "followers") {
  254.             //show all the tweets of the user
  255.             int cursor_begin(request_url.find("cursor=")+7), cursor_end(request_url.size());
  256.             string cursor_str(request_url.substr(cursor_begin, cursor_end-cursor_begin));
  257.             int cursor(atoi(cursor_str.c_str()));
  258.             //MYSQL request here
  259.  
  260.             std::string sql = "SELECT id, name FROM user WHERE id = 1";
  261.             mysqlpp::Query query = conn.query(sql);
  262.             // this is mysqlpp version 3
  263.             if(mysqlpp::UseQueryResult res = query.use()) {
  264.                 // fetch one row
  265.                 while(mysqlpp::Row row = res.fetch_row()) {
  266.                     std::cout << "<user><user_id>" << row["id"] << "</user_id>"
  267.                               << "<screen_name>" << row["name"] << "</screen_name></user>";
  268.                 }
  269.  
  270.                 // Check for error: can't distinguish "end of results" and
  271.                 // error cases in return from fetch_row() otherwise.
  272.                 if(conn.errnum()) {
  273.                     std::cerr << "Error fetching a row: " << conn.error() << std::endl;
  274.                 }
  275.             } else {
  276.                 std::cerr << "Failed to query SQL: " << sql << std::endl;
  277.             }
  278.  
  279.         }
  280.     } else if (action == "user_timeline") {
  281.         //see all user's tweets
  282.         int count(10);
  283.         int count_begin(request_url.find("count=")+7), count_end(request_url.find("&"));
  284.         string count_str(request_url.substr(count_begin, count_end-count_begin));
  285.         if (!count_str.empty())
  286.             count = (atoi(count_str.c_str())); //set count
  287.         int since_id_begin(request_url.find("since_id=")+9), since_id_end(request_url.find("&"));
  288.         string since_id_str(request_url.substr(since_id_begin, since_id_end-since_id_begin));
  289.         int since_id(atoi(since_id_str.c_str()));
  290.         int max_id_begin(request_url.find("max_id=")+7), max_id_end(request_url.find("&"));
  291.         string max_id_str(request_url.substr(max_id_begin, max_id_end-max_id_begin));
  292.         int max_id(atoi(max_id_str.c_str()));
  293.         //by now, count, max_id and since_id are set
  294.  
  295.         if (is_numeric(page_requested.c_str())) {
  296.             //it's a userid
  297.             //MYSQL request here
  298.         } else {
  299.             //it's a username
  300.             //MYSQL request here
  301.         }
  302.  
  303.     } else if (action == "statuses") {
  304.         if (page_requested == "update") {
  305.             //post a tweet
  306.             int statline_begin(buffer.find("status=")), statline_end(buffer.find_last_of("\r"));
  307.             string statline(buffer.substr(statline_begin, statline_end-statline_begin));
  308.             int status_begin(statline.find_first_of("status=")+12), status_end(statline.find_first_of("&"));
  309.             string status(statline.substr(status_begin, status_end-status_begin));
  310.  
  311.         }
  312.     } else {
  313.         //can't understand what's going on, error 400
  314.     }
  315.  
  316.     //debug
  317. #ifdef Debug
  318.     cout << "url = " << request_url << "\n";
  319.     cout << "action = " << action << "; page_requested = " << page_requested << "\n\n";
  320. #endif
  321.  
  322.     /*
  323.     string get, login, host;
  324.     int auth_begin(buffer.find("Basic ")+6), auth_end(buffer.find("Host")-2);
  325.     string auth64(buffer.substr(auth_begin, auth_end-auth_begin));
  326.     cout << "\n\n" << base64_decode(auth64) << endl;
  327.     */
  328.  
  329.     /*replyToClient = "Testing testing 123321 wooooooooooooo.";
  330.     for (int i=0;i<=replyToClient.size();i++)
  331.         {
  332.             buf[i]=replyToClient[i];
  333.         }
  334.     cout << buf;
  335.     buf[sizeof(replyToClient)-1] = '\0';*/
  336.     int write_return = write(ns, replyToClient.c_str(), replyToClient.size()-1);
  337. #ifdef Debug
  338.     cout << "Write returned: " << write_return << endl;
  339. #endif
  340.     //write(ns, buf, k);
  341.     close(ns);
  342.     close(soc);
  343.     return(0);
  344. }
  345. /***** end of inetserver.c *****/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement