Kernel/serial - Debugging added (disabled)
[tpg/acess2.git] / KernelLand / Kernel / drv / pty.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang)
4  *
5  * drv/pty.c
6  * - Pseudo Terminals
7  */
8 #define DEBUG   0
9 #include <acess.h>
10 #include <vfs.h>
11 #include <fs_devfs.h>
12 #include <drv_pty.h>
13 #include <modules.h>
14 #include <rwlock.h>
15 #include <mutex.h>
16 #include <posix_signals.h>
17
18 // === CONSTANTS ===
19 #define OUTPUT_RINGBUFFER_LEN   1024    // Number of bytes in output queue before client blocks
20 #define INPUT_RINGBUFFER_LEN    256     // Number of bytes in input queue before being dropped
21 #define INPUT_LINE_LEN  256
22
23 // === TYPES ===
24 struct sPTY
25 {
26         tPTY    *Next;
27         
28         char    *Name;
29          int    NumericName;
30         
31         void    *OutputHandle;
32         tPTY_OutputFcn  OutputFcn;
33         tPTY_ReqResize  ReqResize;
34         tPTY_ModeSet    ModeSet;
35
36         struct ptymode  Mode;
37         struct ptydims  Dims;
38
39          int    HasHitEOF;      
40         tMutex  InputMutex;
41          int    InputWritePos;
42          int    InputReadPos;
43         char    InputData[INPUT_RINGBUFFER_LEN];
44         
45          int    LineLength;
46         char    LineData[INPUT_LINE_LEN];
47
48         tMutex  OutputMutex;    
49          int    OutputWritePos;
50          int    OutputReadPos;
51         char    OutputData[OUTPUT_RINGBUFFER_LEN];
52         
53         tVFS_Node       *ServerNode;
54         tVFS_Node       ClientNode;
55         tVFS_ACL        OwnerRW;
56
57         tPGID   ControllingProcGroup;
58 };
59
60 // === PROTOTYPES ===
61  int    PTY_Install(char **Arguments);
62  int    PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX]);
63 tVFS_Node       *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
64
65 size_t  _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len);
66 size_t  _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len);
67 size_t  PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length);
68 size_t  PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length);
69 // PTY_SendInput
70 size_t  PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
71 size_t  PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
72 void    PTY_ReferenceClient(tVFS_Node *Node);
73 void    PTY_CloseClient(tVFS_Node *Node);
74 size_t  PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags);
75 size_t  PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags);
76 void    PTY_CloseServer(tVFS_Node *Node);
77  int    PTY_IOCtl(tVFS_Node *Node, int ID, void *Arg);
78
79 // === GLOBALS ===
80 MODULE_DEFINE(0, 0x100, PTY, PTY_Install, NULL, NULL);
81 tVFS_NodeType   gPTY_NodeType_Root = {
82         .TypeName = "PTY-Root",
83         .ReadDir = PTY_ReadDir,
84         .FindDir = PTY_FindDir,
85 };
86 tVFS_NodeType   gPTY_NodeType_Client = {
87         .TypeName = "PTY-Client",
88         .Read = PTY_ReadClient,
89         .Write = PTY_WriteClient,
90         .IOCtl = PTY_IOCtl,
91         .Reference = PTY_ReferenceClient,
92         .Close = PTY_CloseClient
93 };
94 tVFS_NodeType   gPTY_NodeType_Server = {
95         .TypeName = "PTY-Server",
96         .Read = PTY_ReadServer,
97         .Write = PTY_WriteServer,
98         .IOCtl = PTY_IOCtl,
99         .Close = PTY_CloseServer
100 };
101 tDevFS_Driver   gPTY_Driver = {
102         .Name = "pts",
103         .RootNode = {
104                 .Flags = VFS_FFLAG_DIRECTORY,
105                 .Type = &gPTY_NodeType_Root,
106                 .Size = -1
107         }
108 };
109  int    giPTY_NumCount;
110 tRWLock glPTY_NumPTYs;
111 tPTY    *gpPTY_FirstNumPTY;
112  int    giPTY_NamedCount;
113 tRWLock glPTY_NamedPTYs;
114 tPTY    *gpPTY_FirstNamedPTY;
115
116 // === CODE ===
117 int PTY_Install(char **Arguments)
118 {
119         DevFS_AddDevice(&gPTY_Driver);
120         return MODULE_ERR_OK;
121 }
122
123 // --- Management ---
124 tPTY *PTY_Create(const char *Name, void *Handle, tPTY_OutputFcn Output, tPTY_ReqResize ReqResize, tPTY_ModeSet ModeSet, const struct ptydims *InitialDims, const struct ptymode *InitialMode)
125 {
126         tPTY    **prev_np = NULL;
127         size_t  namelen;
128          int    idx = 1;
129         
130         if( !Name )
131                 Name = "";
132         
133         if( Name[0] == '\0' )
134         {
135                 RWLock_AcquireWrite(&glPTY_NumPTYs);
136                 // Get a pty ID if Name==NULL
137                 prev_np = &gpPTY_FirstNumPTY;
138                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; prev_np = &pty->Next, pty = pty->Next )
139                 {
140                         if( pty->NumericName > idx )
141                                 break;
142                         idx ++;
143                 }
144                 namelen = snprintf(NULL,0, "%u", idx);
145         }
146         else if( Name[strlen(Name)-1] == '#' )
147         {
148                 // Sequenced PTYs
149                 // - "gui#" would translate to "gui0", "gui1", "gui2", ...
150                 //   whichever is free
151                 prev_np = &gpPTY_FirstNamedPTY;
152
153                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
154                 idx = 0;
155                 namelen = strlen(Name)-1;
156                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
157                 {
158                          int    cmp = strncmp(pty->Name, Name, namelen);
159                         if( cmp < 0 )
160                                 continue ;
161                         if( cmp > 0 )
162                                 break;
163
164                         // Skip non-numbered
165                         if( pty->Name[namelen] == '\0' )
166                                 continue ;                      
167
168                         // Find an unused index
169                         char    *name_end;
170                          int    this_idx = strtol(pty->Name+namelen, &name_end, 10);
171                         if( *name_end != '\0' )
172                                 continue;
173                         if( this_idx > idx )
174                                 break;
175                         idx ++;
176                 }
177                 
178                 namelen += snprintf(NULL, 0, "%u", idx);
179         }
180         else
181         {
182                 prev_np = &gpPTY_FirstNamedPTY;
183                 
184                 // Check the name isn't decimal
185                 char *end;
186                 if( strtol(Name, &end, 10) != 0 && *end == '\0' ) {
187                         errno = EINVAL;
188                         return NULL;
189                 }
190
191                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
192                 // Detect duplicates
193                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; prev_np = &pty->Next, pty = pty->Next )
194                 {
195                          int    cmp = strcmp(pty->Name, Name);
196                         if( cmp < 0 )
197                                 continue;
198                         if( cmp == 0 ) {
199                                 RWLock_Release(&glPTY_NamedPTYs);
200                                 errno = EEXIST;
201                                 return NULL;
202                         }
203                         break;
204                 }
205                 namelen = strlen(Name);
206                 idx = -1;
207         }
208         
209         tPTY *ret = calloc(sizeof(tPTY) + namelen + 1, 1);
210         if(!ret) {
211                 errno = ENOMEM;
212                 return NULL;
213         }
214         
215         // - List maintainance
216         ret->Next = *prev_np;
217         *prev_np = ret;
218         // - PTY Name (Used by VT)
219         ret->Name = (char*)(ret + 1);
220         if( idx == -1 )
221                 strcpy(ret->Name, Name);
222         else if( Name[0] )
223                 sprintf(ret->Name, "%.*s%u", strlen(Name)-1, Name, idx);
224         else
225                 sprintf(ret->Name, "%u", idx);
226         ret->NumericName = idx;
227         // - Output function and handle (same again)
228         ret->OutputHandle = Handle;
229         ret->OutputFcn = Output;
230         ret->ReqResize = ReqResize;
231         ret->ModeSet = ModeSet;
232         // - Initialise modes
233         if( InitialDims )
234                 ret->Dims = *InitialDims;
235         if( InitialMode )
236                 ret->Mode = *InitialMode;
237         // - Client node
238         ret->ClientNode.ImplPtr = ret;
239         ret->ClientNode.Type = &gPTY_NodeType_Client;
240         ret->ClientNode.UID = Threads_GetUID();
241         ret->ClientNode.GID = Threads_GetGID();
242         ret->ClientNode.NumACLs = 1;
243         ret->ClientNode.ACLs = &ret->OwnerRW;
244         // - Owner Read-Write ACL
245         ret->OwnerRW.Ent.ID = Threads_GetUID();
246         ret->OwnerRW.Perm.Perms = -1;
247
248         if( Name[0] ) {
249                 giPTY_NamedCount ++;
250                 RWLock_Release(&glPTY_NamedPTYs);
251         }
252         else {
253                 giPTY_NumCount ++;
254                 RWLock_Release(&glPTY_NumPTYs); 
255         }
256
257         return ret;
258 }
259
260 int PTY_SetAttrib(tPTY *PTY, const struct ptydims *Dims, const struct ptymode *Mode, int WasClient)
261 {
262         if( Mode )
263         {
264                 // (for now) userland terminals can't be put into framebuffer mode
265                 // - Userland PTYs are streams, framebuffer is a block
266                 if( !PTY->OutputFcn && (Mode->OutputMode & PTYOMODE_BUFFMT) == PTYBUFFMT_FB ) {
267                         errno = EINVAL;
268                         return -1;
269                 }
270                 if( WasClient )
271                 {
272                         if( PTY->ModeSet && PTY->ModeSet(PTY->OutputHandle, Mode) )
273                         {
274                                 errno = EINVAL;
275                                 return -1;
276                         }
277                         else if( !PTY->OutputFcn )
278                         {
279                                 Log_Warning("PTY", "TODO: Inform server of client SETMODE, halt output");
280                                 // Block slave write until master ACKs
281                                 // 0-length read on master indicates need to GETMODE
282                         }
283                 }
284                 else
285                 {
286                         // Should the client be informed that the server just twiddled the modes?
287                         Log_Warning("PTY", "Server changed mode, TODO: inform client?");
288                 }
289                 LOG("PTY %p mode set to {0%o, 0%o}", PTY, Mode->InputMode, Mode->OutputMode);
290                 PTY->Mode = *Mode;
291         }
292         if( Dims )
293         {
294                 if( WasClient )
295                 {
296                         // Poke the server?
297                         if( PTY->ReqResize && PTY->ReqResize(PTY->OutputHandle, Dims) )
298                         {
299                                 errno = EINVAL;
300                                 return -1;
301                         }
302                         else if( !PTY->OutputFcn )
303                         {
304                                 // Inform server process... somehow
305                                 Log_Warning("PTY", "TODO: Inform server of client resize request");
306                         }
307                 }
308                 else
309                 {
310                         // SIGWINSZ to client
311                         if( PTY->ControllingProcGroup > 0 )
312                                 Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
313                 }
314                 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
315                 PTY->Dims = *Dims;
316         }
317         return 0;
318 }
319
320 void PTY_Close(tPTY *PTY)
321 {
322         
323 }
324
325 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
326 {
327         size_t space = (*rd - *wr + buflen - 1) % buflen;
328         len = MIN(space, len);
329         if(*wr + len >= buflen) {
330                 size_t prelen = buflen - *wr;
331                 memcpy((char*)buf + *wr, data, prelen);
332                 memcpy(buf, (char*)data + prelen, len - prelen);
333                 *wr = len - prelen;
334         }
335         else {
336                 memcpy((char*)buf + *wr, data, len);
337                 *wr += len;
338         }
339         return len;
340 }
341 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
342 {
343         size_t space = (*wr - *rd + buflen) % buflen;
344         len = MIN(space, len);
345         if(*rd + len >= buflen) {
346                 size_t prelen = buflen - *rd;
347                 memcpy(data, (char*)buf + *rd, prelen);
348                 memcpy((char*)data + prelen, buf, len - prelen);
349                 *rd = len - prelen;
350         }
351         else {
352                 memcpy(data, (char*)buf + *rd, len);
353                 *rd += len;
354         }
355         return len;
356 }
357
358 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
359 {
360         size_t  ret;
361
362         Mutex_Acquire(&PTY->InputMutex);        
363
364         ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
365                 Input, Length);
366         
367         Mutex_Release(&PTY->InputMutex);
368
369         VFS_MarkAvaliable(&PTY->ClientNode, 1);
370         if(ret < Length && PTY->ServerNode)
371                 VFS_MarkFull(PTY->ServerNode, 1);       
372
373         return ret;
374 }
375
376 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
377 {
378         size_t  ret = 1, print = 1;
379         
380         // Input mode stuff only counts for text output mode
381         // - Any other mode sends Uint32 keypresses
382         if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
383                 return PTY_int_WriteInput(PTY, Input, Length);
384         // If in raw mode, flush directly
385         if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
386                 return PTY_int_WriteInput(PTY, Input, Length);
387         
388         if( PTY->Mode.InputMode & PTYIMODE_CANON )
389         {
390                 
391                 switch(Input[0])
392                 {
393                 case 3: // INTR - ^C
394                         // Send SIGINT
395                         if( PTY->ControllingProcGroup > 0 )
396                                 Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
397                         print = 0;
398                         break;
399                 case 4: // EOF - ^D
400                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
401                         PTY->HasHitEOF = (PTY->LineLength == 0);
402                         PTY->LineLength = 0;
403                         print = 0;
404                         break;
405                 case 8: // Backspace
406                         if(PTY->LineLength != 0) {
407                                 PTY->LineLength --;
408                                 PTY_WriteClient(&PTY->ClientNode, 0, 3, "\b \b", 0);
409                         }
410                         print = 0;
411                         break;
412                 case 'w'-'a':   // Word erase
413                         while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
414                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, "\b", 0);
415                         PTY_WriteClient(&PTY->ClientNode, 0, 3, "\x1b[K", 0);
416                         print = 0;
417                         break;
418                 case 'u'-'a':   // Kill
419                         PTY_WriteClient(&PTY->ClientNode, 0, 8, "\x1b[2K\x1b[0G", 0);
420                         PTY->LineLength = 0;
421                         print = 0;
422                         break;
423                 case 'v'-'a':
424                         Input ++;
425                         Length --;
426                         ret ++;
427                         goto _default;
428                 case '\0':
429                 case '\n':
430                         if(PTY->LineLength == INPUT_LINE_LEN) {
431                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
432                                 PTY->LineLength = 0;
433                         }
434                         PTY->LineData[PTY->LineLength++] = '\n';
435                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
436                         PTY->LineLength = 0;
437                         break;
438                 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
439                 //case 0x1B:
440                 //      break;
441                 default:
442                 _default:
443                         if(PTY->LineLength == INPUT_LINE_LEN) {
444                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
445                                 PTY->LineLength = 0;
446                         }
447                         PTY->LineData[PTY->LineLength++] = Input[0];
448                         break;
449                 }
450         }
451         else
452         {
453                 #if 0
454                 if( PTY->Mode.InputMode & PTYIMODE_NLCR )
455                 {
456                         if( Input[0] == '\n' ) {
457                                 char ch = '\r';
458                                 ret = PTY_int_WriteInput(PTY, &ch, 1);
459                         }
460                         else {
461                                  int    i;
462                                 for( i = 0; i < Length && Input[i] != '\n'; i ++ )
463                                         ;
464                                 ret = PTY_int_WriteInput(PTY, Input, i);
465                         }
466                 }
467                 // TODO: CRNL mode?
468                 else
469                 #endif
470                         ret = PTY_int_WriteInput(PTY, Input, Length);
471         }
472         
473         // Echo if requested
474         if( PTY->Mode.InputMode & PTYIMODE_ECHO )
475         {
476                 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
477         }
478         
479         return ret;
480 }
481
482 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
483 {
484         size_t ret = 0;
485         while( ret < Length && !PTY->ClientNode.BufferFull )
486         {
487                 // TODO: Detect blocking?
488                 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
489         }
490         return ret;
491 }
492
493 // --- VFS ---
494 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
495 {
496         tPTY    *pty = NULL;
497          int    idx = Pos;
498         if( idx < giPTY_NumCount )
499         {
500                 RWLock_AcquireRead(&glPTY_NumPTYs);
501                 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
502                         idx --;
503                 RWLock_Release(&glPTY_NumPTYs);
504         }
505         else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
506         {
507                 idx -= giPTY_NumCount;
508                 RWLock_AcquireRead(&glPTY_NamedPTYs);
509                 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
510                         idx --;
511                 RWLock_Release(&glPTY_NamedPTYs);
512         }
513
514         if( !pty ) {
515                 return -1;
516         }
517
518         strncpy(Name, pty->Name, FILENAME_MAX);
519         return 0;
520 }
521
522 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
523 {
524         char    *end;
525          int    num = strtol(Name, &end, 10);
526
527         if( strcmp(Name, "ptmx") == 0 ) {
528                 tVFS_Node       *ret = calloc(sizeof(tVFS_Node), 1);
529                 ret->Size = -1;
530                 ret->Type = &gPTY_NodeType_Server;
531                 return ret;
532         } 
533         
534         if( Name[0] == '\0' )
535                 return NULL;
536         
537         tPTY    *ret = NULL;
538         if( num && end[0] == '\0' )
539         {
540                 // Numeric name
541                 RWLock_AcquireRead(&glPTY_NumPTYs);
542                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
543                 {
544                         if( pty->NumericName > num )
545                                 break;
546                         if( pty->NumericName == num ) {
547                                 ret = pty;
548                                 break;
549                         }
550                 }
551                 RWLock_Release(&glPTY_NumPTYs);
552         }
553         else
554         {
555                 // String name
556                 RWLock_AcquireRead(&glPTY_NamedPTYs);
557                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
558                 {
559                         int cmp = strcmp(pty->Name, Name);
560                         if(cmp > 0)
561                                 break;
562                         if(cmp == 0 ) {
563                                 ret = pty;
564                                 break;
565                         }
566                 }
567                 RWLock_Release(&glPTY_NamedPTYs);
568         }
569 //      Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
570         if( ret ) {
571                 tVFS_Node       *retnode = &ret->ClientNode;
572                 retnode->ReferenceCount ++;
573                 return retnode;
574         }
575         else
576                 return NULL;
577 }
578
579 //\! Read from the client's input
580 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
581 {
582         tPTY *pty = Node->ImplPtr;
583         
584         // Read from flushed queue
585         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
586          int    rv;
587 _select:
588         // If server has disconnected, return EIO
589         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
590                 //Threads_PostSignal(SIGPIPE);
591                 errno = EIO;
592                 return -1;
593         }
594         // Wait for data to be ready
595         rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
596         if(!rv) {
597                 errno = (timeout ? EWOULDBLOCK : EINTR);
598                 return -1;
599         }
600
601         Mutex_Acquire(&pty->InputMutex);
602         Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
603                 Buffer, Length);
604         if( Length && pty->ServerNode )
605                 VFS_MarkFull(pty->ServerNode, 0);
606         Mutex_Release(&pty->InputMutex);
607
608         if(pty->InputReadPos == pty->InputWritePos)
609                 VFS_MarkAvaliable(Node, 0);
610
611         if(Length == 0 && !pty->HasHitEOF) {
612                 goto _select;
613         }
614         pty->HasHitEOF = 0;
615
616         return Length;
617 }
618
619 //\! Write to the client's output
620 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
621 {
622         tPTY *pty = Node->ImplPtr;
623
624         // If the server has terminated, send SIGPIPE
625         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
626         {
627                 Threads_PostSignal(SIGPIPE);
628                 errno = EIO;
629                 return -1;
630         }       
631
632         // Write to either FIFO or directly to output function
633         if( pty->OutputFcn ) {
634                 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
635                 return Length;
636         }
637         
638         // FIFO
639         size_t remaining = Length;
640         do
641         {
642                 tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
643                  int    rv;
644                 
645                 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
646                 if(!rv) {
647                         errno = (timeout ? EWOULDBLOCK : EINTR);
648                         return -1;
649                 }
650                 
651                 // Write to output ringbuffer
652                 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
653                         &pty->OutputReadPos, &pty->OutputWritePos,
654                         Buffer, remaining);
655                 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
656                 VFS_MarkAvaliable(pty->ServerNode, 1);
657                 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
658                         VFS_MarkFull(Node, 1);
659                 
660                 remaining -= written;
661                 Buffer = (const char*)Buffer + written;
662         } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
663         
664         return Length - remaining;
665 }
666
667 void PTY_ReferenceClient(tVFS_Node *Node)
668 {
669         Node->ReferenceCount ++;
670 }
671
672 void PTY_CloseClient(tVFS_Node *Node)
673 {
674         tPTY    *pty = Node->ImplPtr;
675         Node->ReferenceCount --;
676
677         // Remove PID from list
678         // TODO: Maintain list of client processes
679
680         // Free structure if this was the last open handle
681         if( Node->ReferenceCount > 0 )
682                 return ;
683         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
684         {
685                 // Free the structure! (Should be off the PTY list now)
686                 free(pty->ServerNode);
687                 free(pty);
688         }
689 }
690
691 //\! Read from the client's output
692 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
693 {
694         tPTY *pty = Node->ImplPtr;
695         if( !pty ) {
696                 errno = EIO;
697                 return -1;
698         }
699
700         // TODO: Prevent two servers fighting over client's output      
701         if( pty->OutputFcn )
702         {
703                 // Kernel-land PTYs can't be read from userland
704                 return 0;
705         }
706         
707         // Read back from fifo
708         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
709         int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
710         if(!rv) {
711                 errno = (timeout ? EWOULDBLOCK : EINTR);
712                 return -1;
713         }
714         
715         Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
716                 &pty->OutputReadPos, &pty->OutputWritePos,
717                 Buffer, Length);
718         LOG("Read %i '%.*s'", Length, Length, Buffer);
719         if( pty->OutputReadPos == pty->OutputWritePos )
720                 VFS_MarkAvaliable(Node, 0);
721         VFS_MarkFull(&pty->ClientNode, 0);
722         
723         return Length;
724 }
725
726 //\! Write to the client's input
727 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
728 {
729         tPTY    *pty = Node->ImplPtr;
730         if( !pty ) {
731                 errno = EIO;
732                 return -1;
733         }
734
735         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
736         int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
737         if(!rv) {
738                 errno = (timeout ? EWOULDBLOCK : EINTR);
739                 return -1;
740         }
741         size_t  used = 0;
742         do {
743                 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
744         } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
745         
746         if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
747                 VFS_MarkFull(Node, 1);
748         return used;
749 }
750
751 void PTY_CloseServer(tVFS_Node *Node)
752 {
753         tPTY    *pty = Node->ImplPtr;
754         // Dereference node
755         Node->ReferenceCount --;
756         // If reference count == 0, remove from main list
757         if( Node->ReferenceCount > 0 )
758                 return ;
759         
760         // Locate on list and remove
761         tPTY    **prev_np;
762         if( pty->NumericName == -1 ) {
763                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
764                 prev_np = &gpPTY_FirstNamedPTY;
765         }
766         else {
767                 RWLock_AcquireWrite(&glPTY_NumPTYs);
768                 prev_np = &gpPTY_FirstNumPTY;
769         }
770
771         // Search list until *prev_np is equal to pty   
772         for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
773                 ;
774         
775         // Remove
776         if( *prev_np != pty ) {
777                 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
778         }
779         else {
780                 *prev_np = pty->Next;
781         }
782         
783         // Clean up lock
784         if( pty->NumericName == -1 ) {
785                 RWLock_Release(&glPTY_NamedPTYs);
786                 giPTY_NamedCount --;
787         }
788         else {
789                 RWLock_Release(&glPTY_NumPTYs);
790                 giPTY_NumCount --;
791         }
792
793         // Send SIGHUP to controling PGID
794         if( pty->ControllingProcGroup > 0 ) {
795                 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
796         }
797
798         // If there are no open children, we can safely free this PTY
799         if( pty->ClientNode.ReferenceCount == 0 ) {
800                 free(Node);
801                 free(pty);
802         }
803 }
804
805 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
806 {
807         tPTY    *pty = Node->ImplPtr;
808         struct ptymode  *mode = Data;
809         struct ptydims  *dims = Data;
810         
811         int     is_server = !pty || Node == pty->ServerNode;
812
813         LOG("(%i,%p) %s", ID, Data, (is_server?"Server":"Client"));
814
815         switch(ID)
816         {
817         case DRV_IOCTL_TYPE:    return DRV_TYPE_TERMINAL;
818         case DRV_IOCTL_IDENT:   memcpy(Data, "PTY\0", 4);       return 0;
819         case DRV_IOCTL_VERSION: return 0x100;
820         case DRV_IOCTL_LOOKUP:  return 0;
821         
822         case PTY_IOCTL_GETMODE:
823                 if( !pty )      return 0;
824                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
825                 *mode = pty->Mode;
826                 // TODO: ACK client's SETMODE
827                 return 0;
828         case PTY_IOCTL_SETMODE:
829                 if( !pty )      return 0;
830                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
831                 PTY_SetAttrib(pty, NULL, mode, !is_server);
832                 return 0;
833         case PTY_IOCTL_GETDIMS:
834                 if( !pty )      return 0;
835                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
836                 *dims = pty->Dims;
837                 return 0;
838         case PTY_IOCTL_SETDIMS:
839                 if( !pty )      return 0;
840                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
841                 PTY_SetAttrib(pty, dims, NULL, !is_server);
842                 return 0;
843         case PTY_IOCTL_GETID:
844                 if( pty )
845                 {
846                         size_t  len = strlen(pty->Name)+1;
847                         if( Data )
848                         {
849                                 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
850                                 strcpy(Data, pty->Name);
851                         }
852                         return len;
853                 }
854                 return 0;
855         case PTY_IOCTL_SETID:
856                 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
857                 if( pty )       return EALREADY;
858                 pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
859                 if(pty == NULL)
860                         return 1;
861                 Node->ImplPtr = pty;
862                 pty->ServerNode = Node;
863                 return 0;
864         case PTY_IOCTL_SETPGRP:
865                 // TODO: Should this only be done by client?
866                 if( Data )
867                 {
868                         if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
869                         pty->ControllingProcGroup = *(tPGID*)Data;
870                         Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
871                 }
872                 return pty->ControllingProcGroup;
873         }
874         errno = ENOSYS;
875         return -1;
876 }
877

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