Skip to Content
go-dicom(3)

Building an SCP

How to run a DICOM server in Go: listen, decide who may associate and what they may negotiate, answer requests with handlers, bound what a peer can cost, and stop cleanly. The echoscp and storescp commands are covered at the end. It assumes the terms of Network concepts.

Overview

A server is an SCPConfig and a Handler. Each association runs on a goroutine of its own; each request on it goes to the handler method for its command.

There are two ways to run one:

BlocksStops withPort 0 means
NewSCP(config) then scp.ListenAndServe(ctx)yescanceling ctx, or scp.Close()11112 (DefaultPort)
StartServer(ctx, config, handler)no; returns a *ServerStop() or Shutdown(ctx)any free port; Addr() says which

BindAddress empty listens on every interface. StartServerOn and scp.Serve take a listener you made yourself; see Your own listener.

A first server

Everything below comes from one program that was compiled and run: a storage archive that admits two calling AE titles and keeps each instance as the bytes the peer sent.

known := map[string]bool{"CT_SCANNER": true, "MY_APP": true}
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn}))

server, err := network.StartServer(ctx, network.SCPConfig{
	AETitle:          "ARCHIVE",
	Port:             0, // StartServer: any free port; Addr says which
	BindAddress:      "127.0.0.1",
	MaxAssociations:  32,
	AbstractSyntaxes: network.StorageAndVerificationSyntaxes(),
	TransferSyntaxes: network.AllTransferSyntaxes(), // compressed too: kept as sent
	Network: network.NetworkConfig{
		MaxDataSetSize:         2 << 30, // 2 GiB a message
		MaxNonStoreDataSetSize: 1 << 20, // 1 MiB for anything that is not a C-STORE
	},
	Admit: func(ctx context.Context, req *network.AssociationRequest) *network.AssociationRejection {
		if !known[req.CallingAE] {
			return network.RejectCallingAE()
		}
		return nil // admitted
	},
	Logger: logger,
}, &Archive{Dir: dir})
if err != nil {
	return err
}

Handlers

BaseHandler implements every method: it answers C-ECHO with Success and refuses everything else with C000, C-STORE included, so a handler says Success for an instance only when it has kept it. Embed it and override what you serve.

HandlerServes
EchoHandlerC‑ECHO only
StorageHandler{OnStore}C‑STORE, given the decoded data set; OnStore returns the status
QueryRetrieveHandler{OnFind, OnGet, OnMoveInstances}C‑FIND, C‑GET and C‑MOVE through functions that return data sets
WorklistHandler{OnWorklist}Modality Worklist C‑FIND
MPPSHandler, UPSHandler, StorageCommitmentHandlerSee Workflow services
dcmstore.HandlerAn on-disk archive; see Query/retrieve
CompositeHandlerOne handler per service: SetEchoHandler, SetStoreHandler, SetFindHandler, SetMoveHandler, SetGetHandler

A C-FIND handler returns its matches, each with status Pending; the SCP sends them and then the final Success. To choose the failure a requestor sees, return a *StatusError (A700, A701, A702, A801, A900 or Cxxx, with an Error Comment); any other error is sent as C000:

type Finder struct {
	network.BaseHandler
}

func (*Finder) HandleCFind(ctx context.Context, req *network.CFindRequest) ([]*network.CFindResponse, error) {
	if req.DataSet.GetStringByKeyword("QueryRetrieveLevel") != "STUDY" {
		return nil, network.NewStatusError(0xA900, "only STUDY level is answered")
	}
	match := dataset.NewDataset()
	if err := match.AddByKeyword("QueryRetrieveLevel", dataelem.CS, []byte("STUDY")); err != nil {
		return nil, err
	}
	if err := match.AddByKeyword("StudyInstanceUID", dataelem.UI, []byte("1.2.3.4")); err != nil {
		return nil, err
	}
	return []*network.CFindResponse{{Status: network.StatusPending, DataSet: match}}, nil
}

A handler that returns a slice builds all of it before the first response. The optional interfaces send as they go and stop on C-CANCEL: CFindStreamer, CMoveStreamer and CGetStreamer, and, to retrieve straight from stored files, CMoveStoredSender and CGetStoredSender (see Query/retrieve). A C-FIND, C-MOVE or C-GET handler's context is canceled when a C-CANCEL for its message arrives.

Inside any handler, AssociationInfoFromContext(ctx) gives the calling AE title, the peer's address, the accepted contexts and its implementation class UID, and config.LoggerFromContext(ctx) the server's logger.

Important

Handlers are called concurrently for different associations and must be safe for concurrent use. A handler runs on its association's goroutine, so a slow one holds that association; the SCP puts no timeout on it.

