10 #include <acess/devices/pty.h>
14 typedef struct sServer {
22 typedef struct sMessage
24 struct sMessage *Next;
28 char *Source; // Pointer into `Data`
32 typedef struct sWindow
36 tServer *Server; //!< Canonical server (can be NULL)
38 char Name[]; // Channel name / remote user
44 MSG_TYPE_SERVER, // Server message
46 MSG_TYPE_NOTICE, // NOTICE command
47 MSG_TYPE_JOIN, // JOIN command
48 MSG_TYPE_PART, // PART command
49 MSG_TYPE_QUIT, // QUIT command
51 MSG_TYPE_STANDARD, // Standard line
52 MSG_TYPE_ACTION, // /me
58 int main(int argc, const char *argv[], const char *envp[]);
60 int ParseArguments(int argc, const char *argv[]);
61 int ParseUserCommand(char *String);
63 tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber);
64 tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...) __attribute__((format(__printf__,5,6)));
65 tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message);
66 tWindow *Window_Create(tServer *Server, const char *Name);
67 void Redraw_Screen(void);
69 int ProcessIncoming(tServer *Server);
71 void SetCursorPos(int Row, int Col);
72 int writef(int FD, const char *Format, ...);
73 int OpenTCP(const char *AddressString, short PortNumber);
74 char *GetValue(char *Str, int *Ofs);
75 static inline int isdigit(int ch);
78 char *gsUsername = "user";
79 char *gsHostname = "acess";
80 char *gsRealName = "Acess2 IRC Client";
81 char *gsNickname = "acess";
83 tWindow gWindow_Status = {
84 NULL, NULL, NULL, // No next, empty list, no server
85 0, {""} // No activity, empty name (rendered as status)
87 tWindow *gpWindows = &gWindow_Status;
88 tWindow *gpCurrentWindow = &gWindow_Status;
89 int giTerminal_Width = 80;
90 int giTerminal_Height = 25;
93 void ExitHandler(void)
95 printf("\x1B[?1047l");
99 int main(int argc, const char *argv[], const char *envp[])
103 // Parse Command line
104 if( (tmp = ParseArguments(argc, argv)) ) return tmp;
108 if( _SysIOCtl(1, DRV_IOCTL_TYPE, NULL) != DRV_TYPE_TERMINAL ) {
109 fprintf(stderr, "note: assuming 80x25, can't get terminal dimensions\n");
110 giTerminal_Width = 80;
111 giTerminal_Height = 25;
115 _SysIOCtl(1, PTY_IOCTL_GETDIMS, &dims);
116 giTerminal_Width = dims.W;
117 giTerminal_Height = dims.H;
120 printf("\x1B[?1047h");
121 printf("\x1B[%i;%ir", 0, giTerminal_Height-1);
123 SetCursorPos(giTerminal_Height-1, 0);
124 printf("[(status)] ");
126 // HACK: Static server entry
127 // UCC (University [of Western Australia] Computer Club) IRC Server
128 gWindow_Status.Server = Server_Connect( "UCC", "130.95.13.18", 6667 );
130 // gWindow_Status.Server = Server_Connect( "Freenode", "89.16.176.16", 6667 );
132 // gWindow_Status.Server = Server_Connect( "VMHost", "10.0.2.2", 6667 );
133 // gWindow_Status.Server = Server_Connect( "BitlBee", "192.168.1.39", 6667 );
135 if( !gWindow_Status.Server )
140 for( tServer *srv = gpServers; srv; srv = srv->Next )
148 SetCursorPos(giTerminal_Height-1, 0);
149 printf("[(status)] ");
152 tReadline *readline_info = Readline_Init(1);
156 fd_set readfds, errorfds;
161 FD_SET(0, &readfds); // stdin
165 // Fill server FDs in fd_set
166 for( tServer *srv = gpServers; srv; srv = srv->Next )
168 FD_SET(srv->FD, &readfds);
169 FD_SET(srv->FD, &errorfds);
170 if( srv->FD > maxFD )
174 int rv = _SysSelect(maxFD+1, &readfds, 0, &errorfds, NULL, 0);
175 if( rv == -1 ) break;
177 if(FD_ISSET(0, &readfds))
180 char *cmd = Readline_NonBlock(readline_info);
185 ParseUserCommand(cmd);
189 SetCursorPos(giTerminal_Height-1, 0);
190 printf("\x1B[2K"); // Clear line
191 if( gpCurrentWindow->Name[0] )
193 gpCurrentWindow->Server->Name, gpCurrentWindow->Name);
195 printf("[(status)] ");
200 for( tServer *srv = gpServers; srv; srv = srv->Next )
202 if(FD_ISSET(srv->FD, &readfds))
204 if( ProcessIncoming(srv) != 0 ) {
206 _SysDebug("ProcessIncoming failed on FD%i (Server %p %s)",
207 srv->FD, srv, srv->Name);
212 if(FD_ISSET(srv->FD, &errorfds))
214 _SysDebug("Error on FD%i (Server %p %s)",
215 srv->FD, srv, srv->Name);
224 * \todo Actually implement correctly :)
226 int ParseArguments(int argc, const char *argv[])
232 void Cmd_join(char *ArgString)
235 char *channel_name = GetValue(ArgString, &pos);
237 if( gpCurrentWindow->Server )
239 gpCurrentWindow = Window_Create(gpCurrentWindow->Server, channel_name);
241 writef(gpCurrentWindow->Server->FD, "JOIN :%s\n", channel_name);
245 void Cmd_quit(char *ArgString)
247 const char *quit_message = ArgString;
248 if( quit_message == NULL || quit_message[0] == '\0' )
249 quit_message = "/quit - Acess2 IRC Client";
251 for( tServer *srv = gpServers; srv; srv = srv->Next )
253 writef(srv->FD, "QUIT :%s\n", quit_message);
259 void Cmd_window(char *ArgString)
262 char *window_id = GetValue(ArgString, &pos);
263 int window_num = atoi(window_id);
268 window_num --; // Move to base 0
269 // Get `window_num`th window
270 for( win = gpWindows; win && window_num--; win = win->Next );
272 gpCurrentWindow = win;
275 // Otherwise, silently ignore
280 for( tWindow *win = gpWindows; win; win = win->Next, window_num ++ )
283 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
284 "%i: %s/%s", window_num, win->Server->Name, win->Name);
287 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
288 "%i: (status)", window_num);
296 void (*Fcn)(char *ArgString);
300 {"window", Cmd_window},
304 const int ciNumCommands = sizeof(caCommands)/sizeof(caCommands[0]);
307 * \brief Handle a line from the prompt
309 int ParseUserCommand(char *String)
311 if( String[0] == '/' )
316 command = GetValue(String, &pos)+1;
318 // TODO: Prefix matches
320 for( int i = 0; i < ciNumCommands; i ++ )
322 if( strcmp(command, caCommands[i].Name) == 0 ) {
328 caCommands[cmdIdx].Fcn(String+pos);
332 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "", "Unknown command %s", command);
338 // - Only send if server is valid and window name is non-empty
339 if( gpCurrentWindow->Server && gpCurrentWindow->Name[0] )
341 Message_Append(gpCurrentWindow->Server, MSG_TYPE_STANDARD,
342 gsNickname, gpCurrentWindow->Name, String);
343 writef(gpCurrentWindow->Server->FD,
344 "PRIVMSG %s :%s\n", gpCurrentWindow->Name,
354 * \brief Connect to a server
356 tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber)
360 ret = calloc(1, sizeof(tServer) + strlen(Name) + 1);
362 strcpy(ret->Name, Name);
364 // Connect to the remove server
365 ret->FD = OpenTCP( AddressString, PortNumber );
366 if( ret->FD == -1 ) {
367 fprintf(stderr, "%s: Unable to create socket\n", Name);
371 // Append to open list
372 ret->Next = gpServers;
375 // Read some initial data
376 Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Connection opened");
377 ProcessIncoming(ret);
380 writef(ret->FD, "USER %s %s %s : %s\n", gsUsername, gsHostname, AddressString, gsRealName);
381 writef(ret->FD, "NICK %s\n", gsNickname);
382 Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Identified");
383 //printf("%s: Identified\n", Name);
388 tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...)
392 va_start(args, Message);
393 len = vsnprintf(NULL, 0, Message, args);
397 va_start(args, Message);
398 vsnprintf(buf, len+1, Message, args);
401 return Message_Append(Server, Type, Source, Dest, buf);
404 tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message)
407 int msgLen = strlen(Message);
409 // Server==NULL indicates an internal message
410 if( Server == NULL || Source[0] == '\0' )
412 win = &gWindow_Status;
414 // Determine if it's a channel or PM
415 else if( Dest[0] == '#' || Dest[0] == '&' ) // TODO: Better determining here
417 for(win = gpWindows; win; win = win->Next)
419 if( win->Server == Server && strcmp(win->Name, Dest) == 0 )
425 //win = Window_Create(Server, Dest);
426 win = &gWindow_Status; // Stick it in the status window, just in case
430 else if( strcmp(Dest, Server->Nick) != 0 )
432 // Umm... message for someone who isn't us?
433 win = &gWindow_Status; // Stick it in the status window, just in case
437 else if( strchr(Source, '.') ) // TODO: And again, less hack please
440 for(win = gpWindows; win; win = win->Next)
442 if( win->Server == Server && strcmp(win->Name, Source) == 0 )
449 win = &gWindow_Status;
452 // Set source to the server name (instead of the hostname)
453 Source = Server->Name;
458 for(win = gpWindows; win; win = win->Next)
460 if( win->Server == Server && strcmp(win->Name, Source) == 0 )
466 win = Window_Create(Server, Dest);
470 // Create message cache
471 _SysDebug("Win (%s) msg: <%s> %s", win->Name, Source, Message);
473 ret = malloc( sizeof(tMessage) + msgLen + 1 + strlen(Source) + 1 );
474 ret->Source = ret->Data + msgLen + 1;
475 strcpy(ret->Source, Source);
476 strcpy(ret->Data, Message);
478 ret->Server = Server;
480 // Append to window message list
481 ret->Next = win->Messages;
484 // Print now if current window
485 if( win == gpCurrentWindow )
488 printf("\33[T"); // Scroll down 1 (free space below)
489 SetCursorPos(giTerminal_Height-2, 0);
490 int prefixlen = strlen(Source) + 3;
491 int avail = giTerminal_Width - prefixlen;
492 int msglen = strlen(Message);
493 printf("[%s] %.*s", Source, avail, Message);
494 while( msglen > avail ) {
498 SetCursorPos(giTerminal_Height-2, prefixlen);
499 printf("%.*s", avail, Message);
507 tWindow *Window_Create(tServer *Server, const char *Name)
509 tWindow *ret, *prev = NULL;
512 // Get the end of the list
513 // TODO: Cache this instead
514 for( ret = gpCurrentWindow; ret; prev = ret, ret = ret->Next )
517 ret = malloc(sizeof(tWindow) + strlen(Name) + 1);
518 ret->Messages = NULL;
519 ret->Server = Server;
520 ret->ActivityLevel = 1;
521 strcpy(ret->Name, Name);
524 ret->Next = prev->Next;
527 else { // Shouldn't happen really
528 ret->Next = gpWindows;
532 // printf("Win %i %s:%s created\n", num, Server->Name, Name);
537 void Redraw_Screen(void)
542 printf("\x1B[2J"); // Clear screen
543 printf("\x1B[0;0H"); // Reset cursor
545 msg = gpCurrentWindow->Messages;
549 // Note: This renders from the bottom up
550 for( y = giTerminal_Height - 1; y -- && msg; msg = msg->Next)
552 int msglen = strlen(msg->Data);
553 int prefix_len = 3 + strlen(msg->Source);
554 int line_avail = giTerminal_Width - prefix_len;
557 y -= msglen / line_avail; // Extra lines (y-- above handles the 1 line case)
559 printf("[%s] ", msg->Source);
561 while(done < msglen) {
562 done += printf("%.*s", line_avail, msg->Data+done);
564 SetCursorPos(y+i, prefix_len);
568 // Bottom line is rendered by the prompt
571 void Cmd_PRIVMSG(tServer *Server, const char *Dest, const char *Src, const char *Message)
573 Message_Append(Server, MSG_TYPE_STANDARD, Dest, Src, Message);
574 //printf("<%s:%s:%s> %s\n", Server->Name, Dest, Src, Message);
577 void ParseServerLine_Numeric(tServer *Server, const char *ident, int Num, char *Line)
581 const char *user = GetValue(Line, &pos);
583 if( Line[pos] == ':' ) {
584 message = Line + pos + 1;
587 message = GetValue(Line, &pos);
593 user = message; // Channel
594 message = Line + pos + 1; // Topic
595 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Topic: %s", message);
597 case 333: // Topic set by
598 user = message; // Channel
599 message = GetValue(Line, &pos); // User
600 GetValue(Line, &pos); // Timestamp
601 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Set by %s", message);
603 case 353: // /NAMES list
604 // <user> = <channel> :list
605 // '=' was eaten in and set to message
606 user = GetValue(Line, &pos); // Actually channel
607 message = Line + pos + 1; // List
608 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Names: %s", message);
610 case 366: // end of /NAMES list
611 // <user> <channel> :msg
613 message = Line + pos + 1;
614 Message_Append(Server, MSG_TYPE_SERVER, user, user, message);
616 case 372: // MOTD Data
617 case 375: // MOTD Start
618 case 376: // MOTD End
621 //printf("[%s] %i %s\n", Server->Name, num, message);
622 Message_Append(Server, MSG_TYPE_SERVER, ident, user, message);
627 void ParseServerLine_String(tServer *Server, const char *ident, const char *cmd, char *Line)
630 _SysDebug("ident=%s,cmd=%s,Line=%s", ident, cmd, Line);
631 if( strcmp(cmd, "NOTICE") == 0 )
633 const char *class = GetValue(Line, &pos);
634 _SysDebug("NOTICE class='%s'", class);
636 const char *message = (Line[pos] == ':') ? Line + pos + 1 : GetValue(Line, &pos);
638 //printf("[%s] NOTICE %s: %s\n", Server->Name, ident, message);
639 char *ident_bang = strchr(ident, '!');
643 Message_Append(Server, MSG_TYPE_NOTICE, ident, "", message);
645 else if( strcmp(cmd, "PRIVMSG") == 0 )
647 const char *dest = GetValue(Line, &pos);
648 const char *message = (Line[pos] == ':') ? Line + pos + 1 : GetValue(Line, &pos);
650 // TODO: Catch when the privmsg is addressed to the user
652 // Cmd_PRIVMSG(Server, dest, ident, message);
653 char *ident_bang = strchr(ident, '!');
657 Message_Append(Server, MSG_TYPE_STANDARD, ident, dest, message);
659 else if( strcmp(cmd, "JOIN" ) == 0 )
661 const char *channel = Line + pos + 1;
663 Message_AppendF(Server, MSG_TYPE_JOIN, "", channel, "%s has joined", ident);
664 //Window_Create(Server, channel);
666 else if( strcmp(cmd, "PART" ) == 0 )
668 const char *channel = Line + pos + 1;
670 Message_AppendF(Server, MSG_TYPE_PART, "", channel, "%s has left", ident);
671 //Window_Create(Server, channel);
675 Message_AppendF(Server, MSG_TYPE_SERVER, "", "", "Unknown message %s (%s)", cmd, Line);
681 void ParseServerLine(tServer *Server, char *Line)
685 _SysDebug("[%s] %s", Server->Name, Line);
691 const char *ident = GetValue(Line, &pos); // Ident (user or server)
692 const char *cmd = GetValue(Line, &pos);
695 if( isdigit(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2]) )
698 num = (cmd[0] - '0') * 100;
699 num += (cmd[1] - '0') * 10;
700 num += (cmd[2] - '0') * 1;
702 ParseServerLine_Numeric(Server, ident, num, Line+pos);
706 ParseServerLine_String(Server, ident, cmd, Line+pos);
710 const char *cmd = GetValue(Line, &pos);
712 if( strcmp(cmd, "PING") == 0 ) {
713 writef(Server->FD, "PONG %s\n", gsHostname);
718 Message_AppendF(NULL, MSG_TYPE_UNK, "", "", "Client Command: %s", Line);
724 * \brief Process incoming lines from the server
726 int ProcessIncoming(tServer *Server)
731 // While there is data in the buffer, read it into user memory and
732 // process it line by line
733 // ioctl#8 on a TCP client gets the number of bytes in the recieve buffer
734 // - Used to avoid blocking
736 while( (len = _SysIOCtl(Server->FD, 8, NULL)) > 0 )
740 len = _SysRead(Server->FD, &Server->InBuf[Server->ReadPos], BUFSIZ - Server->ReadPos);
744 Server->InBuf[Server->ReadPos + len] = '\0';
748 while( (newline = strchr(ptr, '\n')) )
751 if( newline[-1] == '\r' ) newline[-1] = '\0';
752 ParseServerLine(Server, ptr);
756 // Handle incomplete lines
757 if( ptr - Server->InBuf < len + Server->ReadPos ) {
758 // Update the read position
759 // InBuf ReadPos ptr ReadPos+len
760 // | old | new used | new unused |
761 Server->ReadPos = len + Server->ReadPos - (ptr - Server->InBuf);
762 // Copy stuff back (moving "new unused" to the start of the buffer)
763 memcpy(Server->InBuf, ptr, Server->ReadPos);
776 * \brief Write a formatted string to a file descriptor
779 int writef(int FD, const char *Format, ...)
784 va_start(args, Format);
785 len = vsnprintf(NULL, 0, Format, args);
790 va_start(args, Format);
791 vsnprintf(buf, len+1, Format, args);
794 return _SysWrite(FD, buf, len);
799 * \brief Initialise a TCP connection to \a AddressString on port \a PortNumber
801 int OpenTCP(const char *AddressString, short PortNumber)
807 addrType = Net_ParseAddress(AddressString, addrBuffer);
808 if( addrType == 0 ) {
809 fprintf(stderr, "Unable to parse '%s' as an IP address\n", AddressString);
810 _SysDebug("Unable to parse '%s' as an IP address\n", AddressString);
814 // Finds the interface for the destination address
815 fd = Net_OpenSocket(addrType, addrBuffer, "tcpc");
817 fprintf(stderr, "Unable to open TCP Client to '%s'\n", AddressString);
818 _SysDebug("Unable to open TCP client to '%s'\n", AddressString);
822 // Set remote port and address
823 // printf("Setting port and remote address\n");
824 _SysIOCtl(fd, 5, &PortNumber);
825 _SysIOCtl(fd, 6, addrBuffer);
828 // printf("Initiating connection\n");
829 if( _SysIOCtl(fd, 7, NULL) == 0 ) {
830 // Shouldn't happen :(
831 fprintf(stderr, "Unable to start connection\n");
840 * \brief Read a space-separated value from a string
842 char *GetValue(char *Src, int *Ofs)
845 char *ret = Src + pos;
848 if( !Src ) return NULL;
850 while( *ret == ' ' ) ret ++;
852 end = strchr(ret, ' ');
857 end = ret + strlen(ret) - 1;
861 while( *ret == ' ' ) end ++;
867 void SetCursorPos(int Row, int Col)
869 printf("\x1B[%i;%iH", Row, Col);
872 static inline int isdigit(int ch)
874 return '0' <= ch && ch < '9';