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

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