Streamed C-STORE

HandleCStore is given a decoded data set, which the SCP builds by holding the whole message in memory. A handler that also implements CStoreStreamer is given the bytes as they arrive instead, two PDUs at a time, and WriteCStoreFile writes them as a Part 10 file without decoding them:

type Archive struct {
	network.BaseHandler // C-ECHO answered; everything else refused
	Dir                 string
}

func (a *Archive) HandleCStoreStream(ctx context.Context, req *network.CStoreRequest,
	transferSyntax string, data io.Reader) (*network.CStoreResponse, error) {
	f, err := os.CreateTemp(a.Dir, "*.part")
	if err != nil {
		return nil, err // the rest is read and discarded, then 0xC000 is sent
	}
	defer os.Remove(f.Name()) // a no-op once renamed

	_, err = network.WriteCStoreFile(ctx, f, req, transferSyntax, data)
	if closeErr := f.Close(); err == nil {
		err = closeErr
	}
	if errors.Is(err, network.ErrInvalidSOPInstanceUID) {
		return &network.CStoreResponse{Status: network.StatusInvalidObjectInstance}, nil
	}
	if err != nil {
		return nil, err // the data set did not arrive whole: never keep it
	}
	final := filepath.Join(a.Dir, req.AffectedSOPInstance+".dcm") // checked by WriteCStoreFile
	if err := os.Rename(f.Name(), final); err != nil {
		return nil, err
	}
	return &network.CStoreResponse{Status: network.StatusSuccess}, nil
}
  • A read error means the data set did not arrive whole. It is io.ErrUnexpectedEOF to errors.Is, never io.EOF; the association is over and no response is sent.
  • A handler that returns early has the rest read and discarded, bounded by MaxDataSetSize, and then its status sent.
  • The command's UIDs are not compared with the data set's own. WriteCStoreFile checks they are UIDs before it writes, so one is safe in a path.

Who may associate

SCPConfig.Admit is asked once per association, after the A-ASSOCIATE-RQ is read and before anything is negotiated, so a refused caller learns nothing of what the SCP supports. It is given an AssociationRequest: both AE titles (trimmed, well formed), both addresses, the TLS certificate chains the handshake verified, and the User Identity item unchecked. It returns nil to admit, or an AssociationRejection: RejectCallingAE(), RejectCalledAE(), RejectBusy() or one of your own.

  • The called AE title is still checked unless AcceptAnyCalledAE is set, so a function that only logs does not open the SCP to every title.
  • It has ARTIMTimeout to answer, runs on a goroutine of its own, and a panic in it refuses the caller.
  • NarrowAbstractSyntaxes runs after it and returns the SOP classes this caller may negotiate, never more than the SCP supports.

A caller refused this way sees result 1 (permanent), source 1 (service user), reason 3 (calling AE title not recognized):

stranger := network.NewSCU(network.SCUConfig{CallingAE: "STRANGER", CalledAE: "ARCHIVE", Address: server.Addr()})
err = stranger.Associate(ctx, nil)
var assocErr *network.AssociationError
if errors.As(err, &assocErr) {
	fmt.Printf("refused: result %d source %d reason %d\n", assocErr.Result, assocErr.Source, assocErr.Reason)
}

Printed: refused: result 1 source 1 reason 3. On the command line, storescp, qrscp and wlmscp take -allow and -allow-file; see TLS and security.

What it accepts

AbstractSyntaxes and TransferSyntaxes are read before the listener opens.

FieldNilA list
AbstractSyntaxesVerification, every storage class, Patient Root, Study Root and Patient/Study Only FIND, MOVE and GET, and Storage Commitmentused exactly; an empty list accepts nothing
TransferSyntaxesthe four uncompressed syntaxes (DefaultTransferSyntaxes)used exactly; AllTransferSyntaxes adds the 37 compressed ones
  • StorageAndVerificationSyntaxes() is the list for a storage-only archive.
  • Storage Commitment is withdrawn at negotiation unless the handler implements StorageCommitmentProvider or StorageCommitmentResultReceiver.
  • Modality Worklist is not in the defaults; add ModalityWorklistInformationModelFindUID when a handler answers it.
  • An archive should accept every transfer syntax. Keeping an instance does not need decoding it; with the defaults a modality that stores JPEG-LS or JPEG 2000 has every compressed context refused.
  • SetSupportedAbstractSyntaxes and SetSupportedTransferSyntaxes still work, for associations negotiated after the call.

Several operations per association

An association carries any number of operations. By default the SCP performs them one at a time, in the order received. With SCPConfig.MaxOperationsPerformed above one, and a requestor that negotiated an asynchronous operations window, C-ECHO, C-FIND, C-MOVE and most N-services run concurrently and C-STOREs beside them; C-GET and storage commitment N-ACTION wait and run alone. The table is in CONFORMANCE.md §1.3.

