10 #include <acess/devices/pty.h>
13 typedef struct sServer {
21 typedef struct sMessage
23 struct sMessage *Next;
27 char *Source; // Pointer into `Data`
31 typedef struct sWindow
35 tServer *Server; //!< Canoical server (can be NULL)
37 char Name[]; // Channel name / remote user
43 MSG_TYPE_SERVER, // Server message
45 MSG_TYPE_NOTICE, // NOTICE command
46 MSG_TYPE_JOIN, // JOIN command
47 MSG_TYPE_PART, // PART command
48 MSG_TYPE_QUIT, // QUIT command
50 MSG_TYPE_STANDARD, // Standard line
51 MSG_TYPE_ACTION, // /me
57 int ParseArguments(int argc, const char *argv[]);
58 int ParseUserCommand(char *String);
60 tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber);
61 tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...);
62 tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message);
63 tWindow *Window_Create(tServer *Server, const char *Name);
64 void Redraw_Screen(void);
66 int ProcessIncoming(tServer *Server);
68 void SetCursorPos(int Row, int Col);
69 int writef(int FD, const char *Format, ...);
70 int OpenTCP(const char *AddressString, short PortNumber);
71 char *GetValue(char *Str, int *Ofs);
72 static inline int isdigit(int ch);
75 char *gsUsername = "user";
76 char *gsHostname = "acess";
77 char *gsRealName = "Acess2 IRC Client";
78 char *gsNickname = "acess";
80 tWindow gWindow_Status = {
81 NULL, NULL, NULL, // No next, empty list, no server
82 0, {""} // No activity, empty name (rendered as status)
84 tWindow *gpWindows = &gWindow_Status;
85 tWindow *gpCurrentWindow = &gWindow_Status;
86 int giTerminal_Width = 80;
87 int giTerminal_Height = 25;
90 void ExitHandler(void)
92 printf("\x1B[?1047l");
96 int main(int argc, const char *argv[], const char *envp[])
99 tReadline *readline_info;
101 // Parse Command line
102 if( (tmp = ParseArguments(argc, argv)) ) return tmp;
106 if( _SysIOCtl(1, DRV_IOCTL_TYPE, NULL) != DRV_TYPE_TERMINAL ) {
107 printf(stderr, "note: assuming 80x25, can't get terminal dimensions\n");
108 giTerminal_Width = 80;
109 giTerminal_Height = 25;
113 _SysIOCtl(1, PTY_IOCTL_GETDIMS, &dims);
114 giTerminal_Width = dims.W;
115 giTerminal_Height = dims.H;
118 printf("\x1B[?1047h");
119 printf("\x1B[%i;%ir", 0, giTerminal_Height-1);
121 SetCursorPos(giTerminal_Height-1, 0);
122 printf("[(status)] ");
124 // HACK: Static server entry
125 // UCC (University [of Western Australia] Computer Club) IRC Server
126 gWindow_Status.Server = Server_Connect( "UCC", "130.95.13.18", 6667 );
128 // gWindow_Status.Server = Server_Connect( "Freenode", "89.16.176.16", 6667 );
129 // gWindow_Status.Server = Server_Connect( "Host", "10.0.2.2", 6667 );
131 // gWindow_Status.Server = Server_Connect( "BitlBee", "192.168.1.39", 6667 );
133 if( !gWindow_Status.Server )
136 SetCursorPos(giTerminal_Height-1, 0);
137 printf("[(status)] ");
139 readline_info = Readline_Init(1);
143 fd_set readfds, errorfds;
149 FD_SET(0, &readfds); // stdin
151 // Fill server FDs in fd_set
152 for( srv = gpServers; srv; srv = srv->Next )
154 FD_SET(srv->FD, &readfds);
155 FD_SET(srv->FD, &errorfds);
156 if( srv->FD > maxFD )
160 rv = _SysSelect(maxFD+1, &readfds, 0, &errorfds, NULL, 0);
161 if( rv == -1 ) break;
163 if(FD_ISSET(0, &readfds))
166 char *cmd = Readline_NonBlock(readline_info);
171 ParseUserCommand(cmd);
175 SetCursorPos(giTerminal_Height-1, 0);
176 printf("\x1B[K"); // Clear line
177 if( gpCurrentWindow->Name[0] )
178 printf("[%s:%s] ", gpCurrentWindow->Server->Name, gpCurrentWindow->Name);
180 printf("[(status)] ");
186 for( srv = gpServers; srv; srv = srv->Next )
188 if(FD_ISSET(srv->FD, &readfds))
190 if( ProcessIncoming(srv) != 0 ) {
196 if(FD_ISSET(srv->FD, &errorfds))
208 for( srv = gpServers; srv; srv = srv->Next )
215 * \todo Actually implement correctly :)
217 int ParseArguments(int argc, const char *argv[])
223 void Cmd_join(char *ArgString)
226 char *channel_name = GetValue(ArgString, &pos);
228 if( gpCurrentWindow->Server )
230 writef(gpCurrentWindow->Server->FD, "JOIN :%s\n", channel_name);
234 void Cmd_quit(char *ArgString)
236 const char *quit_message = ArgString;
237 if( quit_message == NULL || quit_message[0] == '\0' )
238 quit_message = "/quit - Acess2 IRC Client";
240 for( tServer *srv = gpServers; srv; srv = srv->Next )
242 writef(srv->FD, "QUIT :%s\n", quit_message);
248 void Cmd_window(char *ArgString)
251 char *window_id = GetValue(ArgString, &pos);
252 int window_num = atoi(window_id);
257 window_num --; // Move to base 0
258 // Get `window_num`th window
259 for( win = gpWindows; win && window_num--; win = win->Next );
261 gpCurrentWindow = win;
264 // Otherwise, silently ignore
269 for( tWindow *win = gpWindows; win; win = win->Next, window_num ++ )
272 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
273 "%i: %s/%s", window_num, win->Server->Name, win->Name);
276 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
277 "%i: (status)", window_num);
285 void (*Fcn)(char *ArgString);
289 {"window", Cmd_window},
293 const int ciNumCommands = sizeof(caCommands)/sizeof(caCommands[0]);
296 * \brief Handle a line from the prompt
298 int ParseUserCommand(char *String)
300 if( String[0] == '/' )
305 command = GetValue(String, &pos)+1;
307 // TODO: Prefix matches
309 for( int i = 0; i < ciNumCommands; i ++ )
311 if( strcmp(command, caCommands[i].Name) == 0 ) {
317 caCommands[cmdIdx].Fcn(String+pos);
321 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "", "Unknown command %s", command);
327 // - Only send if server is valid and window name is non-empty
328 if( gpCurrentWindow->Server && gpCurrentWindow->Name[0] )
330 Message_Append(gpCurrentWindow->Server, MSG_TYPE_STANDARD,
331 gsNickname, gpCurrentWindow->Name, String);
332 writef(gpCurrentWindow->Server->FD,
333 "PRIVMSG %s :%s\n", gpCurrentWindow->Name,
343 * \brief Connect to a server
345 tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber)
349 ret = calloc(1, sizeof(tServer) + strlen(Name) + 1);
351 strcpy(ret->Name, Name);
353 // Connect to the remove server
354 ret->FD = OpenTCP( AddressString, PortNumber );
355 if( ret->FD == -1 ) {
356 fprintf(stderr, "%s: Unable to create socket\n", Name);
360 // Append to open list
361 ret->Next = gpServers;
364 // Read some initial data
365 Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Connection opened");
366 ProcessIncoming(ret);
369 writef(ret->FD, "USER %s %s %s : %s\n", gsUsername, gsHostname, AddressString, gsRealName);
370 writef(ret->FD, "NICK %s\n", gsNickname);
371 Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Identified");
372 //printf("%s: Identified\n", Name);
377 tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...)
381 va_start(args, Message);
382 len = vsnprintf(NULL, 0, Message, args);
385 vsnprintf(buf, len+1, Message, args);
386 return Message_Append(Server, Type, Source, Dest, buf);
390 tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message)
393 int msgLen = strlen(Message);
395 // Server==NULL indicates an internal message
396 if( Server == NULL || Source[0] == '\0' )
398 win = &gWindow_Status;
400 // Determine if it's a channel or PM
401 else if( Dest[0] == '#' || Dest[0] == '&' ) // TODO: Better determining here
403 for(win = gpWindows; win; win = win->Next)
405 if( win->Server == Server && strcmp(win->Name, Dest) == 0 )
411 win = Window_Create(Server, Dest);
415 else if( strcmp(Dest, Server->Nick) != 0 )
417 // Umm... message for someone who isn't us?
418 win = &gWindow_Status; // Stick it in the status window, just in case
422 else if( strchr(Source, '.') ) // TODO: And again, less hack please
425 for(win = gpWindows; win; win = win->Next)
427 if( win->Server == Server && strcmp(win->Name, Source) == 0 )
434 win = &gWindow_Status;
441 for(win = gpWindows; win; win = win->Next)
443 if( win->Server == Server && strcmp(win->Name, Source) == 0 )
449 win = Window_Create(Server, Dest);
453 // Create message cache
454 _SysDebug("Win (%s) msg: <%s> %s", win->Name, Source, Message);
456 ret = malloc( sizeof(tMessage) + msgLen + 1 + strlen(Source) + 1 );
457 ret->Source = ret->Data + msgLen + 1;
458 strcpy(ret->Source, Source);
459 strcpy(ret->Data, Message);
461 ret->Server = Server;
463 // Append to window message list
464 ret->Next = win->Messages;
467 // Print now if current window
468 if( win == gpCurrentWindow )
471 SetCursorPos(giTerminal_Height-2, 0);
472 int prefixlen = strlen(Source) + 3;
473 int avail = giTerminal_Width - prefixlen;
474 int msglen = strlen(Message);
475 printf("\x1B[T"); // Scroll down 1 (free space below)
476 printf("[%s] %.*s\n", Source, avail, Message);
477 while( msglen > avail ) {
481 SetCursorPos(giTerminal_Height-2, prefixlen);
482 printf("%.*s\n", avail, Message);
490 tWindow *Window_Create(tServer *Server, const char *Name)
492 tWindow *ret, *prev = NULL;
495 // Get the end of the list
496 // TODO: Cache this instead
497 for( ret = gpCurrentWindow; ret; prev = ret, ret = ret->Next )
500 ret = malloc(sizeof(tWindow) + strlen(Name) + 1);
501 ret->Messages = NULL;
502 ret->Server = Server;
503 ret->ActivityLevel = 1;
504 strcpy(ret->Name, Name);
507 ret->Next = prev->Next;
510 else { // Shouldn't happen really
511 ret->Next = gpWindows;
515 // printf("Win %i %s:%s created\n", num, Server->Name, Name);
520 void Redraw_Screen(void)
525 printf("\x1B[2J"); // Clear screen
526 printf("\x1B[0;0H"); // Reset cursor
528 msg = gpCurrentWindow->Messages;
532 // Note: This renders from the bottom up
533 for( y = giTerminal_Height - 1; y -- && msg; msg = msg->Next)
535 int msglen = strlen(msg->Data);
536 int prefix_len = 3 + strlen(msg->Source);
537 int line_avail = giTerminal_Width - prefix_len;
540 y -= msglen / line_avail; // Extra lines (y-- above handles the 1 line case)
542 printf("[%s] ", msg->Source);
544 while(done < msglen) {
545 done += printf("%.*s", line_avail, msg->Data+done);
547 SetCursorPos(y+i, prefix_len);
551 // Bottom line is rendered by the prompt
554 void Cmd_PRIVMSG(tServer *Server, const char *Dest, const char *Src, const char *Message)
556 Message_Append(Server, MSG_TYPE_STANDARD, Dest, Src, Message);
557 //printf("<%s:%s:%s> %s\n", Server->Name, Dest, Src, Message);
562 void ParseServerLine(tServer *Server, char *Line)
567 // _SysDebug("[%s] %s", Server->Name, Line);
573 ident = GetValue(Line, &pos); // Ident (user or server)
574 cmd = GetValue(Line, &pos);
577 if( isdigit(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2]) )
579 char *user, *message;
581 num = (cmd[0] - '0') * 100;
582 num += (cmd[1] - '0') * 10;
583 num += (cmd[2] - '0') * 1;
585 user = GetValue(Line, &pos);
587 if( Line[pos] == ':' ) {
588 message = Line + pos + 1;
591 message = GetValue(Line, &pos);
597 user = message; // Channel
598 message = Line + pos + 1; // Topic
599 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Topic: %s", message);
601 case 333: // Topic set by
602 user = message; // Channel
603 message = GetValue(Line, &pos); // User
604 GetValue(Line, &pos); // Timestamp
605 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Set by %s", message);
607 case 353: // /NAMES list
608 // <user> = <channel> :list
609 // '=' was eaten in and set to message
610 user = GetValue(Line, &pos); // Actually channel
611 message = Line + pos + 1; // List
612 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Names: %s", message);
614 case 366: // end of /NAMES list
615 // <user> <channel> :msg
617 message = Line + pos + 1;
618 Message_Append(Server, MSG_TYPE_SERVER, user, user, message);
620 case 372: // MOTD Data
621 case 375: // MOTD Start
622 case 376: // MOTD End
625 //printf("[%s] %i %s\n", Server->Name, num, message);
626 Message_Append(Server, MSG_TYPE_SERVER, ident, user, message);
630 else if( strcmp(cmd, "NOTICE") == 0 )
632 char *class, *message;
634 class = GetValue(Line, &pos);
635 _SysDebug("NOTICE class='%s'", class);
637 if( Line[pos] == ':' ) {
638 message = Line + pos + 1;
641 message = GetValue(Line, &pos);
644 //printf("[%s] NOTICE %s: %s\n", Server->Name, ident, message);
645 char *ident_bang = strchr(ident, '!');
649 Message_Append(Server, MSG_TYPE_NOTICE, ident, "", message);
651 else if( strcmp(cmd, "PRIVMSG") == 0 )
653 char *dest, *message;
654 dest = GetValue(Line, &pos);
656 if( Line[pos] == ':' ) {
657 message = Line + pos + 1;
660 message = GetValue(Line, &pos);
663 // TODO: Catch when the privmsg is addressed to the user
665 // Cmd_PRIVMSG(Server, dest, ident, message);
666 char *ident_bang = strchr(ident, '!');
670 Message_Append(Server, MSG_TYPE_STANDARD, ident, dest, message);
672 else if( strcmp(cmd, "JOIN" ) == 0 )
675 channel = Line + pos + 1;
676 Window_Create(Server, channel);
680 Message_AppendF(Server, MSG_TYPE_SERVER, "", "", "Unknown message %s (%s)\n", cmd, Line+pos);
684 cmd = GetValue(Line, &pos);
686 if( strcmp(cmd, "PING") == 0 ) {
687 writef(Server->FD, "PONG %s\n", gsHostname);
692 Message_AppendF(NULL, MSG_TYPE_UNK, "", "", "Client Command: %s", Line);
698 * \brief Process incoming lines from the server
700 int ProcessIncoming(tServer *Server)
705 // While there is data in the buffer, read it into user memory and
706 // process it line by line
707 // ioctl#8 on a TCP client gets the number of bytes in the recieve buffer
708 // - Used to avoid blocking
710 while( (len = _SysIOCtl(Server->FD, 8, NULL)) > 0 )
714 len = _SysRead(Server->FD, &Server->InBuf[Server->ReadPos], BUFSIZ - Server->ReadPos);
718 Server->InBuf[Server->ReadPos + len] = '\0';
722 while( (newline = strchr(ptr, '\n')) )
725 if( newline[-1] == '\r' ) newline[-1] = '\0';
726 ParseServerLine(Server, ptr);
730 // Handle incomplete lines
731 if( ptr - Server->InBuf < len + Server->ReadPos ) {
732 // Update the read position
733 // InBuf ReadPos ptr ReadPos+len
734 // | old | new used | new unused |
735 Server->ReadPos = len + Server->ReadPos - (ptr - Server->InBuf);
736 // Copy stuff back (moving "new unused" to the start of the buffer)
737 memcpy(Server->InBuf, ptr, Server->ReadPos);
750 * \brief Write a formatted string to a file descriptor
753 int writef(int FD, const char *Format, ...)
758 va_start(args, Format);
759 len = vsnprintf(NULL, 0, Format, args);
764 va_start(args, Format);
765 vsnprintf(buf, len+1, Format, args);
768 return _SysWrite(FD, buf, len);
773 * \brief Initialise a TCP connection to \a AddressString on port \a PortNumber
775 int OpenTCP(const char *AddressString, short PortNumber)
781 addrType = Net_ParseAddress(AddressString, addrBuffer);
782 if( addrType == 0 ) {
783 fprintf(stderr, "Unable to parse '%s' as an IP address\n", AddressString);
784 _SysDebug("Unable to parse '%s' as an IP address\n", AddressString);
788 // Finds the interface for the destination address
789 fd = Net_OpenSocket(addrType, addrBuffer, "tcpc");
791 fprintf(stderr, "Unable to open TCP Client to '%s'\n", AddressString);
792 _SysDebug("Unable to open TCP client to '%s'\n", AddressString);
796 // Set remote port and address
797 // printf("Setting port and remote address\n");
798 _SysIOCtl(fd, 5, &PortNumber);
799 _SysIOCtl(fd, 6, addrBuffer);
802 // printf("Initiating connection\n");
803 if( _SysIOCtl(fd, 7, NULL) == 0 ) {
804 // Shouldn't happen :(
805 fprintf(stderr, "Unable to start connection\n");
814 * \brief Read a space-separated value from a string
816 char *GetValue(char *Src, int *Ofs)
819 char *ret = Src + pos;
822 if( !Src ) return NULL;
824 while( *ret == ' ' ) ret ++;
826 end = strchr(ret, ' ');
831 end = ret + strlen(ret) - 1;
835 while( *ret == ' ' ) end ++;
841 void SetCursorPos(int Row, int Col)
843 printf("\x1B[%i;%iH", Row, Col);
846 static inline int isdigit(int ch)
848 return '0' <= ch && ch < '9';