Kernel/PTYs - NL->CR translation (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                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGWINCH);
312                 }
313                 LOG("PTY %p dims set to %ix%i", PTY, Dims->W, Dims->H);
314                 PTY->Dims = *Dims;
315         }
316         return 0;
317 }
318
319 void PTY_Close(tPTY *PTY)
320 {
321         
322 }
323
324 size_t _rb_write(void *buf, size_t buflen, int *rd, int *wr, const void *data, size_t len)
325 {
326         size_t space = (*rd - *wr + buflen - 1) % buflen;
327         len = MIN(space, len);
328         if(*wr + len >= buflen) {
329                 size_t prelen = buflen - *wr;
330                 memcpy((char*)buf + *wr, data, prelen);
331                 memcpy(buf, (char*)data + prelen, len - prelen);
332                 *wr = len - prelen;
333         }
334         else {
335                 memcpy((char*)buf + *wr, data, len);
336                 *wr += len;
337         }
338         return len;
339 }
340 size_t _rb_read(void *buf, size_t buflen, int *rd, int *wr, void *data, size_t len)
341 {
342         size_t space = (*wr - *rd + buflen) % buflen;
343         len = MIN(space, len);
344         if(*rd + len >= buflen) {
345                 size_t prelen = buflen - *rd;
346                 memcpy(data, (char*)buf + *rd, prelen);
347                 memcpy((char*)data + prelen, buf, len - prelen);
348                 *rd = len - prelen;
349         }
350         else {
351                 memcpy(data, (char*)buf + *rd, len);
352                 *rd += len;
353         }
354         return len;
355 }
356
357 size_t PTY_int_WriteInput(tPTY *PTY, const char *Input, size_t Length)
358 {
359         size_t  ret;
360
361         Mutex_Acquire(&PTY->InputMutex);        
362
363         ret = _rb_write(PTY->InputData, INPUT_RINGBUFFER_LEN, &PTY->InputReadPos, &PTY->InputWritePos,
364                 Input, Length);
365         
366         Mutex_Release(&PTY->InputMutex);
367
368         VFS_MarkAvaliable(&PTY->ClientNode, 1);
369         if(ret < Length && PTY->ServerNode)
370                 VFS_MarkFull(PTY->ServerNode, 1);       
371
372         return ret;
373 }
374
375 size_t PTY_int_SendInput(tPTY *PTY, const char *Input, size_t Length)
376 {
377         size_t  ret = 1, print = 1;
378         
379         // Input mode stuff only counts for text output mode
380         // - Any other mode sends Uint32 keypresses
381         if( (PTY->Mode.OutputMode & PTYOMODE_BUFFMT) != PTYBUFFMT_TEXT )
382                 return PTY_int_WriteInput(PTY, Input, Length);
383         // If in raw mode, flush directly
384         if( (PTY->Mode.InputMode & PTYIMODE_RAW) )
385                 return PTY_int_WriteInput(PTY, Input, Length);
386         
387         if( PTY->Mode.InputMode & PTYIMODE_CANON )
388         {
389                 const char      char_bs = '\b';
390                 switch(Input[0])
391                 {
392                 case 3: // INTR - ^C
393                         // Send SIGINT
394                         Threads_SignalGroup(PTY->ControllingProcGroup, SIGINT);
395                         print = 0;
396                         break;
397                 case 4: // EOF - ^D
398                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
399                         PTY->HasHitEOF = (PTY->LineLength == 0);
400                         PTY->LineLength = 0;
401                         print = 0;
402                         break;
403                 case 8: // Backspace
404                         if(PTY->LineLength != 0)
405                                 PTY->LineLength --;
406                         break;
407                 case 'w'-'a':   // Word erase
408                         while(PTY->LineLength != 0 && isalnum(PTY->LineData[--PTY->LineLength]))
409                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
410                         print = 0;
411                         break;
412                 case 'u'-'a':   // Kill
413                         while(PTY->LineLength > 0)
414                                 PTY_WriteClient(&PTY->ClientNode, 0, 1, &char_bs, 0);
415                         print = 0;
416                         break;
417                 case 'v'-'a':
418                         Input ++;
419                         Length --;
420                         ret ++;
421                         goto _default;
422                 case '\0':
423                 case '\n':
424                         if(PTY->LineLength == INPUT_LINE_LEN) {
425                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
426                                 PTY->LineLength = 0;
427                         }
428                         PTY->LineData[PTY->LineLength++] = '\n';
429                         PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
430                         PTY->LineLength = 0;
431                         break;
432                 // TODO: Handle ^[[D and ^[[C for in-line editing, also ^[[1~/^[[4~ (home/end)
433                 //case 0x1B:
434                 //      break;
435                 default:
436                 _default:
437                         if(PTY->LineLength == INPUT_LINE_LEN) {
438                                 PTY_int_WriteInput(PTY, PTY->LineData, PTY->LineLength);
439                                 PTY->LineLength = 0;
440                         }
441                         PTY->LineData[PTY->LineLength++] = Input[0];
442                         break;
443                 }
444         }
445         else
446         {
447                 #if 0
448                 if( PTY->Mode.InputMode & PTYIMODE_NLCR )
449                 {
450                         if( Input[0] == '\n' ) {
451                                 char ch = '\r';
452                                 ret = PTY_int_WriteInput(PTY, &ch, 1);
453                         }
454                         else {
455                                  int    i;
456                                 for( i = 0; i < Length && Input[i] != '\n'; i ++ )
457                                         ;
458                                 ret = PTY_int_WriteInput(PTY, Input, i);
459                         }
460                 }
461                 // TODO: CRNL mode?
462                 else
463                 #endif
464                         ret = PTY_int_WriteInput(PTY, Input, Length);
465         }
466         
467         // Echo if requested
468         if( PTY->Mode.InputMode & PTYIMODE_ECHO )
469         {
470                 PTY_WriteClient(&PTY->ClientNode, 0, print, Input, 0);
471         }
472         
473         return ret;
474 }
475
476 size_t PTY_SendInput(tPTY *PTY, const char *Input, size_t Length)
477 {
478         size_t ret = 0;
479         while( ret < Length && !PTY->ClientNode.BufferFull )
480         {
481                 // TODO: Detect blocking?
482                 ret += PTY_int_SendInput(PTY, Input + ret, Length - ret);
483         }
484         return ret;
485 }
486
487 // --- VFS ---
488 int PTY_ReadDir(tVFS_Node *Node, int Pos, char Name[FILENAME_MAX])
489 {
490         tPTY    *pty = NULL;
491          int    idx = Pos;
492         if( idx < giPTY_NumCount )
493         {
494                 RWLock_AcquireRead(&glPTY_NumPTYs);
495                 for( pty = gpPTY_FirstNumPTY; pty && idx; pty = pty->Next )
496                         idx --;
497                 RWLock_Release(&glPTY_NumPTYs);
498         }
499         else if( idx < (giPTY_NumCount + giPTY_NamedCount) )
500         {
501                 idx -= giPTY_NumCount;
502                 RWLock_AcquireRead(&glPTY_NamedPTYs);
503                 for( pty = gpPTY_FirstNamedPTY; pty && idx; pty = pty->Next )
504                         idx --;
505                 RWLock_Release(&glPTY_NamedPTYs);
506         }
507
508         if( !pty ) {
509                 return -1;
510         }
511
512         strncpy(Name, pty->Name, FILENAME_MAX);
513         return 0;
514 }
515
516 tVFS_Node *PTY_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
517 {
518         char    *end;
519          int    num = strtol(Name, &end, 10);
520
521         if( strcmp(Name, "ptmx") == 0 ) {
522                 tVFS_Node       *ret = calloc(sizeof(tVFS_Node), 1);
523                 ret->Size = -1;
524                 ret->Type = &gPTY_NodeType_Server;
525                 return ret;
526         } 
527         
528         if( Name[0] == '\0' )
529                 return NULL;
530         
531         tPTY    *ret = NULL;
532         if( num && end[0] == '\0' )
533         {
534                 // Numeric name
535                 RWLock_AcquireRead(&glPTY_NumPTYs);
536                 for( tPTY *pty = gpPTY_FirstNumPTY; pty; pty = pty->Next )
537                 {
538                         if( pty->NumericName > num )
539                                 break;
540                         if( pty->NumericName == num ) {
541                                 ret = pty;
542                                 break;
543                         }
544                 }
545                 RWLock_Release(&glPTY_NumPTYs);
546         }
547         else
548         {
549                 // String name
550                 RWLock_AcquireRead(&glPTY_NamedPTYs);
551                 for( tPTY *pty = gpPTY_FirstNamedPTY; pty; pty = pty->Next )
552                 {
553                         int cmp = strcmp(pty->Name, Name);
554                         if(cmp > 0)
555                                 break;
556                         if(cmp == 0 ) {
557                                 ret = pty;
558                                 break;
559                         }
560                 }
561                 RWLock_Release(&glPTY_NamedPTYs);
562         }
563 //      Debug("PTY_FindDir('%s') returned %p", Name, &ret->ClientNode);
564         if( ret ) {
565                 tVFS_Node       *retnode = &ret->ClientNode;
566                 retnode->ReferenceCount ++;
567                 return retnode;
568         }
569         else
570                 return NULL;
571 }
572
573 //\! Read from the client's input
574 size_t PTY_ReadClient(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
575 {
576         tPTY *pty = Node->ImplPtr;
577         
578         // Read from flushed queue
579         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
580          int    rv;
581 _select:
582         // If server has disconnected, return EIO
583         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 ) {
584                 //Threads_PostSignal(SIGPIPE);
585                 errno = EIO;
586                 return -1;
587         }
588         // Wait for data to be ready
589         rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadClient");
590         if(!rv) {
591                 errno = (timeout ? EWOULDBLOCK : EINTR);
592                 return -1;
593         }
594
595         Mutex_Acquire(&pty->InputMutex);
596         Length = _rb_read(pty->InputData, INPUT_RINGBUFFER_LEN, &pty->InputReadPos, &pty->InputWritePos,
597                 Buffer, Length);
598         if( Length && pty->ServerNode )
599                 VFS_MarkFull(pty->ServerNode, 0);
600         Mutex_Release(&pty->InputMutex);
601
602         if(pty->InputReadPos == pty->InputWritePos)
603                 VFS_MarkAvaliable(Node, 0);
604
605         if(Length == 0 && !pty->HasHitEOF) {
606                 goto _select;
607         }
608         pty->HasHitEOF = 0;
609
610         return Length;
611 }
612
613 //\! Write to the client's output
614 size_t PTY_WriteClient(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
615 {
616         tPTY *pty = Node->ImplPtr;
617
618         // If the server has terminated, send SIGPIPE
619         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
620         {
621                 Threads_PostSignal(SIGPIPE);
622                 errno = EIO;
623                 return -1;
624         }       
625
626         // Write to either FIFO or directly to output function
627         if( pty->OutputFcn ) {
628                 pty->OutputFcn(pty->OutputHandle, Length, Buffer);
629                 return Length;
630         }
631         
632         // FIFO
633         size_t remaining = Length;
634         do
635         {
636                 tTime   timeout_z, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
637                  int    rv;
638                 
639                 rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteClient");
640                 if(!rv) {
641                         errno = (timeout ? EWOULDBLOCK : EINTR);
642                         return -1;
643                 }
644                 
645                 // Write to output ringbuffer
646                 size_t written = _rb_write(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
647                         &pty->OutputReadPos, &pty->OutputWritePos,
648                         Buffer, remaining);
649                 LOG("Wrote %i of %i : '%.*s'", written, remaining, written, Buffer);
650                 VFS_MarkAvaliable(pty->ServerNode, 1);
651                 if( (pty->OutputWritePos + 1) % OUTPUT_RINGBUFFER_LEN == pty->OutputReadPos )
652                         VFS_MarkFull(Node, 1);
653                 
654                 remaining -= written;
655                 Buffer = (const char*)Buffer + written;
656         } while( remaining > 0 || (Flags & VFS_IOFLAG_NOBLOCK) );
657         
658         return Length - remaining;
659 }
660
661 void PTY_ReferenceClient(tVFS_Node *Node)
662 {
663         Node->ReferenceCount ++;
664 }
665
666 void PTY_CloseClient(tVFS_Node *Node)
667 {
668         tPTY    *pty = Node->ImplPtr;
669         Node->ReferenceCount --;
670
671         // Remove PID from list
672         // TODO: Maintain list of client processes
673
674         // Free structure if this was the last open handle
675         if( Node->ReferenceCount > 0 )
676                 return ;
677         if( pty->ServerNode && pty->ServerNode->ReferenceCount == 0 )
678         {
679                 // Free the structure! (Should be off the PTY list now)
680                 free(pty->ServerNode);
681                 free(pty);
682         }
683 }
684
685 //\! Read from the client's output
686 size_t PTY_ReadServer(tVFS_Node *Node, off_t Offset, size_t Length, void *Buffer, Uint Flags)
687 {
688         tPTY *pty = Node->ImplPtr;
689         if( !pty ) {
690                 errno = EIO;
691                 return -1;
692         }
693
694         // TODO: Prevent two servers fighting over client's output      
695         if( pty->OutputFcn )
696         {
697                 // Kernel-land PTYs can't be read from userland
698                 return 0;
699         }
700         
701         // Read back from fifo
702         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
703         int rv = VFS_SelectNode(Node, VFS_SELECT_READ, timeout, "PTY_ReadServer");
704         if(!rv) {
705                 errno = (timeout ? EWOULDBLOCK : EINTR);
706                 return -1;
707         }
708         
709         Length = _rb_read(pty->OutputData, OUTPUT_RINGBUFFER_LEN,
710                 &pty->OutputReadPos, &pty->OutputWritePos,
711                 Buffer, Length);
712         LOG("Read %i '%.*s'", Length, Length, Buffer);
713         if( pty->OutputReadPos == pty->OutputWritePos )
714                 VFS_MarkAvaliable(Node, 0);
715         VFS_MarkFull(&pty->ClientNode, 0);
716         
717         return Length;
718 }
719
720 //\! Write to the client's input
721 size_t PTY_WriteServer(tVFS_Node *Node, off_t Offset, size_t Length, const void *Buffer, Uint Flags)
722 {
723         tPTY    *pty = Node->ImplPtr;
724         if( !pty ) {
725                 errno = EIO;
726                 return -1;
727         }
728
729         tTime   timeout_z = 0, *timeout = (Flags & VFS_IOFLAG_NOBLOCK) ? &timeout_z : NULL;
730         int rv = VFS_SelectNode(Node, VFS_SELECT_WRITE, timeout, "PTY_WriteServer");
731         if(!rv) {
732                 errno = (timeout ? EWOULDBLOCK : EINTR);
733                 return -1;
734         }
735         size_t  used = 0;
736         do {
737                 used += PTY_SendInput(Node->ImplPtr, Buffer, Length);
738         } while( used < Length && !(Flags & VFS_IOFLAG_NOBLOCK) );
739         
740         if( (pty->InputWritePos+1)%INPUT_RINGBUFFER_LEN == pty->InputReadPos )
741                 VFS_MarkFull(Node, 1);
742         return used;
743 }
744
745 void PTY_CloseServer(tVFS_Node *Node)
746 {
747         tPTY    *pty = Node->ImplPtr;
748         // Dereference node
749         Node->ReferenceCount --;
750         // If reference count == 0, remove from main list
751         if( Node->ReferenceCount > 0 )
752                 return ;
753         
754         // Locate on list and remove
755         tPTY    **prev_np;
756         if( pty->NumericName == -1 ) {
757                 RWLock_AcquireWrite(&glPTY_NamedPTYs);
758                 prev_np = &gpPTY_FirstNamedPTY;
759         }
760         else {
761                 RWLock_AcquireWrite(&glPTY_NumPTYs);
762                 prev_np = &gpPTY_FirstNumPTY;
763         }
764
765         // Search list until *prev_np is equal to pty   
766         for( tPTY *tmp = *prev_np; *prev_np != pty && tmp; prev_np = &tmp->Next, tmp = tmp->Next )
767                 ;
768         
769         // Remove
770         if( *prev_np != pty ) {
771                 Log_Error("PTY", "PTY %p(%i/%s) not on list at deletion time", pty, pty->NumericName, pty->Name);
772         }
773         else {
774                 *prev_np = pty->Next;
775         }
776         
777         // Clean up lock
778         if( pty->NumericName == -1 ) {
779                 RWLock_Release(&glPTY_NamedPTYs);
780                 giPTY_NamedCount --;
781         }
782         else {
783                 RWLock_Release(&glPTY_NumPTYs);
784                 giPTY_NumCount --;
785         }
786
787         // Send SIGHUP to controling PGID
788         if( pty->ControllingProcGroup > 0 ) {
789                 Threads_SignalGroup(pty->ControllingProcGroup, SIGHUP);
790         }
791
792         // If there are no open children, we can safely free this PTY
793         if( pty->ClientNode.ReferenceCount == 0 ) {
794                 free(Node);
795                 free(pty);
796         }
797 }
798
799 int PTY_IOCtl(tVFS_Node *Node, int ID, void *Data)
800 {
801         tPTY    *pty = Node->ImplPtr;
802         struct ptymode  *mode = Data;
803         struct ptydims  *dims = Data;
804         
805         int     is_server = !pty || Node == pty->ServerNode;
806
807         switch(ID)
808         {
809         case DRV_IOCTL_TYPE:    return DRV_TYPE_TERMINAL;
810         case DRV_IOCTL_IDENT:   memcpy(Data, "PTY\0", 4);       return 0;
811         case DRV_IOCTL_VERSION: return 0x100;
812         case DRV_IOCTL_LOOKUP:  return 0;
813         
814         case PTY_IOCTL_GETMODE:
815                 if( !pty )      return 0;
816                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
817                 *mode = pty->Mode;
818                 // TODO: ACK client's SETMODE
819                 return 0;
820         case PTY_IOCTL_SETMODE:
821                 if( !pty )      return 0;
822                 if( !CheckMem(Data, sizeof(*mode)) ) { errno = EINVAL; return -1; }
823                 PTY_SetAttrib(pty, NULL, mode, !is_server);
824                 return 0;
825         case PTY_IOCTL_GETDIMS:
826                 if( !pty )      return 0;
827                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
828                 *dims = pty->Dims;
829                 return 0;
830         case PTY_IOCTL_SETDIMS:
831                 if( !pty )      return 0;
832                 if( !CheckMem(Data, sizeof(*dims)) ) { errno = EINVAL; return -1; }
833                 PTY_SetAttrib(pty, dims, NULL, !is_server);
834                 return 0;
835         case PTY_IOCTL_GETID:
836                 if( pty )
837                 {
838                         size_t  len = strlen(pty->Name)+1;
839                         if( Data )
840                         {
841                                 if( !CheckMem(Data, len) ) { errno = EINVAL; return -1; }
842                                 strcpy(Data, pty->Name);
843                         }
844                         return len;
845                 }
846                 return 0;
847         case PTY_IOCTL_SETID:
848                 if( Data && !CheckString(Data) ) { errno = EINVAL; return -1; }
849                 if( pty )       return EALREADY;
850                 pty = PTY_Create(Data, NULL, NULL,NULL, NULL, NULL,NULL);
851                 if(pty == NULL)
852                         return 1;
853                 Node->ImplPtr = pty;
854                 pty->ServerNode = Node;
855                 return 0;
856         case PTY_IOCTL_SETPGRP:
857                 // TODO: Should this only be done by client?
858                 if( Data )
859                 {
860                         if( !CheckMem(Data, sizeof(tPGID)) ) { errno = EINVAL; return -1; }
861                         pty->ControllingProcGroup = *(tPGID*)Data;
862                         Log_Debug("PTY", "Set controlling PGID to %i", pty->ControllingProcGroup);
863                 }
864                 return pty->ControllingProcGroup;
865         }
866         errno = ENOSYS;
867         return -1;
868 }
869

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