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

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