-/*\r
- * Acess2 IRC Client\r
- */\r
-#include <acess/sys.h>\r
-#include <stdlib.h>\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include <net.h>\r
-#include <readline.h>\r
-\r
-#define BUFSIZ 1023\r
-\r
-// === TYPES ===\r
-typedef struct sServer {\r
- struct sServer *Next;\r
- int FD;\r
- char InBuf[BUFSIZ+1];\r
- int ReadPos;\r
- char Name[];\r
-} tServer;\r
-\r
-typedef struct sMessage\r
-{\r
- struct sMessage *Next;\r
- time_t Timestamp;\r
- tServer *Server;\r
- int Type;\r
- char *Source; // Pointer into `Data`\r
- char Data[];\r
-} tMessage;\r
-\r
-typedef struct sWindow\r
-{\r
- struct sWindow *Next;\r
- tMessage *Messages;\r
- tServer *Server; //!< Canoical server (can be NULL)\r
- int ActivityLevel;\r
- char Name[]; // Channel name / remote user\r
-} tWindow;\r
-\r
-enum eMessageTypes\r
-{\r
- MSG_TYPE_NULL,\r
- MSG_TYPE_SERVER, // Server message\r
- \r
- MSG_TYPE_NOTICE, // NOTICE command\r
- MSG_TYPE_JOIN, // JOIN command\r
- MSG_TYPE_PART, // PART command\r
- MSG_TYPE_QUIT, // QUIT command\r
- \r
- MSG_TYPE_STANDARD, // Standard line\r
- MSG_TYPE_ACTION, // /me\r
- \r
- MSG_TYPE_UNK\r
-};\r
-\r
-// === PROTOTYPES ===\r
- int ParseArguments(int argc, const char *argv[]);\r
- int ParseUserCommand(char *String);\r
-// --- \r
-tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber);\r
-tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message);\r
-tWindow *Window_Create(tServer *Server, const char *Name);\r
-\r
- int ProcessIncoming(tServer *Server);\r
-// --- Helpers\r
- int SetCursorPos(int Row, int Col);\r
- int writef(int FD, const char *Format, ...);\r
- int OpenTCP(const char *AddressString, short PortNumber);\r
-char *GetValue(char *Str, int *Ofs);\r
-static inline int isdigit(int ch);\r
-\r
-// === GLOBALS ===\r
-char *gsUsername = "user";\r
-char *gsHostname = "acess";\r
-char *gsRealName = "Acess2 IRC Client";\r
-char *gsNickname = "acess";\r
-tServer *gpServers;\r
-tWindow gWindow_Status = {\r
- NULL, NULL, NULL, // No next, empty list, no server\r
- 0, "" // No activity, empty name (rendered as status)\r
-};\r
-tWindow *gpWindows = &gWindow_Status;\r
-tWindow *gpCurrentWindow = &gWindow_Status;\r
- int giTerminal_Width = 80;\r
- int giTerminal_Height = 25;\r
-\r
-// ==== CODE ====\r
-void ExitHandler(void)\r
-{\r
- printf("\x1B[?1047l");\r
-}\r
-\r
-int main(int argc, const char *argv[], const char *envp[])\r
-{\r
- int tmp;\r
- tReadline *readline_info;\r
- \r
- // Parse Command line\r
- if( (tmp = ParseArguments(argc, argv)) ) return tmp;\r
- \r
- atexit(ExitHandler);\r
- \r
- giTerminal_Width = ioctl(1, 5, NULL); // getset_width\r
- giTerminal_Height = ioctl(1, 6, NULL); // getset_height\r
- \r
- printf("\x1B[?1047h");\r
- printf("\x1B[%i;%ir", 0, giTerminal_Height-1);\r
- \r
- // HACK: Static server entry\r
- // UCC (University [of Western Australia] Computer Club) IRC Server\r
- gWindow_Status.Server = Server_Connect( "UCC", "130.95.13.18", 6667 );\r
- \r
- if( !gWindow_Status.Server )\r
- return -1;\r
- \r
- readline_info = Readline_Init(1);\r
- \r
- SetCursorPos(giTerminal_Height-1, 0);\r
- printf("[(status)] ");\r
- \r
- for( ;; )\r
- {\r
- fd_set readfds, errorfds;\r
- int rv, maxFD = 0;\r
- tServer *srv;\r
- \r
- FD_ZERO(&readfds);\r
- FD_ZERO(&errorfds);\r
- FD_SET(0, &readfds); // stdin\r
- \r
- // Fill server FDs in fd_set\r
- for( srv = gpServers; srv; srv = srv->Next )\r
- {\r
- FD_SET(srv->FD, &readfds);\r
- FD_SET(srv->FD, &errorfds);\r
- if( srv->FD > maxFD )\r
- maxFD = srv->FD;\r
- }\r
- \r
- rv = select(maxFD+1, &readfds, 0, &errorfds, NULL);\r
- if( rv == -1 ) break;\r
- \r
- if(FD_ISSET(0, &readfds))\r
- {\r
- // User input\r
- char *cmd = Readline_NonBlock(readline_info);\r
- if( cmd )\r
- {\r
- if( cmd[0] )\r
- {\r
- ParseUserCommand(cmd);\r
- }\r
- free(cmd);\r
- // Prompt\r
- SetCursorPos(giTerminal_Height-1, 0);\r
- if( gpCurrentWindow->Name[0] )\r
- printf("[%s:%s] ", gpCurrentWindow->Server->Name, gpCurrentWindow->Name);\r
- else\r
- printf("[(status)] ");\r
- }\r
- }\r
- \r
- // Server response\r
- for( srv = gpServers; srv; srv = srv->Next )\r
- {\r
- if(FD_ISSET(srv->FD, &readfds))\r
- {\r
- if( ProcessIncoming(srv) != 0 ) {\r
- // Oops, error\r
- break;\r
- }\r
- }\r
- \r
- if(FD_ISSET(srv->FD, &errorfds))\r
- {\r
- break;\r
- }\r
- }\r
- \r
- // Oops, an error\r
- if( srv ) break;\r
- }\r
- \r
- {\r
- tServer *srv;\r
- for( srv = gpServers; srv; srv = srv->Next )\r
- close(srv->FD);\r
- }\r
- return 0;\r
-}\r
-\r
-/**\r
- * \todo Actually implement correctly :)\r
- */\r
-int ParseArguments(int argc, const char *argv[])\r
-{\r
- return 0;\r
-}\r
-\r
-int ParseUserCommand(char *String)\r
-{\r
- if( String[0] == '/' )\r
- {\r
- char *command;\r
- int pos = 0;\r
- \r
- command = GetValue(String, &pos);\r
- \r
- if( strcmp(command, "/join") == 0 )\r
- {\r
- char *channel_name = GetValue(String, &pos);\r
- \r
- if( gpCurrentWindow->Server )\r
- {\r
- writef(gpCurrentWindow->Server->FD, "JOIN :%s\n", channel_name);\r
- }\r
- }\r
- else if( strcmp(command, "/quit") == 0 )\r
- {\r
- char *quit_message = GetValue(String, &pos);\r
- tServer *srv;\r
- \r
- if( quit_message == NULL || quit_message[0] == '\0' )\r
- quit_message = "/quit - Acess2 IRC Client";\r
- \r
- for( srv = gpServers; srv; srv = srv->Next )\r
- {\r
- writef(srv->FD, "QUIT :%s\n", quit_message);\r
- }\r
- \r
- exit(0);\r
- }\r
- else if( strcmp(command, "/window") == 0 || strcmp(command, "/win") == 0 || strcmp(command, "/w") == 0 )\r
- {\r
- char *window_id = GetValue(String, &pos);\r
- int window_num = atoi(window_id);\r
- \r
- if( window_num > 0 )\r
- {\r
- tWindow *win;\r
- window_num --; // Move to base 0\r
- // Get `window_num`th window\r
- for( win = gpWindows; win && window_num--; win = win->Next );\r
- if( win ) {\r
- gpCurrentWindow = win;\r
- }\r
- // Otherwise, silently ignore\r
- }\r
- else\r
- {\r
- tWindow *win;\r
- window_num = 1;\r
- for( win = gpWindows; win; win = win->Next, window_num ++ )\r
- {\r
- char tmp[snprintf(NULL, 1000, "%i: %s/%s", window_num, win->Server->Name, win->Name)+1];\r
- snprintf(tmp, 1000, "%i: %s/%s", window_num, win->Server->Name, win->Name);\r
- Message_Append(NULL, MSG_TYPE_SERVER, "client", "", tmp);\r
- }\r
- }\r
- }\r
- else\r
- {\r
- int len = snprintf(NULL, 0, "Unknown command %s", command);\r
- char buf[len+1];\r
- snprintf(buf, len+1, "Unknown command %s", command);\r
- Message_Append(NULL, MSG_TYPE_SERVER, "client", "", buf);\r
- }\r
- }\r
- else\r
- {\r
- // Message\r
- // - Only send if server is valid and window name is non-empty\r
- if( gpCurrentWindow->Server && gpCurrentWindow->Name[0] )\r
- {\r
- writef(gpCurrentWindow->Server->FD,\r
- "PRIVMSG %s :%s\n", gpCurrentWindow->Name,\r
- String\r
- );\r
- }\r
- }\r
- \r
- return 0;\r
-}\r
-\r
-/**\r
- * \brief Connect to a server\r
- */\r
-tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber)\r
-{\r
- tServer *ret;\r
- \r
- ret = calloc(1, sizeof(tServer) + strlen(Name) + 1);\r
- \r
- strcpy(ret->Name, Name);\r
- \r
- // Connect to the remove server\r
- ret->FD = OpenTCP( AddressString, PortNumber );\r
- if( ret->FD == -1 ) {\r
- fprintf(stderr, "%s: Unable to create socket\n", Name);\r
- return NULL;\r
- }\r
- \r
- // Append to open list\r
- ret->Next = gpServers;\r
- gpServers = ret;\r
- \r
- // Read some initial data\r
- printf("%s: Connection opened\n", Name);\r
- ProcessIncoming(ret);\r
- \r
- // Identify\r
- writef(ret->FD, "USER %s %s %s : %s\n", gsUsername, gsHostname, AddressString, gsRealName);\r
- writef(ret->FD, "NICK %s\n", gsNickname);\r
- printf("%s: Identified\n", Name);\r
- \r
- return ret;\r
-}\r
-\r
-tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message)\r
-{\r
- tMessage *ret;\r
- tWindow *win = NULL;\r
- int msgLen = strlen(Message);\r
- \r
- // NULL servers are internal messages\r
- if( Server == NULL )\r
- {\r
- win = &gWindow_Status;\r
- }\r
- // Determine if it's a channel or PM message\r
- else if( Dest[0] == '#' || Dest[0] == '&' ) // TODO: Better determining here\r
- {\r
- tWindow *prev = NULL;\r
- for(win = gpWindows; win; prev = win, win = win->Next)\r
- {\r
- if( win->Server == Server && strcmp(win->Name, Dest) == 0 )\r
- {\r
- break;\r
- }\r
- }\r
- if( !win ) {\r
- win = Window_Create(Server, Dest);\r
- }\r
- }\r
- #if 0\r
- else if( strcmp(Dest, Server->Nick) != 0 )\r
- {\r
- // Umm... message for someone who isn't us?\r
- win = &gWindow_Status; // Stick it in the status window, just in case\r
- }\r
- #endif\r
- // Server message?\r
- else if( strchr(Source, '.') ) // TODO: And again, less hack please\r
- {\r
- #if 1\r
- for(win = gpWindows; win; win = win->Next)\r
- {\r
- if( win->Server == Server && strcmp(win->Name, Source) == 0 )\r
- {\r
- break;\r
- }\r
- }\r
- #endif\r
- if( !win ) {\r
- win = &gWindow_Status;\r
- }\r
- \r
- }\r
- // Private message\r
- else\r
- {\r
- for(win = gpWindows; win; win = win->Next)\r
- {\r
- if( win->Server == Server && strcmp(win->Name, Source) == 0 )\r
- {\r
- break;\r
- }\r
- }\r
- if( !win ) {\r
- win = Window_Create(Server, Dest);\r
- }\r
- }\r
- \r
- ret = malloc( sizeof(tMessage) + msgLen + 1 + strlen(Source) + 1 );\r
- ret->Source = ret->Data + msgLen + 1;\r
- strcpy(ret->Source, Source);\r
- strcpy(ret->Data, Message);\r
- ret->Type = Type;\r
- ret->Server = Server;\r
- \r
- // TODO: Append to window message list\r
- ret->Next = win->Messages;\r
- win->Messages = ret;\r
- \r
- //TODO: Set location\r
- \r
- #if 1\r
- if( win == gpCurrentWindow ) {\r
- int pos = SetCursorPos(giTerminal_Height-2, 0);\r
- printf("\x1B[S"); // Scroll up 1\r
- printf("[%s] %s\n", Source, Message);\r
- SetCursorPos(-1, pos);\r
- }\r
- #else\r
- if(win->Name[0])\r
- printf("%s/%s [%s] %s\n", win->Server->Name, win->Name, Source, Message);\r
- else\r
- printf("(status) [%s] %s\n", Source, Message);\r
- #endif\r
- \r
- return ret;\r
-}\r
-\r
-tWindow *Window_Create(tServer *Server, const char *Name)\r
-{\r
- tWindow *ret, *prev = NULL;\r
- int num = 1;\r
- \r
- // Get the end of the list\r
- // TODO: Cache this instead\r
- for( ret = gpCurrentWindow; ret; prev = ret, ret = ret->Next )\r
- num ++;\r
- \r
- ret = malloc(sizeof(tWindow) + strlen(Name) + 1);\r
- ret->Messages = NULL;\r
- ret->Server = Server;\r
- ret->ActivityLevel = 1;\r
- strcpy(ret->Name, Name);\r
- \r
- if( prev ) {\r
- ret->Next = prev->Next;\r
- prev->Next = ret;\r
- }\r
- else { // Shouldn't happen really\r
- ret->Next = gpWindows;\r
- gpWindows = ret;\r
- }\r
- \r
-// printf("Win %i %s:%s created\n", num, Server->Name, Name);\r
- \r
- return ret;\r
-}\r
-\r
-void Cmd_PRIVMSG(tServer *Server, const char *Dest, const char *Src, const char *Message)\r
-{\r
- Message_Append(Server, MSG_TYPE_STANDARD, Dest, Src, Message);\r
- //printf("<%s:%s:%s> %s\n", Server->Name, Dest, Src, Message);\r
-}\r
-\r
-/**\r
- */\r
-void ParseServerLine(tServer *Server, char *Line)\r
-{\r
- int pos = 0;\r
- char *ident, *cmd;\r
- \r
- // Message?\r
- if( *Line == ':' )\r
- {\r
- ident = GetValue(Line, &pos); // Ident (user or server)\r
- cmd = GetValue(Line, &pos);\r
- \r
- // Numeric command\r
- if( isdigit(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2]) )\r
- {\r
- char *user, *message;\r
- int num;\r
- num = (cmd[0] - '0') * 100;\r
- num += (cmd[1] - '0') * 10;\r
- num += (cmd[2] - '0') * 1;\r
- \r
- user = GetValue(Line, &pos);\r
- \r
- if( Line[pos] == ':' ) {\r
- message = Line + pos + 1;\r
- }\r
- else {\r
- message = GetValue(Line, &pos);\r
- }\r
- \r
- switch(num)\r
- {\r
- default:\r
- //printf("[%s] %i %s\n", Server->Name, num, message);\r
- Message_Append(Server, MSG_TYPE_SERVER, ident, user, message);\r
- break;\r
- }\r
- }\r
- else if( strcmp(cmd, "NOTICE") == 0 )\r
- {\r
- char *class, *message;\r
- \r
- class = GetValue(Line, &pos);\r
- \r
- if( Line[pos] == ':' ) {\r
- message = Line + pos + 1;\r
- }\r
- else {\r
- message = GetValue(Line, &pos);\r
- }\r
- \r
- //printf("[%s] NOTICE %s: %s\n", Server->Name, ident, message);\r
- Message_Append(Server, MSG_TYPE_NOTICE, ident, "", message);\r
- }\r
- else if( strcmp(cmd, "PRIVMSG") == 0 )\r
- {\r
- char *dest, *message;\r
- dest = GetValue(Line, &pos);\r
- \r
- if( Line[pos] == ':' ) {\r
- message = Line + pos + 1;\r
- }\r
- else {\r
- message = GetValue(Line, &pos);\r
- }\r
- Cmd_PRIVMSG(Server, dest, ident, message);\r
- Message_Append(Server, MSG_TYPE_STANDARD, ident, dest, message);\r
- }\r
- else if( strcmp(cmd, "JOIN" ) == 0 )\r
- {\r
- char *channel;\r
- channel = GetValue(Line, &pos) + 1;\r
- Window_Create(Server, channel);\r
- }\r
- else\r
- {\r
- printf("Unknown message %s (%s)\n", cmd, Line+pos);\r
- }\r
- }\r
- else {\r
- \r
- // Command to client\r
- printf("Client Command: %s", Line);\r
- }\r
-}\r
-\r
-/**\r
- * \brief Process incoming lines from the server\r
- */\r
-int ProcessIncoming(tServer *Server)\r
-{ \r
- char *ptr, *newline;\r
- int len;\r
- \r
- // While there is data in the buffer, read it into user memory and \r
- // process it line by line\r
- // ioctl#8 on a TCP client gets the number of bytes in the recieve buffer\r
- // - Used to avoid blocking\r
- #if NON_BLOCK_READ\r
- while( (len = ioctl(Server->FD, 8, NULL)) > 0 )\r
- {\r
- #endif\r
- // Read data\r
- len = read(Server->FD, BUFSIZ - Server->ReadPos, &Server->InBuf[Server->ReadPos]);\r
- if( len == -1 ) {\r
- return -1;\r
- }\r
- Server->InBuf[Server->ReadPos + len] = '\0';\r
- \r
- // Break into lines\r
- ptr = Server->InBuf;\r
- while( (newline = strchr(ptr, '\n')) )\r
- {\r
- *newline = '\0';\r
- if( newline[-1] == '\r' ) newline[-1] = '\0';\r
- ParseServerLine(Server, ptr);\r
- ptr = newline + 1;\r
- }\r
- \r
- // Handle incomplete lines\r
- if( ptr - Server->InBuf < len + Server->ReadPos ) {\r
- // Update the read position\r
- // InBuf ReadPos ptr ReadPos+len\r
- // | old | new used | new unused |\r
- Server->ReadPos = len + Server->ReadPos - (ptr - Server->InBuf);\r
- // Copy stuff back (moving "new unused" to the start of the buffer)\r
- memcpy(Server->InBuf, ptr, Server->ReadPos);\r
- }\r
- else {\r
- Server->ReadPos = 0;\r
- }\r
- #if NON_BLOCK_READ\r
- }\r
- #endif\r
- \r
- return 0;\r
-}\r
-\r
-/**\r
- * \brief Write a formatted string to a file descriptor\r
- * \r
- */\r
-int writef(int FD, const char *Format, ...)\r
-{\r
- va_list args;\r
- int len;\r
- \r
- va_start(args, Format);\r
- len = vsnprintf(NULL, 1000, Format, args);\r
- va_end(args);\r
- \r
- {\r
- char buf[len+1];\r
- va_start(args, Format);\r
- vsnprintf(buf, len+1, Format, args);\r
- va_end(args);\r
- \r
- return write(FD, len, buf);\r
- }\r
-}\r
-\r
-/**\r
- * \brief Initialise a TCP connection to \a AddressString on port \a PortNumber\r
- */\r
-int OpenTCP(const char *AddressString, short PortNumber)\r
-{\r
- int fd, addrType;\r
- char *iface;\r
- char addrBuffer[8];\r
- \r
- // Parse IP Address\r
- addrType = Net_ParseAddress(AddressString, addrBuffer);\r
- if( addrType == 0 ) {\r
- fprintf(stderr, "Unable to parse '%s' as an IP address\n", AddressString);\r
- return -1;\r
- }\r
- \r
- // Finds the interface for the destination address\r
- iface = Net_GetInterface(addrType, addrBuffer);\r
- if( iface == NULL ) {\r
- fprintf(stderr, "Unable to find a route to '%s'\n", AddressString);\r
- return -1;\r
- }\r
- \r
- printf("iface = '%s'\n", iface);\r
- \r
- // Open client socket\r
- // TODO: Move this out to libnet?\r
- {\r
- int len = snprintf(NULL, 100, "/Devices/ip/%s/tcpc", iface);\r
- char path[len+1];\r
- snprintf(path, 100, "/Devices/ip/%s/tcpc", iface);\r
- fd = open(path, OPENFLAG_READ|OPENFLAG_WRITE);\r
- }\r
- \r
- free(iface);\r
- \r
- if( fd == -1 ) {\r
- fprintf(stderr, "Unable to open TCP Client for reading\n");\r
- return -1;\r
- }\r
- \r
- // Set remote port and address\r
- printf("Setting port and remote address\n");\r
- ioctl(fd, 5, &PortNumber);\r
- ioctl(fd, 6, addrBuffer);\r
- \r
- // Connect\r
- printf("Initiating connection\n");\r
- if( ioctl(fd, 7, NULL) == 0 ) {\r
- // Shouldn't happen :(\r
- fprintf(stderr, "Unable to start connection\n");\r
- return -1;\r
- }\r
- \r
- // Return descriptor\r
- return fd;\r
-}\r
-\r
-/**\r
- * \brief Read a space-separated value from a string\r
- */\r
-char *GetValue(char *Src, int *Ofs)\r
-{\r
- int pos = *Ofs;\r
- char *ret = Src + pos;\r
- char *end;\r
- \r
- if( !Src ) return NULL;\r
- \r
- while( *ret == ' ' ) ret ++;\r
- \r
- end = strchr(ret, ' ');\r
- if( end ) {\r
- *end = '\0';\r
- }\r
- else {\r
- end = ret + strlen(ret) - 1;\r
- }\r
- \r
- end ++ ;\r
- while( *ret == ' ' ) end ++;\r
- *Ofs = end - Src;\r
- \r
- return ret;\r
-}\r
-\r
-int SetCursorPos(int Row, int Col)\r
-{\r
- if( Row == -1 ) {\r
- Row = Col / giTerminal_Width;\r
- Col = Col % giTerminal_Width;\r
- }\r
- printf("\x1B[%i;%iH", Col, Row);\r
- return ioctl(1, 9, NULL); // Ugh, constants\r
-}\r
-\r
-static inline int isdigit(int ch)\r
-{\r
- return '0' <= ch && ch < '9';\r
-}\r
+/*
+ * Acess2 IRC Client
+ */
+#include <acess/sys.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <net.h>
+#include <readline.h>
+#include <acess/devices/pty.h>
+
+// === TYPES ===
+typedef struct sServer {
+ struct sServer *Next;
+ int FD;
+ char InBuf[BUFSIZ+1];
+ int ReadPos;
+ char Name[];
+} tServer;
+
+typedef struct sMessage
+{
+ struct sMessage *Next;
+ time_t Timestamp;
+ tServer *Server;
+ int Type;
+ char *Source; // Pointer into `Data`
+ char Data[];
+} tMessage;
+
+typedef struct sWindow
+{
+ struct sWindow *Next;
+ tMessage *Messages;
+ tServer *Server; //!< Canoical server (can be NULL)
+ int ActivityLevel;
+ char Name[]; // Channel name / remote user
+} tWindow;
+
+enum eMessageTypes
+{
+ MSG_TYPE_NULL,
+ MSG_TYPE_SERVER, // Server message
+
+ MSG_TYPE_NOTICE, // NOTICE command
+ MSG_TYPE_JOIN, // JOIN command
+ MSG_TYPE_PART, // PART command
+ MSG_TYPE_QUIT, // QUIT command
+
+ MSG_TYPE_STANDARD, // Standard line
+ MSG_TYPE_ACTION, // /me
+
+ MSG_TYPE_UNK
+};
+
+// === PROTOTYPES ===
+ int ParseArguments(int argc, const char *argv[]);
+ int ParseUserCommand(char *String);
+// ---
+tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber);
+tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...);
+tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message);
+tWindow *Window_Create(tServer *Server, const char *Name);
+void Redraw_Screen(void);
+
+ int ProcessIncoming(tServer *Server);
+// --- Helpers
+void SetCursorPos(int Row, int Col);
+ int writef(int FD, const char *Format, ...);
+ int OpenTCP(const char *AddressString, short PortNumber);
+char *GetValue(char *Str, int *Ofs);
+static inline int isdigit(int ch);
+
+// === GLOBALS ===
+char *gsUsername = "user";
+char *gsHostname = "acess";
+char *gsRealName = "Acess2 IRC Client";
+char *gsNickname = "acess";
+tServer *gpServers;
+tWindow gWindow_Status = {
+ NULL, NULL, NULL, // No next, empty list, no server
+ 0, {""} // No activity, empty name (rendered as status)
+};
+tWindow *gpWindows = &gWindow_Status;
+tWindow *gpCurrentWindow = &gWindow_Status;
+ int giTerminal_Width = 80;
+ int giTerminal_Height = 25;
+
+// ==== CODE ====
+void ExitHandler(void)
+{
+ printf("\x1B[?1047l");
+ printf("Quit\n");
+}
+
+int main(int argc, const char *argv[], const char *envp[])
+{
+ int tmp;
+ tReadline *readline_info;
+
+ // Parse Command line
+ if( (tmp = ParseArguments(argc, argv)) ) return tmp;
+
+ atexit(ExitHandler);
+
+ if( _SysIOCtl(1, DRV_IOCTL_TYPE, NULL) != DRV_TYPE_TERMINAL ) {
+ fprintf(stderr, "note: assuming 80x25, can't get terminal dimensions\n");
+ giTerminal_Width = 80;
+ giTerminal_Height = 25;
+ }
+ else {
+ struct ptydims dims;
+ _SysIOCtl(1, PTY_IOCTL_GETDIMS, &dims);
+ giTerminal_Width = dims.W;
+ giTerminal_Height = dims.H;
+ }
+
+ printf("\x1B[?1047h");
+ printf("\x1B[%i;%ir", 0, giTerminal_Height-1);
+
+ SetCursorPos(giTerminal_Height-1, 0);
+ printf("[(status)] ");
+
+ // HACK: Static server entry
+ // UCC (University [of Western Australia] Computer Club) IRC Server
+ gWindow_Status.Server = Server_Connect( "UCC", "130.95.13.18", 6667 );
+ // Freenode (#osdev)
+// gWindow_Status.Server = Server_Connect( "Freenode", "89.16.176.16", 6667 );
+// gWindow_Status.Server = Server_Connect( "Host", "10.0.2.2", 6667 );
+ // Local server
+// gWindow_Status.Server = Server_Connect( "BitlBee", "192.168.1.39", 6667 );
+
+ if( !gWindow_Status.Server )
+ return -1;
+
+ SetCursorPos(giTerminal_Height-1, 0);
+ printf("[(status)] ");
+ fflush(stdout);
+ readline_info = Readline_Init(1);
+
+ for( ;; )
+ {
+ fd_set readfds, errorfds;
+ int rv, maxFD = 0;
+ tServer *srv;
+
+ FD_ZERO(&readfds);
+ FD_ZERO(&errorfds);
+ FD_SET(0, &readfds); // stdin
+
+ fflush(stdout);
+
+ // Fill server FDs in fd_set
+ for( srv = gpServers; srv; srv = srv->Next )
+ {
+ FD_SET(srv->FD, &readfds);
+ FD_SET(srv->FD, &errorfds);
+ if( srv->FD > maxFD )
+ maxFD = srv->FD;
+ }
+
+ rv = _SysSelect(maxFD+1, &readfds, 0, &errorfds, NULL, 0);
+ if( rv == -1 ) break;
+
+ if(FD_ISSET(0, &readfds))
+ {
+ // User input
+ char *cmd = Readline_NonBlock(readline_info);
+ if( cmd )
+ {
+ if( cmd[0] )
+ {
+ ParseUserCommand(cmd);
+ }
+ free(cmd);
+ // Prompt
+ SetCursorPos(giTerminal_Height-1, 0);
+ printf("\x1B[2K"); // Clear line
+ if( gpCurrentWindow->Name[0] )
+ printf("[%s:%s] ", gpCurrentWindow->Server->Name, gpCurrentWindow->Name);
+ else
+ printf("[(status)] ");
+ }
+ }
+
+ // Server response
+ for( srv = gpServers; srv; srv = srv->Next )
+ {
+ if(FD_ISSET(srv->FD, &readfds))
+ {
+ if( ProcessIncoming(srv) != 0 ) {
+ // Oops, error
+ break;
+ }
+ }
+
+ if(FD_ISSET(srv->FD, &errorfds))
+ {
+ break;
+ }
+ }
+
+ // Oops, an error
+ if( srv ) break;
+ }
+
+ {
+ tServer *srv;
+ for( srv = gpServers; srv; srv = srv->Next )
+ _SysClose(srv->FD);
+ }
+ return 0;
+}
+
+/**
+ * \todo Actually implement correctly :)
+ */
+int ParseArguments(int argc, const char *argv[])
+{
+ return 0;
+}
+
+
+void Cmd_join(char *ArgString)
+{
+ int pos=0;
+ char *channel_name = GetValue(ArgString, &pos);
+
+ if( gpCurrentWindow->Server )
+ {
+ writef(gpCurrentWindow->Server->FD, "JOIN :%s\n", channel_name);
+ }
+}
+
+void Cmd_quit(char *ArgString)
+{
+ const char *quit_message = ArgString;
+ if( quit_message == NULL || quit_message[0] == '\0' )
+ quit_message = "/quit - Acess2 IRC Client";
+
+ for( tServer *srv = gpServers; srv; srv = srv->Next )
+ {
+ writef(srv->FD, "QUIT :%s\n", quit_message);
+ }
+
+ exit(0);
+}
+
+void Cmd_window(char *ArgString)
+{
+ int pos = 0;
+ char *window_id = GetValue(ArgString, &pos);
+ int window_num = atoi(window_id);
+
+ if( window_num > 0 )
+ {
+ tWindow *win;
+ window_num --; // Move to base 0
+ // Get `window_num`th window
+ for( win = gpWindows; win && window_num--; win = win->Next );
+ if( win ) {
+ gpCurrentWindow = win;
+ Redraw_Screen();
+ }
+ // Otherwise, silently ignore
+ }
+ else
+ {
+ window_num = 1;
+ for( tWindow *win = gpWindows; win; win = win->Next, window_num ++ )
+ {
+ if( win->Name[0] ) {
+ Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
+ "%i: %s/%s", window_num, win->Server->Name, win->Name);
+ }
+ else {
+ Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
+ "%i: (status)", window_num);
+ }
+ }
+ }
+}
+
+const struct {
+ const char *Name;
+ void (*Fcn)(char *ArgString);
+} caCommands[] = {
+ {"join", Cmd_join},
+ {"quit", Cmd_quit},
+ {"window", Cmd_window},
+ {"win", Cmd_window},
+ {"w", Cmd_window},
+};
+const int ciNumCommands = sizeof(caCommands)/sizeof(caCommands[0]);
+
+/**
+ * \brief Handle a line from the prompt
+ */
+int ParseUserCommand(char *String)
+{
+ if( String[0] == '/' )
+ {
+ char *command;
+ int pos = 0;
+
+ command = GetValue(String, &pos)+1;
+
+ // TODO: Prefix matches
+ int cmdIdx = -1;
+ for( int i = 0; i < ciNumCommands; i ++ )
+ {
+ if( strcmp(command, caCommands[i].Name) == 0 ) {
+ cmdIdx = i;
+ break;
+ }
+ }
+ if( cmdIdx != -1 ) {
+ caCommands[cmdIdx].Fcn(String+pos);
+ }
+ else
+ {
+ Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "", "Unknown command %s", command);
+ }
+ }
+ else
+ {
+ // Message
+ // - Only send if server is valid and window name is non-empty
+ if( gpCurrentWindow->Server && gpCurrentWindow->Name[0] )
+ {
+ Message_Append(gpCurrentWindow->Server, MSG_TYPE_STANDARD,
+ gsNickname, gpCurrentWindow->Name, String);
+ writef(gpCurrentWindow->Server->FD,
+ "PRIVMSG %s :%s\n", gpCurrentWindow->Name,
+ String
+ );
+ }
+ }
+
+ return 0;
+}
+
+/**
+ * \brief Connect to a server
+ */
+tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber)
+{
+ tServer *ret;
+
+ ret = calloc(1, sizeof(tServer) + strlen(Name) + 1);
+
+ strcpy(ret->Name, Name);
+
+ // Connect to the remove server
+ ret->FD = OpenTCP( AddressString, PortNumber );
+ if( ret->FD == -1 ) {
+ fprintf(stderr, "%s: Unable to create socket\n", Name);
+ return NULL;
+ }
+
+ // Append to open list
+ ret->Next = gpServers;
+ gpServers = ret;
+
+ // Read some initial data
+ Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Connection opened");
+ ProcessIncoming(ret);
+
+ // Identify
+ writef(ret->FD, "USER %s %s %s : %s\n", gsUsername, gsHostname, AddressString, gsRealName);
+ writef(ret->FD, "NICK %s\n", gsNickname);
+ Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Identified");
+ //printf("%s: Identified\n", Name);
+
+ return ret;
+}
+
+tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...)
+{
+ va_list args;
+ int len;
+ va_start(args, Message);
+ len = vsnprintf(NULL, 0, Message, args);
+ {
+ char buf[len+1];
+ vsnprintf(buf, len+1, Message, args);
+ return Message_Append(Server, Type, Source, Dest, buf);
+ }
+}
+
+tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message)
+{
+ tWindow *win = NULL;
+ int msgLen = strlen(Message);
+
+ // Server==NULL indicates an internal message
+ if( Server == NULL || Source[0] == '\0' )
+ {
+ win = &gWindow_Status;
+ }
+ // Determine if it's a channel or PM
+ else if( Dest[0] == '#' || Dest[0] == '&' ) // TODO: Better determining here
+ {
+ for(win = gpWindows; win; win = win->Next)
+ {
+ if( win->Server == Server && strcmp(win->Name, Dest) == 0 )
+ {
+ break;
+ }
+ }
+ if( !win ) {
+ win = Window_Create(Server, Dest);
+ }
+ }
+ #if 0
+ else if( strcmp(Dest, Server->Nick) != 0 )
+ {
+ // Umm... message for someone who isn't us?
+ win = &gWindow_Status; // Stick it in the status window, just in case
+ }
+ #endif
+ // Server message?
+ else if( strchr(Source, '.') ) // TODO: And again, less hack please
+ {
+ #if 1
+ for(win = gpWindows; win; win = win->Next)
+ {
+ if( win->Server == Server && strcmp(win->Name, Source) == 0 )
+ {
+ break;
+ }
+ }
+ #endif
+ if( !win ) {
+ win = &gWindow_Status;
+ }
+
+ // Set source to the server name (instead of the hostname)
+ Source = Server->Name;
+ }
+ // Private message
+ else
+ {
+ for(win = gpWindows; win; win = win->Next)
+ {
+ if( win->Server == Server && strcmp(win->Name, Source) == 0 )
+ {
+ break;
+ }
+ }
+ if( !win ) {
+ win = Window_Create(Server, Dest);
+ }
+ }
+
+ // Create message cache
+ _SysDebug("Win (%s) msg: <%s> %s", win->Name, Source, Message);
+ tMessage *ret;
+ ret = malloc( sizeof(tMessage) + msgLen + 1 + strlen(Source) + 1 );
+ ret->Source = ret->Data + msgLen + 1;
+ strcpy(ret->Source, Source);
+ strcpy(ret->Data, Message);
+ ret->Type = Type;
+ ret->Server = Server;
+
+ // Append to window message list
+ ret->Next = win->Messages;
+ win->Messages = ret;
+
+ // Print now if current window
+ if( win == gpCurrentWindow )
+ {
+ printf("\x1b[s");
+ printf("\x1b""D"); // Scroll down 1 (free space below)
+ SetCursorPos(giTerminal_Height-2, 0);
+ int prefixlen = strlen(Source) + 3;
+ int avail = giTerminal_Width - prefixlen;
+ int msglen = strlen(Message);
+ printf("[%s] %.*s", Source, avail, Message);
+ while( msglen > avail ) {
+ msglen -= avail;
+ Message += avail;
+ printf("\x1b""D");
+ SetCursorPos(giTerminal_Height-2, prefixlen);
+ printf("%.*s", avail, Message);
+ }
+ printf("\x1b[u");
+ }
+
+ return ret;
+}
+
+tWindow *Window_Create(tServer *Server, const char *Name)
+{
+ tWindow *ret, *prev = NULL;
+ int num = 1;
+
+ // Get the end of the list
+ // TODO: Cache this instead
+ for( ret = gpCurrentWindow; ret; prev = ret, ret = ret->Next )
+ num ++;
+
+ ret = malloc(sizeof(tWindow) + strlen(Name) + 1);
+ ret->Messages = NULL;
+ ret->Server = Server;
+ ret->ActivityLevel = 1;
+ strcpy(ret->Name, Name);
+
+ if( prev ) {
+ ret->Next = prev->Next;
+ prev->Next = ret;
+ }
+ else { // Shouldn't happen really
+ ret->Next = gpWindows;
+ gpWindows = ret;
+ }
+
+// printf("Win %i %s:%s created\n", num, Server->Name, Name);
+
+ return ret;
+}
+
+void Redraw_Screen(void)
+{
+ int y = 0;
+ tMessage *msg;
+
+ printf("\x1B[2J"); // Clear screen
+ printf("\x1B[0;0H"); // Reset cursor
+
+ msg = gpCurrentWindow->Messages;
+
+ // TODO: Title bar?
+
+ // Note: This renders from the bottom up
+ for( y = giTerminal_Height - 1; y -- && msg; msg = msg->Next)
+ {
+ int msglen = strlen(msg->Data);
+ int prefix_len = 3 + strlen(msg->Source);
+ int line_avail = giTerminal_Width - prefix_len;
+ int i = 0, done = 0;
+
+ y -= msglen / line_avail; // Extra lines (y-- above handles the 1 line case)
+ SetCursorPos(y, 0);
+ printf("[%s] ", msg->Source);
+
+ while(done < msglen) {
+ done += printf("%.*s", line_avail, msg->Data+done);
+ i ++;
+ SetCursorPos(y+i, prefix_len);
+ }
+ }
+
+ // Bottom line is rendered by the prompt
+}
+
+void Cmd_PRIVMSG(tServer *Server, const char *Dest, const char *Src, const char *Message)
+{
+ Message_Append(Server, MSG_TYPE_STANDARD, Dest, Src, Message);
+ //printf("<%s:%s:%s> %s\n", Server->Name, Dest, Src, Message);
+}
+
+/**
+ */
+void ParseServerLine(tServer *Server, char *Line)
+{
+ int pos = 0;
+ char *ident, *cmd;
+
+// _SysDebug("[%s] %s", Server->Name, Line);
+
+ // Message?
+ if( *Line == ':' )
+ {
+ pos ++;
+ ident = GetValue(Line, &pos); // Ident (user or server)
+ cmd = GetValue(Line, &pos);
+
+ // Numeric command
+ if( isdigit(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2]) )
+ {
+ char *user, *message;
+ int num;
+ num = (cmd[0] - '0') * 100;
+ num += (cmd[1] - '0') * 10;
+ num += (cmd[2] - '0') * 1;
+
+ user = GetValue(Line, &pos);
+
+ if( Line[pos] == ':' ) {
+ message = Line + pos + 1;
+ }
+ else {
+ message = GetValue(Line, &pos);
+ }
+
+ switch(num)
+ {
+ case 332: // Topic
+ user = message; // Channel
+ message = Line + pos + 1; // Topic
+ Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Topic: %s", message);
+ break;
+ case 333: // Topic set by
+ user = message; // Channel
+ message = GetValue(Line, &pos); // User
+ GetValue(Line, &pos); // Timestamp
+ Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Set by %s", message);
+ break;
+ case 353: // /NAMES list
+ // <user> = <channel> :list
+ // '=' was eaten in and set to message
+ user = GetValue(Line, &pos); // Actually channel
+ message = Line + pos + 1; // List
+ Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Names: %s", message);
+ break;
+ case 366: // end of /NAMES list
+ // <user> <channel> :msg
+ user = message;
+ message = Line + pos + 1;
+ Message_Append(Server, MSG_TYPE_SERVER, user, user, message);
+ break;
+ case 372: // MOTD Data
+ case 375: // MOTD Start
+ case 376: // MOTD End
+
+ default:
+ //printf("[%s] %i %s\n", Server->Name, num, message);
+ Message_Append(Server, MSG_TYPE_SERVER, ident, user, message);
+ break;
+ }
+ }
+ else if( strcmp(cmd, "NOTICE") == 0 )
+ {
+ char *class, *message;
+
+ class = GetValue(Line, &pos);
+ _SysDebug("NOTICE class='%s'", class);
+
+ if( Line[pos] == ':' ) {
+ message = Line + pos + 1;
+ }
+ else {
+ message = GetValue(Line, &pos);
+ }
+
+ //printf("[%s] NOTICE %s: %s\n", Server->Name, ident, message);
+ char *ident_bang = strchr(ident, '!');
+ if( ident_bang ) {
+ *ident_bang = '\0';
+ }
+ Message_Append(Server, MSG_TYPE_NOTICE, ident, "", message);
+ }
+ else if( strcmp(cmd, "PRIVMSG") == 0 )
+ {
+ char *dest, *message;
+ dest = GetValue(Line, &pos);
+
+ if( Line[pos] == ':' ) {
+ message = Line + pos + 1;
+ }
+ else {
+ message = GetValue(Line, &pos);
+ }
+
+ // TODO: Catch when the privmsg is addressed to the user
+
+// Cmd_PRIVMSG(Server, dest, ident, message);
+ char *ident_bang = strchr(ident, '!');
+ if( ident_bang ) {
+ *ident_bang = '\0';
+ }
+ Message_Append(Server, MSG_TYPE_STANDARD, ident, dest, message);
+ }
+ else if( strcmp(cmd, "JOIN" ) == 0 )
+ {
+ char *channel;
+ channel = Line + pos + 1;
+ Window_Create(Server, channel);
+ }
+ else
+ {
+ Message_AppendF(Server, MSG_TYPE_SERVER, "", "", "Unknown message %s (%s)", cmd, Line+pos);
+ }
+ }
+ else {
+ cmd = GetValue(Line, &pos);
+
+ if( strcmp(cmd, "PING") == 0 ) {
+ writef(Server->FD, "PONG %s\n", gsHostname);
+
+ }
+ else {
+ // Command to client
+ Message_AppendF(NULL, MSG_TYPE_UNK, "", "", "Client Command: %s", Line);
+ }
+ }
+}
+
+/**
+ * \brief Process incoming lines from the server
+ */
+int ProcessIncoming(tServer *Server)
+{
+ char *ptr, *newline;
+ int len;
+
+ // While there is data in the buffer, read it into user memory and
+ // process it line by line
+ // ioctl#8 on a TCP client gets the number of bytes in the recieve buffer
+ // - Used to avoid blocking
+ #if NON_BLOCK_READ
+ while( (len = _SysIOCtl(Server->FD, 8, NULL)) > 0 )
+ {
+ #endif
+ // Read data
+ len = _SysRead(Server->FD, &Server->InBuf[Server->ReadPos], BUFSIZ - Server->ReadPos);
+ if( len == -1 ) {
+ return -1;
+ }
+ Server->InBuf[Server->ReadPos + len] = '\0';
+
+ // Break into lines
+ ptr = Server->InBuf;
+ while( (newline = strchr(ptr, '\n')) )
+ {
+ *newline = '\0';
+ if( newline[-1] == '\r' ) newline[-1] = '\0';
+ ParseServerLine(Server, ptr);
+ ptr = newline + 1;
+ }
+
+ // Handle incomplete lines
+ if( ptr - Server->InBuf < len + Server->ReadPos ) {
+ // Update the read position
+ // InBuf ReadPos ptr ReadPos+len
+ // | old | new used | new unused |
+ Server->ReadPos = len + Server->ReadPos - (ptr - Server->InBuf);
+ // Copy stuff back (moving "new unused" to the start of the buffer)
+ memcpy(Server->InBuf, ptr, Server->ReadPos);
+ }
+ else {
+ Server->ReadPos = 0;
+ }
+ #if NON_BLOCK_READ
+ }
+ #endif
+
+ return 0;
+}
+
+/**
+ * \brief Write a formatted string to a file descriptor
+ *
+ */
+int writef(int FD, const char *Format, ...)
+{
+ va_list args;
+ int len;
+
+ va_start(args, Format);
+ len = vsnprintf(NULL, 0, Format, args);
+ va_end(args);
+
+ {
+ char buf[len+1];
+ va_start(args, Format);
+ vsnprintf(buf, len+1, Format, args);
+ va_end(args);
+
+ return _SysWrite(FD, buf, len);
+ }
+}
+
+/**
+ * \brief Initialise a TCP connection to \a AddressString on port \a PortNumber
+ */
+int OpenTCP(const char *AddressString, short PortNumber)
+{
+ int fd, addrType;
+ char addrBuffer[8];
+
+ // Parse IP Address
+ addrType = Net_ParseAddress(AddressString, addrBuffer);
+ if( addrType == 0 ) {
+ fprintf(stderr, "Unable to parse '%s' as an IP address\n", AddressString);
+ _SysDebug("Unable to parse '%s' as an IP address\n", AddressString);
+ return -1;
+ }
+
+ // Finds the interface for the destination address
+ fd = Net_OpenSocket(addrType, addrBuffer, "tcpc");
+ if( fd == -1 ) {
+ fprintf(stderr, "Unable to open TCP Client to '%s'\n", AddressString);
+ _SysDebug("Unable to open TCP client to '%s'\n", AddressString);
+ return -1;
+ }
+
+ // Set remote port and address
+// printf("Setting port and remote address\n");
+ _SysIOCtl(fd, 5, &PortNumber);
+ _SysIOCtl(fd, 6, addrBuffer);
+
+ // Connect
+// printf("Initiating connection\n");
+ if( _SysIOCtl(fd, 7, NULL) == 0 ) {
+ // Shouldn't happen :(
+ fprintf(stderr, "Unable to start connection\n");
+ return -1;
+ }
+
+ // Return descriptor
+ return fd;
+}
+
+/**
+ * \brief Read a space-separated value from a string
+ */
+char *GetValue(char *Src, int *Ofs)
+{
+ int pos = *Ofs;
+ char *ret = Src + pos;
+ char *end;
+
+ if( !Src ) return NULL;
+
+ while( *ret == ' ' ) ret ++;
+
+ end = strchr(ret, ' ');
+ if( end ) {
+ *end = '\0';
+ }
+ else {
+ end = ret + strlen(ret) - 1;
+ }
+
+ end ++ ;
+ while( *ret == ' ' ) end ++;
+ *Ofs = end - Src;
+
+ return ret;
+}
+
+void SetCursorPos(int Row, int Col)
+{
+ printf("\x1B[%i;%iH", Row, Col);
+}
+
+static inline int isdigit(int ch)
+{
+ return '0' <= ch && ch < '9';
+}