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

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