Usermode/IRC Client - Fixed incorrect ordering on \e[H arguments
[tpg/acess2.git] / Usermode / Applications / irc_src / main.c
1 /*
2  * Acess2 IRC Client
3  */
4 #include <acess/sys.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <net.h>
9 #include <readline.h>
10 #include <acess/devices/pty.h>
11
12 // === TYPES ===
13 typedef struct sServer {
14         struct sServer  *Next;
15          int    FD;
16         char    InBuf[BUFSIZ+1];
17          int    ReadPos;
18         char    Name[];
19 } tServer;
20
21 typedef struct sMessage
22 {
23         struct sMessage *Next;
24         time_t  Timestamp;
25         tServer *Server;
26          int    Type;
27         char    *Source;        // Pointer into `Data`
28         char    Data[];
29 }       tMessage;
30
31 typedef struct sWindow
32 {
33         struct sWindow  *Next;
34         tMessage        *Messages;
35         tServer *Server;        //!< Canoical server (can be NULL)
36          int    ActivityLevel;
37         char    Name[]; // Channel name / remote user
38 }       tWindow;
39
40 enum eMessageTypes
41 {
42         MSG_TYPE_NULL,
43         MSG_TYPE_SERVER,        // Server message
44         
45         MSG_TYPE_NOTICE,        // NOTICE command
46         MSG_TYPE_JOIN,  // JOIN command
47         MSG_TYPE_PART,  // PART command
48         MSG_TYPE_QUIT,  // QUIT command
49         
50         MSG_TYPE_STANDARD,      // Standard line
51         MSG_TYPE_ACTION,        // /me
52         
53         MSG_TYPE_UNK
54 };
55
56 // === PROTOTYPES ===
57  int    ParseArguments(int argc, const char *argv[]);
58  int    ParseUserCommand(char *String);
59 // --- 
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);
65
66  int    ProcessIncoming(tServer *Server);
67 // --- Helpers
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);
73
74 // === GLOBALS ===
75 char    *gsUsername = "user";
76 char    *gsHostname = "acess";
77 char    *gsRealName = "Acess2 IRC Client";
78 char    *gsNickname = "acess";
79 tServer *gpServers;
80 tWindow gWindow_Status = {
81         NULL, NULL, NULL,       // No next, empty list, no server
82         0, {""} // No activity, empty name (rendered as status)
83 };
84 tWindow *gpWindows = &gWindow_Status;
85 tWindow *gpCurrentWindow = &gWindow_Status;
86  int    giTerminal_Width = 80;
87  int    giTerminal_Height = 25;
88
89 // ==== CODE ====
90 void ExitHandler(void)
91 {
92         printf("\x1B[?1047l");
93         printf("Quit\n");
94 }
95
96 int main(int argc, const char *argv[], const char *envp[])
97 {
98          int    tmp;
99         tReadline       *readline_info;
100         
101         // Parse Command line
102         if( (tmp = ParseArguments(argc, argv)) )        return tmp;
103         
104         atexit(ExitHandler);
105         
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;
110         }
111         else {
112                 struct ptydims  dims;
113                 _SysIOCtl(1, PTY_IOCTL_GETDIMS, &dims);
114                 giTerminal_Width = dims.W;
115                 giTerminal_Height = dims.H;
116         }
117         
118         printf("\x1B[?1047h");
119         printf("\x1B[%i;%ir", 0, giTerminal_Height-1);
120         
121         SetCursorPos(giTerminal_Height-1, 0);
122         printf("[(status)] ");
123         
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 );
127         // Freenode (#osdev)
128 //      gWindow_Status.Server = Server_Connect( "Freenode", "89.16.176.16", 6667 );
129 //      gWindow_Status.Server = Server_Connect( "Host", "10.0.2.2", 6667 );
130         // Local server
131 //      gWindow_Status.Server = Server_Connect( "BitlBee", "192.168.1.39", 6667 );
132         
133         if( !gWindow_Status.Server )
134                 return -1;
135         
136         SetCursorPos(giTerminal_Height-1, 0);
137         printf("[(status)] ");
138         fflush(stdout);
139         readline_info = Readline_Init(1);
140         
141         for( ;; )
142         {
143                 fd_set  readfds, errorfds;
144                  int    rv, maxFD = 0;
145                 tServer *srv;
146                 
147                 FD_ZERO(&readfds);
148                 FD_ZERO(&errorfds);
149                 FD_SET(0, &readfds);    // stdin
150                 
151                 // Fill server FDs in fd_set
152                 for( srv = gpServers; srv; srv = srv->Next )
153                 {
154                         FD_SET(srv->FD, &readfds);
155                         FD_SET(srv->FD, &errorfds);
156                         if( srv->FD > maxFD )
157                                 maxFD = srv->FD;
158                 }
159                 
160                 rv = _SysSelect(maxFD+1, &readfds, 0, &errorfds, NULL, 0);
161                 if( rv == -1 )  break;
162                 
163                 if(FD_ISSET(0, &readfds))
164                 {
165                         // User input
166                         char    *cmd = Readline_NonBlock(readline_info);
167                         if( cmd )
168                         {
169                                 if( cmd[0] )
170                                 {
171                                         ParseUserCommand(cmd);
172                                 }
173                                 free(cmd);
174                                 // Prompt
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);
179                                 else
180                                         printf("[(status)] ");
181                                 fflush(stdout);
182                         }
183                 }
184                 
185                 // Server response
186                 for( srv = gpServers; srv; srv = srv->Next )
187                 {
188                         if(FD_ISSET(srv->FD, &readfds))
189                         {
190                                 if( ProcessIncoming(srv) != 0 ) {
191                                         // Oops, error
192                                         break;
193                                 }
194                         }
195                         
196                         if(FD_ISSET(srv->FD, &errorfds))
197                         {
198                                 break;
199                         }
200                 }
201                 
202                 // Oops, an error
203                 if( srv )       break;
204         }
205         
206         {
207                 tServer *srv;
208                 for( srv = gpServers; srv; srv = srv->Next )
209                         _SysClose(srv->FD);
210         }
211         return 0;
212 }
213
214 /**
215  * \todo Actually implement correctly :)
216  */
217 int ParseArguments(int argc, const char *argv[])
218 {
219         return 0;
220 }
221
222
223 void Cmd_join(char *ArgString)
224 {
225          int    pos=0;
226         char    *channel_name = GetValue(ArgString, &pos);
227         
228         if( gpCurrentWindow->Server )
229         {
230                 writef(gpCurrentWindow->Server->FD, "JOIN :%s\n", channel_name);
231         }
232 }
233
234 void Cmd_quit(char *ArgString)
235 {
236         const char *quit_message = ArgString;
237         if( quit_message == NULL || quit_message[0] == '\0' )
238                 quit_message = "/quit - Acess2 IRC Client";
239         
240         for( tServer *srv = gpServers; srv; srv = srv->Next )
241         {
242                 writef(srv->FD, "QUIT :%s\n", quit_message);
243         }
244         
245         exit(0);
246 }
247
248 void Cmd_window(char *ArgString)
249 {
250          int    pos = 0;
251         char    *window_id = GetValue(ArgString, &pos);
252          int    window_num = atoi(window_id);
253         
254         if( window_num > 0 )
255         {
256                 tWindow *win;
257                 window_num --;  // Move to base 0
258                 // Get `window_num`th window
259                 for( win = gpWindows; win && window_num--; win = win->Next );
260                 if( win ) {
261                         gpCurrentWindow = win;
262                         Redraw_Screen();
263                 }
264                 // Otherwise, silently ignore
265         }
266         else
267         {
268                 window_num = 1;
269                 for( tWindow *win = gpWindows; win; win = win->Next, window_num ++ )
270                 {
271                         if( win->Name[0] ) {
272                                 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
273                                         "%i: %s/%s", window_num, win->Server->Name, win->Name);
274                         }
275                         else {
276                                 Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "",
277                                         "%i: (status)", window_num);
278                         }
279                 }
280         }
281 }
282
283 const struct {
284         const char *Name;
285         void    (*Fcn)(char *ArgString);
286 } caCommands[] = {
287         {"join", Cmd_join},
288         {"quit", Cmd_quit},
289         {"window", Cmd_window},
290         {"win",    Cmd_window},
291         {"w",      Cmd_window},
292 };
293 const int ciNumCommands = sizeof(caCommands)/sizeof(caCommands[0]);
294
295 /**
296  * \brief Handle a line from the prompt
297  */
298 int ParseUserCommand(char *String)
299 {
300         if( String[0] == '/' )
301         {
302                 char    *command;
303                  int    pos = 0;
304                 
305                 command = GetValue(String, &pos)+1;
306
307                 // TODO: Prefix matches
308                  int    cmdIdx = -1;
309                 for( int i = 0; i < ciNumCommands; i ++ )
310                 {
311                         if( strcmp(command, caCommands[i].Name) == 0 ) {
312                                 cmdIdx = i;
313                                 break;
314                         }
315                 }
316                 if( cmdIdx != -1 ) {
317                         caCommands[cmdIdx].Fcn(String+pos);
318                 }
319                 else
320                 {
321                         Message_AppendF(NULL, MSG_TYPE_SERVER, "client", "", "Unknown command %s", command);
322                 }
323         }
324         else
325         {
326                 // Message
327                 // - Only send if server is valid and window name is non-empty
328                 if( gpCurrentWindow->Server && gpCurrentWindow->Name[0] )
329                 {
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,
334                                 String
335                                 );
336                 }
337         }
338         
339         return 0;
340 }
341
342 /**
343  * \brief Connect to a server
344  */
345 tServer *Server_Connect(const char *Name, const char *AddressString, short PortNumber)
346 {
347         tServer *ret;
348         
349         ret = calloc(1, sizeof(tServer) + strlen(Name) + 1);
350         
351         strcpy(ret->Name, Name);
352         
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);
357                 return NULL;
358         }
359         
360         // Append to open list
361         ret->Next = gpServers;
362         gpServers = ret;
363         
364         // Read some initial data
365         Message_Append(NULL, MSG_TYPE_SERVER, Name, "", "Connection opened");
366         ProcessIncoming(ret);
367         
368         // Identify
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);
373         
374         return ret;
375 }
376
377 tMessage *Message_AppendF(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message, ...)
378 {
379         va_list args;
380          int    len;
381         va_start(args, Message);
382         len = vsnprintf(NULL, 0, Message, args);
383         {
384                 char    buf[len+1];
385                 vsnprintf(buf, len+1, Message, args);
386                 return Message_Append(Server, Type, Source, Dest, buf);
387         }
388 }
389
390 tMessage *Message_Append(tServer *Server, int Type, const char *Source, const char *Dest, const char *Message)
391 {
392         tWindow *win = NULL;
393          int    msgLen = strlen(Message);
394         
395         // Server==NULL indicates an internal message
396         if( Server == NULL || Source[0] == '\0' )
397         {
398                 win = &gWindow_Status;
399         }
400         // Determine if it's a channel or PM
401         else if( Dest[0] == '#' || Dest[0] == '&' )     // TODO: Better determining here
402         {
403                 for(win = gpWindows; win; win = win->Next)
404                 {
405                         if( win->Server == Server && strcmp(win->Name, Dest) == 0 )
406                         {
407                                 break;
408                         }
409                 }
410                 if( !win ) {
411                         win = Window_Create(Server, Dest);
412                 }
413         }
414         #if 0
415         else if( strcmp(Dest, Server->Nick) != 0 )
416         {
417                 // Umm... message for someone who isn't us?
418                 win = &gWindow_Status;  // Stick it in the status window, just in case
419         }
420         #endif
421         // Server message?
422         else if( strchr(Source, '.') )  // TODO: And again, less hack please
423         {
424                 #if 1
425                 for(win = gpWindows; win; win = win->Next)
426                 {
427                         if( win->Server == Server && strcmp(win->Name, Source) == 0 )
428                         {
429                                 break;
430                         }
431                 }
432                 #endif
433                 if( !win ) {
434                         win = &gWindow_Status;
435                 }
436                 
437         }
438         // Private message
439         else
440         {
441                 for(win = gpWindows; win; win = win->Next)
442                 {
443                         if( win->Server == Server && strcmp(win->Name, Source) == 0 )
444                         {
445                                 break;
446                         }
447                 }
448                 if( !win ) {
449                         win = Window_Create(Server, Dest);
450                 }
451         }
452
453         // Create message cache 
454         _SysDebug("Win (%s) msg: <%s> %s", win->Name, Source, Message);
455         tMessage        *ret;
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);
460         ret->Type = Type;
461         ret->Server = Server;
462         
463         // Append to window message list
464         ret->Next = win->Messages;
465         win->Messages = ret;
466         
467         // Print now if current window
468         if( win == gpCurrentWindow )
469         {
470                 printf("\x1b[s");
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 ) {
478                         msglen -= avail;
479                         Message += avail;
480                         printf("\x1B[T");
481                         SetCursorPos(giTerminal_Height-2, prefixlen);
482                         printf("%.*s\n", avail, Message);
483                 }
484                 printf("\x1b[u");
485         }
486         
487         return ret;
488 }
489
490 tWindow *Window_Create(tServer *Server, const char *Name)
491 {
492         tWindow *ret, *prev = NULL;
493          int    num = 1;
494         
495         // Get the end of the list
496         // TODO: Cache this instead
497         for( ret = gpCurrentWindow; ret; prev = ret, ret = ret->Next )
498                 num ++;
499         
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);
505         
506         if( prev ) {
507                 ret->Next = prev->Next;
508                 prev->Next = ret;
509         }
510         else {  // Shouldn't happen really
511                 ret->Next = gpWindows;
512                 gpWindows = ret;
513         }
514         
515 //      printf("Win %i %s:%s created\n", num, Server->Name, Name);
516         
517         return ret;
518 }
519
520 void Redraw_Screen(void)
521 {
522          int    y = 0;
523         tMessage        *msg;
524
525         printf("\x1B[2J");      // Clear screen
526         printf("\x1B[0;0H");    // Reset cursor
527
528         msg = gpCurrentWindow->Messages;
529         
530         // TODO: Title bar?
531
532         // Note: This renders from the bottom up
533         for( y = giTerminal_Height - 1; y -- && msg; msg = msg->Next)
534         {
535                  int    msglen = strlen(msg->Data);
536                  int    prefix_len = 3 + strlen(msg->Source);
537                  int    line_avail = giTerminal_Width - prefix_len;
538                  int    i = 0, done = 0;
539                 
540                 y -= msglen / line_avail;       // Extra lines (y-- above handles the 1 line case)
541                 SetCursorPos(y, 0);
542                 printf("[%s] ", msg->Source);
543                 
544                 while(done < msglen) {
545                         done += printf("%.*s", line_avail, msg->Data+done);
546                         i ++;
547                         SetCursorPos(y+i, prefix_len);
548                 }
549         }
550
551         // Bottom line is rendered by the prompt
552 }
553
554 void Cmd_PRIVMSG(tServer *Server, const char *Dest, const char *Src, const char *Message)
555 {
556         Message_Append(Server, MSG_TYPE_STANDARD, Dest, Src, Message);
557         //printf("<%s:%s:%s> %s\n", Server->Name, Dest, Src, Message);
558 }
559
560 /**
561  */
562 void ParseServerLine(tServer *Server, char *Line)
563 {
564          int    pos = 0;
565         char    *ident, *cmd;
566
567 //      _SysDebug("[%s] %s", Server->Name, Line);       
568         
569         // Message?
570         if( *Line == ':' )
571         {
572                 pos ++;
573                 ident = GetValue(Line, &pos);   // Ident (user or server)
574                 cmd = GetValue(Line, &pos);
575                 
576                 // Numeric command
577                 if( isdigit(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2]) )
578                 {
579                         char    *user, *message;
580                          int    num;
581                         num  = (cmd[0] - '0') * 100;
582                         num += (cmd[1] - '0') * 10;
583                         num += (cmd[2] - '0') * 1;
584                         
585                         user = GetValue(Line, &pos);
586                         
587                         if( Line[pos] == ':' ) {
588                                 message = Line + pos + 1;
589                         }
590                         else {
591                                 message = GetValue(Line, &pos);
592                         }
593                         
594                         switch(num)
595                         {
596                         case 332:       // Topic
597                                 user = message; // Channel
598                                 message = Line + pos + 1;       // Topic
599                                 Message_AppendF(Server, MSG_TYPE_SERVER, user, user, "Topic: %s", message);
600                                 break;
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);
606                                 break;
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);
613                                 break;
614                         case 366:       // end of /NAMES list
615                                 // <user> <channel> :msg
616                                 user = message;
617                                 message = Line + pos + 1;
618                                 Message_Append(Server, MSG_TYPE_SERVER, user, user, message);
619                                 break;
620                         case 372:       // MOTD Data
621                         case 375:       // MOTD Start
622                         case 376:       // MOTD End
623                                 
624                         default:
625                                 //printf("[%s] %i %s\n", Server->Name, num, message);
626                                 Message_Append(Server, MSG_TYPE_SERVER, ident, user, message);
627                                 break;
628                         }
629                 }
630                 else if( strcmp(cmd, "NOTICE") == 0 )
631                 {
632                         char    *class, *message;
633                         
634                         class = GetValue(Line, &pos);
635                         _SysDebug("NOTICE class='%s'", class);
636                         
637                         if( Line[pos] == ':' ) {
638                                 message = Line + pos + 1;
639                         }
640                         else {
641                                 message = GetValue(Line, &pos);
642                         }
643                         
644                         //printf("[%s] NOTICE %s: %s\n", Server->Name, ident, message);
645                         char *ident_bang = strchr(ident, '!');
646                         if( ident_bang ) {
647                                 *ident_bang = '\0';
648                         }
649                         Message_Append(Server, MSG_TYPE_NOTICE, ident, "", message);
650                 }
651                 else if( strcmp(cmd, "PRIVMSG") == 0 )
652                 {
653                         char    *dest, *message;
654                         dest = GetValue(Line, &pos);
655                         
656                         if( Line[pos] == ':' ) {
657                                 message = Line + pos + 1;
658                         }
659                         else {
660                                 message = GetValue(Line, &pos);
661                         }
662
663                         // TODO: Catch when the privmsg is addressed to the user
664
665 //                      Cmd_PRIVMSG(Server, dest, ident, message);
666                         char *ident_bang = strchr(ident, '!');
667                         if( ident_bang ) {
668                                 *ident_bang = '\0';
669                         }
670                         Message_Append(Server, MSG_TYPE_STANDARD, ident, dest, message);
671                 }
672                 else if( strcmp(cmd, "JOIN" ) == 0 )
673                 {
674                         char    *channel;
675                         channel = Line + pos + 1;
676                         Window_Create(Server, channel);
677                 }
678                 else
679                 {
680                         Message_AppendF(Server, MSG_TYPE_SERVER, "", "", "Unknown message %s (%s)\n", cmd, Line+pos);
681                 }
682         }
683         else {          
684                 cmd = GetValue(Line, &pos);
685                 
686                 if( strcmp(cmd, "PING") == 0 ) {
687                         writef(Server->FD, "PONG %s\n", gsHostname);
688                         
689                 }
690                 else {
691                         // Command to client
692                         Message_AppendF(NULL, MSG_TYPE_UNK, "", "", "Client Command: %s", Line);
693                 }
694         }
695 }
696
697 /**
698  * \brief Process incoming lines from the server
699  */
700 int ProcessIncoming(tServer *Server)
701 {       
702         char    *ptr, *newline;
703          int    len;
704         
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
709         #if NON_BLOCK_READ
710         while( (len = _SysIOCtl(Server->FD, 8, NULL)) > 0 )
711         {
712         #endif
713                 // Read data
714                 len = _SysRead(Server->FD, &Server->InBuf[Server->ReadPos], BUFSIZ - Server->ReadPos);
715                 if( len == -1 ) {
716                         return -1;
717                 }
718                 Server->InBuf[Server->ReadPos + len] = '\0';
719                 
720                 // Break into lines
721                 ptr = Server->InBuf;
722                 while( (newline = strchr(ptr, '\n')) )
723                 {
724                         *newline = '\0';
725                         if( newline[-1] == '\r' )       newline[-1] = '\0';
726                         ParseServerLine(Server, ptr);
727                         ptr = newline + 1;
728                 }
729                 
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);
738                 }
739                 else {
740                         Server->ReadPos = 0;
741                 }
742         #if NON_BLOCK_READ
743         }
744         #endif
745         
746         return 0;
747 }
748
749 /**
750  * \brief Write a formatted string to a file descriptor
751  * 
752  */
753 int writef(int FD, const char *Format, ...)
754 {
755         va_list args;
756          int    len;
757         
758         va_start(args, Format);
759         len = vsnprintf(NULL, 0, Format, args);
760         va_end(args);
761         
762         {
763                 char    buf[len+1];
764                 va_start(args, Format);
765                 vsnprintf(buf, len+1, Format, args);
766                 va_end(args);
767                 
768                 return _SysWrite(FD, buf, len);
769         }
770 }
771
772 /**
773  * \brief Initialise a TCP connection to \a AddressString on port \a PortNumber
774  */
775 int OpenTCP(const char *AddressString, short PortNumber)
776 {
777          int    fd, addrType;
778         char    addrBuffer[8];
779         
780         // Parse IP Address
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);
785                 return -1;
786         }
787         
788         // Finds the interface for the destination address
789         fd = Net_OpenSocket(addrType, addrBuffer, "tcpc");
790         if( fd == -1 ) {
791                 fprintf(stderr, "Unable to open TCP Client to '%s'\n", AddressString);
792                 _SysDebug("Unable to open TCP client to '%s'\n", AddressString);
793                 return -1;
794         }
795         
796         // Set remote port and address
797 //      printf("Setting port and remote address\n");
798         _SysIOCtl(fd, 5, &PortNumber);
799         _SysIOCtl(fd, 6, addrBuffer);
800         
801         // Connect
802 //      printf("Initiating connection\n");
803         if( _SysIOCtl(fd, 7, NULL) == 0 ) {
804                 // Shouldn't happen :(
805                 fprintf(stderr, "Unable to start connection\n");
806                 return -1;
807         }
808         
809         // Return descriptor
810         return fd;
811 }
812
813 /**
814  * \brief Read a space-separated value from a string
815  */
816 char *GetValue(char *Src, int *Ofs)
817 {
818          int    pos = *Ofs;
819         char    *ret = Src + pos;
820         char    *end;
821         
822         if( !Src )      return NULL;
823         
824         while( *ret == ' ' )    ret ++;
825         
826         end = strchr(ret, ' ');
827         if( end ) {
828                 *end = '\0';
829         }
830         else {
831                 end = ret + strlen(ret) - 1;
832         }
833         
834         end ++ ;
835         while( *ret == ' ' )    end ++;
836         *Ofs = end - Src;
837         
838         return ret;
839 }
840
841 void SetCursorPos(int Row, int Col)
842 {
843         printf("\x1B[%i;%iH", Row, Col);
844 }
845
846 static inline int isdigit(int ch)
847 {
848         return '0' <= ch && ch < '9';
849 }

UCC git Repository :: git.ucc.asn.au