[434c75]: contrib / sockets / sockets.lisp Maximize Restore History

Download this file

sockets.lisp    1663 lines (1457 with data), 55.1 kB

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
;; -*- Mode: Lisp; Syntax: Common-Lisp -*-
;; $Id$
;; This file is based on SBCL's SB-BSD-SOCKET module and has been
;; heavily modified to work with ECL by Julian Stecklina.
;; Port to Windows Sockets contributed by M. Goffioul.
;; You may do whatever you want with this file. (PUBLIC DOMAIN)
;; Trivial stuff is copied from SBCL's SB-BSD-SOCKETS, which is also
;; in the public domain.
(in-package "SB-BSD-SOCKETS")
;; Obviously this requires the one or other form of BSD compatible
;; socket interface.
#+(or :win32 :mingw32)
(eval-when (:compile-toplevel :load-toplevel :execute)
(push :wsock *features*))
;; Include the neccessary headers
#-:wsock
(clines
"#include <sys/types.h>"
"#include <sys/socket.h>"
"#include <sys/un.h>"
"#define wincoerce(t,x) (x)"
#-:win32
"#include <sys/time.h>"
"#include <netdb.h>"
"#include <string.h>"
"#include <unistd.h>"
"#include <netinet/in.h>"
"#include <netinet/tcp.h>"
"#include <errno.h>"
"#include <fcntl.h>"
#+:cygwin
"#ifndef MSG_WAITALL
#define MSG_WAITALL 0
#endif"
"#ifndef MSG_CONFIRM"
"#define MSG_CONFIRM 0"
"#endif"
"#ifndef MSG_NOSIGNAL"
"#define MSG_NOSIGNAL 0"
"#endif"
"#ifndef MSG_DONTWAIT"
"#define MSG_DONTWAIT 0"
"#endif"
"#ifndef MSG_EOR"
"#define MSG_EOR 0"
"#endif")
#+:wsock
(clines
"#include <winsock2.h>"
"typedef unsigned int uint32_t;"
"#define wincoerce(t,x) ((t)(x))"
#-:mingw32
"typedef int ssize_t;"
"typedef int socklen_t;"
"#define MSG_WAITALL 0"
"#define MSG_EOR 0"
"#define MSG_DONTWAIT 0"
"#define MSG_NOSIGNAL 0"
"#define MSG_CONFIRM 0"
"#include <errno.h>"
"#include <fcntl.h>"
"#include <stdio.h>")
#+:wsock
(progn
(defvar +wsock-initialized+ nil)
(defun wsock-initialize ()
(unless +wsock-initialized+
(if (c-inline () () :object
"
{
WSADATA wsadata;
cl_object output;
ecl_disable_interrupts();
if (WSAStartup(MAKEWORD(2,2), &wsadata) == NO_ERROR)
output = ECL_T;
else
output = ECL_NIL;
ecl_enable_interrupts();
@(return) = output;
}")
(setf +wsock-initialized+ t)
(error "Unable to initialize Windows Socket library"))))
(wsock-initialize)
); #+:wsock
(eval-when (:compile-toplevel :execute)
(defmacro c-constant (c-name)
`(c-inline () () :int ,c-name :one-liner t))
(defmacro define-c-constants (&rest args)
`(let () ; Prevents evaluation of constant value form
,@(loop
for (lisp-name c-name) on args by #'cddr
collect `(defconstant ,lisp-name (c-constant ,c-name))))))
#+:wsock
(Clines
"#define AF_LOCAL -1"
)
(define-c-constants
+af-inet+ "AF_INET"
+af-local+ #-sun4sol2 "AF_LOCAL" #+sun4sol2 "AF_UNIX"
+eagain+ "EAGAIN"
+eintr+ "EINTR")
#+:wsock
(defconstant +af-named-pipe+ -2)
;; Foreign functions
(defentry ff-socket (:int :int :int) (:int "socket") :no-interrupts t)
(defentry ff-listen (:int :int) (:int "listen") :no-interrupts t)
(defentry ff-close (:int) (:int "close") :no-interrupts t)
#+:wsock (defentry ff-closesocket (:int) (:int "closesocket") :no-interrupts t)
;;; This courtesy of Pierre Mai in comp.lang.lisp 08 Jan 1999 00:51:44 +0100
;;; Message-ID: <87lnjebq0f.fsf@orion.dent.isdn.cs.tu-berlin.de>
(defun split (string &optional max (ws '(#\Space #\Tab)))
"Split `string' along whitespace as defined by the sequence `ws'.
The whitespace is elided from the result. The whole string will be
split, unless `max' is a non-negative integer, in which case the
string will be split into `max' tokens at most, the last one
containing the whole rest of the given `string', if any."
(flet ((is-ws (char) (find char ws)))
(loop for start = (position-if-not #'is-ws string)
then (position-if-not #'is-ws string :start index)
for index = (and start
(if (and max (= (1+ word-count) max))
nil
(position-if #'is-ws string :start start)))
while start
collect (subseq string start index)
count 1 into word-count
while index)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; NAME RESOLVING
;;;
(defclass host-ent ()
((name :initarg :name :accessor host-ent-name)
(aliases :initarg :aliases :accessor host-ent-aliases)
(address-type :initarg :type :accessor host-ent-address-type)
; presently always AF_INET
(addresses :initarg :addresses :accessor host-ent-addresses))
(:documentation ""))
(defgeneric host-ent-address (host-ent)
(:documentation ""))
(defmethod host-ent-address ((host-ent host-ent))
(car (host-ent-addresses host-ent)))
;; FIXME: We should move this to using getaddrinfo
(defun get-host-by-name (host-name)
"Returns a HOST-ENT instance for HOST-NAME or throws some kind of condition.
HOST-NAME may also be an IP address in dotted quad notation or some other
weird stuff - see gethostbyname(3) for grisly details."
(let ((host-ent (make-instance 'host-ent)))
(if (c-inline (host-name host-ent
#'(setf host-ent-name)
#'(setf host-ent-aliases)
#'(setf host-ent-address-type)
#'(setf host-ent-addresses))
(:cstring t t t t t) t
"
{
struct hostent *hostent = gethostbyname(#0);
if (hostent != NULL) {
char **aliases;
char **addrs;
cl_object aliases_list = ECL_NIL;
cl_object addr_list = ECL_NIL;
int length = hostent->h_length;
funcall(3,#2,make_simple_base_string(hostent->h_name),#1);
funcall(3,#4,ecl_make_integer(hostent->h_addrtype),#1);
for (aliases = hostent->h_aliases; *aliases != NULL; aliases++) {
aliases_list = CONS(make_simple_base_string(*aliases),aliases_list);
}
funcall(3,#3,aliases_list,#1);
for (addrs = hostent->h_addr_list; *addrs != NULL; addrs++) {
int pos;
cl_object vector = funcall(2,@make-array,MAKE_FIXNUM(length));
for (pos = 0; pos < length; pos++)
ecl_aset(vector, pos, MAKE_FIXNUM((unsigned char)((*addrs)[pos])));
addr_list = CONS(vector, addr_list);
}
funcall(3,#5,addr_list,#1);
@(return) = #1;
} else {
@(return) = ECL_NIL;
}
}"
:side-effects t)
host-ent
(name-service-error "get-host-by-name"))))
(defun get-host-by-address (address)
(assert (and (typep address 'vector)
(= (length address) 4)))
(let ((host-ent (make-instance 'host-ent)))
(if
(c-inline (address host-ent
#'(setf host-ent-name)
#'(setf host-ent-aliases)
#'(setf host-ent-address-type)
#'(setf host-ent-addresses))
(t t t t t t) t
"
{
unsigned char vector[4];
struct hostent *hostent;
vector[0] = fixint(ecl_aref(#0,0));
vector[1] = fixint(ecl_aref(#0,1));
vector[2] = fixint(ecl_aref(#0,2));
vector[3] = fixint(ecl_aref(#0,3));
ecl_disable_interrupts();
hostent = gethostbyaddr(wincoerce(const char *, vector),4,AF_INET);
ecl_enable_interrupts();
if (hostent != NULL) {
char **aliases;
char **addrs;
cl_object aliases_list = ECL_NIL;
cl_object addr_list = ECL_NIL;
int length = hostent->h_length;
funcall(3,#2,make_simple_base_string(hostent->h_name),#1);
funcall(3,#4,ecl_make_integer(hostent->h_addrtype),#1);
for (aliases = hostent->h_aliases; *aliases != NULL; aliases++) {
aliases_list = CONS(make_simple_base_string(*aliases),aliases_list);
}
funcall(3,#3,aliases_list,#1);
for (addrs = hostent->h_addr_list; *addrs != NULL; addrs++) {
int pos;
cl_object vector = funcall(2,@make-array,MAKE_FIXNUM(length));
for (pos = 0; pos < length; pos++)
ecl_aset(vector, pos, MAKE_FIXNUM((unsigned char)((*addrs)[pos])));
addr_list = CONS(vector, addr_list);
}
funcall(3,#5,addr_list,#1);
@(return) = #1;
} else {
@(return) = ECL_NIL;
}
}"
:side-effects t)
host-ent
(name-service-error "get-host-by-address"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; SOCKET BASE CLASS AND GENERIC FUNCTIONS
;;;
(defclass socket ()
((file-descriptor :initarg :descriptor
:reader socket-file-descriptor)
(family :initform (error "No socket family")
:reader socket-family)
(protocol :initarg :protocol
:reader socket-protocol
:documentation "Protocol used by the socket. If a
keyword, the symbol-name of the keyword will be passed to
GET-PROTOCOL-BY-NAME downcased, and the returned value used as
protocol. Other values are used as-is.")
(type :initarg :type
:reader socket-type
:initform :stream
:documentation "Type of the socket: :STREAM or :DATAGRAM.")
(stream)
#+:wsock
(non-blocking-p :initform nil))
(:documentation "Common base class of all sockets, not meant to be
directly instantiated."))
(defmethod print-object ((object socket) stream)
(print-unreadable-object (object stream :type t :identity t)
(princ "descriptor " stream)
(princ (slot-value object 'file-descriptor) stream)))
(defmethod shared-initialize :after ((socket socket) slot-names
&key protocol type
&allow-other-keys)
(let* ((proto-num
(cond ((and protocol (keywordp protocol))
(get-protocol-by-name (string-downcase (symbol-name protocol))))
(protocol protocol)
(t 0)))
(fd (or (and (slot-boundp socket 'file-descriptor)
(socket-file-descriptor socket))
#+:wsock
(and (member (socket-family socket) (list +af-named-pipe+ +af-local+)) 0)
(ff-socket (socket-family socket)
(ecase (or type
(socket-type socket))
((:datagram) (c-constant "SOCK_DGRAM"))
((:stream) (c-constant "SOCK_STREAM")))
proto-num))))
(if (= fd -1) (socket-error "socket"))
(setf (slot-value socket 'file-descriptor) fd
(slot-value socket 'protocol) proto-num)
#+ ignore
(sb-ext:finalize socket (lambda () (sockint::close fd)))))
;; Generics
(defgeneric socket-bind (socket &rest address)
(:documentation "Bind SOCKET to ADDRESS, which may vary according to
socket family. For the INET family, pass ADDRESS and PORT as two
arguments; for FILE address family sockets, pass the filename string.
See also bind(2)"))
(defgeneric socket-accept (socket)
(:documentation "Perform the accept(2) call, returning a
newly-created connected socket and the peer address as multiple
values"))
(defgeneric socket-connect (socket &rest address)
(:documentation "Perform the connect(2) call to connect SOCKET to a
remote PEER. No useful return value."))
(defgeneric socket-peername (socket)
(:documentation "Return the socket's peer; depending on the address
family this may return multiple values"))
(defgeneric socket-name (socket)
(:documentation "Return the address (as vector of bytes) and port
that the socket is bound to, as multiple values."))
(defgeneric socket-listen (socket backlog)
(:documentation "Mark SOCKET as willing to accept incoming connections. BACKLOG
defines the maximum length that the queue of pending connections may
grow to before new connection attempts are refused. See also listen(2)"))
(defgeneric socket-receive (socket buffer length
&key
oob peek waitall element-type)
(:documentation "Read LENGTH octets from SOCKET into BUFFER (or a freshly-consed buffer if
NIL), using recvfrom(2). If LENGTH is NIL, the length of BUFFER is
used, so at least one of these two arguments must be non-NIL. If
BUFFER is supplied, it had better be of an element type one octet wide.
Returns the buffer, its length, and the address of the peer
that sent it, as multiple values. On datagram sockets, sets MSG_TRUNC
so that the actual packet length is returned even if the buffer was too
small"))
(defgeneric socket-send (socket buffer length
&key
address external-format oob eor dontroute dontwait
nosignal confirm more)
(:documentation "Send length octets from buffer into socket, using sendto(2).
If buffer is a string, it will converted to octets according to external-format&
If length is nil, the length of the octet buffer is used. The format of address
depends on the socket type (for example for inet domain sockets it would be a
list of an ip address and a port). If no socket address is provided, send(2)
will be called instead. Returns the number of octets written."))
(defgeneric socket-close (socket)
(:documentation "Close SOCKET. May throw any kind of error that write(2) would have
thrown. If SOCKET-MAKE-STREAM has been called, calls CLOSE on that
stream instead"))
(defgeneric socket-make-stream (socket &rest args)
(:documentation "Find or create a STREAM that can be used for IO
on SOCKET (which must be connected). ARGS are passed onto
SB-SYS:MAKE-FD-STREAM."))
(defgeneric non-blocking-mode (socket)
(:documentation "Is SOCKET in non-blocking mode?"))
(defgeneric (setf non-blocking-mode) (non-blocking-p socket)
(:documentation "Put SOCKET in non-blocking mode - or not, according to NON-BLOCKING-P"))
(defgeneric socket-close-low-level (socket)
(:documentation "Close SOCKET at low level. Do not use directly."))
;; Methods
(defmethod socket-listen ((socket socket) backlog)
(let ((r (ff-listen (socket-file-descriptor socket) backlog)))
(if (= r -1)
(socket-error "listen"))))
(defmethod socket-close-low-level ((socket socket))
(ff-close (socket-file-descriptor socket)))
(defmethod socket-close ((socket socket))
;; the close(2) manual page has all kinds of warning about not
;; checking the return value of close, on the grounds that an
;; earlier write(2) might have returned successfully w/o actually
;; writing the stuff to disk. It then goes on to define the only
;; possible error return as EBADF (fd isn't a valid open file
;; descriptor). Presumably this is an oversight and we could also
;; get anything that write(2) would have given us.
;; note that if you have a socket _and_ a stream on the same fd,
;; the socket will avoid doing anything to close the fd in case
;; the stream has done it already - if so, it may have been
;; reassigned to some other file, and closing it would be bad
(let ((fd (socket-file-descriptor socket)))
(unless (eql fd -1) ; already closed
(cond ((slot-boundp socket 'stream)
(let ((stream (slot-value socket 'stream)))
#+threads
(close (two-way-stream-input-stream stream))
#+threads
(close (two-way-stream-output-stream stream))
#-threads
(close stream)) ;; closes fd indirectly
(slot-makunbound socket 'stream))
((= (socket-close-low-level socket) -1)
(socket-error "close")))
(setf (slot-value socket 'file-descriptor) -1))))
(ffi::clines "
static void *
safe_buffer_pointer(cl_object x, cl_index size)
{
cl_type t = type_of(x);
int ok = 0;
if (t == t_base_string) {
ok = (size <= x->base_string.dim);
} else if (t == t_vector) {
cl_elttype aet = (cl_elttype)x->vector.elttype;
if (aet == aet_b8 || aet == aet_i8 || aet == aet_bc) {
ok = (size <= x->vector.dim);
} else if (aet == aet_fix || aet == aet_index) {
cl_index divisor = sizeof(cl_index);
size = (size + divisor - 1) / divisor;
ok = (size <= x->vector.dim);
}
}
if (!ok) {
FEerror(\"Lisp object is not a valid socket buffer: ~A\", 1, x);
}
return (void *)x->vector.self.t;
}
")
;; FIXME: How bad is manipulating fillp directly?
(defmethod socket-receive ((socket socket) buffer length
&key oob peek waitall element-type)
(unless (or buffer length) (error "You have to supply either buffer or length!"))
(let ((buffer (or buffer (make-array length :element-type element-type)))
(length (or length (length buffer)))
(fd (socket-file-descriptor socket)))
(multiple-value-bind (len-recv errno)
(c-inline (fd buffer length
oob peek waitall)
(:int :object :int :bool :bool :bool)
(values :long :int)
"
{
int flags = ( #3 ? MSG_OOB : 0 ) |
( #4 ? MSG_PEEK : 0 ) |
( #5 ? MSG_WAITALL : 0 );
cl_type type = type_of(#1);
ssize_t len;
ecl_disable_interrupts();
len = recvfrom(#0, wincoerce(char*, safe_buffer_pointer(#1, #2)),
#2, flags, NULL,NULL);
ecl_enable_interrupts();
if (len >= 0) {
if (type == t_vector) { #1->vector.fillp = len; }
else if (type == t_base_string) { #1->base_string.fillp = len; }
}
@(return 0) = len;
@(return 1) = errno;
}
"
:one-liner nil)
(cond ((and (= len-recv -1)
(member errno (list +eagain+ +eintr+)))
nil)
((= len-recv -1)
(socket-error "receive"))
(t
(values buffer len-recv))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; INET SOCKETS
;;;
;; We could refactor a lot here, if we pass sockaddr_foo structs around in Lisp. But
;; I do not feel comfortable with that.
(defun get-protocol-by-name (string-or-symbol)
"Calls getprotobyname"
(let ((string (string string-or-symbol)))
(c-inline (string) (:cstring) :int
"getprotobyname(#0)->p_proto"
:one-liner t)))
(defun make-inet-address (dotted-quads)
"Return a vector of octets given a string DOTTED-QUADS in the format
\"127.0.0.1\""
(map 'vector
#'parse-integer
(split dotted-quads nil '(#\.))))
(defclass inet-socket (socket)
((family :initform +af-inet+))
(:documentation "Class representing TCP and UDP sockets.
Examples:
(make-instance 'inet-socket :type :stream :protocol :tcp)
(make-instance 'inet-socket :type :datagram :protocol :udp)
"))
(defun make-inet-socket (type protocol)
"Make an INET socket. Deprecated in favour of make-instance"
(make-instance 'inet-socket :type type :protocol protocol))
(Clines
"
static void fill_inet_sockaddr(struct sockaddr_in *sockaddr, int port,
int a1, int a2, int a3, int a4)
{
#if defined(_MSC_VER) || defined(mingw32)
memset(sockaddr,0,sizeof(struct sockaddr_in));
#else
bzero(sockaddr,sizeof(struct sockaddr_in));
#endif
sockaddr->sin_family = AF_INET;
sockaddr->sin_port = htons(port);
sockaddr->sin_addr.s_addr= htonl((uint32_t)a1<<24 | (uint32_t)a2<<16 | (uint32_t)a3<<8 | (uint32_t)a4) ;
}
")
(defmethod socket-bind ((socket inet-socket) &rest address)
(assert (= 2 (length address)) (address) "Socket-bind needs three parameters for inet sockets.")
(let ((ip (first address))
(port (second address)))
(if (= -1
(c-inline (port (aref ip 0) (aref ip 1) (aref ip 2) (aref ip 3)
(socket-file-descriptor socket))
(:int :int :int :int :int :int)
:int
"
{
struct sockaddr_in sockaddr;
int output;
ecl_disable_interrupts();
fill_inet_sockaddr(&sockaddr, #0, #1, #2, #3, #4);
output = bind(#5,(struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in));
ecl_enable_interrupts();
@(return) = output;
}"
:side-effects t))
(socket-error "bind"))))
(defmethod socket-accept ((socket inet-socket))
(let ((sfd (socket-file-descriptor socket)))
(multiple-value-bind (fd vector port)
(c-inline (sfd) (:int) (values :int :object :int)
"{
struct sockaddr_in sockaddr;
socklen_t addr_len = (socklen_t)sizeof(struct sockaddr_in);
int new_fd;
ecl_disable_interrupts();
new_fd = accept(#0, (struct sockaddr*)&sockaddr, &addr_len);
ecl_enable_interrupts();
@(return 0) = new_fd;
@(return 1) = ECL_NIL;
@(return 2) = 0;
if (new_fd != -1) {
uint32_t ip = ntohl(sockaddr.sin_addr.s_addr);
uint16_t port = ntohs(sockaddr.sin_port);
cl_object vector = cl_make_array(1,MAKE_FIXNUM(4));
ecl_aset(vector,0, MAKE_FIXNUM( ip>>24 ));
ecl_aset(vector,1, MAKE_FIXNUM( (ip>>16) & 0xFF));
ecl_aset(vector,2, MAKE_FIXNUM( (ip>>8) & 0xFF));
ecl_aset(vector,3, MAKE_FIXNUM( ip & 0xFF ));
@(return 1) = vector;
@(return 2) = port;
}
}")
(cond
((= fd -1)
(socket-error "accept"))
(t
(values
(make-instance (class-of socket)
:type (socket-type socket)
:protocol (socket-protocol socket)
:descriptor fd)
vector
port))))))
(defmethod socket-connect ((socket inet-socket) &rest address)
(let ((ip (first address))
(port (second address)))
(if (= -1
(c-inline (port (aref ip 0) (aref ip 1) (aref ip 2) (aref ip 3)
(socket-file-descriptor socket))
(:int :int :int :int :int :int)
:int
"
{
struct sockaddr_in sockaddr;
int output;
ecl_disable_interrupts();
fill_inet_sockaddr(&sockaddr, #0, #1, #2, #3, #4);
output = connect(#5,(struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in));
ecl_enable_interrupts();
@(return) = output;
}"))
(socket-error "connect"))))
(defmethod socket-peername ((socket inet-socket))
(let* ((vector (make-array 4))
(fd (socket-file-descriptor socket))
(port (c-inline (fd vector) (:int t) :int
"@01;{
struct sockaddr_in name;
socklen_t len = sizeof(struct sockaddr_in);
int ret;
ecl_disable_interrupts();
ret = getpeername(#0,(struct sockaddr*)&name,&len);
ecl_enable_interrupts();
if (ret == 0) {
uint32_t ip = ntohl(name.sin_addr.s_addr);
uint16_t port = ntohs(name.sin_port);
ecl_aset(#1,0, MAKE_FIXNUM( ip>>24 ));
ecl_aset(#1,1, MAKE_FIXNUM( (ip>>16) & 0xFF));
ecl_aset(#1,2, MAKE_FIXNUM( (ip>>8) & 0xFF));
ecl_aset(#1,3, MAKE_FIXNUM( ip & 0xFF ));
@(return) = port;
} else {
@(return) = -1;
}
}")))
(if (>= port 0)
(values vector port)
(socket-error "getpeername"))))
(defmethod socket-name ((socket inet-socket))
(let* ((vector (make-array 4))
(fd (socket-file-descriptor socket))
(port (c-inline (fd vector) (:int t) :int
"@01;{
struct sockaddr_in name;
socklen_t len = sizeof(struct sockaddr_in);
int ret;
ecl_disable_interrupts();
ret = getsockname(#0,(struct sockaddr*)&name,&len);
ecl_enable_interrupts();
if (ret == 0) {
uint32_t ip = ntohl(name.sin_addr.s_addr);
uint16_t port = ntohs(name.sin_port);
ecl_aset(#1,0, MAKE_FIXNUM( ip>>24 ));
ecl_aset(#1,1, MAKE_FIXNUM( (ip>>16) & 0xFF));
ecl_aset(#1,2, MAKE_FIXNUM( (ip>>8) & 0xFF));
ecl_aset(#1,3, MAKE_FIXNUM( ip & 0xFF ));
@(return) = port;
} else {
@(return) = -1;
}
}")))
(if (>= port 0)
(values vector port)
(socket-error "getsockname"))))
#+:wsock
(defmethod socket-close-low-level ((socket inet-socket))
(ff-closesocket (socket-file-descriptor socket)))
(defmethod socket-send ((socket socket) buffer length
&key address external-format oob eor dontroute dontwait nosignal confirm more)
(declare (ignore external-format more))
(assert (or (stringp buffer)
(typep buffer 'vector)))
(let (;eh, here goes string->octet convertion...
;When will ecl support Unicode?
(length (or length (length buffer)))
(fd (socket-file-descriptor socket)))
(let ((len-sent
(if address
(progn
(assert (= 2 (length address)))
(c-inline (fd buffer length
(second address)
(aref (first address) 0)
(aref (first address) 1)
(aref (first address) 2)
(aref (first address) 3)
oob eor dontroute dontwait nosignal confirm)
(:int :object :int
:int :int :int :int :int
:bool :bool :bool :bool :bool :bool)
:long
"
{
int sock = #0;
int length = #2;
void *buffer = safe_buffer_pointer(#1, length);
int flags = ( #8 ? MSG_OOB : 0 ) |
( #9 ? MSG_EOR : 0 ) |
( #a ? MSG_DONTROUTE : 0 ) |
( #b ? MSG_DONTWAIT : 0 ) |
( #c ? MSG_NOSIGNAL : 0 ) |
( #d ? MSG_CONFIRM : 0 );
cl_type type = type_of(#1);
struct sockaddr_in sockaddr;
ssize_t len;
ecl_disable_interrupts();
fill_inet_sockaddr(&sockaddr, #3, #4, #5, #6, #7);
##if (MSG_NOSIGNAL == 0) && defined(SO_NOSIGPIPE)
{
int sockopt = #c;
setsockopt(#0,SOL_SOCKET,SO_NOSIGPIPE,
wincoerce(char *,&sockopt),
sizeof(int));
}
##endif
len = sendto(sock, wincoerce(char *,buffer),
length, flags,(struct sockaddr*)&sockaddr,
sizeof(struct sockaddr_in));
ecl_enable_interrupts();
@(return) = len;
}
"
:one-liner nil))
(c-inline (fd buffer length
oob eor dontroute dontwait nosignal confirm)
(:int :object :int
:bool :bool :bool :bool :bool :bool)
:long
"
{
int sock = #0;
int length = #2;
void *buffer = safe_buffer_pointer(#1, length);
int flags = ( #3 ? MSG_OOB : 0 ) |
( #4 ? MSG_EOR : 0 ) |
( #5 ? MSG_DONTROUTE : 0 ) |
( #6 ? MSG_DONTWAIT : 0 ) |
( #7 ? MSG_NOSIGNAL : 0 ) |
( #8 ? MSG_CONFIRM : 0 );
cl_type type = type_of(#1);
ssize_t len;
ecl_disable_interrupts();
##if (MSG_NOSIGNAL == 0) && defined(SO_NOSIGPIPE)
{
int sockopt = #7;
setsockopt(#0,SOL_SOCKET,SO_NOSIGPIPE,
wincoerce(char *,&sockopt),
sizeof(int));
}
##endif
len = send(sock, wincoerce(char *, buffer), length, flags);
ecl_enable_interrupts();
@(return) = len;
}
"
:one-liner nil))))
(if (= len-sent -1)
(socket-error "send")
len-sent))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; UNIX SOCKETS
;;;
#-:wsock
(progn
(defclass local-socket (socket)
((family :initform +af-local+))
(:documentation "Class representing local domain (AF_LOCAL) sockets,
also known as unix-domain sockets."))
(defmethod socket-bind ((socket local-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-bind needs two parameters for local sockets.")
(let ((name (first address))
(fd (socket-file-descriptor socket))
(family (socket-family socket)))
(if (= -1
(c-inline (fd name family) (:int :cstring :int) :int
"
{
struct sockaddr_un sockaddr;
size_t size;
int output;
##ifdef BSD
sockaddr.sun_len = sizeof(struct sockaddr_un);
##endif
sockaddr.sun_family = #2;
strncpy(sockaddr.sun_path,#1,sizeof(sockaddr.sun_path));
sockaddr.sun_path[sizeof(sockaddr.sun_path)-1] = '\0';
ecl_disable_interrupts();
output = bind(#0,(struct sockaddr*)&sockaddr, sizeof(struct sockaddr_un));
ecl_enable_interrupts();
@(return) = output;
}"))
(socket-error "bind"))))
(defmethod socket-accept ((socket local-socket))
(multiple-value-bind (fd name)
(c-inline ((socket-file-descriptor socket)) (:int) (values :int :object)
"{
struct sockaddr_un sockaddr;
socklen_t addr_len = (socklen_t)sizeof(struct sockaddr_un);
int new_fd;
ecl_disable_interrupts();
new_fd = accept(#0, (struct sockaddr *)&sockaddr, &addr_len);
ecl_enable_interrupts();
@(return 0) = new_fd;
@(return 1) = (new_fd == -1) ? ECL_NIL : make_base_string_copy(sockaddr.sun_path);
}")
(cond
((= fd -1)
(socket-error "accept"))
(t
(values
(make-instance (class-of socket)
:type (socket-type socket)
:protocol (socket-protocol socket)
:descriptor fd)
name)))))
(defmethod socket-connect ((socket local-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-connect needs two parameters for local sockets.")
(let ((path (first address))
(fd (socket-file-descriptor socket))
(family (socket-family socket)))
(if (= -1
(c-inline (fd family path) (:int :int :cstring) :int
"
{
struct sockaddr_un sockaddr;
int output;
##ifdef BSD
sockaddr.sun_len = sizeof(struct sockaddr_un);
##endif
sockaddr.sun_family = #1;
strncpy(sockaddr.sun_path,#2,sizeof(sockaddr.sun_path));
sockaddr.sun_path[sizeof(sockaddr.sun_path)-1] = '\0';
ecl_disable_interrupts();
output = connect(#0,(struct sockaddr*)&sockaddr, sizeof(struct sockaddr_un));
ecl_enable_interrupts();
@(return) = output;
}"))
(socket-error "connect"))))
(defmethod socket-peername ((socket local-socket))
(let* ((fd (socket-file-descriptor socket))
(peer (c-inline (fd) (:int) t
"
{
struct sockaddr_un name;
socklen_t len = sizeof(struct sockaddr_un);
int ret;
ecl_disable_interrupts();
ret = getpeername(#0,(struct sockaddr*)&name,&len);
ecl_enable_interrupts();
if (ret == 0) {
@(return) = make_base_string_copy(name.sun_path);
} else {
@(return) = ECL_NIL;
}
}")))
(if peer
peer
(socket-error "getpeername"))))
) ;#-:wsock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; UNIX SOCKETS [WIN32, using the cygwin way]
;;;
#+:wsock
(progn
(defclass local-socket (socket)
((family :initform +af-local+)
proxy-socket local-path)
(:documentation "Class representing local domain (AF_LOCAL) sockets,
also known as unix-domain sockets."))
(defmethod initialize-instance :after ((socket local-socket) &rest args)
(declare (ignore args))
(with-slots (protocol type) socket
(setf (slot-value socket 'proxy-socket)
(make-instance 'inet-socket :protocol protocol :type type))))
(defmethod socket-bind ((socket local-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-bind needs two parameters for local sockets.")
(with-slots (proxy-socket local-path) socket
(socket-bind proxy-socket #(127 0 0 1) 0)
(multiple-value-bind (ip port) (socket-peername proxy-socket)
(handler-case
(with-open-file (fd (first address) :if-exists :error :if-does-not-exist :create :direction :output)
(format fd "!<socket >~D 00000000-00000000-00000000-00000000" port))
(file-error ()
(socket-close proxy-socket)
(c-inline () () nil "WSASetLastError(WSAEADDRINUSE)" :one-liner t)
(socket-error "socket-bind")))
(setf local-path (first address))
socket)))
(defmethod socket-accept ((socket local-socket))
(multiple-value-bind (new-socket addr) (socket-accept (slot-value socket 'proxy-socket))
(values socket (slot-value socket 'local-path))))
(defmethod socket-connect ((socket local-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-connect needs two parameters for local sockets.")
(with-slots (proxy-socket local-path) socket
(handler-case
(with-open-file (fd (first address) :if-does-not-exist :error :direction :input)
(let ((buf (make-string 128)) port)
(read-sequence buf fd)
(unless (and (string-equal "!<socket >" (subseq buf 0 10))
(typep (setq port (read-from-string (subseq buf 10) nil 'eof)) '(integer 0 65535)))
(c-inline () () nil "WSASetLastError(WSAEFAULT)" :one-liner t)
(socket-error "connect"))
(prog1
(socket-connect proxy-socket #(127 0 0 1) port)
(setf local-path (first address)))))
(file-error ()
(socket-error "connect")))))
(defmethod socket-peername ((socket local-socket))
(unless (slot-boundp socket 'local-path)
(c-inline () () nil "WSASetLastError(WSAENOTCONN)" :one-liner t)
(socket-error "socket-peername"))
(slot-value socket 'local-path))
(defmethod socket-close ((socket local-socket))
(socket-close (slot-value socket 'proxy-socket))
(slot-makunbound socket 'local-path))
(defmethod socket-make-stream ((socket local-socket) &rest args)
(apply #'socket-make-stream (cons (slot-value socket 'proxy-socket) args)))
(defmethod non-blocking-mode ((socket local-socket))
(non-blocking-mode (slot-value socket 'proxy-socket)))
(defmethod (setf non-blocking-mode) (non-blocking-p (socket local-socket))
(setf (non-blocking-mode (slot-value socket 'proxy-socket)) non-blocking-p))
) ;#+:wsock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; NAMED PIPE SOCKETS [WIN32]
;;;
#+:wsock
(progn
(defclass named-pipe-socket (socket)
((family :initform +af-named-pipe+)
(pipe-name :initarg :pipe-name))
(:documentation "Class representing Win32 named pipe, using a socket-like interface."))
(defmethod socket-bind ((socket named-pipe-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-bind needs two parameters for local sockets.")
(let* ((pipe-name (concatenate 'string "\\\\.\\pipe\\" (first address)))
(hnd (c-inline (pipe-name) (:cstring) :int
"
{
HANDLE hnd;
ecl_disable_interrupts();
hnd = CreateNamedPipe(
#0,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
4096,
4096,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
ecl_enable_interrupts();
if (hnd == INVALID_HANDLE_VALUE)
@(return) = -1;
else
@(return) = _open_osfhandle((intptr_t)hnd, O_RDWR);
}")))
(when (= hnd -1)
(socket-error "CreateNamedPipe"))
(setf (slot-value socket 'pipe-name) pipe-name)
(setf (slot-value socket 'file-descriptor) hnd)))
(defmethod socket-accept ((socket named-pipe-socket))
(let* ((fd (socket-file-descriptor socket))
(afd (c-inline (fd) (:int) :int
"
{
HANDLE hnd = (HANDLE)_get_osfhandle(#0), dupHnd;
ecl_disable_interrupts();
if (ConnectNamedPipe(hnd, NULL) != 0 || GetLastError() == ERROR_PIPE_CONNECTED) {
@(return) = #0;
} else
@(return) = -1;
ecl_enable_interrupts();
}"
:one-liner nil)))
(cond
((= afd -1)
(socket-error "accept"))
(t
;; rebind the socket to create a new named pipe instance in the server
(socket-bind socket (subseq (slot-value socket 'pipe-name) 9))
(values
(make-instance (class-of socket)
:type (socket-type socket)
:protocol (socket-protocol socket)
:descriptor afd
:pipe-name (slot-value socket 'pipe-name))
(slot-value socket 'pipe-name))))))
(defmethod socket-connect ((socket named-pipe-socket) &rest address)
(assert (= 1 (length address)) (address) "Socket-connect needs two parameters for local sockets.")
(let* ((path (first address))
(pipe-name (concatenate 'string "\\\\.\\pipe\\" path)))
(if (= -1
(setf (slot-value socket 'file-descriptor)
(c-inline (pipe-name) (:cstring) :int
"
{
HANDLE hnd;
ecl_disable_interrupts();
hnd = CreateFile(
#0,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hnd == INVALID_HANDLE_VALUE)
@(return) = -1;
else
@(return) = _open_osfhandle((intptr_t)hnd, O_RDWR);
ecl_enable_interrupts();
}")))
(socket-error "connect")
(setf (slot-value socket 'pipe-name) pipe-name))))
(defmethod socket-peername ((socket named-pipe-socket))
(slot-value socket 'pipe-name))
(defmethod (setf non-blocking-mode) (non-blocking-p (socket named-pipe-socket))
(let ((fd (socket-file-descriptor socket)))
(if (= 0
(c-inline (fd non-blocking-p) (:int t) :int
"
{
DWORD mode = PIPE_READMODE_BYTE | (#1 == ECL_T ? PIPE_NOWAIT : PIPE_WAIT);
HANDLE h = (HANDLE)_get_osfhandle(#0);
ecl_disable_interrupts();
@(return) = SetNamedPipeHandleState(h, &mode, NULL, NULL);
ecl_enable_interrupts();
}"
:one-liner nil))
(socket-error "SetNamedPipeHandleState")
(setf (slot-value socket 'non-blocking-p) non-blocking-p))))
(defmethod socket-close ((socket named-pipe-socket))
(let ((fd (socket-file-descriptor socket)))
(unless (c-inline (fd) (:int) t
"
{
DWORD flags;
HANDLE h = (HANDLE)_get_osfhandle(#0);
ecl_disable_interrupts();
if (!GetNamedPipeInfo(h, &flags, NULL, NULL, NULL))
@(return) = ECL_NIL;
if (flags == PIPE_CLIENT_END || DisconnectNamedPipe(h))
@(return) = ECL_T;
else
@(return) = ECL_NIL;
ecl_enable_interrupts();
}"
:one-liner nil)
(socket-error "DisconnectNamedPipe"))
(call-next-method)))
) ;#+:wsock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; NON-BLOCKING MODE
;;;
(defmethod non-blocking-mode ((socket socket))
#-:wsock
(let ((fd (socket-file-descriptor socket)))
(not (zerop (c-inline (fd) (:int) :int "fcntl(#0,F_GETFL,NULL)&O_NONBLOCK" :one-liner t))))
#+:wsock
(slot-value socket 'non-blocking-p)
)
(defmethod (setf non-blocking-mode) (non-blocking-p (socket socket))
(let ((fd (socket-file-descriptor socket))
(nblock (if non-blocking-p 1 0)))
(if (= -1 (c-inline (fd nblock) (:int :int) :int
#+:wsock
"
{
int blocking_flag = (#1 ? 1 : 0);
ecl_disable_interrupts();
@(return) = ioctlsocket(#0, FIONBIO, (u_long*)&blocking_flag);
ecl_enable_interrupts();
}"
#-:wsock
"
{
int oldflags = fcntl(#0,F_GETFL,NULL);
int newflags = (oldflags & ~O_NONBLOCK) |
(#1 ? O_NONBLOCK : 0);
ecl_disable_interrupts();
@(return) = fcntl(#0,F_SETFL,newflags);
ecl_enable_interrupts();
}"))
(socket-error #-:wsock "fcntl" #+:wsock "ioctlsocket")
#-:wsock non-blocking-p
#+:wsock (setf (slot-value socket 'non-blocking-p) non-blocking-p))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; STREAMS
;;;
;;; To actually read/write to/from the sockets, we use Lisp streams. The
;;; following functions take care of building the streams. Fortunately
;;; we do not have to care about things like buffering, binary streams,
;;; etc, but we rather reuse the code from the C core. (For instance
;;; the sockets will be closed upon garbage collection)
;;;
(defun dup (fd)
(ffi:c-inline (fd) (:int) :int "dup(#0)" :one-liner t))
(defun make-stream-from-fd (fd mode &key buffering element-type (external-format :default)
(name "FD-STREAM"))
(assert (stringp name) (name) "name must be a string.")
(let* ((smm-mode (ecase mode
(:input (c-constant "ecl_smm_input"))
(:output (c-constant "ecl_smm_output"))
(:input-output (c-constant "ecl_smm_io"))
#+:wsock
(:input-wsock (c-constant "ecl_smm_input_wsock"))
#+:wsock
(:output-wsock (c-constant "ecl_smm_output_wsock"))
#+:wsock
(:input-output-wsock (c-constant "ecl_smm_io_wsock"))
))
(external-format (unless (subtypep element-type 'integer) external-format))
(stream (ffi:c-inline (name fd smm-mode element-type external-format)
(t :int :int t t)
t
"
ecl_make_stream_from_fd(#0,#1,(enum ecl_smmode)#2,
ecl_normalize_stream_element_type(#3),
0,#4)"
:one-liner t)))
(when buffering
(si::set-buffering-mode stream buffering))
stream))
(defun auto-close-two-way-stream (stream)
(declare (si::c-local))
(ffi:c-inline (stream) (t) :void
"(#0)->stream.flags |= ECL_STREAM_CLOSE_COMPONENTS"
:one-liner t))
(defun socket-make-stream-inner (fd input output buffering element-type external-format)
;; In Unix we have to create one stream per channel. The reason is
;; that buffered I/O is done using ANSI C FILEs which do not support
;; concurrent reads and writes -- if one thread is listening to the
;; FILE it blocks all output. The solution is to create a
;; two-way-stream when both input and output are T, and force that
;; stream to close its components (small hack in ECL). In Windows we
;; do not have this problem because we do not know how to wrap a
;; FILE around a socket.
(cond ((and input output)
#+wsock
(make-stream-from-fd fd :input-output-wsock
:buffering buffering
:element-type element-type
:external-format external-format)
#-wsock
(let* ((in (socket-make-stream-inner (dup fd) t nil buffering
element-type external-format))
(out (socket-make-stream-inner fd nil t buffering
element-type external-format))
(stream (make-two-way-stream in out)))
(auto-close-two-way-stream stream)
stream))
(input
(make-stream-from-fd fd #-wsock :input #+wsock :input-wsock
:buffering buffering
:element-type element-type
:external-format external-format))
(output
(make-stream-from-fd fd #-wsock :output #+wsock :output-wsock
:buffering buffering
:element-type element-type
:external-format external-format))
(t
(error "SOCKET-MAKE-STREAM: at least one of :INPUT or :OUTPUT has to be true."))))
(defmethod socket-make-stream ((socket socket)
&key (input nil input-p)
(output nil output-p)
(buffering :full)
(element-type 'base-char)
(external-format :default))
(let ((stream (and (slot-boundp socket 'stream)
(slot-value socket 'stream))))
(unless stream
;; Complicated default logic for compatibility with previous releases
;; should disappear soon. (FIXME!)
(unless (or input-p output-p)
(setf input t output t))
(setf stream (socket-make-stream-inner (socket-file-descriptor socket)
input output buffering element-type
external-format))
(setf (slot-value socket 'stream) stream)
#+ ignore
(sb-ext:cancel-finalization socket))
stream))
(defmethod ext::stream-fd ((socket socket))
(socket-file-descriptor socket))
#+:wsock
(defmethod socket-make-stream ((socket named-pipe-socket)
&key input output
(buffering :full) (external-format :default))
(let ((stream (and (slot-boundp socket 'stream)
(slot-value socket 'stream))))
(unless stream
(setf stream
(let* ((fd (socket-file-descriptor socket))
(in (make-stream-from-fd fd :smm-input buffering external-format))
(out (make-stream-from-fd fd :smm-output buffering external-format)))
(make-two-way-stream in out)))
(setf (slot-value socket 'stream) stream))
stream))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ERROR HANDLING
;;;
;;; A plethora of conditions are defined below, almost one for each
;;; possible error produced by the socket or DNS interface.
;;;
#+:wsock
(defun get-win32-error-string (num)
(c-inline (num) (:int) t
"{char *lpMsgBuf;
cl_object msg;
ecl_disable_interrupts();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
#0,
0,
(LPTSTR)&lpMsgBuf,
0,
NULL);
msg = make_base_string_copy(lpMsgBuf);
LocalFree(lpMsgBuf);
ecl_enable_interrupts();
@(return) = msg;}"
:one-liner nil))
;;;
;;; 1) SOCKET ERRORS
;;;
(define-condition socket-error (error)
((errno :initform nil
:initarg :errno
:reader socket-error-errno)
(symbol :initform nil :initarg :symbol :reader socket-error-symbol)
(syscall :initform "outer space" :initarg :syscall :reader socket-error-syscall))
(:report (lambda (c s)
(let ((num (socket-error-errno c)))
(format s "Socket error in \"~A\": ~A (~A)"
(socket-error-syscall c)
(or (socket-error-symbol c) (socket-error-errno c))
#+:wsock
(get-win32-error-string num)
#-:wsock
(c-inline (num) (:int) :cstring
"strerror(#0)" :one-liner t)))))
(:documentation "Common base class of socket related conditions."))
(defmacro define-socket-condition (symbol name)
`(let () ; Prevents evaluation of constant value at compilation time
(defconstant ,symbol (c-constant ,(symbol-name symbol)))
(define-condition ,name (socket-error)
((symbol :reader socket-error-symbol :initform (quote ,symbol))))
(export ',name)
(push (cons ,symbol (quote ,name)) *conditions-for-errno*)))
(defparameter *conditions-for-errno* nil)
;;; this needs the rest of the list adding to it, really. They also
;;; need symbols to be added to constants.ccon
;;; I haven't yet thought of a non-kludgey way of keeping all this in
;;; the same place
#+:wsock
(Clines
"#define EADDRINUSE WSAEADDRINUSE"
"#define ECONNREFUSED WSAECONNREFUSED"
"#define ETIMEDOUT WSAETIMEDOUT"
"#define ENOBUFS WSAENOBUFS"
"#define EOPNOTSUPP WSAEOPNOTSUPP"
"#define EPROTONOSUPPORT WSAEPROTONOSUPPORT"
"#define ESOCKTNOSUPPORT WSAESOCKTNOSUPPORT"
"#define ENETUNREACH WSAENETUNREACH"
"#define NETDB_INTERNAL WSAEAFNOSUPPORT"
"#define NETDB_SUCCESS 0"
)
(define-socket-condition EADDRINUSE address-in-use-error)
(define-socket-condition EAGAIN interrupted-error)
(define-socket-condition EBADF bad-file-descriptor-error)
(define-socket-condition ECONNREFUSED connection-refused-error)
(define-socket-condition ETIMEDOUT operation-timeout-error)
(define-socket-condition EINTR interrupted-error)
(define-socket-condition EINVAL invalid-argument-error)
(define-socket-condition ENOBUFS no-buffers-error)
(define-socket-condition ENOMEM out-of-memory-error)
(define-socket-condition EOPNOTSUPP operation-not-supported-error)
(define-socket-condition EPERM operation-not-permitted-error)
(define-socket-condition EPROTONOSUPPORT protocol-not-supported-error)
(define-socket-condition ESOCKTNOSUPPORT socket-type-not-supported-error)
(define-socket-condition ENETUNREACH network-unreachable-error)
(defun condition-for-errno (err)
(or (cdr (assoc err *conditions-for-errno* :test #'eql)) 'socket-error))
(defun socket-error (where)
(let* ((errno (c-constant #-:wsock "errno" #+:wsock "WSAGetLastError()"))
(condition (condition-for-errno errno)))
(error condition :errno errno :syscall where)))
;;;
;;; 2) DNS ERRORS
;;;
(defvar *name-service-errno* 0
"The value of h_errno, after it's been fetched from Unix-land by calling
GET-NAME-SERVICE-ERRNO")
(defun name-service-error (where)
(get-name-service-errno)
;; Comment next to NETDB_INTERNAL in netdb.h says "See errno.".
;; This special case treatment hasn't actually been tested yet.
(if (= *name-service-errno* (c-constant "NETDB_INTERNAL"))
(socket-error where)
(let ((condition
(condition-for-name-service-errno *name-service-errno*)))
(error condition :errno *name-service-errno* :syscall where))))
(define-condition name-service-error (condition)
((errno :initform nil
:initarg :errno
:reader name-service-error-errno)
(symbol :initform nil :initarg :symbol :reader name-service-error-symbol)
(syscall :initform "an unknown location" :initarg :syscall :reader name-service-error-syscall))
(:report (lambda (c s)
(let ((num (name-service-error-errno c)))
(format s "Name service error in \"~A\": ~A (~A)"
(name-service-error-syscall c)
(or (name-service-error-symbol c)
(name-service-error-errno c))
(get-name-service-error-message num))))))
(defmacro define-name-service-condition (symbol name)
`(let ()
(defconstant ,symbol (c-constant ,(symbol-name symbol)))
(define-condition ,name (name-service-error)
((symbol :reader name-service-error-symbol :initform (quote ,symbol))))
(push (cons ,symbol (quote ,name)) *conditions-for-name-service-errno*)
(export (quote ,symbol))))
(defparameter *conditions-for-name-service-errno* nil)
(define-name-service-condition NETDB_INTERNAL netdb-internal-error)
(define-name-service-condition NETDB_SUCCESS netdb-success-error)
(define-name-service-condition HOST_NOT_FOUND host-not-found-error)
(define-name-service-condition TRY_AGAIN try-again-error)
(define-name-service-condition NO_RECOVERY no-recovery-error)
;; this is the same as the next one
;;(define-name-service-condition NO_DATA no-data-error)
(define-name-service-condition NO_ADDRESS no-address-error)
(defun condition-for-name-service-errno (err)
(or (cdr (assoc err *conditions-for-name-service-errno* :test #'eql))
'name-service))
(defun get-name-service-errno ()
(setf *name-service-errno* (c-constant #-:wsock "h_errno" #+:wsock "WSAGetLastError()")))
(defun get-name-service-error-message (num)
#+:nsr
(c-inline (num) (:int) :cstring "strerror(#0)" :one-liner t)
#+:wsock
(get-win32-error-string num)
#-(or :wsock :nsr)
(c-inline (num) (:int) :cstring "strerror(#0)" :one-liner t)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; SOCKET OPTIONS
;;;
(defun get-sockopt-int (fd level const)
(let ((ret (c-inline (fd level const) (:int :int :int) t
"{
int sockopt, ret;
socklen_t socklen = sizeof(int);
ecl_disable_interrupts();
ret = getsockopt(#0,#1,#2,wincoerce(char*,&sockopt),&socklen);
ecl_enable_interrupts();
@(return) = (ret == 0) ? ecl_make_integer(sockopt) : ECL_NIL;
}")))
(if ret
ret
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
(defun get-sockopt-bool (fd level const)
(let ((ret (c-inline (fd level const) (:int :int :int) t
"{
int sockopt, ret;
socklen_t socklen = sizeof(int);
ecl_disable_interrupts();
ret = getsockopt(#0,#1,#2,wincoerce(char*,&sockopt),&socklen);
ecl_enable_interrupts();
@(return) = (ret == 0) ? ecl_make_integer(sockopt) : ECL_NIL;
}")))
(if ret
(/= ret 0)
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
#+wsock
(defun get-sockopt-timeval (fd level const)
(* 1000 (get-sockopt-int fd level const)))
#-wsock
(defun get-sockopt-timeval (fd level const)
(let ((ret (c-inline (fd level const) (:int :int :int) t
"{
struct timeval tv;
socklen_t socklen = sizeof(struct timeval);
int ret;
ecl_disable_interrupts();
ret = getsockopt(#0,#1,#2,wincoerce(char*,&tv),&socklen);
ecl_enable_interrupts();
@(return) = (ret == 0) ? ecl_make_doublefloat((double)tv.tv_sec
+ ((double)tv.tv_usec) / 1000000.0) : ECL_NIL;
}")))
(if ret
ret
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
(defun get-sockopt-linger (fd level const)
(let ((ret (c-inline (fd level const) (:int :int :int) t
"{
struct linger sockopt;
socklen_t socklen = sizeof(struct linger);
int ret;
ecl_disable_interrupts();
ret = getsockopt(#0,#1,#2,wincoerce(char*,&sockopt),&socklen);
ecl_enable_interrupts();
@(return) = (ret == 0) ? ecl_make_integer((sockopt.l_onoff != 0) ? sockopt.l_linger : 0) : ECL_NIL;
}")))
(if ret
ret
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
(defun set-sockopt-int (fd level const value)
(let ((ret (c-inline (fd level const value) (:int :int :int :int) t
"{
int sockopt = #3;
int ret;
ecl_disable_interrupts();
ret = setsockopt(#0,#1,#2,wincoerce(char *,&sockopt),sizeof(int));
ecl_enable_interrupts();
@(return) = (ret == 0) ? ECL_T : ECL_NIL;
}")))
(if ret
value
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
(defun set-sockopt-bool (fd level const value)
(let ((ret (c-inline (fd level const value) (:int :int :int :object) t
"{
int sockopt = (#3 == ECL_NIL) ? 0 : 1;
int ret;
ecl_disable_interrupts();
ret = setsockopt(#0,#1,#2,wincoerce(char *,&sockopt),sizeof(int));
ecl_enable_interrupts();
@(return) = (ret == 0) ? ECL_T : ECL_NIL;
}")))
(if ret
value
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
#-wsock
(defun set-sockopt-timeval (fd level const value)
(let ((ret (c-inline (fd level const value) (:int :int :int :double) t
"{
struct timeval tv;
double tmp = #3;
int ret;
ecl_disable_interrupts();
tv.tv_sec = (int)tmp;
tv.tv_usec = (int)((tmp-floor(tmp))*1000000.0);
ret = setsockopt(#0,#1,#2,&tv,sizeof(struct timeval));
ecl_enable_interrupts();
@(return) = (ret == 0) ? ECL_T : ECL_NIL;
}")))
(if ret
value
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
#+wsock
(defun set-sockopt-timeval (fd level const value)
(set-sockopt-int fd level const (* 1000 value)))
(defun set-sockopt-linger (fd level const value)
(let ((ret (c-inline (fd level const value) (:int :int :int :int) t
"{
struct linger sockopt = {0, 0};
int value = #3;
int ret;
if (value > 0) {
sockopt.l_onoff = 1;
sockopt.l_linger = value;
}
ecl_disable_interrupts();
ret = setsockopt(#0,#1,#2,wincoerce(char *,&sockopt),
sizeof(struct linger));
ecl_enable_interrupts();
@(return) = (ret == 0) ? ECL_T : ECL_NIL;
}")))
(if ret
value
(error "Sockopt error: ~A" (c-inline () () :cstring "strerror(errno)" :one-liner t)))))
(eval-when (:compile-toplevel :load-toplevel)
(defmacro define-sockopt (name c-level c-const type &optional (read-only nil))
`(progn
(export ',name)
(defun ,name (socket)
(,(intern (format nil "GET-SOCKOPT-~A" type))
(socket-file-descriptor socket)
(c-constant ,c-level)
(c-constant ,c-const)))
,@(unless read-only
`((defun (setf ,name) (value socket)
(,(intern (format nil "SET-SOCKOPT-~A" type))
(socket-file-descriptor socket)
(c-constant ,c-level)
(c-constant ,c-const)
value)))))))
(define-sockopt sockopt-type "SOL_SOCKET" "SO_TYPE" int t)
(define-sockopt sockopt-receive-buffer "SOL_SOCKET" "SO_RCVBUF" int)
(define-sockopt sockopt-receive-timeout "SOL_SOCKET" "SO_RCVTIMEO" timeval)
(define-sockopt sockopt-send-timeout "SOL_SOCKET" "SO_SNDTIMEO" timeval)
(define-sockopt sockopt-reuse-address "SOL_SOCKET" "SO_REUSEADDR" bool)
(define-sockopt sockopt-keep-alive "SOL_SOCKET" "SO_KEEPALIVE" bool)
(define-sockopt sockopt-dont-route "SOL_SOCKET" "SO_DONTROUTE" bool)
(define-sockopt sockopt-linger "SOL_SOCKET" "SO_LINGER" linger)
#-(or :sun4sol2 :linux :wsock :cygwin)
(define-sockopt sockopt-reuse-port "SOL_SOCKET" "SO_REUSEPORT" bool)
(define-sockopt sockopt-tcp-nodelay "IPPROTO_TCP" "TCP_NODELAY" bool)
;; Add sockopts here as you need them...
;; Finished loading
(provide 'sockets)
(provide 'sb-bsd-sockets)