Limits for untrusted peers

SettingDefaultBounds
MaxAssociationsunlimitedConcurrent associations; the next caller is refused transient, local-limit-exceeded, so it may retry.
Network.MaxDataSetSizeunlimitedThe data set of one message, held whole or read from a stream; a peer sending more is aborted.
Network.MaxNonStoreDataSetSizeMaxDataSetSizeIdentifiers and N-service attribute lists, which are kilobytes in practice.
Network.ARTIMTimeout, DIMSETimeout30 s, 60 sA peer that connects and sends nothing, or goes quiet partway.
Network.MaxPDUSize16384The largest P‑DATA‑TF a peer may send; longer is aborted.

Warning

With MaxDataSetSize at zero a handler that refuses an instance early still has the SCP read and discard the whole data set, however large the peer makes it. Set it on any SCP that faces peers you do not control.

The fixed bounds (128 MiB a PDU, 1 MiB an A-ASSOCIATE-RQ, 256 MiB inflated) are in CONFORMANCE.md §7. A panic in a handler aborts only its own association, with the stack logged.

Stopping

Stop cancels the context every handler was given and closes the listener at once. Shutdown lets work in progress finish:

stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var cut *network.ShutdownError
if err := server.Shutdown(stopCtx); errors.As(err, &cut) {
	log.Printf("%d associations aborted at the bound", cut.Aborted)
} else if err != nil {
	return err
}

While it drains, the server goes on accepting connections and refuses each association with rejected-transient, temporary-congestion, so a caller knows to try later. An association waiting for its next request is aborted at once; one in an operation finishes it. When stopCtx ends first, what is left is aborted and counted in the *ShutdownError, which unwraps to the context's error.

Your own listener

A program that must bind the socket itself, to choose IPv4 or IPv6 or to use a descriptor it was given, passes the listener. The server wraps it for TLS when the configuration has TLS, ignores Port and BindAddress, and closes it when it stops:

l, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
	return err
}
h := network.NewCompositeHandler()
h.SetEchoHandler(&network.EchoHandler{})
h.SetFindHandler(&Finder{})
qr, err := network.StartServerOn(ctx, network.SCPConfig{AETitle: "QR"}, h, l)
if err != nil {
	return err
}
defer qr.Stop()

Logging

Everything the package logs goes to config.Logger through network.DefaultLogger, at warning level and above, with component=network. network.SetDefaultLogLevel changes the network layer alone. SCPConfig.Logger gives one server a *slog.Logger of its own: every line of that server goes there, at every level, and nothing to the global logger, so two servers in one process keep their AE titles and SOP Instance UIDs apart.

The command line

echoscp answers C-ECHO only, on the four uncompressed syntaxes. storescp accepts every storage class in all 41 transfer syntaxes and writes each instance to -output as <SOP Instance UID>.dcm:

$ go-dicom echoscp -port 41001
Starting DICOM Echo SCP
  AE Title: ECHOSCP
  Port:     41001
Listening for verification requests... (Ctrl+C to stop)
$ go-dicom storescp -port 41005 -output received2 -allow CT_SCANNER
Starting DICOM Store SCP
  AE Title: STORESCP
  Port:     41005
  Output:   received2
  Allow:    AE titles CT_SCANNER
Listening for associations... (Ctrl+C to stop)
Refused "STORESCU" from 127.0.0.1:61234: the calling AE title is not on -allow
Received: 1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322 (SOP Class: 1.2.840.10008.5.1.4.1.1.2) -> received2/1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322.dcm
FlagMeaningIn SCPConfig
-portListen port (default 11112)Port
-aetThe AE title it answers toAETitle
-allow, -allow-fileCalling AE titles, addresses, CIDR ranges, TITLE@ADDRESS; storescp has it, echoscp does notAdmit
-tls, -tls-cert, -tls-key, -tls-caTLS, and mutual TLS with -tls-caTLS
-eventsThe -events logEvents

Both listen on every interface; neither has a bind-address flag.

Limits and gotchas

  • StorageHandler holds each instance in memory decoded. For large instances implement CStoreStreamer; storescp uses StorageHandler.
  • A handler that says Success must have kept the instance. A modality may delete its copy on that word.
  • No timeout is put on a handler. One that waits on a disk or database should also wait on ctx.
  • A C-STORE whose SOP class is not the context's is answered 0122 before its data set is read; the association continues.
  • CONFORMANCE.md §2.2 to §2.4 list the services and what is refused when a handler does not implement it.

See also

On this page